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
256,046
<p>Is it generally better to run functions on the webserver, or in the database?</p> <p>Example:</p> <pre><code>INSERT INTO example (hash) VALUE (MD5('hello')) </code></pre> <p>or</p> <pre><code>INSERT INTO example (hash) VALUE ('5d41402abc4b2a76b9719d911017c592') </code></pre> <p>Ok so that's a really trivial example, but for scalability when a site grows to multiple websites or database servers, where is it best to "do the work"?</p>
[ { "answer_id": 256054, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 5, "selected": true, "text": "<p>I try to think of the database as the place to persist stuff only, and put all abstraction code elsewhere. Database expressions are complex enough already without adding functions to them.</p>\n\n<p>Also, the query optimizer will trip over any expressions with functions if you should ever end up wanting to do something like \"SELECT .... WHERE MD5(xxx) = ... \"</p>\n\n<p>And database functions aren't very portable in general.</p>\n" }, { "answer_id": 256062, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "<p>Personally, I try to keep the database as simple (to the minimum) with Insert, Update, Delete without having too much function that can be used in code. Stored Proc is the same, contain only task that are very close to persistence data and not business logic related.</p>\n\n<p>I would put the MD5 outside. This will let met have this \"data manipulation\" outside the storage scope of the database. </p>\n\n<p>But, your example is quite \"easy\" and I do not think it's bad to have it inside...</p>\n" }, { "answer_id": 256090, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 0, "selected": false, "text": "<p>I think most of the time, you're going to want to leave the data manipulation to the webserver but, if you want to process databases with regards to tables, relations, etc., then go for the DB.</p>\n\n<p>I'm personally lobbying my company to upgrade our MySQL server to 5.0 so that I can start taking advantage of procedures (which is killing a couple of sites we administer).</p>\n" }, { "answer_id": 256117, "author": "Blank", "author_id": 19521, "author_profile": "https://Stackoverflow.com/users/19521", "pm_score": 2, "selected": false, "text": "<p>I try to use functions in my scripting language whenever calculations like that are required. I keep my SQL function useage down to a minimum, for a number of reasons.</p>\n\n<p>The primary reason is that my one SQL database is responsible for hosting multiple websites. If the SQL server were to get bogged down with requests from one site, it would adversely affect the rest. This is even more important to consider if you are working on a shared server for example, although in this case you have little control over what the other users are doing.</p>\n\n<p>The secondary reason is that I like my SQL code to be as portable as possible. I don't even want to <em>try</em> to count the different flavors of SQL that exist, so I try to keep functions (especially non-standard extensions) out of my SQL code, except for things like SUM or MIN/MAX.</p>\n\n<p>I guess what I'm saying is, SQL is designed to store and retrieve data, and it should be kept to that purpose. Use your serving language of choice to perform any calculations beforehand, and keep your SQL code portable.</p>\n" }, { "answer_id": 256199, "author": "Francisco Soto", "author_id": 3695, "author_profile": "https://Stackoverflow.com/users/3695", "pm_score": 2, "selected": false, "text": "<p>Use your database as means of persisting and mantaining data integrity. And leave business logic outside of it. </p>\n\n<p>If you put business logic, any of it, in your database, you are making it more complex to manage and mantain in the future.</p>\n" }, { "answer_id": 257004, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "<p>Like the other answers so far, I prefer to keep all the business logic in one place. Namely, my application language. (More specifically, in the object model, if one is present, but not all code is OO.)</p>\n\n<p>However, if you look around StackOverflow for (my)sql-tagged questions about whether to use inline SQL or stored procedures, you'll find that most of the people responding to those are strongly in favor of using stored procs whenever and whereever possible, even for the most trivial queries. You may want to check out some of those questions to see some of the arguments favoring the other approach.</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33322/" ]
Is it generally better to run functions on the webserver, or in the database? Example: ``` INSERT INTO example (hash) VALUE (MD5('hello')) ``` or ``` INSERT INTO example (hash) VALUE ('5d41402abc4b2a76b9719d911017c592') ``` Ok so that's a really trivial example, but for scalability when a site grows to multiple websites or database servers, where is it best to "do the work"?
I try to think of the database as the place to persist stuff only, and put all abstraction code elsewhere. Database expressions are complex enough already without adding functions to them. Also, the query optimizer will trip over any expressions with functions if you should ever end up wanting to do something like "SELECT .... WHERE MD5(xxx) = ... " And database functions aren't very portable in general.
256,073
<p>I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized? </p> <pre><code>public static void Main(String[] args) { Byte maxSize; Queue queue; if(args.Length != 0) { if(Byte.TryParse(args[0], out maxSize)) queue = new Queue(){MaxSize = maxSize}; else Environment.Exit(0); } else { Environment.Exit(0); } for(Byte j = 0; j &lt; queue.MaxSize; j++) queue.Insert(j); for(Byte j = 0; j &lt; queue.MaxSize; j++) Console.WriteLine(queue.Remove()); } </code></pre> <p>So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?</p> <p>Hope ya'll can give me some pointers :)</p> <p>Thanks.</p>
[ { "answer_id": 256075, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "<p>The compiler doesn't know that Environment.Exit() does not return. Why not just \"return\" from Main()?</p>\n" }, { "answer_id": 256078, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 7, "selected": true, "text": "<p>The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize <code>queue</code> to null when you declare it.</p>\n\n<pre><code>Queue queue = null;\n</code></pre>\n" }, { "answer_id": 256091, "author": "Nelson Reis", "author_id": 29544, "author_profile": "https://Stackoverflow.com/users/29544", "pm_score": 0, "selected": false, "text": "<p>The compiler only knows that the code is or isn't reachable if you use \"return\". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.</p>\n" }, { "answer_id": 256375, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<p>A couple of different ways to solve the problem:</p>\n\n<p>Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.</p>\n\n<pre><code>static void Main(string[] args) {\n if(args.Length != 0) {\n if(Byte.TryParse(args[0], out maxSize))\n queue = new Queue(){MaxSize = maxSize};\n else\n return;\n } else {\n return; \n}\n</code></pre>\n\n<p>Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method </p>\n\n<pre><code>static int Main(string[] args) {\n if(args.Length != 0) {\n if(Byte.TryParse(args[0], out maxSize))\n queue = new Queue(){MaxSize = maxSize};\n else\n return 1;\n } else {\n return 2;\n }\n}\n</code></pre>\n\n<p>Initialize queue to null, which is really just a compiler trick that says \"I'll figure out my own uninitialized variables, thank you very much\". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you <em>really</em> wanted to do it this way, something like this would be clearer:</p>\n\n<pre><code>static void Main(string[] args) {\n Byte maxSize;\n Queue queue = null;\n\n if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {\n Environment.Exit(0);\n }\n queue = new Queue(){MaxSize = maxSize};\n\n for(Byte j = 0; j &lt; queue.MaxSize; j++)\n queue.Insert(j);\n for(Byte j = 0; j &lt; queue.MaxSize; j++)\n Console.WriteLine(queue.Remove());\n}\n</code></pre>\n\n<p>Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)</p>\n\n<pre><code>static void Main(String[] args) {\n if(args.Length != 0) {\n if(Byte.TryParse(args[0], out maxSize)) {\n queue = new Queue(){MaxSize = maxSize};\n } else {\n Environment.Exit(0);\n return;\n }\n } else { \n Environment.Exit(0);\n return;\n }\n\n for(Byte j = 0; j &lt; queue.MaxSize; j++)\n queue.Insert(j);\n for(Byte j = 0; j &lt; queue.MaxSize; j++)\n Console.WriteLine(queue.Remove());\n}\n</code></pre>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33324/" ]
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized? ``` public static void Main(String[] args) { Byte maxSize; Queue queue; if(args.Length != 0) { if(Byte.TryParse(args[0], out maxSize)) queue = new Queue(){MaxSize = maxSize}; else Environment.Exit(0); } else { Environment.Exit(0); } for(Byte j = 0; j < queue.MaxSize; j++) queue.Insert(j); for(Byte j = 0; j < queue.MaxSize; j++) Console.WriteLine(queue.Remove()); } ``` So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)? Hope ya'll can give me some pointers :) Thanks.
The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize `queue` to null when you declare it. ``` Queue queue = null; ```
256,093
<p>I'm trying to use class names to change the color of a link after it has been selected, so that It will remain the new color, but only until another link is selected, and then it will change back.</p> <p>I'm using this code that was posted by Martin Kool in <a href="https://stackoverflow.com/questions/206689/changing-the-bg-color-of-a-selected-link">this</a> question:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el &amp;&amp; el.className == "unselected") { el.className = "selected"; var siblings = el.parentNode.childNodes; for (var i = 0, l = siblings.length; i &lt; l; i++) { var sib = siblings[i]; if (sib != el &amp;&amp; sib.className == "selected") sib.className = "unselected"; } } } &lt;/script&gt; &lt;style&gt; .selected { background: #f00; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" class="selected"&gt;One&lt;/a&gt; &lt;a href="#" class="unselected"&gt;Two&lt;/a&gt; &lt;a href="#" class="unselected"&gt;Three&lt;/a&gt; &lt;/body&gt; </code></pre> <p>It works fine until I try to out the links in a table. Why is this? Be easy, I'm a beginner.</p> <hr> <p>There is no error, the links are changing to the "selected" class, but when another link is selected, the old links are keeping the "selected" class instead of changing to "unselected". Basically, as far as I can tell, it's functioning like a vlink attribute, which is not what I'm going for.</p> <p>And yes, the links are all in different cells, how would you suggest I change the code so that it works correctly?</p> <hr> <p>OK, actually, I spoke too soon.</p> <pre><code>document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el &amp;&amp; el.className == 'unselected') { var links = document.getElementsByTagName('a'); for (var i = links.length - 1; i &gt;= 0; i--) { if (links[i].className == 'selected') links[i].className = 'unselected'; } el.className = 'selected'; } return false; } </code></pre> <p>This code you gave me works great, visually, it does exactly what I want it to do. However, It makes my links stop working... They change color, but dont link to anything, and then when I remove the script, they work fine. What am I doing wrong/what do I have to change to make this work?</p> <p>Also, I want to do the same thing somewhere else in my website, where the links are all in one <code>&lt;div&gt;</code> tag, separated by <code>&lt;p&gt;</code> tags. How can I make this work?</p>
[ { "answer_id": 256107, "author": "lacker", "author_id": 2652, "author_profile": "https://Stackoverflow.com/users/2652", "pm_score": 0, "selected": false, "text": "<p>Is there an error or is there just nothing happening? A good first step if you are a javascript beginner is to use a tool like Firebug so you see detailed error messages, and you can add in console.log statements to see what's going on while you run your code.</p>\n" }, { "answer_id": 256113, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<p>By ‘in tables’ do you mean putting each link in its own cell? Because that would make this line:</p>\n\n<pre><code>var siblings = el.parentNode.childNodes;\n</code></pre>\n\n<p>fail to select other links outside of the cell. You'd have to find another way to signal which element is the link container.</p>\n" }, { "answer_id": 256143, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": true, "text": "<p>You're looping through the siblings. If the links are in separate <code>&lt;td&gt;</code>'s then they're no longer siblings.</p>\n\n<p>You can loop through all the links like this:</p>\n\n<pre><code>document.onclick = function(evt)\n{\n var el = window.event? event.srcElement : evt.target;\n if (el &amp;&amp; el.className == 'unselected')\n {\n var links = document.getElementsByTagName('a');\n for (var i = links.length - 1; i &gt;= 0; i--)\n {\n if (links[i].className == 'selected')\n links[i].className = 'unselected';\n }\n el.className = 'selected';\n }\n\n return false;\n}\n</code></pre>\n\n<p>I've also added a <code>return false;</code> at the end of the function to stop you going to '#'</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to use class names to change the color of a link after it has been selected, so that It will remain the new color, but only until another link is selected, and then it will change back. I'm using this code that was posted by Martin Kool in [this](https://stackoverflow.com/questions/206689/changing-the-bg-color-of-a-selected-link) question: ``` <html> <head> <script> document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el && el.className == "unselected") { el.className = "selected"; var siblings = el.parentNode.childNodes; for (var i = 0, l = siblings.length; i < l; i++) { var sib = siblings[i]; if (sib != el && sib.className == "selected") sib.className = "unselected"; } } } </script> <style> .selected { background: #f00; } </style> </head> <body> <a href="#" class="selected">One</a> <a href="#" class="unselected">Two</a> <a href="#" class="unselected">Three</a> </body> ``` It works fine until I try to out the links in a table. Why is this? Be easy, I'm a beginner. --- There is no error, the links are changing to the "selected" class, but when another link is selected, the old links are keeping the "selected" class instead of changing to "unselected". Basically, as far as I can tell, it's functioning like a vlink attribute, which is not what I'm going for. And yes, the links are all in different cells, how would you suggest I change the code so that it works correctly? --- OK, actually, I spoke too soon. ``` document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el && el.className == 'unselected') { var links = document.getElementsByTagName('a'); for (var i = links.length - 1; i >= 0; i--) { if (links[i].className == 'selected') links[i].className = 'unselected'; } el.className = 'selected'; } return false; } ``` This code you gave me works great, visually, it does exactly what I want it to do. However, It makes my links stop working... They change color, but dont link to anything, and then when I remove the script, they work fine. What am I doing wrong/what do I have to change to make this work? Also, I want to do the same thing somewhere else in my website, where the links are all in one `<div>` tag, separated by `<p>` tags. How can I make this work?
You're looping through the siblings. If the links are in separate `<td>`'s then they're no longer siblings. You can loop through all the links like this: ``` document.onclick = function(evt) { var el = window.event? event.srcElement : evt.target; if (el && el.className == 'unselected') { var links = document.getElementsByTagName('a'); for (var i = links.length - 1; i >= 0; i--) { if (links[i].className == 'selected') links[i].className = 'unselected'; } el.className = 'selected'; } return false; } ``` I've also added a `return false;` at the end of the function to stop you going to '#'
256,109
<p>I've almost completely installed Boost, but I have a problem with how to set my path to Boost in <em>Tools->options->projects->VC++ Directories</em>.</p> <p>I've written the path to include files and libraries (my folder contains two subfolders, <code>lib</code> and <code>include</code>), but when I try to use Boost with <code>#include boost/regex.hpp</code>, I got this linking error:</p> <pre><code>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc90-mt-gd-1_36.lib </code></pre> <p>Could you please tell me how to install Boost correctly for Visual Studio 2008?</p>
[ { "answer_id": 256114, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p>Use the <a href=\"http://www.boostpro.com/download/\" rel=\"nofollow noreferrer\">Boost Installer</a> by the Boost consulting group.</p>\n" }, { "answer_id": 256145, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 2, "selected": false, "text": "<p>You might be interested in the Visual Studio 2008 Feature pack. It adds many of the features that have only been available from Boost until now, the features that are part of the C++ TR1.</p>\n" }, { "answer_id": 290021, "author": "Filip Frącz", "author_id": 21704, "author_profile": "https://Stackoverflow.com/users/21704", "pm_score": 2, "selected": false, "text": "<p>Also checkout <a href=\"https://stackoverflow.com/questions/289909/boost-137\">this post</a> for instructions on how to build Boost yourself.</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28298/" ]
I've almost completely installed Boost, but I have a problem with how to set my path to Boost in *Tools->options->projects->VC++ Directories*. I've written the path to include files and libraries (my folder contains two subfolders, `lib` and `include`), but when I try to use Boost with `#include boost/regex.hpp`, I got this linking error: ``` LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc90-mt-gd-1_36.lib ``` Could you please tell me how to install Boost correctly for Visual Studio 2008?
Use the [Boost Installer](http://www.boostpro.com/download/) by the Boost consulting group.
256,142
<p>When I try to commit the first revision to my git repository (git commit) from Cygwin, I'm getting an error in gvim which says "Unable to open swap file for "foo\.git\COMMIT_EDITMSG" [New Directory]. I think it might be some sort of permission problem, but I've tried removing the read-only flag from the folder, as well as recursively adjusting the owner (using the windows property tab, not chown under Cygwin) to be the account I'm running under, without any luck. If I change the default editor to notepad, I get "The system cannot find the file specified", even though the file (COMMIT_EDITMSG) does exist and even contains:</p> <pre><code># Please enter the commit message for your changes. # (Comment lines starting with '#' will not be included) # etc... </code></pre> <p>How can I troubleshoot this problem further?</p>
[ { "answer_id": 256168, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Unable to open swap file for \"foo\\.git\\COMMIT_EDITMSG\" [New Directory].</p>\n</blockquote>\n\n<p>Looks like the <code>git commit</code> is passing the file path as a Windows path, not a POSIX path. note the <code>\\</code> in the message.</p>\n\n<p><code>gvim</code> is going to try to open `foo.gitCOMMIT_EDITMSG\", which doesn't exist.</p>\n\n<p>I don't use <code>git</code>, but I imagine it uses an environment var similar to <code>SVN_EDITOR</code>. You may need to wrap the editing session with a small script that uses <code>cygpath</code> to change the file path from Windows to Posix separators.</p>\n\n<pre><code>#!/bin/bash\ngvim \"$(cygpath --unix \"${1}\")\"\n</code></pre>\n\n<p>Caveat Emptor, untested.</p>\n" }, { "answer_id": 2209825, "author": "Wahid Shalaly", "author_id": 49508, "author_profile": "https://Stackoverflow.com/users/49508", "pm_score": 0, "selected": false, "text": "<p>I faced the same issue first time but I found out that this is normal. Only I don't remember how to deal with Vim. I found solution in that link: <a href=\"http://vim.runpaint.org/basics/quitting-vim/\" rel=\"nofollow noreferrer\">http://vim.runpaint.org/basics/quitting-vim/</a>. I used the vim command :x that resulted in saving my comment &amp; committing modifcation.\nYou may read about this integration between Git &amp; Vim through this link: <a href=\"http://vim.runpaint.org/extending/integrating-vim-with-git/\" rel=\"nofollow noreferrer\">http://vim.runpaint.org/extending/integrating-vim-with-git/</a>.</p>\n" }, { "answer_id": 4493905, "author": "rurban", "author_id": 414279, "author_profile": "https://Stackoverflow.com/users/414279", "pm_score": 1, "selected": false, "text": "<p>You are using mingw or msysgit git in cygwin (<em>windows native</em>). This will not work when using a cygwin editor (gvim). The \\ is no path seperator in POSIX, it rather escapes the next character. </p>\n\n<p>You need to install the cygwin git package or use a proper mingw/msysgit editor.</p>\n\n<p>It might also be that the mingw git.exe is in the PATH before /usr/bin. Fix your PATH then.</p>\n\n<p>Such questions are usually handled via <a href=\"http://cygwin.com/problems.html\" rel=\"nofollow\">http://cygwin.com/problems.html</a>, esp. cygcheck -s -v -r > cygcheck.out in the mailinglist. Then we could see more.</p>\n" }, { "answer_id": 4774715, "author": "zerox", "author_id": 586454, "author_profile": "https://Stackoverflow.com/users/586454", "pm_score": 0, "selected": false, "text": "<p>For `cygpath', try:</p>\n\n<p><code>cygdrive -a -m COMMIT_EDITMSG</code></p>\n\n<p>You possibly want path in the following style:</p>\n\n<p><code>D:/path/to/your/working_directory/.git/COMMIT_EDITMSG</code></p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32539/" ]
When I try to commit the first revision to my git repository (git commit) from Cygwin, I'm getting an error in gvim which says "Unable to open swap file for "foo\.git\COMMIT\_EDITMSG" [New Directory]. I think it might be some sort of permission problem, but I've tried removing the read-only flag from the folder, as well as recursively adjusting the owner (using the windows property tab, not chown under Cygwin) to be the account I'm running under, without any luck. If I change the default editor to notepad, I get "The system cannot find the file specified", even though the file (COMMIT\_EDITMSG) does exist and even contains: ``` # Please enter the commit message for your changes. # (Comment lines starting with '#' will not be included) # etc... ``` How can I troubleshoot this problem further?
> > Unable to open swap file for "foo\.git\COMMIT\_EDITMSG" [New Directory]. > > > Looks like the `git commit` is passing the file path as a Windows path, not a POSIX path. note the `\` in the message. `gvim` is going to try to open `foo.gitCOMMIT\_EDITMSG", which doesn't exist. I don't use `git`, but I imagine it uses an environment var similar to `SVN_EDITOR`. You may need to wrap the editing session with a small script that uses `cygpath` to change the file path from Windows to Posix separators. ``` #!/bin/bash gvim "$(cygpath --unix "${1}")" ``` Caveat Emptor, untested.
256,148
<p>This is going to sound like a silly question, but I'm still learning C, so please bear with me. :)</p> <p>I'm working on chapter 6 of K&amp;R (structs), and thus far through the book have seen great success. I decided to work with structs pretty heavily, and therefore did a lot of work early in the chapter with the point and rect examples. One of the things I wanted to try was changing the <code>canonrect</code> function (2nd Edition, p 131) work via pointers, and hence return <code>void</code>.</p> <p>I have this working, but ran into a hiccup I was hoping you guys could help me out with. I wanted <code>canonRect</code> to create a temporary rectangle object, perform its changes, then reassign the pointer it's passed to the temporary rectangle, thus simplifying the code. </p> <p>However, if I do that, the rect doesn't change. Instead, I find myself manually repopulating the fields of the rect I'm passed in, which does work.</p> <p>The code follows:</p> <pre><code>#include &lt;stdio.h&gt; #define min(a, b) ((a) &lt; (b) ? (a) : (b)) #define max(a, b) ((a) &gt; (b) ? (a) : (b)) struct point { int x; int y; }; struct rect { struct point lowerLeft; struct point upperRight; }; // canonicalize coordinates of rectangle void canonRect(struct rect *r); int main(void) { struct point p1, p2; struct rect r; p1.x = 10; p1.y = 10; p2.x = 20; p2.y = 40; r.lowerLeft = p2; // note that I'm inverting my points intentionally r.upperRight = p1; printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n", r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y); // can't pass a pointer, only a reference. // (Passing pointers results in illegal indirection compile time errors) canonRect(&amp;r); printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n", r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y); } void canonRect(struct rect *r) { struct rect temp; temp.lowerLeft.x = min(r-&gt;lowerLeft.x, r-&gt;upperRight.x); temp.lowerLeft.y = min(r-&gt;lowerLeft.y, r-&gt;upperRight.y); temp.upperRight.x = max(r-&gt;lowerLeft.x, r-&gt;upperRight.x); temp.upperRight.y = max(r-&gt;lowerLeft.y, r-&gt;upperRight.y); r = &amp;temp; // doesn't work; my passed-in rect remains the same // I wind up doing the following instead, to reassign all // the members of my passed-in rect //r-&gt;lowerLeft = temp.lowerLeft; //r-&gt;upperRight = temp.upperRight; } </code></pre> <p>So here are the questions:</p> <ol> <li>Why does <code>r = &amp;temp;</code> not work? (I <strong>think</strong> this is because I pass in a reference instead of a pointer; am I correct in thinking that references are not modifiable but pointers are?)</li> <li>Why might I get an illegal indirection compile-time error if I try to pass in a pointer to <code>canonRect</code>? (IE, if I had <code>canonRect(*r);</code> in <code>main()</code>.)</li> </ol> <p>I suspect I already know the answer to #1, but #2 perplexes me -- I thought it was legal to pass pointers around.</p> <p>Anyway ... please forgive the C newb.</p>
[ { "answer_id": 256153, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": true, "text": "<p><strong>I think what you want to do is this:</strong></p>\n\n<pre><code>void canonRect(struct rect *r) {\n struct rect temp;\n temp.lowerLeft.x = min(r-&gt;lowerLeft.x, r-&gt;upperRight.x);\n temp.lowerLeft.y = min(r-&gt;lowerLeft.y, r-&gt;upperRight.y);\n temp.upperRight.x = max(r-&gt;lowerLeft.x, r-&gt;upperRight.x);\n temp.upperRight.y = max(r-&gt;lowerLeft.y, r-&gt;upperRight.y);\n\n *r = temp; \n}\n</code></pre>\n\n<p>In the above code you are setting *r which is of type rect to temp which is of type rect.</p>\n\n<p>Re 1: If you want to change what r is pointing to you need to use a pointer to a pointer. If that's really what you want (see above, it is not really what you want) then you'd have to make sure to point it to something on the heap. If you point it to something not created with 'new' or malloc then it will fall out of scope and you will be pointing to memory that is no longer used for that variable. </p>\n\n<p><em>Why doesn't your code work with r = &amp;temp?</em></p>\n\n<p>Because r is of rect* type. That means that r is a variable that holds a memory address who's memory contains a rect. If you change what r is pointing to, that's fine but that doesn't change the passed in variable. </p>\n\n<p>Re 2: * when not used in a type declaration is the dereference unary operator. This means that it will lookup what is inside the address of the pointer. So by passing *r you are not passing a pointer at all. In face since r is not a pointer, that is invalid syntax. </p>\n" }, { "answer_id": 256155, "author": "Joel Cunningham", "author_id": 5360, "author_profile": "https://Stackoverflow.com/users/5360", "pm_score": 4, "selected": false, "text": "<p>Its also worth noting your variable 'struct rec temp' is going to go out of scope as soon as that method canonRect ends and you will be pointing to invalid memory.</p>\n" }, { "answer_id": 256166, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>It sounds like you're confusing the 'dereference' operator (<code>*</code>) with the 'address of' operator (<code>&amp;</code>).</p>\n\n<p>When you write <code>&amp;r</code>, that gets the address of r and returns a pointer to r (a pointer is just a memory address of a variable). So you really are passing a pointer into the function.</p>\n\n<p>When you write <code>*r</code>, you are trying to dereference r. If r is a pointer, that will return the value that r is pointing to. But r isn't a pointer, it's a rect, so you'll get an error.</p>\n\n<p>To make things more confusing, the <code>*</code> character is also used when declaring pointer variables. In this function declaration:</p>\n\n<pre><code>void canonRect(struct rect *r) {\n</code></pre>\n\n<p><code>r</code> is declared to be a pointer to a <code>struct rect</code>. This is completely different from using <code>*</code> like this:</p>\n\n<pre><code>canonRect(*r); \n</code></pre>\n\n<p>In both cases, the * character means something completely different.</p>\n" }, { "answer_id": 256170, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>You might want to read up on the different ways parameters can (conceptually) be passed to functions. C is <a href=\"http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value\" rel=\"nofollow noreferrer\">call-by-value</a>, so when you pass your pointer to a rect into the function you are passing a copy of the pointer. Any changes the function makes to the value r directly (not indirectly) will not be visible to the caller. </p>\n\n<p>If you want the function to provide the caller with a new struct then there are two ways of doing it:\n 1. you can return a rect:\n 2. you can pass a pointer to a pointer to a rect in:</p>\n\n<p>The first way would be more natural:</p>\n\n<pre><code>struct rect* canonRect(struct rect* r)\n{\n struct rect* cr = (struct rect*) malloc(sizeof(struct rect));\n ...\n return cr;\n}\n</code></pre>\n\n<p>The second way would be:</p>\n\n<pre><code>void canonRect(struct rect** r)\n{\n *r = (struct rect*) malloc(sizeof(struct rect));\n}\n</code></pre>\n\n<p>and the caller would then use:</p>\n\n<pre><code> canonRect(&amp;r);\n</code></pre>\n\n<p>But the caller loses original pointer it had, and you would have to be careful not to leak structs.</p>\n\n<p>Whichever technique you use, the function will need to allocate memory for the new struct on the heap using malloc. You can't allocate the space on the stack by just declaring a struct because that memory becomes invalid when the function returns.</p>\n" }, { "answer_id": 256171, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "<p>First, K&amp;R c does not have a concept of \"references\", just pointers. The <code>&amp;</code> operator means \"take the address of\".</p>\n\n<hr>\n\n<p>Secondly, the <code>r</code> in <code>cannonRect()</code> is a local variable, and is <em>not</em> the <code>r</code> in <code>main()</code>. Changing where the local <code>r</code> points does not effect the <code>r</code> in the calling routine.</p>\n\n<hr>\n\n<p>Finally, as already noted the local <code>struct rect</code> is allocated on the stack, and goes out-of-scope at the close brace,</p>\n" }, { "answer_id": 261993, "author": "plan9assembler", "author_id": 1710672, "author_profile": "https://Stackoverflow.com/users/1710672", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>2.Why might I get an illegal indirection compile-time error if I try to pass in a pointer to canonRect? (IE, if I had canonRect(*r); in main().)</p>\n</blockquote>\n\n<p>Because, it is not the purpose of <strong>pointer</strong>.</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
This is going to sound like a silly question, but I'm still learning C, so please bear with me. :) I'm working on chapter 6 of K&R (structs), and thus far through the book have seen great success. I decided to work with structs pretty heavily, and therefore did a lot of work early in the chapter with the point and rect examples. One of the things I wanted to try was changing the `canonrect` function (2nd Edition, p 131) work via pointers, and hence return `void`. I have this working, but ran into a hiccup I was hoping you guys could help me out with. I wanted `canonRect` to create a temporary rectangle object, perform its changes, then reassign the pointer it's passed to the temporary rectangle, thus simplifying the code. However, if I do that, the rect doesn't change. Instead, I find myself manually repopulating the fields of the rect I'm passed in, which does work. The code follows: ``` #include <stdio.h> #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) struct point { int x; int y; }; struct rect { struct point lowerLeft; struct point upperRight; }; // canonicalize coordinates of rectangle void canonRect(struct rect *r); int main(void) { struct point p1, p2; struct rect r; p1.x = 10; p1.y = 10; p2.x = 20; p2.y = 40; r.lowerLeft = p2; // note that I'm inverting my points intentionally r.upperRight = p1; printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n", r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y); // can't pass a pointer, only a reference. // (Passing pointers results in illegal indirection compile time errors) canonRect(&r); printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n", r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y); } void canonRect(struct rect *r) { struct rect temp; temp.lowerLeft.x = min(r->lowerLeft.x, r->upperRight.x); temp.lowerLeft.y = min(r->lowerLeft.y, r->upperRight.y); temp.upperRight.x = max(r->lowerLeft.x, r->upperRight.x); temp.upperRight.y = max(r->lowerLeft.y, r->upperRight.y); r = &temp; // doesn't work; my passed-in rect remains the same // I wind up doing the following instead, to reassign all // the members of my passed-in rect //r->lowerLeft = temp.lowerLeft; //r->upperRight = temp.upperRight; } ``` So here are the questions: 1. Why does `r = &temp;` not work? (I **think** this is because I pass in a reference instead of a pointer; am I correct in thinking that references are not modifiable but pointers are?) 2. Why might I get an illegal indirection compile-time error if I try to pass in a pointer to `canonRect`? (IE, if I had `canonRect(*r);` in `main()`.) I suspect I already know the answer to #1, but #2 perplexes me -- I thought it was legal to pass pointers around. Anyway ... please forgive the C newb.
**I think what you want to do is this:** ``` void canonRect(struct rect *r) { struct rect temp; temp.lowerLeft.x = min(r->lowerLeft.x, r->upperRight.x); temp.lowerLeft.y = min(r->lowerLeft.y, r->upperRight.y); temp.upperRight.x = max(r->lowerLeft.x, r->upperRight.x); temp.upperRight.y = max(r->lowerLeft.y, r->upperRight.y); *r = temp; } ``` In the above code you are setting \*r which is of type rect to temp which is of type rect. Re 1: If you want to change what r is pointing to you need to use a pointer to a pointer. If that's really what you want (see above, it is not really what you want) then you'd have to make sure to point it to something on the heap. If you point it to something not created with 'new' or malloc then it will fall out of scope and you will be pointing to memory that is no longer used for that variable. *Why doesn't your code work with r = &temp?* Because r is of rect\* type. That means that r is a variable that holds a memory address who's memory contains a rect. If you change what r is pointing to, that's fine but that doesn't change the passed in variable. Re 2: \* when not used in a type declaration is the dereference unary operator. This means that it will lookup what is inside the address of the pointer. So by passing \*r you are not passing a pointer at all. In face since r is not a pointer, that is invalid syntax.
256,195
<p>I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in <code>$(document).ready</code> . For example:</p> <pre><code>$(function() { $('div._Foo').bind("mouseover", function(e) { // Do something exciting }); }); </code></pre> <p>Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel. </p> <p>What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of <code>$(document).ready</code>?</p>
[ { "answer_id": 256211, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 3, "selected": false, "text": "<p>I would use one of the following approaches:</p>\n\n<ol>\n<li><p>Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.</p></li>\n<li><p>Use the <a href=\"http://docs.jquery.com/Plugins/livequery\" rel=\"noreferrer\">livequery</a> plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.</p></li>\n</ol>\n" }, { "answer_id": 256253, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 10, "selected": true, "text": "<p>An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.</p>\n\n<p>What I've done to work around this is re-subscribe to the events I need after every update. I use <code>$(document).ready()</code> for the initial load, then use Microsoft's <a href=\"https://learn.microsoft.com/en-us/previous-versions/bb311028%28v%3dvs.140%29\" rel=\"noreferrer\"><code>PageRequestManager</code></a> (available if you have an update panel on your page) to re-subscribe every update. </p>\n\n<pre><code>$(document).ready(function() {\n // bind your jQuery events here initially\n});\n\nvar prm = Sys.WebForms.PageRequestManager.getInstance();\n\nprm.add_endRequest(function() {\n // re-bind your jQuery events here\n});\n</code></pre>\n\n<p>The <code>PageRequestManager</code> is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.</p>\n\n<p>If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments <code>(sender, eventArgs)</code> so you can see what raised the event and only re-bind if needed.</p>\n\n<p>Here is the latest version of the documentation from Microsoft: <a href=\"http://msdn.microsoft.com/en-us/library/bb383810.aspx\" rel=\"noreferrer\">msdn.microsoft.com/.../bb383810.aspx</a></p>\n\n<hr>\n\n<p>A better option you may have, depending on your needs, is to use jQuery's <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\"><code>.on()</code></a>. These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use <code>.delegate()</code> or <code>.on()</code>, so in those cases, you're better off re-subscribing.</p>\n" }, { "answer_id": 258497, "author": "Joe Brinkman", "author_id": 4820, "author_profile": "https://Stackoverflow.com/users/4820", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem and found the way that worked best was to rely on Event Bubbling and event delegation to handle it. The nice thing about event delegation is that once setup, you don't have to rebind events after an AJAX update.</p>\n\n<p>What I do in my code is setup a delegate on the parent element of the update panel. This parent element is not replaced on an update and therefore the event binding is unaffected.</p>\n\n<p>There are a number of good articles and plugins to handle event delegation in jQuery and the feature will likely be baked into the 1.3 release. The article/plugin I use for reference is:</p>\n\n<p><a href=\"http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery\" rel=\"nofollow noreferrer\">http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery</a></p>\n\n<p>Once you understand what it happening, I think you'll find this a much more elegant solution that is more reliable than remembering to re-bind events after every update. This also has the added benefit of giving you one event to unbind when the page is unloaded.</p>\n" }, { "answer_id": 259168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg</p>\n\n<pre><code>var prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(function() {... \n</code></pre>\n\n<p>Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 443015, "author": "Barbaros Alp", "author_id": 51734, "author_profile": "https://Stackoverflow.com/users/51734", "pm_score": 7, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\"&gt;\n\n function BindEvents() {\n $(document).ready(function() {\n $(\".tr-base\").mouseover(function() {\n $(this).toggleClass(\"trHover\");\n }).mouseout(function() {\n $(this).removeClass(\"trHover\");\n });\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>The area which is going to be updated.</p>\n\n<pre><code>&lt;asp:UpdatePanel...\n&lt;ContentTemplate\n &lt;script type=\"text/javascript\"&gt;\n Sys.Application.add_load(BindEvents);\n &lt;/script&gt;\n *// Staff*\n&lt;/ContentTemplate&gt;\n &lt;/asp:UpdatePanel&gt;\n</code></pre>\n" }, { "answer_id": 518693, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 5, "selected": false, "text": "<p>Upgrade to jQuery 1.3 and use:</p>\n\n<pre><code>$(function() {\n\n $('div._Foo').live(\"mouseover\", function(e) {\n // Do something exciting\n });\n\n});\n</code></pre>\n\n<p>Note: live works with most events, but not all. There is a complete list in <a href=\"http://docs.jquery.com/Events/live#typefn\" rel=\"noreferrer\">the documentation</a>.</p>\n" }, { "answer_id": 2916278, "author": "Brian MacKay", "author_id": 16082, "author_profile": "https://Stackoverflow.com/users/16082", "pm_score": 6, "selected": false, "text": "<p><strong>User Control with jQuery Inside an UpdatePanel</strong></p>\n\n<p>This isn't a direct answer to the question, but I did put this solution together by reading the answers that I found here, and I thought someone might find it useful.</p>\n\n<p>I was trying to use a jQuery textarea limiter inside of a User Control. This was tricky, because the User Control runs inside of an UpdatePanel, and it was losing its bindings on callback.</p>\n\n<p>If this was just a page, the answers here would have applied directly. However, User Controls do not have direct access to the head tag, nor did they have direct access to the UpdatePanel as some of the answers assume. </p>\n\n<p>I ended up putting this script block right into the top of my User Control's markup. For the initial bind, it uses $(document).ready, and then it uses prm.add_endRequest from there:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function BindControlEvents() {\n //jQuery is wrapped in BindEvents function so it can be re-bound after each callback.\n //Your code would replace the following line:\n $('#&lt;%= TextProtocolDrugInstructions.ClientID %&gt;').limit('100', '#charsLeft_Instructions'); \n }\n\n //Initial bind\n $(document).ready(function () {\n BindControlEvents();\n });\n\n //Re-bind for callbacks\n var prm = Sys.WebForms.PageRequestManager.getInstance(); \n\n prm.add_endRequest(function() { \n BindControlEvents();\n }); \n\n&lt;/script&gt;\n</code></pre>\n\n<p>So... Just thought someone might like to know that this works.</p>\n" }, { "answer_id": 4569642, "author": "Daniel Hursan", "author_id": 510109, "author_profile": "https://Stackoverflow.com/users/510109", "pm_score": 4, "selected": false, "text": "<p>You could also try:</p>\n\n<pre><code>&lt;asp:UpdatePanel runat=\"server\" ID=\"myUpdatePanel\"&gt;\n &lt;ContentTemplate&gt;\n\n &lt;script type=\"text/javascript\" language=\"javascript\"&gt;\n function pageLoad() {\n $('div._Foo').bind(\"mouseover\", function(e) {\n // Do something exciting\n });\n }\n &lt;/script&gt;\n\n &lt;/ContentTemplate&gt;\n&lt;/asp:UpdatePanel&gt;\n</code></pre>\n\n<p>,since pageLoad() is an ASP.NET ajax event which is executed each time the page is loaded at client side.</p>\n" }, { "answer_id": 5145710, "author": "Jono", "author_id": 638147, "author_profile": "https://Stackoverflow.com/users/638147", "pm_score": 4, "selected": false, "text": "<p>My answer? </p>\n\n<pre><code>function pageLoad() {\n\n $(document).ready(function(){\n</code></pre>\n\n<p>etc.</p>\n\n<p>Worked like a charm, where a number of other solutions failed miserably.</p>\n" }, { "answer_id": 6387958, "author": "Norm", "author_id": 803490, "author_profile": "https://Stackoverflow.com/users/803490", "pm_score": 3, "selected": false, "text": "<p>function pageLoad() is very dangerous to use in this situation. You could have events become wired multiple times. I would also stay away from .live() as it attaches to the document element and has to traverse the entire page (slow and crappy). </p>\n\n<p>The best solution I have seen so far is to use jQuery .delegate() function on a wrapper outside the update panel and make use of bubbling. Other then that, you could always wire up the handlers using Microsoft's Ajax library which was designed to work with UpdatePanels. </p>\n" }, { "answer_id": 13588643, "author": "Abhishek Shrivastava", "author_id": 328116, "author_profile": "https://Stackoverflow.com/users/328116", "pm_score": 2, "selected": false, "text": "<p>My answer is based on all the expert comments above, but below is the following code that anyone can use to make sure on each postback and on each asynchronous postback the JavaScript code will still be executed.</p>\n\n<p><b>In my case, I had a user control within a page. Just paste the below code in your user control.</b></p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt; \n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.add_endRequest(EndRequestHandler);\n function EndRequestHandler(sender, args) {\n if (args.get_error() == undefined) {\n UPDATEPANELFUNCTION();\n } \n }\n\n function UPDATEPANELFUNCTION() {\n jQuery(document).ready(function ($) {\n /* Insert all your jQuery events and function calls */\n });\n }\n\n UPDATEPANELFUNCTION(); \n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 16927547, "author": "fujiiface", "author_id": 1047907, "author_profile": "https://Stackoverflow.com/users/1047907", "pm_score": 0, "selected": false, "text": "<p>In response to Brian MacKay's answer:</p>\n\n<p>I inject the JavaScript into my page via the ScriptManager instead of putting it directly into the HTML of the UserControl. In my case, I need to scroll to a form that is made visible after the UpdatePanel has finished and returned. This goes in the code behind file. In my sample, I've already created the <strong>prm</strong> variable on the main content page.</p>\n\n<pre><code>private void ShowForm(bool pShowForm) {\n //other code here...\n if (pShowForm) {\n FocusOnControl(GetFocusOnFormScript(yourControl.ClientID), yourControl.ClientID);\n }\n}\n\nprivate void FocusOnControl(string pScript, string pControlId) {\n ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), \"focusControl_\" + pControlId, pScript, true);\n}\n\n/// &lt;summary&gt;\n/// Scrolls to the form that is made visible\n/// &lt;/summary&gt;\n/// &lt;param name=\"pControlId\"&gt;The ClientID of the control to focus on after the form is made visible&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\nprivate string GetFocusOnFormScript(string pControlId) {\n string script = @\"\n function FocusOnForm() {\n var scrollToForm = $('#\" + pControlId + @\"').offset().top;\n $('html, body').animate({ \n scrollTop: scrollToForm}, \n 'slow'\n );\n /* This removes the event from the PageRequestManager immediately after the desired functionality is completed so that multiple events are not added */\n prm.remove_endRequest(ScrollFocusToFormCaller);\n }\n prm.add_endRequest(ScrollFocusToFormCaller);\n function ScrollFocusToFormCaller(sender, args) {\n if (args.get_error() == undefined) {\n FocusOnForm();\n }\n }\";\n return script;\n}\n</code></pre>\n" }, { "answer_id": 24864697, "author": "Rohit Sharma", "author_id": 3172106, "author_profile": "https://Stackoverflow.com/users/3172106", "pm_score": 2, "selected": false, "text": "<p>Update Panel always replaces your Jquery with its inbuilt Scriptmanager's scripts after every load. Its better if you use pageRequestManager's instance methods like this...</p>\n\n<pre><code>Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest)\n function onEndRequest(sender, args) {\n // your jquery code here\n });\n</code></pre>\n\n<p>it will work fine ... </p>\n" }, { "answer_id": 24900805, "author": "Duane", "author_id": 3862312, "author_profile": "https://Stackoverflow.com/users/3862312", "pm_score": 2, "selected": false, "text": "<pre><code>pageLoad = function () {\n $('#div').unbind();\n //jquery here\n}\n</code></pre>\n\n<p>The pageLoad function is perfect for this case since it runs on the initial page load and every updatepanel async postback. I just had to add the unbind method to make the jquery work on updatepanel postbacks.</p>\n\n<p><a href=\"http://encosia.com/document-ready-and-pageload-are-not-the-same/\" rel=\"nofollow\">http://encosia.com/document-ready-and-pageload-are-not-the-same/</a></p>\n" }, { "answer_id": 31445710, "author": "Pradeep More", "author_id": 4733252, "author_profile": "https://Stackoverflow.com/users/4733252", "pm_score": 3, "selected": false, "text": "<p>When <code>$(document).ready(function (){...})</code> not work after page post back then use JavaScript function pageLoad in Asp.page as follow: </p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\nfunction pageLoad() {\n// Initialization code here, meant to run once. \n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 47877311, "author": "Tony Dong", "author_id": 760139, "author_profile": "https://Stackoverflow.com/users/760139", "pm_score": 0, "selected": false, "text": "<pre><code>Sys.Application.add_load(LoadHandler); //This load handler solved update panel did not bind control after partial postback\nfunction LoadHandler() {\n $(document).ready(function () {\n //rebind any events here for controls under update panel\n });\n}\n</code></pre>\n" }, { "answer_id": 50942963, "author": "mzonerz", "author_id": 2582841, "author_profile": "https://Stackoverflow.com/users/2582841", "pm_score": 1, "selected": false, "text": "<p>Use below script and change the body of the script accordingly.</p>\n\n<pre><code> &lt;script&gt;\n //Re-Create for on page postbacks\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n prm.add_endRequest(function () {\n //your codes here!\n });\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 72405957, "author": "Christopher", "author_id": 826308, "author_profile": "https://Stackoverflow.com/users/826308", "pm_score": 0, "selected": false, "text": "<p>For anyone else in my situation, I was trying to get jquery document ready function to work for a DevExpress ASPxCallbackPanel and nothing above (to-date) worked. This is what did work for me.</p>\n<pre><code>&lt;script&gt;\nfunction myDocReadyFunction(){ /* do stuff */ }\n&lt;/script&gt;\n\n&lt;dx:ASPxCallbackPanel ID=&quot;myCallbackPanel&quot; ... &gt;\n &lt;ClientSideEvents EndCallback=&quot;function(){ myDocReadyFunction();}&quot;&gt; \n &lt;/ClientSideEvents&gt;\n &lt;PanelCollection ...&gt;\n&lt;/dx:ASPxCallbackPanel&gt;\n</code></pre>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in `$(document).ready` . For example: ``` $(function() { $('div._Foo').bind("mouseover", function(e) { // Do something exciting }); }); ``` Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel. What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of `$(document).ready`?
An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel. What I've done to work around this is re-subscribe to the events I need after every update. I use `$(document).ready()` for the initial load, then use Microsoft's [`PageRequestManager`](https://learn.microsoft.com/en-us/previous-versions/bb311028%28v%3dvs.140%29) (available if you have an update panel on your page) to re-subscribe every update. ``` $(document).ready(function() { // bind your jQuery events here initially }); var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(function() { // re-bind your jQuery events here }); ``` The `PageRequestManager` is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page. If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments `(sender, eventArgs)` so you can see what raised the event and only re-bind if needed. Here is the latest version of the documentation from Microsoft: [msdn.microsoft.com/.../bb383810.aspx](http://msdn.microsoft.com/en-us/library/bb383810.aspx) --- A better option you may have, depending on your needs, is to use jQuery's [`.on()`](http://api.jquery.com/on/). These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use `.delegate()` or `.on()`, so in those cases, you're better off re-subscribing.
256,204
<p>I use the <code>:e</code> and <code>:w</code> commands to edit and to write a file. I am not sure if there is "close" command to close the current file without leaving Vim?</p> <p>I know that the <code>:q</code> command can be used to close a file, but if it is the last file, Vim is closed as well; Actually on Mac OS MacVim does quit. Only the Vim window is closed and I could use <kbd>Control</kbd>-<kbd>N</kbd> to open a blank Vim window again. I would like Vim to remain open with a blank screen.</p>
[ { "answer_id": 256206, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 3, "selected": false, "text": "<p>If you've saved the last file already, then <code>:enew</code> is your friend (<code>:enew!</code> if you don't want to save the last file). Note that the original file will still be in your buffer list (the one accessible via <code>:ls</code>).</p>\n" }, { "answer_id": 256208, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": true, "text": "<p>This deletes the buffer (which translates to close the file)</p>\n\n<pre><code>:bd \n</code></pre>\n" }, { "answer_id": 256210, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<pre>:[N]bd[elete][!] *:bd* *:bdel* *:bdelete* *E516*\n:bd[elete][!] [N]\n Unload buffer [N] (default: current buffer) and delete it from\n the buffer list. If the buffer was changed, this fails,\n unless when [!] is specified, in which case changes are lost.\n The file remains unaffected. Any windows for this buffer are\n closed. If buffer [N] is the current buffer, another buffer\n will be displayed instead. This is the most recent entry in\n the jump list that points into a loaded buffer.\n Actually, the buffer isn't completely deleted, it is removed\n from the buffer list |unlisted-buffer| and option values,\n variables and mappings/abbreviations for the buffer are\n cleared.</pre>\n" }, { "answer_id": 290110, "author": "Gowri", "author_id": 3253, "author_profile": "https://Stackoverflow.com/users/3253", "pm_score": 5, "selected": false, "text": "<p>If you have multiple split windows in your Vim window then <code>:bd</code> closes the split window of the current file, so I like to use something a little more advanced:</p>\n\n<pre><code>map fc &lt;Esc&gt;:call CleanClose(1)\n\nmap fq &lt;Esc&gt;:call CleanClose(0)\n\n\nfunction! CleanClose(tosave)\nif (a:tosave == 1)\n w!\nendif\nlet todelbufNr = bufnr(\"%\")\nlet newbufNr = bufnr(\"#\")\nif ((newbufNr != -1) &amp;&amp; (newbufNr != todelbufNr) &amp;&amp; buflisted(newbufNr))\n exe \"b\".newbufNr\nelse\n bnext\nendif\n\nif (bufnr(\"%\") == todelbufNr)\n new\nendif\nexe \"bd\".todelbufNr\nendfunction\n</code></pre>\n" }, { "answer_id": 2531039, "author": "wbogacz", "author_id": 123931, "author_profile": "https://Stackoverflow.com/users/123931", "pm_score": 2, "selected": false, "text": "<p><code>:bd</code> can be mapped. I map it to <kbd>F4</kbd>, <kbd>Shift</kbd>-<kbd>F4</kbd> if I need to force-close because of some change I no longer want.</p>\n" }, { "answer_id": 4334306, "author": "sebnow", "author_id": 64423, "author_profile": "https://Stackoverflow.com/users/64423", "pm_score": 6, "selected": false, "text": "<p>As already mentioned, you're looking for <code>:bd</code>, however this doesn't completely remove the buffer, it's still accessible:</p>\n\n<pre><code>:e foo\n:e bar\n:buffers\n 1 #h \"foo\" line 1\n 2 %a \"bar\" line 1\nPress ENTER or type command to continue\n:bd 2\n:buffers\n 1 %a \"foo\" line 1\nPress ENTER or type command to continue\n:b 2\n2 bar\n</code></pre>\n\n<p>You may instead want <code>:bw</code> which completely removes it.</p>\n\n<pre><code>:bw 2\n:b 2 \nE86: Buffer 2 does not exist\n</code></pre>\n\n<p>Not knowing about <code>:bw</code> bugged me for quite a while.</p>\n" }, { "answer_id": 12531154, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://www.vim.org/scripts/script.php?script_id=1147\" rel=\"nofollow noreferrer\">bufkill.vim</a> plugin adds <code>BD</code> etc., to delete the buffer without closing any splits (as <code>bd</code>) would alone.</p>\n" }, { "answer_id": 16416741, "author": "Gary Willoughby", "author_id": 13227, "author_profile": "https://Stackoverflow.com/users/13227", "pm_score": 0, "selected": false, "text": "<p>Look at the <a href=\"https://github.com/Soares/butane.vim\" rel=\"nofollow noreferrer\">Butane plugin</a> to keep the window layout when closing a buffer.</p>\n" }, { "answer_id": 19825539, "author": "pablofiumara", "author_id": 2623074, "author_profile": "https://Stackoverflow.com/users/2623074", "pm_score": 3, "selected": false, "text": "<p>If you <em>modify</em> a file and want to close it without quitting Vim and without saving, you should type <code>:bd!</code>.</p>\n" }, { "answer_id": 26597295, "author": "Takashi Kojima", "author_id": 4187609, "author_profile": "https://Stackoverflow.com/users/4187609", "pm_score": -1, "selected": false, "text": "<p>I have the same issue so I made the plugin.\nThis plugin replace :q and other commands and then prevent the window closed.</p>\n\n<p>if you still have issue, please try to use following plugin. \n<a href=\"https://github.com/taka-vagyok/prevent-win-closed.vim\" rel=\"nofollow\">https://github.com/taka-vagyok/prevent-win-closed.vim</a></p>\n" }, { "answer_id": 39252624, "author": "Stryker", "author_id": 1406420, "author_profile": "https://Stackoverflow.com/users/1406420", "pm_score": 2, "selected": false, "text": "<p>Insert the following in your .vimrc file and, with pressing <kbd>F4</kbd>, it will close the current file.</p>\n\n<pre><code>:map &lt;F4&gt; :bd&lt;CR&gt;\n</code></pre>\n" }, { "answer_id": 71458320, "author": "Joannes", "author_id": 5941807, "author_profile": "https://Stackoverflow.com/users/5941807", "pm_score": 0, "selected": false, "text": "<p>For me <a href=\"https://github.com/Asheq/close-buffers.vim\" rel=\"nofollow noreferrer\">close-buffers</a> is pretty useful plugin:</p>\n<p><code>:Bdelete this</code> to close that you can remap.</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
I use the `:e` and `:w` commands to edit and to write a file. I am not sure if there is "close" command to close the current file without leaving Vim? I know that the `:q` command can be used to close a file, but if it is the last file, Vim is closed as well; Actually on Mac OS MacVim does quit. Only the Vim window is closed and I could use `Control`-`N` to open a blank Vim window again. I would like Vim to remain open with a blank screen.
This deletes the buffer (which translates to close the file) ``` :bd ```
256,218
<p>Let's say I have a <code>char* str = "0123456789"</code> and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?</p> <p>Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.</p>
[ { "answer_id": 256223, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 7, "selected": true, "text": "<p>You can use <code>printf()</code>, and a special format string:</p>\n\n<pre><code>char *str = \"0123456789\";\nprintf(\"%.6s\\n\", str + 1);\n</code></pre>\n\n<p>The precision in the <code>%s</code> conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:</p>\n\n<pre><code>int length = 6;\nchar *str = \"0123456789\"; \nprintf(\"%.*s\\n\", length, str + 1);\n</code></pre>\n\n<p>In this example, the * is used to indicate that the next argument (<code>length</code>) will contain the precision for the <code>%s</code> conversion, the corresponding argument must be an <code>int</code>.</p>\n\n<p>Pointer arithmetic can be used to specify the starting position as I did above.</p>\n\n<p><strong>[EDIT]</strong></p>\n\n<p>One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:</p>\n\n<pre><code>int length = 10;\nchar *str = \"0123456789\";\nprintf(\"%.*s\\n\", length, str + 5);\n</code></pre>\n\n<p>Will print \"<code>56789</code>\". If you always want to print a certain number of characters, specify both a minimum field width and a precision:</p>\n\n<pre><code>printf(\"%10.10s\\n\", str + 5);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>printf(\"%*.*s\\n\", length, length, str + 5);\n</code></pre>\n\n<p>which will print:</p>\n\n<pre><code>\" 56789\"\n</code></pre>\n\n<p>You can use the minus sign to left-justify the output in the field:</p>\n\n<pre><code>printf(\"%-10.10s\\n\", str + 5);\n</code></pre>\n\n<p>Finally, the minimum field width and the precision can be different, i.e. </p>\n\n<pre><code>printf(\"%8.5s\\n\", str);\n</code></pre>\n\n<p>will print at most 5 characters right-justified in an 8 character field.</p>\n" }, { "answer_id": 256224, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "<p>If you don't mind modifying the data, you could just do some pointer arithmetic. This is assuming that str is a char pointer and not an array:</p>\n\n<pre><code>char string[] = \"0123456789\";\nchar *str = string;\n\nstr += 3; // \"removes\" the first 3 items\nstr[4] = '\\0'; // sets the 5th item to NULL, effectively truncating the string\n\nprintf(str); // prints \"3456\"\n</code></pre>\n" }, { "answer_id": 256226, "author": "Dan Olson", "author_id": 33346, "author_profile": "https://Stackoverflow.com/users/33346", "pm_score": -1, "selected": false, "text": "<p>I believe there is some magic you can do with printf that will only print a certain number of characters, but it's not commonly understood or used. We tried to do it at a previous job and couldn't get it to work consistently.</p>\n\n<p>What I would do is save off a character, null that character in the string, print it, then save it back.</p>\n" }, { "answer_id": 256232, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>Robert Gamble and Steve separately have most of the pieces.\nAssembled into a whole:</p>\n\n<pre><code>void print_substring(const char *str, int skip, int tail)\n{\n int len = strlen(str);\n assert(skip &gt;= 0);\n assert(tail &gt;= 0 &amp;&amp; tail &lt; len);\n assert(len &gt; skip + tail);\n printf(\"%.*s\", len - skip - tail, str + skip);\n}\n</code></pre>\n\n<p>Invocation for the example:</p>\n\n<pre><code>print_substring(\"0123456789\", 1, 3);\n</code></pre>\n" }, { "answer_id": 257731, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 0, "selected": false, "text": "<p>Here is a clean and simple substring function I dug up from my personal library that may be useful:</p>\n\n<pre><code>char *\nsubstr(const char *src, size_t start, size_t len)\n{\n char *dest = malloc(len+1);\n if (dest) {\n memcpy(dest, src+start, len);\n dest[len] = '\\0';\n }\n return dest;\n}\n</code></pre>\n\n<p>It's probably self-explanatory but it takes a string, a starting position (starting at zero), and a length and returns a substring of the original string or a null pointer if malloc fails. The pointer returned can be <code>free</code>'d by the caller when the memory is no longer needed. In the spirit of C, the function doesn't validate the starting position and length provided.</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21648/" ]
Let's say I have a `char* str = "0123456789"` and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it? Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char\*, or a very small one.
You can use `printf()`, and a special format string: ``` char *str = "0123456789"; printf("%.6s\n", str + 1); ``` The precision in the `%s` conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well: ``` int length = 6; char *str = "0123456789"; printf("%.*s\n", length, str + 1); ``` In this example, the \* is used to indicate that the next argument (`length`) will contain the precision for the `%s` conversion, the corresponding argument must be an `int`. Pointer arithmetic can be used to specify the starting position as I did above. **[EDIT]** One more point, if your string is shorter than your precision specifier, less characters will be printed, for example: ``` int length = 10; char *str = "0123456789"; printf("%.*s\n", length, str + 5); ``` Will print "`56789`". If you always want to print a certain number of characters, specify both a minimum field width and a precision: ``` printf("%10.10s\n", str + 5); ``` or ``` printf("%*.*s\n", length, length, str + 5); ``` which will print: ``` " 56789" ``` You can use the minus sign to left-justify the output in the field: ``` printf("%-10.10s\n", str + 5); ``` Finally, the minimum field width and the precision can be different, i.e. ``` printf("%8.5s\n", str); ``` will print at most 5 characters right-justified in an 8 character field.
256,222
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p> <pre><code>def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass </code></pre> <p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p>
[ { "answer_id": 256235, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "<p>I've mostly just seen the builtin <code>ValueError</code> used in this situation.</p>\n" }, { "answer_id": 256236, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 7, "selected": false, "text": "<p>I would inherit from <code>ValueError</code></p>\n\n<pre><code>class IllegalArgumentError(ValueError):\n pass\n</code></pre>\n\n<p>It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.</p>\n\n<p>If you need to catch that specific error, it is helpful to have a name.</p>\n" }, { "answer_id": 256239, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": -1, "selected": false, "text": "<p>I'm not sure I agree with inheritance from <code>ValueError</code> -- my interpretation of the documentation is that <code>ValueError</code> is <em>only</em> supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.</p>\n\n<blockquote>\n <p>Raised when a built-in operation or\n function receives an argument that has\n the right type but an inappropriate\n value, and the situation is not\n described by a more precise exception\n such as IndexError.</p>\n</blockquote>\n\n<p>-- <a href=\"http://docs.python.org/library/exceptions.html?highlight=valueerror#exceptions.ValueError\" rel=\"nofollow noreferrer\">ValueError documentation</a></p>\n" }, { "answer_id": 256260, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 11, "selected": true, "text": "<p>I would just raise <a href=\"https://docs.python.org/3/library/exceptions.html#ValueError\" rel=\"noreferrer\">ValueError</a>, unless you need a more specific exception..</p>\n\n<pre><code>def import_to_orm(name, save=False, recurse=False):\n if recurse and not save:\n raise ValueError(\"save must be True if recurse is True\")\n</code></pre>\n\n<p>There's really no point in doing <code>class BadValueError(ValueError):pass</code> - your custom class is identical in use to <a href=\"https://docs.python.org/3/library/exceptions.html#ValueError\" rel=\"noreferrer\">ValueError</a>, so why not use that?</p>\n" }, { "answer_id": 46589274, "author": "BobHy", "author_id": 2036651, "author_profile": "https://Stackoverflow.com/users/2036651", "pm_score": 0, "selected": false, "text": "<p>Agree with Markus' suggestion to roll your own exception, but the text of the exception should clarify that the problem is in the argument list, not the individual argument values. I'd propose:</p>\n\n<pre><code>class BadCallError(ValueError):\n pass\n</code></pre>\n\n<p>Used when keyword arguments are missing that were required for the specific call, or argument values are individually valid but inconsistent with each other. <code>ValueError</code> would still be right when a specific argument is right type but out of range.</p>\n\n<p>Shouldn't this be a standard exception in Python? </p>\n\n<p>In general, I'd like Python style to be a bit sharper in distinguishing bad inputs to a function (caller's fault) from bad results within the function (my fault). So there might also be a BadArgumentError to distinguish value errors in arguments from value errors in locals.</p>\n" }, { "answer_id": 51638010, "author": "J Bones", "author_id": 9540833, "author_profile": "https://Stackoverflow.com/users/9540833", "pm_score": 5, "selected": false, "text": "<p>I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example: </p>\n\n<pre><code>$ python -c 'print(sum())'\nTraceback (most recent call last):\nFile \"&lt;string&gt;\", line 1, in &lt;module&gt;\nTypeError: sum expected at least 1 arguments, got 0\n</code></pre>\n\n<p>Our junior dev just found this page in a google search for \"python exception wrong arguments\" and I'm surprised that the obvious (to me) answer wasn't ever suggested in the decade since this question was asked. </p>\n" }, { "answer_id": 56750114, "author": "Gloweye", "author_id": 4331885, "author_profile": "https://Stackoverflow.com/users/4331885", "pm_score": 5, "selected": false, "text": "<p>It depends on what the problem with the arguments is.</p>\n\n<p>If the argument has the wrong type, raise a TypeError. For example, when you get a string instead of one of those Booleans.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if not isinstance(save, bool):\n raise TypeError(f\"Argument save must be of type bool, not {type(save)}\")\n</code></pre>\n\n<p>Note, however, that in Python we rarely make any checks like this. If the argument really is invalid, some deeper function will probably do the complaining for us. And if we only check the boolean value, perhaps some code user will later just feed it a string knowing that non-empty strings are always True. It might save him a cast.</p>\n\n<p>If the arguments have invalid values, raise ValueError. This seems more appropriate in your case:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if recurse and not save:\n raise ValueError(\"If recurse is True, save should be True too\")\n</code></pre>\n\n<p>Or in this specific case, have a True value of recurse imply a True value of save. Since I would consider this a recovery from an error, you might also want to complain in the log.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if recurse and not save:\n logging.warning(\"Bad arguments in import_to_orm() - if recurse is True, so should save be\")\n save = True\n</code></pre>\n" }, { "answer_id": 68747161, "author": "thing10", "author_id": 16476731, "author_profile": "https://Stackoverflow.com/users/16476731", "pm_score": 3, "selected": false, "text": "<p>You would most likely use <code>ValueError</code> (<code>raise ValueError()</code> in full) in this case, but it depends on the type of bad value. For example, if you made a function that only allows strings, and the user put in an integer instead, you would you <code>TypeError</code> instead. If a user inputted a wrong input (meaning it has the right type but it does not qualify certain conditions) a <code>Value Error</code> would be your best choice. <code>Value</code> Error can also be used to block the program from other exceptions, for example, you could use a <code>ValueError</code> to stop the shell form raising a <code>ZeroDivisionError</code>, for example, in this function:</p>\n<pre><code>def function(number):\n if not type(number) == int and not type(number) == float:\n raise TypeError(&quot;number must be an integer or float&quot;)\n if number == 5:\n raise ValueError(&quot;number must not be 5&quot;)\n else:\n return 10/(5-number)\n</code></pre>\n<p>P.S. For a list of python built-in exceptions, go here:\n<a href=\"https://docs.python.org/3/library/exceptions.html\" rel=\"noreferrer\">https://docs.python.org/3/library/exceptions.html</a> (This is the official python databank)</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: ``` def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass ``` The only annoyance with this is that every package has its own, usually slightly differing `BadValueError`. I know that in Java there exists `java.lang.IllegalArgumentException` -- is it well understood that everybody will be creating their own `BadValueError`s in Python or is there another, preferred method?
I would just raise [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError), unless you need a more specific exception.. ``` def import_to_orm(name, save=False, recurse=False): if recurse and not save: raise ValueError("save must be True if recurse is True") ``` There's really no point in doing `class BadValueError(ValueError):pass` - your custom class is identical in use to [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError), so why not use that?
256,228
<p>I'm trying to read data from a photocell resistor and my Arduino Decimila and then graph it in real-time with Processing.</p> <p>Should be painfully simple; but its growing into a little bit of a nightmare for me.</p> <p>code I'm running on my Arduino:</p> <pre class="lang-java prettyprint-override"><code>int photoPin; void setup(){ photoPin = 0; Serial.begin( 9600 ); } void loop(){ int val = int( map( analogRead( photoPin ), 0, 1023, 0, 254 ) ); Serial.println( val ); //sending data over Serial } </code></pre> <p>code I'm running in Processing: </p> <pre class="lang-java prettyprint-override"><code>import processing.serial.*; Serial photocell; int[] yvals; void setup(){ size( 300, 150 ); photocell = new Serial( this, Serial.list()[0], 9600 ); photocell.bufferUntil( 10 ); yvals = new int[width]; } void draw(){ background( 0 ); for( int i = 1; i &lt; width; i++ ){ yvals[i - 1] = yvals[i]; } if( photocell.available() &gt; 0 ){ yvals[width - 1] = photocell.read(); } for( int i = 1; i &lt; width; i++ ){ stroke( #ff0000 ); line( i, yvals[i], i, height ); } println( photocell.read() ); // for debugging } </code></pre> <p>I've tested both bits of code separately and I know that they work. It's only when I try to have the input from the Arduino going to Processing that the problems start.</p> <p>When I view the data in Arduino's "Serial Monitor", I get a nice constant flow of data that seems to look valid.</p> <p>But when I read that same data through Processing, I get a repeating pattern of random values.</p> <p>Halp?</p>
[ { "answer_id": 256397, "author": "Josh Sandlin", "author_id": 13293, "author_profile": "https://Stackoverflow.com/users/13293", "pm_score": 2, "selected": false, "text": "<p>After a closer look at the resources at hand, I realized that the problem had already been solved for me by the folks over at <a href=\"http://arduino.cc\" rel=\"nofollow noreferrer\">http://arduino.cc</a></p>\n\n<blockquote>\n <p><a href=\"http://arduino.cc/en/Tutorial/Graph\" rel=\"nofollow noreferrer\">http://arduino.cc/en/Tutorial/Graph</a></p>\n</blockquote>\n\n<p>Oh how much time I could have saved if I had seen that earlier.</p>\n" }, { "answer_id": 19803246, "author": "Mateo Sanchez", "author_id": 2741380, "author_profile": "https://Stackoverflow.com/users/2741380", "pm_score": 3, "selected": true, "text": "<p>You could transmit that data with the Plotly Arduino API, which along with the documentation and setup is available <a href=\"http://plot.ly/api/arduino\" rel=\"nofollow noreferrer\">here</a>. Basic idea: you can continuously stream data from your Arduino, or transmit a single chunk. </p>\n\n<p>Then, if you want to embed it into a site, you'll want to grab the URL and use this snippet:</p>\n\n<pre><code>&lt;iframe id=\"igraph\" src=\"https://plot.ly/~abhishek.mitra.963/1/400/250/\" width=\"400\" height=\"250\" seamless=\"seamless\" scrolling=\"no\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>You can change the width/height dimensions in that snippet. Note: you need to swap in your own URL there to get it stream through.</p>\n\n<p><a href=\"http://plot.ly/~flann321/9/\" rel=\"nofollow noreferrer\">Here's an example of how it looks to stream Arduino data</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/5QRMO.png\" alt=\"enter image description here\"></p>\n\n<p>Full disclosure: I work for Plotly. </p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13293/" ]
I'm trying to read data from a photocell resistor and my Arduino Decimila and then graph it in real-time with Processing. Should be painfully simple; but its growing into a little bit of a nightmare for me. code I'm running on my Arduino: ```java int photoPin; void setup(){ photoPin = 0; Serial.begin( 9600 ); } void loop(){ int val = int( map( analogRead( photoPin ), 0, 1023, 0, 254 ) ); Serial.println( val ); //sending data over Serial } ``` code I'm running in Processing: ```java import processing.serial.*; Serial photocell; int[] yvals; void setup(){ size( 300, 150 ); photocell = new Serial( this, Serial.list()[0], 9600 ); photocell.bufferUntil( 10 ); yvals = new int[width]; } void draw(){ background( 0 ); for( int i = 1; i < width; i++ ){ yvals[i - 1] = yvals[i]; } if( photocell.available() > 0 ){ yvals[width - 1] = photocell.read(); } for( int i = 1; i < width; i++ ){ stroke( #ff0000 ); line( i, yvals[i], i, height ); } println( photocell.read() ); // for debugging } ``` I've tested both bits of code separately and I know that they work. It's only when I try to have the input from the Arduino going to Processing that the problems start. When I view the data in Arduino's "Serial Monitor", I get a nice constant flow of data that seems to look valid. But when I read that same data through Processing, I get a repeating pattern of random values. Halp?
You could transmit that data with the Plotly Arduino API, which along with the documentation and setup is available [here](http://plot.ly/api/arduino). Basic idea: you can continuously stream data from your Arduino, or transmit a single chunk. Then, if you want to embed it into a site, you'll want to grab the URL and use this snippet: ``` <iframe id="igraph" src="https://plot.ly/~abhishek.mitra.963/1/400/250/" width="400" height="250" seamless="seamless" scrolling="no"></iframe> ``` You can change the width/height dimensions in that snippet. Note: you need to swap in your own URL there to get it stream through. [Here's an example of how it looks to stream Arduino data](http://plot.ly/~flann321/9/) ![enter image description here](https://i.stack.imgur.com/5QRMO.png) Full disclosure: I work for Plotly.
256,234
<p>(If anything here needs clarification/ more detail please let me know.)</p> <p>I have an application (C#, 2.* framework) that interfaces with a third-party webservice using SOAP. I used thinktecture's WSCF add-in against a supplied WSDL to create the client-side implementation. For reasons beyond my control the SOAP message exchange uses WSE2.0 for security (the thinctecture implementation had to be modified to include the WSE2.0 reference). In addition to the 'normal' data package I attach a stored X509 cert and a binary security token from a previous call to a different web service. We are using SSL encryption of some sort - I don't know the details. </p> <p>All the necessary serialization/deserialization is contained in the web service client - meaning when control is returned to me after calling the client the entire XML string contained in the SOAP response is not available to me - just the deserialized components. Don't get me wrong - I think that's good because it means I don't have to do it myself.</p> <p>However, in order for me to have something worth storing/archiving I am having to re-serialize the data at the root element. This seems like a waste of resources since my result was in the SOAP response. </p> <p><strong>Now for my question: How can I get access to a 'clear' version of the SOAP response so that I don't have to re-serialize everything for storage/archiving?</strong></p> <p>Edit- My application is a 'formless' windows app running as a network service - triggered by a WebsphereMQ client trigger monitor. I don't <em>think</em> ASP.NET solutions will apply.</p> <p>Edit - Since the consensus so far is that it doesn't matter whether my app is ASP.NET or not then I will give CodeMelt's (and by extension Chris's) solution a shot.</p>
[ { "answer_id": 256246, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN Library</a> includes example code for obtaining the XML of both the request and the response that you can use to archive it. Obviously you'll have to make some changes since the example stores data in a text file, but it isn't too complicated.</p>\n" }, { "answer_id": 256273, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 4, "selected": true, "text": "<p>You can utilize SoapExtension from existing WSE2.0 framework to intercept the responses from the server.</p>\n\n<pre><code>public class MyClientSOAPExtension : SoapExtension\n{\n\n Stream oldStream;\n Stream newStream;\n\n // Save the Stream representing the SOAP request or SOAP response into\n // a local memory buffer.\n public override Stream ChainStream( Stream stream )\n {\n oldStream = stream;\n newStream = new MemoryStream();\n return newStream;\n }\n\n public override void ProcessMessage(SoapMessage message)\n {\n switch (message.Stage)\n {\n case SoapMessageStage.BeforeDeserialize:\n // before the XML deserialized into object.\n break;\n case SoapMessageStage.AfterDeserialize:\n break; \n case SoapMessageStage.BeforeSerialize:\n break;\n case SoapMessageStage.AfterSerialize:\n break; \n default:\n throw new Exception(\"Invalid stage...\");\n } \n }\n}\n</code></pre>\n\n<p>At stage of SoapMessageStage.BeforeDeserialize,\nYou can read the expected data you want from oldstream (e.g. use XmlReader).\nThen store the expected data somewhere for yourself to use and also you need \nforward the old stream data to the newstream for web service later stage to use the data, e.g. deserialize XML into objects.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension(VS.85).aspx\" rel=\"noreferrer\">The sample of logging all the traffic for the web service from MSDN</a></p>\n" }, { "answer_id": 5180947, "author": "jfburdet", "author_id": 129368, "author_profile": "https://Stackoverflow.com/users/129368", "pm_score": 3, "selected": false, "text": "<p>Here is an example you can setup using Visual studio web reference to <a href=\"http://footballpool.dataaccess.eu/data/info.wso?WSDL\" rel=\"noreferrer\">http://footballpool.dataaccess.eu/data/info.wso?WSDL</a></p>\n\n<p>Basically, you must insert in the webservice call chain a XmlReader spyer that will reconstruct the raw XML.</p>\n\n<p>I believe this way is somehow simpler that using SoapExtensions.</p>\n\n<p>Solution solution was inspired by <a href=\"http://orbinary.com/blog/2010/01/getting-the-raw-soap-xml-sent-via-soaphttpclientprotocol/\" rel=\"noreferrer\">http://orbinary.com/blog/2010/01/getting-the-raw-soap-xml-sent-via-soaphttpclientprotocol/</a></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Net;\nusing System.IO;\nusing System.Reflection;\nusing System.Xml;\n\n\nnamespace ConsoleApplication1 {\n\n public class XmlReaderSpy : XmlReader {\n XmlReader _me;\n public XmlReaderSpy(XmlReader parent) {\n _me = parent;\n }\n\n /// &lt;summary&gt;\n /// Extracted XML.\n /// &lt;/summary&gt;\n public string Xml;\n\n #region Abstract method that must be implemented\n public override XmlNodeType NodeType {\n get {\n\n return _me.NodeType;\n }\n }\n\n public override string LocalName {\n get {\n return _me.LocalName;\n }\n }\n\n public override string NamespaceURI {\n get {\n return _me.NamespaceURI;\n }\n }\n\n public override string Prefix {\n get {\n return _me.Prefix;\n }\n }\n\n public override bool HasValue {\n get { return _me.HasValue; }\n }\n\n public override string Value {\n get { return _me.Value; }\n }\n\n public override int Depth {\n get { return _me.Depth; }\n }\n\n public override string BaseURI {\n get { return _me.BaseURI; }\n }\n\n public override bool IsEmptyElement {\n get { return _me.IsEmptyElement; }\n }\n\n public override int AttributeCount {\n get { return _me.AttributeCount; }\n }\n\n public override string GetAttribute(int i) {\n return _me.GetAttribute(i);\n }\n\n public override string GetAttribute(string name) {\n return _me.GetAttribute(name);\n }\n\n public override string GetAttribute(string name, string namespaceURI) {\n return _me.GetAttribute(name, namespaceURI);\n }\n\n public override void MoveToAttribute(int i) {\n _me.MoveToAttribute(i);\n }\n\n public override bool MoveToAttribute(string name) {\n return _me.MoveToAttribute(name);\n }\n\n public override bool MoveToAttribute(string name, string ns) {\n return _me.MoveToAttribute(name, ns);\n }\n\n public override bool MoveToFirstAttribute() {\n return _me.MoveToFirstAttribute();\n }\n\n public override bool MoveToNextAttribute() {\n return _me.MoveToNextAttribute();\n }\n\n public override bool MoveToElement() {\n return _me.MoveToElement();\n }\n\n public override bool ReadAttributeValue() {\n return _me.ReadAttributeValue();\n }\n\n public override bool Read() {\n bool res = _me.Read();\n\n Xml += StringView();\n\n\n return res;\n }\n\n public override bool EOF {\n get { return _me.EOF; }\n }\n\n public override void Close() {\n _me.Close();\n }\n\n public override ReadState ReadState {\n get { return _me.ReadState; }\n }\n\n public override XmlNameTable NameTable {\n get { return _me.NameTable; }\n }\n\n public override string LookupNamespace(string prefix) {\n return _me.LookupNamespace(prefix);\n }\n\n public override void ResolveEntity() {\n _me.ResolveEntity();\n }\n\n #endregion\n\n\n protected string StringView() {\n string result = \"\";\n\n if (_me.NodeType == XmlNodeType.Element) {\n result = \"&lt;\" + _me.Name;\n\n if (_me.HasAttributes) {\n _me.MoveToFirstAttribute();\n do {\n result += \" \" + _me.Name + \"=\\\"\" + _me.Value + \"\\\"\";\n } while (_me.MoveToNextAttribute());\n\n //Let's put cursor back to Element to avoid messing up reader state.\n _me.MoveToElement();\n }\n\n if (_me.IsEmptyElement) {\n result += \"/\";\n }\n\n result += \"&gt;\";\n }\n\n if (_me.NodeType == XmlNodeType.EndElement) {\n result = \"&lt;/\" + _me.Name + \"&gt;\";\n }\n\n if (_me.NodeType == XmlNodeType.Text || _me.NodeType == XmlNodeType.Whitespace) {\n result = _me.Value;\n }\n\n\n\n if (_me.NodeType == XmlNodeType.XmlDeclaration) {\n result = \"&lt;?\" + _me.Name + \" \" + _me.Value + \"?&gt;\";\n }\n\n return result;\n\n }\n }\n\n public class MyInfo : ConsoleApplication1.eu.dataaccess.footballpool.Info { \n\n protected XmlReaderSpy _xmlReaderSpy;\n\n public string Xml {\n get {\n if (_xmlReaderSpy != null) {\n return _xmlReaderSpy.Xml;\n }\n else {\n return \"\";\n }\n }\n }\n\n\n protected override XmlReader GetReaderForMessage(System.Web.Services.Protocols.SoapClientMessage message, int bufferSize) { \n XmlReader rdr = base.GetReaderForMessage(message, bufferSize);\n _xmlReaderSpy = new XmlReaderSpy((XmlReader)rdr);\n return _xmlReaderSpy;\n }\n\n }\n\n class Program {\n static void Main(string[] args) {\n\n MyInfo info = new MyInfo();\n string[] rest = info.Cities();\n\n System.Console.WriteLine(\"RAW Soap XML response :\\n\"+info.Xml);\n System.Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 8414492, "author": "Wout", "author_id": 241015, "author_profile": "https://Stackoverflow.com/users/241015", "pm_score": 2, "selected": false, "text": "<p>Inspired by jfburdet, I wanted to see if it was possible to directly intercept at stream/byte level rather than reconstructing XML. And it is! See code below:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Services.Protocols;\nusing System.Xml;\n\nusing Test.MyWebReference;\n\nnamespace Test {\n /// &lt;summary&gt;\n /// Adds the ability to retrieve the SOAP request/response.\n /// &lt;/summary&gt;\n public class ServiceSpy : OriginalService {\n private StreamSpy writerStreamSpy;\n private XmlTextWriter xmlWriter;\n\n private StreamSpy readerStreamSpy;\n private XmlTextReader xmlReader;\n\n public MemoryStream WriterStream {\n get { return writerStreamSpy == null ? null : writerStreamSpy.ClonedStream; }\n }\n\n public XmlTextWriter XmlWriter {\n get { return xmlWriter; }\n }\n\n public MemoryStream ReaderStream {\n get { return readerStreamSpy == null ? null : readerStreamSpy.ClonedStream; }\n }\n\n public XmlTextReader XmlReader {\n get { return xmlReader; }\n }\n\n protected override void Dispose(bool disposing) {\n base.Dispose(disposing);\n DisposeWriterStreamSpy();\n DisposeReaderStreamSpy();\n }\n\n protected override XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize) {\n // Dispose previous writer stream spy.\n DisposeWriterStreamSpy();\n\n writerStreamSpy = new StreamSpy(message.Stream);\n // XML should always support UTF8.\n xmlWriter = new XmlTextWriter(writerStreamSpy, Encoding.UTF8);\n\n return xmlWriter;\n }\n\n protected override XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize) {\n // Dispose previous reader stream spy.\n DisposeReaderStreamSpy();\n\n readerStreamSpy = new StreamSpy(message.Stream);\n xmlReader = new XmlTextReader(readerStreamSpy);\n\n return xmlReader;\n }\n\n private void DisposeWriterStreamSpy() {\n if (writerStreamSpy != null) {\n writerStreamSpy.Dispose();\n writerStreamSpy.ClonedStream.Dispose();\n writerStreamSpy = null;\n }\n }\n\n private void DisposeReaderStreamSpy() {\n if (readerStreamSpy != null) {\n readerStreamSpy.Dispose();\n readerStreamSpy.ClonedStream.Dispose();\n readerStreamSpy = null;\n }\n }\n\n /// &lt;summary&gt;\n /// Wrapper class to clone read/write bytes.\n /// &lt;/summary&gt;\n public class StreamSpy : Stream {\n private Stream wrappedStream;\n private long startPosition;\n private MemoryStream clonedStream = new MemoryStream();\n\n public StreamSpy(Stream wrappedStream) {\n this.wrappedStream = wrappedStream;\n startPosition = wrappedStream.Position;\n }\n\n public MemoryStream ClonedStream {\n get { return clonedStream; }\n }\n\n public override bool CanRead {\n get { return wrappedStream.CanRead; }\n }\n\n public override bool CanSeek {\n get { return wrappedStream.CanSeek; }\n }\n\n public override bool CanWrite {\n get { return wrappedStream.CanWrite; }\n }\n\n public override void Flush() {\n wrappedStream.Flush();\n }\n\n public override long Length {\n get { return wrappedStream.Length; }\n }\n\n public override long Position {\n get { return wrappedStream.Position; }\n set { wrappedStream.Position = value; }\n }\n\n public override int Read(byte[] buffer, int offset, int count) {\n long relativeOffset = wrappedStream.Position - startPosition;\n int result = wrappedStream.Read(buffer, offset, count);\n if (clonedStream.Position != relativeOffset) {\n clonedStream.Position = relativeOffset;\n }\n clonedStream.Write(buffer, offset, result);\n return result;\n }\n\n public override long Seek(long offset, SeekOrigin origin) {\n return wrappedStream.Seek(offset, origin);\n }\n\n public override void SetLength(long value) {\n wrappedStream.SetLength(value);\n }\n\n public override void Write(byte[] buffer, int offset, int count) {\n long relativeOffset = wrappedStream.Position - startPosition;\n wrappedStream.Write(buffer, offset, count);\n if (clonedStream.Position != relativeOffset) {\n clonedStream.Position = relativeOffset;\n }\n clonedStream.Write(buffer, offset, count);\n }\n\n public override void Close() {\n wrappedStream.Close();\n base.Close();\n }\n\n protected override void Dispose(bool disposing) {\n if (wrappedStream != null) {\n wrappedStream.Dispose();\n wrappedStream = null;\n }\n base.Dispose(disposing);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 63497474, "author": "Andy Gray", "author_id": 163901, "author_profile": "https://Stackoverflow.com/users/163901", "pm_score": 3, "selected": false, "text": "<p>Old thread, but in case others are looking to do this today: these ideas of leveraging SoapExtension or creating 'spy' classes are great, but don't work in .NET Core.</p>\n<p>@mting923's suggestion to use IClientMessageInspector approach works in .NET Core 3.1; see here: <a href=\"https://stackoverflow.com/questions/461744/get-soap-message-before-sending-it-to-the-webservice-in-net/63497094#63497094\">Get SOAP Message before sending it to the WebService in .NET</a>.</p>\n<p>A generated SOAP proxy class is still just a WCF client under the hood, and so the IClientMessageInspector approach works a treat, even for an .NET Core Azure Function calling an older SOAP web service. The following works for me in a .NET Core 3.1 Azure Function:</p>\n<pre><code>public class SoapMessageInspector : IClientMessageInspector\n{\n public string LastRequestXml { get; private set; }\n public string LastResponseXml { get; private set; }\n\n public object BeforeSendRequest(ref Message request, IClientChannel channel)\n {\n LastRequestXml = request.ToString();\n return request;\n }\n\n public void AfterReceiveReply(ref Message reply, object correlationState)\n {\n LastResponseXml = reply.ToString();\n }\n}\n\npublic class SoapInspectorBehavior : IEndpointBehavior\n{\n private readonly SoapMessageInspector inspector_ = new SoapMessageInspector();\n\n public string LastRequestXml =&gt; inspector_.LastRequestXml;\n public string LastResponseXml =&gt; inspector_.LastResponseXml;\n\n public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)\n {\n }\n\n public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)\n {\n }\n\n public void Validate(ServiceEndpoint endpoint)\n {\n }\n\n public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)\n {\n clientRuntime.ClientMessageInspectors.Add(inspector_);\n }\n}\n</code></pre>\n<p>And then it can be set up like this:</p>\n<pre><code> var client = new ServiceClient();\n var soapInspector = new SoapInspectorBehavior();\n client.Endpoint.EndpointBehaviors.Add(soapInspector);\n</code></pre>\n<p>After invoking a web service call on the client proxy, <code>soapInspector.LastRequestXml</code> and <code>soapInspector.LastResponseXml</code> will contain the raw SOAP request and response (as strings).</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30901/" ]
(If anything here needs clarification/ more detail please let me know.) I have an application (C#, 2.\* framework) that interfaces with a third-party webservice using SOAP. I used thinktecture's WSCF add-in against a supplied WSDL to create the client-side implementation. For reasons beyond my control the SOAP message exchange uses WSE2.0 for security (the thinctecture implementation had to be modified to include the WSE2.0 reference). In addition to the 'normal' data package I attach a stored X509 cert and a binary security token from a previous call to a different web service. We are using SSL encryption of some sort - I don't know the details. All the necessary serialization/deserialization is contained in the web service client - meaning when control is returned to me after calling the client the entire XML string contained in the SOAP response is not available to me - just the deserialized components. Don't get me wrong - I think that's good because it means I don't have to do it myself. However, in order for me to have something worth storing/archiving I am having to re-serialize the data at the root element. This seems like a waste of resources since my result was in the SOAP response. **Now for my question: How can I get access to a 'clear' version of the SOAP response so that I don't have to re-serialize everything for storage/archiving?** Edit- My application is a 'formless' windows app running as a network service - triggered by a WebsphereMQ client trigger monitor. I don't *think* ASP.NET solutions will apply. Edit - Since the consensus so far is that it doesn't matter whether my app is ASP.NET or not then I will give CodeMelt's (and by extension Chris's) solution a shot.
You can utilize SoapExtension from existing WSE2.0 framework to intercept the responses from the server. ``` public class MyClientSOAPExtension : SoapExtension { Stream oldStream; Stream newStream; // Save the Stream representing the SOAP request or SOAP response into // a local memory buffer. public override Stream ChainStream( Stream stream ) { oldStream = stream; newStream = new MemoryStream(); return newStream; } public override void ProcessMessage(SoapMessage message) { switch (message.Stage) { case SoapMessageStage.BeforeDeserialize: // before the XML deserialized into object. break; case SoapMessageStage.AfterDeserialize: break; case SoapMessageStage.BeforeSerialize: break; case SoapMessageStage.AfterSerialize: break; default: throw new Exception("Invalid stage..."); } } } ``` At stage of SoapMessageStage.BeforeDeserialize, You can read the expected data you want from oldstream (e.g. use XmlReader). Then store the expected data somewhere for yourself to use and also you need forward the old stream data to the newstream for web service later stage to use the data, e.g. deserialize XML into objects. [The sample of logging all the traffic for the web service from MSDN](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension(VS.85).aspx)
256,264
<p>The symptom of the problem looks like "[0m[27m[24m[J[34;1" which on a terminal translates into the color blue.</p> <p>-A </p>
[ { "answer_id": 256393, "author": "cefstat", "author_id": 19155, "author_profile": "https://Stackoverflow.com/users/19155", "pm_score": 0, "selected": false, "text": "<p>The following should work in your .bash_profile or .bashrc</p>\n\n<pre><code>case $TERM in\nxterm-color)\nexport PS1='\\[\\e]0;\\W\\007\\]\\[\\e[34;1m\\]\\W\\[\\e[0m\\]\\$ '\n;;\n*)\nexport PS1='\\W\\$ '\n;;\nesac\n</code></pre>\n" }, { "answer_id": 256399, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": false, "text": "<p>I've got the following in my <code>.emacs</code></p>\n\n<pre><code>(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)\n</code></pre>\n" }, { "answer_id": 256894, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "<p>For the \"ignore\" alternative, put something like \"<code>alias ls=ls</code>\" or \"<code>unset LS_COLORS</code>\" in your <code>~/.emacs_{bash,tsch,whatever-your-shell-is-called}</code> file. This file is executed in all subordinate shells created by emacs.</p>\n\n<blockquote>\n <p><a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Interactive-Shell.html\" rel=\"nofollow noreferrer\">Emacs</a> sends the new shell the contents of the file <code>~/.emacs_shellname</code> as input, if it exists, where <code>shellname</code> is the name of the file that the shell was loaded from. For example, if you use bash, the file sent to it is <code>~/.emacs_bash</code>. If this file is not found, Emacs tries to fallback on <code>~/.emacs.d/init_shellname.sh</code>. </p>\n</blockquote>\n" }, { "answer_id": 264241, "author": "Setjmp", "author_id": 30636, "author_profile": "https://Stackoverflow.com/users/30636", "pm_score": 3, "selected": true, "text": "<p>The solution that is currently giving me some success is to redefine the shell function as an ansi term:</p>\n\n<pre><code>;; shell-mode\n(defun sh ()\n (interactive)\n (ansi-term \"/bin/zsh\"))\n</code></pre>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
The symptom of the problem looks like "[0m[27m[24m[J[34;1" which on a terminal translates into the color blue. -A
The solution that is currently giving me some success is to redefine the shell function as an ansi term: ``` ;; shell-mode (defun sh () (interactive) (ansi-term "/bin/zsh")) ```
256,267
<p>I have a windows service connecting to a SqlServer database on the local box. This works fine most all the time. At a large customer, however, the database connectivity gets corrupted for some rare and unknown reason. When this happens, calls to DbDataAdapter.Fill return a DataSet with a different number of columns than in the select command passed in (validated by trace logs showing the sql expected, and the number of columns returned). For the first few errored DataSets it appears the adapter instance is returning results from the previous query. This is happening even though the adapter objects are unique instances, and the connection/adapter creation calls are thread protected (as DbProviderFactory is not thread safe).</p> <p>Has anyone experience this or something similar? Does anyone know what could cause this? At this moment in time, I'm having a hard time thinking up new ideas for a cause of this.</p>
[ { "answer_id": 256393, "author": "cefstat", "author_id": 19155, "author_profile": "https://Stackoverflow.com/users/19155", "pm_score": 0, "selected": false, "text": "<p>The following should work in your .bash_profile or .bashrc</p>\n\n<pre><code>case $TERM in\nxterm-color)\nexport PS1='\\[\\e]0;\\W\\007\\]\\[\\e[34;1m\\]\\W\\[\\e[0m\\]\\$ '\n;;\n*)\nexport PS1='\\W\\$ '\n;;\nesac\n</code></pre>\n" }, { "answer_id": 256399, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": false, "text": "<p>I've got the following in my <code>.emacs</code></p>\n\n<pre><code>(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)\n</code></pre>\n" }, { "answer_id": 256894, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "<p>For the \"ignore\" alternative, put something like \"<code>alias ls=ls</code>\" or \"<code>unset LS_COLORS</code>\" in your <code>~/.emacs_{bash,tsch,whatever-your-shell-is-called}</code> file. This file is executed in all subordinate shells created by emacs.</p>\n\n<blockquote>\n <p><a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Interactive-Shell.html\" rel=\"nofollow noreferrer\">Emacs</a> sends the new shell the contents of the file <code>~/.emacs_shellname</code> as input, if it exists, where <code>shellname</code> is the name of the file that the shell was loaded from. For example, if you use bash, the file sent to it is <code>~/.emacs_bash</code>. If this file is not found, Emacs tries to fallback on <code>~/.emacs.d/init_shellname.sh</code>. </p>\n</blockquote>\n" }, { "answer_id": 264241, "author": "Setjmp", "author_id": 30636, "author_profile": "https://Stackoverflow.com/users/30636", "pm_score": 3, "selected": true, "text": "<p>The solution that is currently giving me some success is to redefine the shell function as an ansi term:</p>\n\n<pre><code>;; shell-mode\n(defun sh ()\n (interactive)\n (ansi-term \"/bin/zsh\"))\n</code></pre>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18313/" ]
I have a windows service connecting to a SqlServer database on the local box. This works fine most all the time. At a large customer, however, the database connectivity gets corrupted for some rare and unknown reason. When this happens, calls to DbDataAdapter.Fill return a DataSet with a different number of columns than in the select command passed in (validated by trace logs showing the sql expected, and the number of columns returned). For the first few errored DataSets it appears the adapter instance is returning results from the previous query. This is happening even though the adapter objects are unique instances, and the connection/adapter creation calls are thread protected (as DbProviderFactory is not thread safe). Has anyone experience this or something similar? Does anyone know what could cause this? At this moment in time, I'm having a hard time thinking up new ideas for a cause of this.
The solution that is currently giving me some success is to redefine the shell function as an ansi term: ``` ;; shell-mode (defun sh () (interactive) (ansi-term "/bin/zsh")) ```
256,277
<p>"C Interfaces and Implementations" shows some interesting usage patterns for data structures, but I am sure there are others out there.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/0201498413" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Interfaces-Implementations-Techniques-Addison-Wesley-Professional/dp/0201498413</a></p>
[ { "answer_id": 256292, "author": "Doug Currie", "author_id": 33252, "author_profile": "https://Stackoverflow.com/users/33252", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.hwaci.com/sw/mkhdr/\" rel=\"nofollow noreferrer\">Makeheaders</a> is an interesting approach: use a tool to generate the headers. Makeheaders is used in D. R. Hipp's <a href=\"http://www.cvstrac.org/\" rel=\"nofollow noreferrer\">cvstrac</a> and <a href=\"http://www.fossil-scm.org/index.html/doc/tip/www/index.wiki\" rel=\"nofollow noreferrer\">fossil</a>.</p>\n" }, { "answer_id": 256415, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 1, "selected": false, "text": "<p>You might want to take a look at Large-Scale C++ Software Design by John Lakos.</p>\n" }, { "answer_id": 256440, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "<p>Look at the Goddard Space Flight Center (NASA) C coding standard (at this <a href=\"http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard\" rel=\"nofollow noreferrer\">URL</a>). It has some good and interesting guidelines.</p>\n\n<p>One specific guideline, which I've adopted for my own code, is that headers should be self-contained. That is, you should be able to write:</p>\n\n<pre><code>#include \"header.h\"\n</code></pre>\n\n<p>and the code should compile correctly, with any other necessary headers included, regardless of what has gone before. The simple way to ensure this is to include the header in the implementation source -- as the first header. If that compiles, the header is self-contained. If it doesn't compile, fix things so that it does. Of course, this also requires you to ensure that headers are idempotent - work the same regardless of how often they are included. There's a standard idiom for that, too:</p>\n\n<pre><code>#ifndef HEADER_H_INCLUDED\n#define HEADER_H_INCLUDED\n...operational body of header.h...\n#endif /* HEADER_H_INCLUDED */\n</code></pre>\n\n<p>It is imperative, of course, to have the #define at the top of the file, not at the bottom. Otherwise, if a header included by this also includes header.h, then you end up with an infinite loop - not healthy. Even if you decide to go with a strategy of:</p>\n\n<pre><code>#ifndef HEADER_H_INCLUDED\n#include \"header.h\"\n#endif /* HEADER_H_INCLUDED */\n</code></pre>\n\n<p>in the code that include the header - a practice which is <strong>not</strong> recommended - it is important to include the guards in the header itself too.</p>\n\n<hr>\n\n<h3>Update 2011-05-01</h3>\n\n<p>The GSFC URL above no longer works. You can find more information in the answers for the question <a href=\"https://stackoverflow.com/questions/1804486/should-i-use-include-in-headers\">Should I use #include in headers</a>, which also contains a cross-reference to this question.</p>\n\n<h3>Update 2012-03-24</h3>\n\n<p>The referenced NASA C coding standard can be accessed and downloaded via the Internet archive:</p>\n\n<p><a href=\"http://web.archive.org/web/20090412090730/http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20090412090730/http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard</a></p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
"C Interfaces and Implementations" shows some interesting usage patterns for data structures, but I am sure there are others out there. [http://www.amazon.com/Interfaces-Implementations-Techniques-Addison-Wesley-Professional/dp/0201498413](https://rads.stackoverflow.com/amzn/click/com/0201498413)
Look at the Goddard Space Flight Center (NASA) C coding standard (at this [URL](http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard)). It has some good and interesting guidelines. One specific guideline, which I've adopted for my own code, is that headers should be self-contained. That is, you should be able to write: ``` #include "header.h" ``` and the code should compile correctly, with any other necessary headers included, regardless of what has gone before. The simple way to ensure this is to include the header in the implementation source -- as the first header. If that compiles, the header is self-contained. If it doesn't compile, fix things so that it does. Of course, this also requires you to ensure that headers are idempotent - work the same regardless of how often they are included. There's a standard idiom for that, too: ``` #ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED ...operational body of header.h... #endif /* HEADER_H_INCLUDED */ ``` It is imperative, of course, to have the #define at the top of the file, not at the bottom. Otherwise, if a header included by this also includes header.h, then you end up with an infinite loop - not healthy. Even if you decide to go with a strategy of: ``` #ifndef HEADER_H_INCLUDED #include "header.h" #endif /* HEADER_H_INCLUDED */ ``` in the code that include the header - a practice which is **not** recommended - it is important to include the guards in the header itself too. --- ### Update 2011-05-01 The GSFC URL above no longer works. You can find more information in the answers for the question [Should I use #include in headers](https://stackoverflow.com/questions/1804486/should-i-use-include-in-headers), which also contains a cross-reference to this question. ### Update 2012-03-24 The referenced NASA C coding standard can be accessed and downloaded via the Internet archive: <http://web.archive.org/web/20090412090730/http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard>
256,282
<p>On <a href="http://andrew.hedges.name/blog/" rel="nofollow noreferrer">my blog</a>, I display in the right nav the 10 most popular articles in terms of page hits. Here's how I get that:</p> <pre><code>SELECT * FROM entries WHERE is_published = 1 ORDER BY hits DESC, created DESC LIMIT 10 </code></pre> <p>What I would like to do is show the top 10 in terms of page hits <em>per day.</em> I'm using MySQL. Is there a way I can do this in the database?</p> <p>BTW, The <code>created</code> field is a datetime.</p> <p>UPDATE: I think I haven't made myself clear. What I want is for the blog post with 10,000 hits that was posted 1,000 days ago to have the same popularity as the blog post with 10 hits that was posted 1 day ago. In pseudo-code:</p> <pre><code>ORDER BY hits / days since posting </code></pre> <p>...where <code>hits</code> is just an int that is incremented each time the blog post is viewed.</p> <p>OK, here's what I'm going to use:</p> <pre><code>SELECT *, AVG( hits / DATEDIFF(NOW(), created) ) AS avg_hits FROM entries WHERE is_published = 1 GROUP BY id ORDER BY avg_hits DESC, hits DESC, created DESC LIMIT 10 </code></pre> <p>Thanks, Stephen! (I love this site...)</p>
[ { "answer_id": 256302, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 4, "selected": true, "text": "<p>I'm not entirely sure you can by using the table structure you suggest in your query. The only way I can think of is to get the top 10 by way of highest <em>average</em> hits per day. By doing that, your query becomes:</p>\n\n<pre><code>SELECT *, AVG(hits / DATEDIFF(NOW(), created)) as avg_hits\nFROM entries\nWHERE is_published = 1\nGROUP BY id\nORDER BY avg_hits DESC\nLIMIT 10\n</code></pre>\n\n<p>This query assumes your created field is of a DATETIME (or similar) data type.</p>\n" }, { "answer_id": 256326, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "<p>I guess you could have a hits_day_count column, which is incremented on each view, and a hits_day_current.</p>\n\n<p>On each page-view, you check if the hits_day_current column is today. If not, reset the hit count.. Then you increment the hits_day_count column, and set hits_day_current to the current datetime.</p>\n\n<p>Pseudo-code:</p>\n\n<pre><code>if article_data['hits_day_current'] == datetime.now():\n article_data['hits_day_count'] ++\nelse:\n article_data['hits_day'] = 0\n\narticle_data['hits_day_current'] = datetime.now()\n</code></pre>\n\n<p>The obvious problem with this is simple - timezones. The totals get reset at 00:00 wherever the server is located, which may not be useful.</p>\n\n<p>A better solution would be a rolling-24-hour total.. Not quite sure how to do this neatly. The easiest (although not so elegant) way would be to parse your web-server logs periodically. Get the last 24 hours of logs, count the number of requests to each article, and put those numbers in the database.</p>\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
On [my blog](http://andrew.hedges.name/blog/), I display in the right nav the 10 most popular articles in terms of page hits. Here's how I get that: ``` SELECT * FROM entries WHERE is_published = 1 ORDER BY hits DESC, created DESC LIMIT 10 ``` What I would like to do is show the top 10 in terms of page hits *per day.* I'm using MySQL. Is there a way I can do this in the database? BTW, The `created` field is a datetime. UPDATE: I think I haven't made myself clear. What I want is for the blog post with 10,000 hits that was posted 1,000 days ago to have the same popularity as the blog post with 10 hits that was posted 1 day ago. In pseudo-code: ``` ORDER BY hits / days since posting ``` ...where `hits` is just an int that is incremented each time the blog post is viewed. OK, here's what I'm going to use: ``` SELECT *, AVG( hits / DATEDIFF(NOW(), created) ) AS avg_hits FROM entries WHERE is_published = 1 GROUP BY id ORDER BY avg_hits DESC, hits DESC, created DESC LIMIT 10 ``` Thanks, Stephen! (I love this site...)
I'm not entirely sure you can by using the table structure you suggest in your query. The only way I can think of is to get the top 10 by way of highest *average* hits per day. By doing that, your query becomes: ``` SELECT *, AVG(hits / DATEDIFF(NOW(), created)) as avg_hits FROM entries WHERE is_published = 1 GROUP BY id ORDER BY avg_hits DESC LIMIT 10 ``` This query assumes your created field is of a DATETIME (or similar) data type.
256,291
<p>What tools do you know, other than those in Visual Studio, to analyze performance bottlenecks in a Windows CE/Mobile application? I'm looking for something like AQTime for CE/Mobile, to profile C/C++ applications compiled to native code.</p>
[ { "answer_id": 256310, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 0, "selected": false, "text": "<p>If you're doing .NET CF development, check out the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=c8174c14-a27d-4148-bf01-86c2e0953eab&amp;displaylang=en\" rel=\"nofollow noreferrer\">Power Toys for .NET CF 3.5</a> for utilities that can help you pinpoint bottlenecks, especially memory-related ones. </p>\n" }, { "answer_id": 256502, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 4, "selected": true, "text": "<p>I haven't found any such tools for WindowsMobile for native development.</p>\n\n<p>The closest I've found is the EnTrek toolset (CodeSnitch / ProcMan), but they aren't really profiling tools.\n<a href=\"http://www.entrek.com/products.htm\" rel=\"noreferrer\">http://www.entrek.com/products.htm</a></p>\n\n<p>What we did do is build own own profiling support into our own products using the Vistual Studio \"/callcap\" switch for VC++. Using that switch you can build a profiling library that dumps out timings and counts, whatever you like. It mostly works out well for us, but sometimes the overhead of these hook functions can be too much and it can skew the timing results to areas of massive number of function calls.</p>\n\n<p>From the MSDN Docs:</p>\n\n<blockquote>\n <p>The /callcap option causes the\n compiler to insert calls to profiling\n hooks at the beginning and end of each\n function. </p>\n \n <p>You must compile profiling hooks\n without the callcap switch. If you\n compile the profiling hook functions\n with the callcap switch, the functions\n will perform infinite recursive calls\n to themselves.</p>\n \n <p>The following code example,\n Callcaphooks.c, shows a profiling hook\n function, _CAP_Enter_Function, for\n compilation without callcap.</p>\n</blockquote>\n\n<pre><code>// File: callcaphooks.c\n\n#include &lt;stdio.h&gt;\nint main();\n\nvoid _CAP_Enter_Function(void *p) \n{\n if (p != main) \n printf(\"Enter function (at address %p) at %d\\n\", \n p, GetTickCount());\n return;\n}\nvoid _CAP_Exit_Function(void *p) \n{\n if (p != main) \n printf(\"Leaving function (at address %p) at %d\\n\", \n p, GetTickCount());\n return;\n}\n</code></pre>\n" }, { "answer_id": 332341, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": false, "text": "<p>Windows CE supports the <a href=\"http://msdn.microsoft.com/en-us/library/ms894533.aspx\" rel=\"noreferrer\">Remote Call Profiler</a> (if the OEM added support for it) out of the box. WinMo images, I believe, typically have support already in the images for it. For CE, you need to the IMAGEPROFILER environment variable set (usnder the project properties).</p>\n\n<p>What's not clear in MSDN is how to instrument an app that isn't built with Platform Builder, but it's actually pretty simple. You have to add the /callcap swith to the compiler command line and add cecap.lib to your linker settings.</p>\n\n<p>Of course you'll need a tool to capture and display the profiler data. For that you can use the evaluation version of Platform Builder (<a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=486e8250-d311-4f67-9fb3-23e8b8944f3e&amp;displaylang=en\" rel=\"noreferrer\">5.0</a> or <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=7e286847-6e06-4a0c-8cac-ca7d4c09cb56&amp;displaylang=en\" rel=\"noreferrer\">6.0</a>) (the eval is free) or <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=1DACDB3D-50D1-41B2-A107-FA75AE960856&amp;displaylang=en\" rel=\"noreferrer\">eVC 4.0</a> (also free).</p>\n\n<p>For more info on the profiler's usage, Sue Loh from the CE core team has blogged a bit about it.</p>\n" }, { "answer_id": 2142867, "author": "Zak Larue-Buckley", "author_id": 259601, "author_profile": "https://Stackoverflow.com/users/259601", "pm_score": 2, "selected": false, "text": "<p>I have written a Call Graph profiler for Windows Mobile. It is currently (as of Jan 2010) in the Beta phase, and can be downloaded for free.</p>\n\n<p><a href=\"http://www.codeprophet.co.cc\" rel=\"nofollow noreferrer\">http://www.codeprophet.co.cc</a></p>\n\n<p>HTH</p>\n\n<p>-Zak</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8999/" ]
What tools do you know, other than those in Visual Studio, to analyze performance bottlenecks in a Windows CE/Mobile application? I'm looking for something like AQTime for CE/Mobile, to profile C/C++ applications compiled to native code.
I haven't found any such tools for WindowsMobile for native development. The closest I've found is the EnTrek toolset (CodeSnitch / ProcMan), but they aren't really profiling tools. <http://www.entrek.com/products.htm> What we did do is build own own profiling support into our own products using the Vistual Studio "/callcap" switch for VC++. Using that switch you can build a profiling library that dumps out timings and counts, whatever you like. It mostly works out well for us, but sometimes the overhead of these hook functions can be too much and it can skew the timing results to areas of massive number of function calls. From the MSDN Docs: > > The /callcap option causes the > compiler to insert calls to profiling > hooks at the beginning and end of each > function. > > > You must compile profiling hooks > without the callcap switch. If you > compile the profiling hook functions > with the callcap switch, the functions > will perform infinite recursive calls > to themselves. > > > The following code example, > Callcaphooks.c, shows a profiling hook > function, \_CAP\_Enter\_Function, for > compilation without callcap. > > > ``` // File: callcaphooks.c #include <stdio.h> int main(); void _CAP_Enter_Function(void *p) { if (p != main) printf("Enter function (at address %p) at %d\n", p, GetTickCount()); return; } void _CAP_Exit_Function(void *p) { if (p != main) printf("Leaving function (at address %p) at %d\n", p, GetTickCount()); return; } ```
256,297
<p>In C++ I'd like to do something like:</p> <pre><code>int n = get_int_from_user(); char* matrix = new char[n][n]; matrix[0][0] = 'c'; //... matrix[n][n] = 'a'; delete [][] matrix; </code></pre> <p>but of course this doesn't work. What is the best way to do something similar? I've seen some solutions to this but they seem pretty messy.</p>
[ { "answer_id": 256303, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "<p>For a true two dimensional array:</p>\n\n<pre><code>int n = get_int_from_user();\n\nchar** matrix = new char*[n];\nfor (int i = 0; i &lt; n; i++) {\n matrix[i] = new char[n];\n}\n\n// Operations on matrix.\n\nfor (int i = 0; i &lt; n; i++) {\n delete [] matrix[i];\n}\ndelete matrix;\n</code></pre>\n\n<p>Just off the top of my head. Mistakes, no doubt. However, other people have posted a more elegant approach, I think.</p>\n" }, { "answer_id": 256304, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>I usually do something like this:</p>\n\n<pre><code>char *matrix = new char [width * height];\n\nmatrix[i + j * width] = 'c'; // same as matrix[i][j] = 'c';\n\ndelete [] matrix;\n</code></pre>\n" }, { "answer_id": 256305, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 6, "selected": true, "text": "<p><strong>The manual dynamic way:</strong></p>\n\n<p>Let's say you want an array of width*height, the most efficient way is to just use a single dimensional array:</p>\n\n<pre><code>char *matrix = new char[width*height];\n</code></pre>\n\n<p>To delete it:</p>\n\n<pre><code>delete[] matrix;\n</code></pre>\n\n<p>To access it: </p>\n\n<pre><code>char getArrayValue(char *matrix, int row, int col)\n{\n return matrix[row + col*width];\n}\n</code></pre>\n\n<p>To modify it:</p>\n\n<pre><code>void setArrayValue(char *matrix, int row, int col, char val)\n{\n matrix[row + col*width] = val;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Boost Matrix:</strong></p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm\" rel=\"noreferrer\">Consider using boost::matrix</a> if you can have the dependency.</p>\n\n<p>You could then tie into the <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/index.htm\" rel=\"noreferrer\">boost linear algebra</a> libraries.</p>\n\n<p>Here is some <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm\" rel=\"noreferrer\">sample code of boost::matrix</a>:</p>\n\n<pre><code>#include &lt;boost/numeric/ublas/matrix.hpp&gt;\nusing namespace boost::numeric::ublas;\nmatrix&lt;char&gt; m (3, 3);\nfor (unsigned i = 0; i &lt; m.size1 (); ++ i)\n for (unsigned j = 0; j &lt; m.size2 (); ++ j)\n m (i, j) = 3 * i + j;\n</code></pre>\n\n<hr>\n\n<p><strong>On the stack for some compilers:</strong></p>\n\n<p>Some compilers actually allow you to create arrays on the stack with runtime determined sizes. g++ is an example of such a compiler. You cannot do this by default VC++ though. </p>\n\n<p>So in g++ this is valid code: </p>\n\n<pre><code>int width = 10;\nint height = 10; \nint matrix[width][height];\n</code></pre>\n\n<p>Drew Hall mentioned that this C99 feature is called Variable Length Arrays (VLAs) and it can probably be turned on in any modern compiler. </p>\n" }, { "answer_id": 256307, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>You seem to be missing the whole point of C++ (C with classes) :-). This is the sort of use that's crying out for a class to implement it.</p>\n\n<p>You <em>could</em> just use STL or other 3rd party class library which I'm sure would have the data structure you're looking for but, if you need to roll your own, just create a class with the following properties.</p>\n\n<ul>\n<li>constructor which, given n, will just create a new n*n array of char (e.g., charray)..</li>\n<li>member functions which get and set values based on x.y which simply refer to charray[x*n+y];</li>\n<li>destructor which delete[]'s the array.</li>\n</ul>\n" }, { "answer_id": 256686, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p>What about <code>std::vector&lt; std::vector&lt;int&gt; &gt; array2d;</code> ?</p>\n" }, { "answer_id": 260341, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 2, "selected": false, "text": "<p>I like the 1-d array approach (the selected answer by Brian R. Bondy) with the extension that you wrap the data members into a class so that you don't need to keep track of the width separately:</p>\n\n<pre><code>class Matrix\n{\n int width;\n int height;\n char* data;\npublic:\n Matrix();\n Matrix(int width, int height);\n ~Matrix();\n\n char getArrayValue(int row, int col);\n void setArrayValue(int row, int col, char val);\n}\n</code></pre>\n\n<p>The implementation is an exercise for the reader. ;)</p>\n" }, { "answer_id": 4236413, "author": "Sridarshan", "author_id": 434354, "author_profile": "https://Stackoverflow.com/users/434354", "pm_score": 0, "selected": false, "text": "<p>I think this would be a good one.</p>\n\n<pre><code>int n = get_int_from_user();\n\nchar **matrix=new (char*)[n];\n\nfor(int i=0;i&lt;n;i++)\n matrix[i]=new char[n];\n\nmatrix[0][0] = 'c';\n//...\nmatrix[n][n] = 'a';\n\nfor(int i=0;i&lt;n;i++)\n delete []matrix;\ndelete []matrix;\n</code></pre>\n" }, { "answer_id": 28756741, "author": "Pavel", "author_id": 4142152, "author_profile": "https://Stackoverflow.com/users/4142152", "pm_score": 0, "selected": false, "text": "<pre><code>std::vector&lt;int&gt; m;\n</code></pre>\n\n<p>Then call m.resize() at runtime.</p>\n\n<pre><code>int* matrix = new int[w*h];\n</code></pre>\n\n<p>if you want to do something like Gaussian elimination your matrix should be</p>\n\n<pre><code>int** matrix = new int*[h];\nfor(size_t i(0); i &lt; h; ++i)\n matrix[i] = new int[w];\n</code></pre>\n\n<p>(in Gaussian elimination we usually need to exchange one row with another so it's better to swap pointers to rows in constant time rather than swapping by copying in linear time).</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
In C++ I'd like to do something like: ``` int n = get_int_from_user(); char* matrix = new char[n][n]; matrix[0][0] = 'c'; //... matrix[n][n] = 'a'; delete [][] matrix; ``` but of course this doesn't work. What is the best way to do something similar? I've seen some solutions to this but they seem pretty messy.
**The manual dynamic way:** Let's say you want an array of width\*height, the most efficient way is to just use a single dimensional array: ``` char *matrix = new char[width*height]; ``` To delete it: ``` delete[] matrix; ``` To access it: ``` char getArrayValue(char *matrix, int row, int col) { return matrix[row + col*width]; } ``` To modify it: ``` void setArrayValue(char *matrix, int row, int col, char val) { matrix[row + col*width] = val; } ``` --- **Boost Matrix:** [Consider using boost::matrix](http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm) if you can have the dependency. You could then tie into the [boost linear algebra](http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/index.htm) libraries. Here is some [sample code of boost::matrix](http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm): ``` #include <boost/numeric/ublas/matrix.hpp> using namespace boost::numeric::ublas; matrix<char> m (3, 3); for (unsigned i = 0; i < m.size1 (); ++ i) for (unsigned j = 0; j < m.size2 (); ++ j) m (i, j) = 3 * i + j; ``` --- **On the stack for some compilers:** Some compilers actually allow you to create arrays on the stack with runtime determined sizes. g++ is an example of such a compiler. You cannot do this by default VC++ though. So in g++ this is valid code: ``` int width = 10; int height = 10; int matrix[width][height]; ``` Drew Hall mentioned that this C99 feature is called Variable Length Arrays (VLAs) and it can probably be turned on in any modern compiler.
256,306
<p>I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.</p> <p>I added a static method to my class CallRate that returns a <code>List&lt;CallRate&gt;</code>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.</p> <pre><code>List&lt;CallRates&gt; cr = CallRates.ProcessCallsFile(file); </code></pre>
[ { "answer_id": 256308, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 5, "selected": true, "text": "<p>It is perfectly fine to get object(s) of its own from the static method.</p>\n\n<p>e.g.</p>\n\n<p>One of the dot net libraries does the same thing as you did,</p>\n\n<pre><code>XmlReadrer reader = XmlReader.Create(filepathString);\n</code></pre>\n" }, { "answer_id": 256313, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>Sure that's fine, even encouraged in some instances. There are several <a href=\"http://en.wikipedia.org/wiki/Design_Patterns#Creational_patterns\" rel=\"nofollow noreferrer\">design patterns that deal with object creation</a>, and a few of them do just what you're describing.</p>\n" }, { "answer_id": 256314, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "<p>Seems fine to me. In other languages you would probably write a function, but in a language like C#, static methods take up that role.</p>\n" }, { "answer_id": 256315, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 1, "selected": false, "text": "<p>It is ok. What you just created is something like a simple factory method. You have a static method that creates a valid instance of a type. Actually your method doesn't even have to be static and you still have a valid code. There is a design pattern (Prototype) that creates a new valid object from an existing object. See details at <a href=\"http://www.dofactory.com/Patterns/PatternPrototype.aspx\" rel=\"nofollow noreferrer\">http://www.dofactory.com/Patterns/PatternPrototype.aspx</a>.</p>\n" }, { "answer_id": 256317, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Sure, for simple parsing (or similar) scenarios - I actually <em>prefer</em> the <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory method</a> be part of the class. Yes - it does break <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>, but it fulfills <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a> - so I call it a net win. For larger apps, or more complicated parsing routines - it makes more sense to have it be an external factory class.</p>\n\n<p>For your particular case, I'd probably prefer a method that took in an IEnumerable&lt;string&gt; instead of a filename - that'd still give you the parsing logic, but allow easy unit tests and \"reuse\". The caller can wrap the file into an IEnumerable easily enough. </p>\n" }, { "answer_id": 256323, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "<p>Factory methods are often a good design. When I write them in C#, I call them 'New', so that:</p>\n\n<pre><code>new MyClass()\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>MyClass.New()\n</code></pre>\n\n<p>Trivially it's implemented like this:</p>\n\n<pre><code>class MyClass\n{\n public static MyClass New()\n {\n return new MyClass();\n }\n}\n</code></pre>\n\n<p>Mostly I do this when there are additional conditions about whether to actually create the class or just return <code>null</code>, or whether to return <code>MyClass</code> or something derived from it.</p>\n" }, { "answer_id": 256340, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 1, "selected": false, "text": "<p>I sometimes use public static methods as an alternative to constructor overloading.</p>\n\n<p>Especially in situations where it is not nice to rely on parameter types alone to indicate what kind of object construction is intended.</p>\n" }, { "answer_id": 256344, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 1, "selected": false, "text": "<p>I'm a fan of having static methods return instances, as suggested plenty of times, above.</p>\n\n<p>@Paul: don't forget to tick the comment above, which you find is the best answer.</p>\n" }, { "answer_id": 256403, "author": "user33366", "author_id": 33366, "author_profile": "https://Stackoverflow.com/users/33366", "pm_score": 1, "selected": false, "text": "<p>Just like to point out \n\"generate new instances of itself by calling one of its own constructors\"</p>\n\n<p>It is not from the constructor, it is from the static method.</p>\n" }, { "answer_id": 256772, "author": "user33416", "author_id": 33416, "author_profile": "https://Stackoverflow.com/users/33416", "pm_score": 1, "selected": false, "text": "<p>I generally use this when I need instant implementations of a class. For example</p>\n\n<pre><code> public class Car\n {\n public static Car RedExpensiveCar = new Car(\"Red\", 250000);\n\n public Car()\n {\n\n }\n\n public Car(string color, int price)\n {\n Color = color;\n Price = price;\n }\n\n public string Color { get; set; }\n public int Price { get; set; }\n }\n</code></pre>\n\n<p>And with this, I don't need to remember or write constructor parameters in my code.</p>\n\n<pre><code>Car car = Car.RedExpensiveCar;\n</code></pre>\n" }, { "answer_id": 257174, "author": "Brent Rockwood", "author_id": 31253, "author_profile": "https://Stackoverflow.com/users/31253", "pm_score": 2, "selected": false, "text": "<p>I often use this pattern when I need to check the validity of parameters. It is strongly discouraged to throw an exception from a constructor. It's not so bad from a factory method, or you can choose to return null.</p>\n" }, { "answer_id": 444412, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 0, "selected": false, "text": "<p>It's perfectly acceptable to do this. When I do, I typically make the real constructors for the class private so that it's clear that the <em>only</em> way to construct instances is through the static method.</p>\n\n<p>This is very useful in cases where \"construction\" may not always return a new instance. For example, you may want to return a previously cached object instead.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10178/" ]
I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file. I added a static method to my class CallRate that returns a `List<CallRate>`. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do. ``` List<CallRates> cr = CallRates.ProcessCallsFile(file); ```
It is perfectly fine to get object(s) of its own from the static method. e.g. One of the dot net libraries does the same thing as you did, ``` XmlReadrer reader = XmlReader.Create(filepathString); ```
256,325
<p>For my Django app I have Events, Ratings, and Users. Ratings are related to Events and Users through a foreign keys. When displaying a list of Events I want to filter the ratings of the Event by a user_id so I know if an event has been rated by the user. </p> <p>If I do:</p> <pre><code>event_list = Event.objects.filter(rating__user=request.user.id) </code></pre> <p>(request.user.id gives the user_id of the current logged in user) ...then I only get the events that are rated by the user and not the entire list of events.</p> <p>What I need can be generated through the custom SQL:</p> <pre><code>SELECT * FROM `events_event` LEFT OUTER JOIN ( SELECT * FROM `events_rating` WHERE user_id = ## ) AS temp ON events_event.id = temp.user_id </code></pre> <p>Is there an easier way so I don't have to use custom SQL?</p>
[ { "answer_id": 256342, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>To make best use of Django, you have to avoid trying to do joins.</p>\n\n<p>A \"left outer join\" is actually a list of objects with optional relationships.</p>\n\n<p>It's simply a list of Events, <code>Event.objects.all()</code>. Some Event objects have a rating, some don't.</p>\n\n<p>You get the list of Events in your view. You handle the optional relationships in your template.</p>\n\n<pre><code>{% for e in event_list %}\n {{ e }}\n {% if e.rating_set.all %}{{ e.rating_set }}{% endif %}\n{% endfor %}\n</code></pre>\n\n<p>is a jumping-off point.</p>\n" }, { "answer_id": 256400, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 3, "selected": false, "text": "<p>In addition to S.Lott's suggestion, you may consider using select_related() to limit the number of database queries; otherwise your template will do a query on each event's pass through the loop.</p>\n\n<pre><code>Event.objects.all().select_related(depth=1)\n</code></pre>\n\n<p>The depth parameter is not required, but if your other models have additional foreign keys it will limit the number of joins.</p>\n" }, { "answer_id": 256782, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": true, "text": "<p>The <code>filter</code> method is for filtering which objects are returned based on the specified criteria, so it's not what you want here. One option is to do a second query to retrieve all ratings for given <code>Event</code> objects for the current <code>User</code>.</p>\n\n<p>Models:</p>\n\n<pre><code>import collections\n\nfrom django.db import models\n\nclass RatingManager(models.Manager):\n def get_for_user(self, events, user):\n ratings = self.filter(event__in=[event.id for event in events],\n user=user)\n rating_dict = collections.defaultdict(lambda: None)\n for rating in ratings:\n rating_dict[rating.event_id] = rating\n return rating_dict\n\nclass Rating(models.Model):\n # ...\n objects = RatingManager()\n</code></pre>\n\n<p>View:</p>\n\n<pre><code>events = Event.objects.all()\nuser_ratings = Rating.objects.get_for_user(events, request.user)\ncontext = {\n 'events': [(event, user_ratings[event.id]) for event in events],\n}\n</code></pre>\n\n<p>Template:</p>\n\n<pre><code>{% for event, user_rating in events %}\n {% if user_rating %} ... {% endif %}\n{% endfor %}\n</code></pre>\n" }, { "answer_id": 3341185, "author": "fastmultiplication", "author_id": 51115, "author_profile": "https://Stackoverflow.com/users/51115", "pm_score": -1, "selected": false, "text": "<p>I think you have to do something like this.</p>\n\n<pre><code>events=Event.objects.filter(rating__user=request.user.id)\nratings='(select rating from ratings where user_id=%d and event_id=event_events.id '%request.user.id\nevents=events.extra(select={'rating':ratings})\n</code></pre>\n" }, { "answer_id": 66053973, "author": "alper", "author_id": 11074329, "author_profile": "https://Stackoverflow.com/users/11074329", "pm_score": 2, "selected": false, "text": "<p>The best practice would be</p>\n<pre><code>from django.db.models import Prefetch\n\n\nevent_list = Event.objects.all().prefetch_related(Prefetch(&lt;related_name&gt;, queryset=Rating.objects.filter(&lt;criteria&gt;)))\n</code></pre>\n<p>&lt;related_name&gt; = 'ratings' if:</p>\n<pre><code>class Rating(models.Model):\n event = models.ForeignKey(Event, related_name='ratings')\n</code></pre>\n<p>This returns events and filtered ratings for those event objects</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5112/" ]
For my Django app I have Events, Ratings, and Users. Ratings are related to Events and Users through a foreign keys. When displaying a list of Events I want to filter the ratings of the Event by a user\_id so I know if an event has been rated by the user. If I do: ``` event_list = Event.objects.filter(rating__user=request.user.id) ``` (request.user.id gives the user\_id of the current logged in user) ...then I only get the events that are rated by the user and not the entire list of events. What I need can be generated through the custom SQL: ``` SELECT * FROM `events_event` LEFT OUTER JOIN ( SELECT * FROM `events_rating` WHERE user_id = ## ) AS temp ON events_event.id = temp.user_id ``` Is there an easier way so I don't have to use custom SQL?
The `filter` method is for filtering which objects are returned based on the specified criteria, so it's not what you want here. One option is to do a second query to retrieve all ratings for given `Event` objects for the current `User`. Models: ``` import collections from django.db import models class RatingManager(models.Manager): def get_for_user(self, events, user): ratings = self.filter(event__in=[event.id for event in events], user=user) rating_dict = collections.defaultdict(lambda: None) for rating in ratings: rating_dict[rating.event_id] = rating return rating_dict class Rating(models.Model): # ... objects = RatingManager() ``` View: ``` events = Event.objects.all() user_ratings = Rating.objects.get_for_user(events, request.user) context = { 'events': [(event, user_ratings[event.id]) for event in events], } ``` Template: ``` {% for event, user_rating in events %} {% if user_rating %} ... {% endif %} {% endfor %} ```
256,345
<p>Could you write a function that takes one argument (a positive integer) and</p> <ul> <li>divides it by two if it's even, or</li> <li>multiplies it by three and adds one if it's odd</li> </ul> <p>and then returns the resulting number.</p> <p>And then a separate function that takes one argument (a positive integer) and repeatedly passes it to the previous function until it reaches 1 (at which point it stops). The function would return the number of steps it took to reduce it to 1.</p> <p>And then another function which takes two arguments a and b (both positive integers with a &lt;= b) and returns the largest number of repeated Collatz steps it takes to reduce any single number in the range to 1 (including the endpoints). (Collatz steps refers to the previous function).</p> <p>And finally, another function that takes two arguments a and b (both positive integers with a &lt;= b) and returns the number between a and b (including the endpoints) that takes the largest number of Collatz steps to be reduced to 1.</p> <p>These functions are related to the Collatz problem, and I find it very interesting. The subsequent functions will obviously borrow other function that were defined previously.</p> <p>Any idea how we could show this in Scheme code?</p>
[ { "answer_id": 256352, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "<p>A function that performs one iteration:</p>\n\n<pre><code>(define (collatz x)\n (if (even? x)\n (/ x 2)\n (+ (* x 3) 1)))\n</code></pre>\n\n<p>This function takes an input and loops until it reaches 1. The function returns the number of iterations required to get to that state (try graphing this - it looks pretty cool):</p>\n\n<pre><code>(define (collatz-loop x)\n (if (= x 1) 1\n (+ (collatz-loop (collatz x)) 1)))\n</code></pre>\n\n<p>As requested, here's a tail-recursive version of collatz-loop:</p>\n\n<pre><code>(define (collatz-loop x)\n (define (internal x counter)\n (if (= x 1) counter\n (internal (collatz x) (+ counter 1))))\n (internal x 1))\n</code></pre>\n\n<p>This function takes a range and returns the number that takes the most number of steps to reach the end along with the number of steps:</p>\n\n<pre><code>(define (collatz-range a b)\n (if (= a b)\n (cons a (collatz-loop a))\n (let ((this (collatz-loop a))\n (rest (collatz-range (+ a 1) b)))\n (if (&lt; this (cdr rest)) rest\n (cons a this)))))\n\n(collatz-range 1 20) ; returns (18 . 21), which means that (collatz-loop 18) returns 21\n</code></pre>\n\n<p>This is collatz-range, tail recursive:</p>\n\n<pre><code>(define (collatz-range a b)\n (define (internal a best)\n (if (&lt; b a) best\n (internal (+ a 1)\n (let ((x (collatz-loop a)))\n (if (&lt; x (cdr best))\n best\n (cons a x))))))\n (internal a (cons -1 -1)))\n</code></pre>\n" }, { "answer_id": 256369, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 1, "selected": false, "text": "<p>For the other two functions, using foldl:</p>\n\n<pre><code>(define (listfrom a b)\n (if (= a b)\n (cons a empty)\n (cons a (listfrom (+ 1 a) b))))\n\n(define (max-collatz a b)\n (foldl max 0 (map collatz-loop (listfrom a b))))\n\n(define (max-collatz-num a b)\n (foldl (lambda (c r)\n (if (&gt; (collatz-loop c) (collatz-loop r)) c r))\n a\n (listfrom a b))) \n</code></pre>\n" }, { "answer_id": 256377, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 2, "selected": false, "text": "<p>i believe this is a great unsolved question of number theory. There is a hypothesis that every number when it goes through this operation enough times will reduce to one.</p>\n\n<p>However i don't really think scheme is the right tool for this, plus since a lot of people have decided that this is homework and not a legit question I will provide my solution in c</p>\n\n<pre><code>inline unsigned int step(unsigned int i)\n{\n return (i&amp;0x1)*(i*3+1)+((i+1)&amp;0x1)*(i&gt;&gt;1);\n}\n</code></pre>\n\n<p>this will do one step on the number (with no branches!!!). Heres how you do the whole calculation:</p>\n\n<pre><code>unsigned int collatz(unsigned int i)\n{\n unsigned int cur = i;\n unsigned steps = 0;\n while((cur=step(cur))!=1) steps++;\n return steps;\n}\n</code></pre>\n\n<p>I don't think its possible to remove the branch entirely. this is number theory problem and thus it is suited to extreme (and possibly unnecessary) optimization. enjoy</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
Could you write a function that takes one argument (a positive integer) and * divides it by two if it's even, or * multiplies it by three and adds one if it's odd and then returns the resulting number. And then a separate function that takes one argument (a positive integer) and repeatedly passes it to the previous function until it reaches 1 (at which point it stops). The function would return the number of steps it took to reduce it to 1. And then another function which takes two arguments a and b (both positive integers with a <= b) and returns the largest number of repeated Collatz steps it takes to reduce any single number in the range to 1 (including the endpoints). (Collatz steps refers to the previous function). And finally, another function that takes two arguments a and b (both positive integers with a <= b) and returns the number between a and b (including the endpoints) that takes the largest number of Collatz steps to be reduced to 1. These functions are related to the Collatz problem, and I find it very interesting. The subsequent functions will obviously borrow other function that were defined previously. Any idea how we could show this in Scheme code?
i believe this is a great unsolved question of number theory. There is a hypothesis that every number when it goes through this operation enough times will reduce to one. However i don't really think scheme is the right tool for this, plus since a lot of people have decided that this is homework and not a legit question I will provide my solution in c ``` inline unsigned int step(unsigned int i) { return (i&0x1)*(i*3+1)+((i+1)&0x1)*(i>>1); } ``` this will do one step on the number (with no branches!!!). Heres how you do the whole calculation: ``` unsigned int collatz(unsigned int i) { unsigned int cur = i; unsigned steps = 0; while((cur=step(cur))!=1) steps++; return steps; } ``` I don't think its possible to remove the branch entirely. this is number theory problem and thus it is suited to extreme (and possibly unnecessary) optimization. enjoy
256,349
<p>I'm trying to find some info on the best and most common RESTful url actions.</p> <p>for example, what url do you use for displaying the details of an item, for editing the item, updating, etc.</p> <pre><code>/question/show/&lt;whatever&gt; /question/edit/&lt;whatever&gt; /question/update/&lt;whatever&gt; (this is the post back url) /question/list (lists the questions) </code></pre> <p>hmm. thanks to anyone helping out :)</p>
[ { "answer_id": 256355, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 4, "selected": false, "text": "<p>Assuming <code>/questions/10</code> is a valid question then the method is used to interact with it.</p>\n\n<p>POST to add to it</p>\n\n<p>PUT to create or replace it</p>\n\n<p>GET to view/query it</p>\n\n<p>and DELETE to well.. delete it.</p>\n\n<p>The url doesn't change.</p>\n" }, { "answer_id": 256359, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 8, "selected": true, "text": "<p><strong>Use URLs to specify your objects, not your actions:</strong></p>\n\n<p>Note what you first mentioned is not RESTful:</p>\n\n<pre><code>/questions/show/&lt;whatever&gt;\n</code></pre>\n\n<p>Instead, you should use your URLs to specify your objects:</p>\n\n<pre><code>/questions/&lt;question&gt;\n</code></pre>\n\n<p>Then you perform one of the below operations on that resource. </p>\n\n<hr>\n\n<p><strong>GET:</strong></p>\n\n<p>Used to obtain a resource, query a list of resources, and also to query read-only information on a resource.</p>\n\n<p>To obtain a question resource:</p>\n\n<pre><code>GET /questions/&lt;question&gt; HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p>To list all question resources:</p>\n\n<pre><code>GET /questions HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p><strong>POST:</strong></p>\n\n<p>Used to create a resource.</p>\n\n<p>Note that the following is an error:</p>\n\n<pre><code>POST /questions/&lt;new_question&gt; HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p>If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a resource not found error because does not exist yet. You should PUT the resource on the server first. You could argue that by creating a new question, you are also updating the /questions resource as it would now return one more question in its list of questions.</p>\n\n<p>You should do something like this to create a resource using POST:</p>\n\n<pre><code>POST /questions HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p>Note that in this case the resource name is not specified, the new objects URL path would be returned to you.</p>\n\n<p><strong>DELETE:</strong></p>\n\n<p>Used to delete the resource.</p>\n\n<pre><code>DELETE /questions/&lt;question&gt; HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p><strong>PUT:</strong> </p>\n\n<p>Used to create a resource, or overwrite it, while you specify the resources URL.</p>\n\n<p>For a new resource:</p>\n\n<pre><code>PUT /questions/&lt;new_question&gt; HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p>To overwrite an existing resource:</p>\n\n<pre><code>PUT /questions/&lt;existing_question&gt; HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p>...Yes, they are the same. PUT is often described as the 'edit' method, as by replacing the entire resource with a slightly altered version, you have edited what clients will GET when they next do.</p>\n\n<hr>\n\n<p><strong>Using REST in HTML forms:</strong></p>\n\n<p>The <a href=\"http://www.w3.org/TR/2012/CR-html5-20121217/forms.html#attr-fs-method\" rel=\"noreferrer\">HTML5 spec defines GET and POST for the form element</a>. </p>\n\n<blockquote>\n <p>The method content attribute is an enumerated attribute with the following keywords and states:</p>\n \n <ul>\n <li>The keyword GET, mapping to the state GET, indicating the HTTP GET method.</li>\n <li>The keyword POST, mapping to the state POST, indicating the HTTP POST method.</li>\n </ul>\n</blockquote>\n\n<hr>\n\n<p>Technically, the HTTP specification does not limit you to only those methods. You are technically free to add any methods you want, in practice though, this is not a good idea. The idea is that everyone knows that you use GET to read the data, so it will confuse matters if you decide to instead use READ. That said...</p>\n\n<p><strong>PATCH:</strong></p>\n\n<p>This is a method that was defined in a formal RFC. It is designed to used for when you wish to send just a partial modification to a resource, it would be used much like PUT:</p>\n\n<pre><code>PATCH /questions/&lt;new_question&gt; HTTP/1.1\nHost: whateverblahblah.com\n</code></pre>\n\n<p>The difference is PUT has to send the entire resource, no matter how big it is compared to what's actually changed, whilst PATCH you can send <em>just</em> the changes.</p>\n" }, { "answer_id": 256374, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I'm going to go out on a limb and guess that you what you mean is what are standard controllers for MVC when you say \"RESTful\" urls, since your examples could be considered non-\"RESTful\" (see <a href=\"http://www.artima.com/weblogs/viewpost.jsp?thread=153170\" rel=\"nofollow noreferrer\">this</a> article).</p>\n\n<p>Since Rails really popularized the URL style you seem to be interested in, I offer below the default controller actions produced by the <a href=\"http://wiki.rubyonrails.org/rails/pages/ScaffoldGenerator\" rel=\"nofollow noreferrer\">ScaffoldingGenerator</a> in Ruby on Rails. These should be familiar to anyone using a Rails application.</p>\n\n<blockquote>\n <p>The scaffolded actions and views are:\n index, list, show, new, create, edit,\n update, destroy</p>\n</blockquote>\n\n<p>Typically you would construct this as:</p>\n\n<pre><code>http://application.com/controller/&lt;action&gt;/&lt;id&gt;\n</code></pre>\n" }, { "answer_id": 263885, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 1, "selected": false, "text": "<p>Here is a mapping of your current URLs using the REST principle:</p>\n\n<pre><code>/question/show/&lt;whatever&gt;\n</code></pre>\n\n<p>If you identify the question as a resource, then it should have a unique URL. Using GET to display it (retrieve it) is the common practice. It becomes:</p>\n\n<pre><code>GET /question/&lt;whatever&gt;\n</code></pre>\n\n<hr>\n\n<pre><code>/question/edit/&lt;whatever&gt;\n</code></pre>\n\n<p>Now you want your user to have another view of the same resource that allows him to edit the resource (maybe with form controls). </p>\n\n<p>Two options here, your application is an application (not a website), then you may be better using JavaScript to transform the resource into an editable resource ono the client side. </p>\n\n<p>If this is a website, then you can use the same URL with additional information to specify another view, the common practice seems to be:</p>\n\n<pre><code>GET /question/&lt;whatever&gt;;edit\n</code></pre>\n\n<hr>\n\n<pre><code>/question/update/&lt;whatever&gt; (this is the post back url)\n</code></pre>\n\n<p>This is to change the question, so PUT is the correct method to use:</p>\n\n<pre><code>PUT /question/&lt;whatever&gt;\n</code></pre>\n\n<hr>\n\n<pre><code>/question/list (lists the questions)\n</code></pre>\n\n<p>The list of question is actually the parent resource of a question, so it naturally is:</p>\n\n<pre><code>GET /question\n</code></pre>\n\n<hr>\n\n<p>Now you may need some more:</p>\n\n<pre><code>POST /question (create a new question and returns its URL)\nDELETE /question/&lt;whatever&gt; (deletes a question if this is relevant)\n</code></pre>\n\n<p>Tada :)</p>\n" }, { "answer_id": 1081730, "author": "pbreitenbach", "author_id": 42048, "author_profile": "https://Stackoverflow.com/users/42048", "pm_score": -1, "selected": false, "text": "<p>Your four examples could be:</p>\n\n<pre><code>GET /questions/123\nPOST (or PUT) /questions/123 q=What+is+the+meaning+of+life\nPOST (or PUT) /questions/123 q=What+is+the+meaning+of+life\nGET /questions\n</code></pre>\n\n<p>To add a question:</p>\n\n<pre><code>POST /questions q=What+is+the+meaning+of+life\n</code></pre>\n\n<p>The server would respond:</p>\n\n<pre><code>200 OK (or 201 Created)\nLocation: /questions/456\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
I'm trying to find some info on the best and most common RESTful url actions. for example, what url do you use for displaying the details of an item, for editing the item, updating, etc. ``` /question/show/<whatever> /question/edit/<whatever> /question/update/<whatever> (this is the post back url) /question/list (lists the questions) ``` hmm. thanks to anyone helping out :)
**Use URLs to specify your objects, not your actions:** Note what you first mentioned is not RESTful: ``` /questions/show/<whatever> ``` Instead, you should use your URLs to specify your objects: ``` /questions/<question> ``` Then you perform one of the below operations on that resource. --- **GET:** Used to obtain a resource, query a list of resources, and also to query read-only information on a resource. To obtain a question resource: ``` GET /questions/<question> HTTP/1.1 Host: whateverblahblah.com ``` To list all question resources: ``` GET /questions HTTP/1.1 Host: whateverblahblah.com ``` **POST:** Used to create a resource. Note that the following is an error: ``` POST /questions/<new_question> HTTP/1.1 Host: whateverblahblah.com ``` If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a resource not found error because does not exist yet. You should PUT the resource on the server first. You could argue that by creating a new question, you are also updating the /questions resource as it would now return one more question in its list of questions. You should do something like this to create a resource using POST: ``` POST /questions HTTP/1.1 Host: whateverblahblah.com ``` Note that in this case the resource name is not specified, the new objects URL path would be returned to you. **DELETE:** Used to delete the resource. ``` DELETE /questions/<question> HTTP/1.1 Host: whateverblahblah.com ``` **PUT:** Used to create a resource, or overwrite it, while you specify the resources URL. For a new resource: ``` PUT /questions/<new_question> HTTP/1.1 Host: whateverblahblah.com ``` To overwrite an existing resource: ``` PUT /questions/<existing_question> HTTP/1.1 Host: whateverblahblah.com ``` ...Yes, they are the same. PUT is often described as the 'edit' method, as by replacing the entire resource with a slightly altered version, you have edited what clients will GET when they next do. --- **Using REST in HTML forms:** The [HTML5 spec defines GET and POST for the form element](http://www.w3.org/TR/2012/CR-html5-20121217/forms.html#attr-fs-method). > > The method content attribute is an enumerated attribute with the following keywords and states: > > > * The keyword GET, mapping to the state GET, indicating the HTTP GET method. > * The keyword POST, mapping to the state POST, indicating the HTTP POST method. > > > --- Technically, the HTTP specification does not limit you to only those methods. You are technically free to add any methods you want, in practice though, this is not a good idea. The idea is that everyone knows that you use GET to read the data, so it will confuse matters if you decide to instead use READ. That said... **PATCH:** This is a method that was defined in a formal RFC. It is designed to used for when you wish to send just a partial modification to a resource, it would be used much like PUT: ``` PATCH /questions/<new_question> HTTP/1.1 Host: whateverblahblah.com ``` The difference is PUT has to send the entire resource, no matter how big it is compared to what's actually changed, whilst PATCH you can send *just* the changes.
256,370
<p>Today, everytime I try to open any <strong>.Net application</strong> I get:</p> <pre><code>CLR error: 80004005 The program will now terminate. </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 256373, "author": "Jeff Donnici", "author_id": 821, "author_profile": "https://Stackoverflow.com/users/821", "pm_score": 5, "selected": true, "text": "<p>I'd start with <a href=\"http://msdn.microsoft.com/en-us/netframework/aa569263.aspx\" rel=\"noreferrer\">downloading</a> and re-installing the .NET framework.</p>\n" }, { "answer_id": 256381, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 0, "selected": false, "text": "<p>A quick search suggests this:</p>\n\n<blockquote>\n <p>\"If you get a Run-time error 80131522\n \"No Server registered or could not\n load class for CLSID ...\", it is\n because you are trying to run the VB\n executable from a directory other than\n where the .NET assembly is located.\n This also happens if you try to run\n the vb code in interactive mode. This\n can be solved by installing the .NET\n assembly into the global application\n cache\"</p>\n</blockquote>\n\n<p>(<a href=\"http://bytes.com/forum/thread353655.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread353655.html</a>)</p>\n\n<p>In an ASP.NET context, it appears this is related to file permissions:</p>\n\n<blockquote>\n <p>The error code for the failure is\n 80004005. This error can be caused when the worker process account has\n insufficient rights to read the .NET\n Framework files. Please ensure</p>\n</blockquote>\n\n<p>(<a href=\"http://weblogs.asp.net/jambrose/archive/2004/09/01/224226.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/jambrose/archive/2004/09/01/224226.aspx</a>)</p>\n" }, { "answer_id": 256386, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>I believe 0x80004005 is (usually) an ACCESS DENIED error - so start with that in mind. If you're on Vista+, try running it as admin. Otherwise, <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monitor</a> should help you track it down.</p>\n" }, { "answer_id": 13986360, "author": "Josh", "author_id": 1920979, "author_profile": "https://Stackoverflow.com/users/1920979", "pm_score": 0, "selected": false, "text": "<p>@MarkBracket: I had a similar issue, but I think I finally fixed it thanks to Process Monitor.</p>\n\n<p>My Solution:\nGo to \"C:\\Windows\" and right click on the \"Microsoft.NET\" folder and click Properties.\nClick the \"Security\" Tab, then click the \"Advanced\" button.\nClick the \"Owner\" Tab, then click the \"Edit...\" button.\nSelect your current user account, then check the box that says \"Replace owner on subcontainers and objects\" and then click \"Ok\".</p>\n\n<p>Problem solved (for now at least). \nAs it turns out, the programs simply didn't have the proper permissions needed to run.</p>\n\n<p>Anyways, Thanks Again Mark\nI hope this post is helpful to any and all who have/get the CLR 80004005 error.</p>\n" }, { "answer_id": 15801700, "author": "mike", "author_id": 2243030, "author_profile": "https://Stackoverflow.com/users/2243030", "pm_score": 3, "selected": false, "text": "<p>I had this problem and uninstalling/reinstalling dot net didn't help.</p>\n\n<p>Randomly I found a suggestion to go to\nc:\\Windows\\Microsoft.NET\\</p>\n\n<p>Then rename the directory called \"Assembly\" to \"Assembly2\" or something so you don't erase it but dot net will think it's gone.</p>\n\n<p>After doing that, install dot net again.</p>\n\n<p>This took hours for me to find and was the ONLY thing that worked.</p>\n" }, { "answer_id": 17419905, "author": "OKEEngine", "author_id": 662649, "author_profile": "https://Stackoverflow.com/users/662649", "pm_score": 0, "selected": false, "text": "<p>Just want to answer this from development prospective, as I got into such problem and solved it.</p>\n\n<p>The problem I had encountered was that I was deploying a WPF application on a none development machine, It crashed immediately with the message \"Fatal CLR Error 80004005\". </p>\n\n<p>I realized that I compiled my application as .Net framework 4.5 and I was using an API call from System.Web namespace. </p>\n\n<p>I solved it by changing the method call and then re-compiled it as .Net framework 4.0 Client Profile.</p>\n" }, { "answer_id": 68414504, "author": "RoadieRich", "author_id": 105886, "author_profile": "https://Stackoverflow.com/users/105886", "pm_score": 0, "selected": false, "text": "<p>I had the same error pop up when I had a lot of other applications running. Closing some of the more memory-intensive programs caused the error to go away.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
Today, everytime I try to open any **.Net application** I get: ``` CLR error: 80004005 The program will now terminate. ``` Any suggestions?
I'd start with [downloading](http://msdn.microsoft.com/en-us/netframework/aa569263.aspx) and re-installing the .NET framework.
256,387
<p>When using copy-on-write semantics to share memory among processes, how can you test if a memory page is writable or if it is marked as read-only? Can this be done by calling a specific assembler code, or reading a certain spot in memory, or through the OS's API?</p>
[ { "answer_id": 256402, "author": "Jim Nelson", "author_id": 32168, "author_profile": "https://Stackoverflow.com/users/32168", "pm_score": 1, "selected": false, "text": "<p>If you're using Win32, there are the calls IsBadReadPtr and IsBadWritePtr. However, their use is discouraged:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb871031.aspx\" rel=\"nofollow noreferrer\">\"The general consensus is that the IsBad family of functions (IsBadReadPtr, IsBadWritePtr, and so forth) is broken and should not be used to validate pointers.\"</a></p>\n\n<p>The title of Raymond Chen's take on this says it all: <a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx\" rel=\"nofollow noreferrer\">\"IsBadXxxPtr should really be called CrashProgramRandomly\"</a></p>\n\n<p>Chen has some helpful advice about how to deal with this issue <a href=\"http://blogs.msdn.com/oldnewthing/archive/2007/06/25/3507294.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>The upshot is, you shouldn't be testing this kind of thing at run-time. Code so that you know what you're being handed, and if it's not what's expected, treat it as a bug. If you really have no choice, look into SEH for handling the exception.</p>\n" }, { "answer_id": 256409, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": true, "text": "<p>On Linux you can examine /proc/<em>pid</em>/maps:</p>\n\n<pre><code>$ cat /proc/self/maps\n\n002b3000-002cc000 r-xp 00000000 68:01 143009 /lib/ld-2.5.so\n002cc000-002cd000 r-xp 00018000 68:01 143009 /lib/ld-2.5.so\n002cd000-002ce000 rwxp 00019000 68:01 143009 /lib/ld-2.5.so\n002d0000-00407000 r-xp 00000000 68:01 143010 /lib/libc-2.5.so\n00407000-00409000 r-xp 00137000 68:01 143010 /lib/libc-2.5.so\n00409000-0040a000 rwxp 00139000 68:01 143010 /lib/libc-2.5.so\n0040a000-0040d000 rwxp 0040a000 00:00 0\n00c6f000-00c70000 r-xp 00c6f000 00:00 0 [vdso]\n08048000-0804d000 r-xp 00000000 68:01 379298 /bin/cat\n0804d000-0804e000 rw-p 00004000 68:01 379298 /bin/cat\n08326000-08347000 rw-p 08326000 00:00 0\nb7d1b000-b7f1b000 r--p 00000000 68:01 226705 /usr/lib/locale/locale-archive\nb7f1b000-b7f1c000 rw-p b7f1b000 00:00 0\nb7f28000-b7f29000 rw-p b7f28000 00:00 0\nbfe37000-bfe4d000 rw-p bfe37000 00:00 0 [stack]\n</code></pre>\n\n<p>The first column is the virtual memory address range, the second column contains the permissions (read, write, execute, and private), columns 3-6 contain the offset, major and minor device numbers, the inode, and the name of memory mapped files.</p>\n" }, { "answer_id": 256427, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 1, "selected": false, "text": "<p>Are you talking abou the variety of shared memory allocated via shmget (on Unix)? I.e.</p>\n\n<pre><code>int shmget(key_t, size_t, int);\n</code></pre>\n\n<p>If so, you can query that memory using</p>\n\n<pre><code>int shmctl(int, int, struct shmid_ds *);\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>key_t key = /* your choice of memory api */\nint flag = /* set of flags for your app */\nint shmid = shmget(key, 4096, flag);\n\nstruct shmid_ds buf;\nint result = shmctl(shmid, IPC_STAT, &amp;buf);\n/* buf.ipc_perm.mode contains the permissions for the memory segment */\n</code></pre>\n" }, { "answer_id": 256479, "author": "Chris Smith", "author_id": 9073, "author_profile": "https://Stackoverflow.com/users/9073", "pm_score": 2, "selected": false, "text": "<p>On Win32, the best way is to use <a href=\"http://msdn.microsoft.com/en-us/library/aa366902(VS.85).aspx\" rel=\"nofollow noreferrer\">VirtualQuery</a>. It returns a <a href=\"http://msdn.microsoft.com/en-us/library/aa366775(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>MEMORY_BASIC_INFORMATION</code></a> for the page an address falls in. One of the members is <code>Protect</code>, which is some combination of <a href=\"http://msdn.microsoft.com/en-us/library/aa366786(VS.85).aspx\" rel=\"nofollow noreferrer\">these</a> flags, which contain the possible protection modes. The function also tells you if the memory is free, committed, reserved, and whether it is private, part of an image or shared memory section.</p>\n\n<p>The OS's API is the best way to detirmine the a page's protection. The CPU reads the protection mode from a page descriptor, which is only accessible from kernel mode.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33364/" ]
When using copy-on-write semantics to share memory among processes, how can you test if a memory page is writable or if it is marked as read-only? Can this be done by calling a specific assembler code, or reading a certain spot in memory, or through the OS's API?
On Linux you can examine /proc/*pid*/maps: ``` $ cat /proc/self/maps 002b3000-002cc000 r-xp 00000000 68:01 143009 /lib/ld-2.5.so 002cc000-002cd000 r-xp 00018000 68:01 143009 /lib/ld-2.5.so 002cd000-002ce000 rwxp 00019000 68:01 143009 /lib/ld-2.5.so 002d0000-00407000 r-xp 00000000 68:01 143010 /lib/libc-2.5.so 00407000-00409000 r-xp 00137000 68:01 143010 /lib/libc-2.5.so 00409000-0040a000 rwxp 00139000 68:01 143010 /lib/libc-2.5.so 0040a000-0040d000 rwxp 0040a000 00:00 0 00c6f000-00c70000 r-xp 00c6f000 00:00 0 [vdso] 08048000-0804d000 r-xp 00000000 68:01 379298 /bin/cat 0804d000-0804e000 rw-p 00004000 68:01 379298 /bin/cat 08326000-08347000 rw-p 08326000 00:00 0 b7d1b000-b7f1b000 r--p 00000000 68:01 226705 /usr/lib/locale/locale-archive b7f1b000-b7f1c000 rw-p b7f1b000 00:00 0 b7f28000-b7f29000 rw-p b7f28000 00:00 0 bfe37000-bfe4d000 rw-p bfe37000 00:00 0 [stack] ``` The first column is the virtual memory address range, the second column contains the permissions (read, write, execute, and private), columns 3-6 contain the offset, major and minor device numbers, the inode, and the name of memory mapped files.
256,460
<p>Is there anything similar to an <code>indexOf</code> function in the NSString objects?</p>
[ { "answer_id": 256464, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 8, "selected": true, "text": "<p>Use <code>-[NSString rangeOfString:]</code>:</p>\n\n<pre><code>- (NSRange)rangeOfString:(NSString *)aString;\n</code></pre>\n\n<blockquote>\n <p>Finds and returns the range of the first occurrence of a given string within the receiver.</p>\n</blockquote>\n" }, { "answer_id": 7329792, "author": "firestoke", "author_id": 555796, "author_profile": "https://Stackoverflow.com/users/555796", "pm_score": 4, "selected": false, "text": "<p>I wrote a category to extend original NSString object. Maybe you guys can reference it.\n(You also can see the <a href=\"http://fstoke.me/blog/?p=3121\">article</a> in my blog too.)</p>\n\n<p>ExtendNSString.h:</p>\n\n<pre><code>#import &lt;Foundation/Foundation.h&gt;\n\n@interface NSString (util)\n\n- (int) indexOf:(NSString *)text;\n\n@end\n</code></pre>\n\n<p>ExtendNSStriing.m:</p>\n\n<pre><code>#import \"ExtendNSString.h\"\n\n@implementation NSString (util)\n\n- (int) indexOf:(NSString *)text {\n NSRange range = [self rangeOfString:text];\n if ( range.length &gt; 0 ) {\n return range.location;\n } else {\n return -1;\n }\n}\n\n@end\n</code></pre>\n" }, { "answer_id": 8036303, "author": "orafaelreis", "author_id": 798430, "author_profile": "https://Stackoverflow.com/users/798430", "pm_score": 5, "selected": false, "text": "<p>If you want just know when String a contains String b use my way to do this.</p>\n\n<pre><code>#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)\n\n//using \nNSString a = @\"PUC MINAS - BRAZIL\";\n\nNSString b = @\"BRAZIL\";\n\nif( contains(a,b) ){\n //TO DO HERE\n}\n</code></pre>\n\n<p>This is less readable but improves performance</p>\n" }, { "answer_id": 20935116, "author": "William Falcon", "author_id": 1552585, "author_profile": "https://Stackoverflow.com/users/1552585", "pm_score": 1, "selected": false, "text": "<p>I know it's late, but I added a category that implements this method and many others similar to javascript string methods<br>\n<a href=\"https://github.com/williamFalcon/WF-iOS-Categories\" rel=\"nofollow\">https://github.com/williamFalcon/WF-iOS-Categories</a></p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
Is there anything similar to an `indexOf` function in the NSString objects?
Use `-[NSString rangeOfString:]`: ``` - (NSRange)rangeOfString:(NSString *)aString; ``` > > Finds and returns the range of the first occurrence of a given string within the receiver. > > >
256,500
<p>I am unlucky to be in charge of maintaining some old Yahoo! Store built using their RTML-based platform.</p> <p>Recently I've noticed that HTML code generated by some RTML functions is sprinkled all over with "padding images" (or whatever is the conventional name for those 1x1 pixel images used to enforce layout). I have nothing against using such images, but... all those images are supplied with an ALT attribute like this:</p> <pre><code>&lt;img href="http://.../image1x1.gif" alt="pad"&gt; </code></pre> <p>With all due respect to the original authors of RTML, but they must have been smoking something when they came up with this "accessibility enhancement"... :-(</p> <p>Anyway, here are my questions:</p> <ol> <li><p>Does anybody know a list of all RTML functions that generate HTML with all these "pad" images?</p></li> <li><p>Is there any way to get rid of all those <strong>alt="pad"</strong> attributes without rewriting a lot of RTML code?</p></li> </ol> <p><strong>NB:</strong> This may sound a little cynical, but improved accessibility is not the main goal here. The main goal is to stop exposing those moronic <strong>alt="pad"</strong> attributes to Google and other smart search engines. So client-side scripting is not going to help, as far as I know.</p> <p>Thank you!</p> <hr> <p>P.S. Probably, most of you are really lucky and never heard of RTML. Because if somebody would establish a prize for software products based on</p> <pre><code>commercial success ------------------ usability </code></pre> <p>ratio, this RTML-based "platform" would probably win the first place.</p> <hr> <p><em>P.P.S. Apparently someone from Yahoo! finally listened, because I can no longer find those silly "pad" tags in the RTML generated for our store. Nevertheless, one of the ideas offered in response to my original question does provide a very practical solution - not just to the original problem but to any similar problem with RTML platform. See the winning answer - it's really good.</em></p>
[ { "answer_id": 256588, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": false, "text": "<p>Well you're right on RTML being relatively untraveled :)</p>\n\n<p>Do you have a way to add your own attributes to these images tags? If so, would it be possible to override the alt attribute? If you specify alt=\"\", I would think that would override Yahoo's... Otherwise consider putting a useful alt tag in there for the blind and dialup types. </p>\n" }, { "answer_id": 258160, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 1, "selected": false, "text": "<p>It's the first time I'm hearing about this platform, but here is an idea: if you can add javascript to the pages, you could write a function that will run after the page has loaded and remove all the alt=\"pad\" attributes from the page.</p>\n\n<p>Unfortunately this solutions works only with browsers that know about scripting, so lynx or some other text based browsers might not support it.</p>\n" }, { "answer_id": 292785, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 2, "selected": false, "text": "<p>The only way I see is to have your own website front-end that will filter whatever you want from the RTML site....</p>\n\n<p>for example, your rtml site is at <a href=\"http://rtmlusglysite.yahoo.com/store/XYZ01134\" rel=\"nofollow noreferrer\">http://rtmlusglysite.yahoo.com/store/XYZ01134</a> , you could host a simple PHP front-end at http:://www.example.com that would be acting like a \"filtering\" HTTP web proxy, so <a href=\"http://rtmlusglysite.yahoo.com/store/XYZ01134/item1234.rtml\" rel=\"nofollow noreferrer\">http://rtmlusglysite.yahoo.com/store/XYZ01134/item1234.rtml</a> would be accessed by <a href=\"http://www.example.com/item1234.html\" rel=\"nofollow noreferrer\">http://www.example.com/item1234.html</a></p>\n\n<p>It's not an ideal solution, but it should work, and you could do some more fancy stuff.</p>\n" }, { "answer_id": 4425018, "author": "bmarti44", "author_id": 451238, "author_profile": "https://Stackoverflow.com/users/451238", "pm_score": 2, "selected": true, "text": "<p>Nice try from the other posters, but there is a very simple RTML command that will do it. . .</p>\n\n<pre>\nTEXT PAT-SUBST s GRAB\n MULTI\n HEAD\n BODY\n TEXT @var-with-alt-tag-equals-pad-in-it\n frompat \"alt=\\\"pad\\\"\"\n topat \"\"\n</pre>\n\n<p>The above RTML will find all instances of alt=\"pad\" and replace it with nothing.</p>\n" }, { "answer_id": 5464998, "author": "Scherbius.com", "author_id": 675937, "author_profile": "https://Stackoverflow.com/users/675937", "pm_score": 0, "selected": false, "text": "<p>I have shared a link official RTML guide from yahoo. Hope it will help. Thanks!</p>\n\n<p><a href=\"https://stackoverflow.com/questions/5464944/list-of-available-rtml-books-and-resources\">List of available RTML books and resources</a></p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31415/" ]
I am unlucky to be in charge of maintaining some old Yahoo! Store built using their RTML-based platform. Recently I've noticed that HTML code generated by some RTML functions is sprinkled all over with "padding images" (or whatever is the conventional name for those 1x1 pixel images used to enforce layout). I have nothing against using such images, but... all those images are supplied with an ALT attribute like this: ``` <img href="http://.../image1x1.gif" alt="pad"> ``` With all due respect to the original authors of RTML, but they must have been smoking something when they came up with this "accessibility enhancement"... :-( Anyway, here are my questions: 1. Does anybody know a list of all RTML functions that generate HTML with all these "pad" images? 2. Is there any way to get rid of all those **alt="pad"** attributes without rewriting a lot of RTML code? **NB:** This may sound a little cynical, but improved accessibility is not the main goal here. The main goal is to stop exposing those moronic **alt="pad"** attributes to Google and other smart search engines. So client-side scripting is not going to help, as far as I know. Thank you! --- P.S. Probably, most of you are really lucky and never heard of RTML. Because if somebody would establish a prize for software products based on ``` commercial success ------------------ usability ``` ratio, this RTML-based "platform" would probably win the first place. --- *P.P.S. Apparently someone from Yahoo! finally listened, because I can no longer find those silly "pad" tags in the RTML generated for our store. Nevertheless, one of the ideas offered in response to my original question does provide a very practical solution - not just to the original problem but to any similar problem with RTML platform. See the winning answer - it's really good.*
Nice try from the other posters, but there is a very simple RTML command that will do it. . . ``` TEXT PAT-SUBST s GRAB MULTI HEAD BODY TEXT @var-with-alt-tag-equals-pad-in-it frompat "alt=\"pad\"" topat "" ``` The above RTML will find all instances of alt="pad" and replace it with nothing.
256,507
<p>I'm a Lisp beginner. I'm trying to memoize a recursive function for calculating the number of terms in a <a href="http://en.wikipedia.org/wiki/Collatz_conjecture" rel="noreferrer">Collatz sequence</a> (for problem 14 in <a href="http://projecteuler.net/index.php?section=problems&amp;id=14" rel="noreferrer">Project Euler</a>). My code as of yet is:</p> <pre><code>(defun collatz-steps (n) (if (= 1 n) 0 (if (evenp n) (1+ (collatz-steps (/ n 2))) (1+ (collatz-steps (1+ (* 3 n))))))) (defun p14 () (defvar m-collatz-steps (memoize #'collatz-steps)) (let ((maxsteps (funcall m-collatz-steps 2)) (n 2) (steps)) (loop for i from 1 to 1000000 do (setq steps (funcall m-collatz-steps i)) (cond ((&gt; steps maxsteps) (setq maxsteps steps) (setq n i)) (t ()))) n)) (defun memoize (fn) (let ((cache (make-hash-table :test #'equal))) #'(lambda (&amp;rest args) (multiple-value-bind (result exists) (gethash args cache) (if exists result (setf (gethash args cache) (apply fn args))))))) </code></pre> <p>The memoize function is the same as the one given in the <a href="http://lib.store.yahoo.net/lib/paulgraham/onlisp.pdf" rel="noreferrer">On Lisp</a> book. </p> <p>This code doesn't actually give any speedup compared to the non-memoized version. I believe it's due to the recursive calls calling the non-memoized version of the function, which sort of defeats the purpose. In that case, what is the correct way to do the memoization here? Is there any way to have all calls to the original function call the memoized version itself, removing the need for the special m-collatz-steps symbol?</p> <p>EDIT: Corrected the code to have </p> <pre><code>(defvar m-collatz-steps (memoize #'collatz-steps)) </code></pre> <p>which is what I had in my code. Before the edit I had erroneously put:</p> <pre><code>(defvar collatz-steps (memoize #'collatz-steps)) </code></pre> <p>Seeing that error gave me another idea, and I tried using this last defvar itself and changing the recursive calls to </p> <pre><code> (1+ (funcall collatz-steps (/ n 2))) (1+ (funcall collatz-steps (1+ (* 3 n)))) </code></pre> <p>This does seem to perform the memoization (speedup from about 60 seconds to 1.5 seconds), but requires changing the original function. Is there a cleaner solution which doesn't involve changing the original function? </p>
[ { "answer_id": 256552, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>something like this:</p>\n\n<pre><code>(setf collatz-steps (memoize lambda (n)\n (if (= 1 n) 0\n (if (evenp n) \n (1+ (collatz-steps (/ n 2)))\n (1+ (collatz-steps (1+ (* 3 n))))))))\n</code></pre>\n\n<p>IOW: your original (non-memoized) function is anonymous, and you only give a name to the result of memoizing it.</p>\n" }, { "answer_id": 257224, "author": "huaiyuan", "author_id": 16240, "author_profile": "https://Stackoverflow.com/users/16240", "pm_score": 5, "selected": true, "text": "<p>I assume you're using Common-Lisp, which has separate namespaces for variable and function names. In order to memoize the function named by a symbol, you need to change its function binding, through the accessor `fdefinition':</p>\n\n<pre><code>(setf (fdefinition 'collatz-steps) (memoize #'collatz-steps))\n\n(defun p14 ()\n (let ((mx 0) (my 0))\n (loop for x from 1 to 1000000\n for y = (collatz-steps x)\n when (&lt; my y) do (setf my y mx x))\n mx))\n</code></pre>\n" }, { "answer_id": 259704, "author": "Eric Normand", "author_id": 7492, "author_profile": "https://Stackoverflow.com/users/7492", "pm_score": 2, "selected": false, "text": "<p>Here is a memoize function that rebinds the symbol function:</p>\n\n<pre><code>(defun memoize-function (function-name)\n (setf (symbol-function function-name)\n (let ((cache (make-hash-table :test #'equal)))\n #'(lambda (&amp;rest args)\n (multiple-value-bind \n (result exists)\n (gethash args cache)\n (if exists\n result\n (setf (gethash args cache)\n (apply fn args)))))))\n</code></pre>\n\n<p>You would then do something like this:</p>\n\n<pre><code>(defun collatz-steps (n)\n (if (= 1 n) 0\n (if (evenp n) \n (1+ (collatz-steps (/ n 2)))\n (1+ (collatz-steps (1+ (* 3 n)))))))\n\n(memoize-function 'collatz-steps)\n</code></pre>\n\n<p>I'll leave it up to you to make an unmemoize-function.</p>\n" }, { "answer_id": 307912, "author": "jonrock", "author_id": 39526, "author_profile": "https://Stackoverflow.com/users/39526", "pm_score": 1, "selected": false, "text": "<p>Changing the \"original\" function is necessary, because, as you say, there's no other way for the recursive call(s) to be updated to call the memoized version.</p>\n\n<p>Fortunately, the way lisp works is to find the function <em>by name</em> each time it needs to be called. This means that it is sufficient to replace the function binding with the memoized version of the function, so that recursive calls will automatically look up and reenter through the memoization.</p>\n\n<p>huaiyuan's code shows the key step:</p>\n\n<pre><code>(setf (fdefinition 'collatz-steps) (memoize #'collatz-steps))\n</code></pre>\n\n<p>This trick also works in Perl. In a language like C, however, a memoized version of a function must be coded separately.</p>\n\n<p>Some lisp implementations provide a system called \"advice\", which provides a standardized structure for replacing functions with enhanced versions of themselves. In addition to functional upgrades like memoization, this can be extremely useful in debugging by inserting debug prints (or completely stopping and giving a continuable prompt) without modifying the original code.</p>\n" }, { "answer_id": 307938, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "<p>A while ago I wrote a little memoization routine for Scheme that used a chain of closures to keep track of the memoized state:</p>\n\n<pre><code>(define (memoize op)\n (letrec ((get (lambda (key) (list #f)))\n (set (lambda (key item)\n (let ((old-get get))\n (set! get (lambda (new-key)\n (if (equal? key new-key) (cons #t item)\n (old-get new-key))))))))\n (lambda args\n (let ((ans (get args)))\n (if (car ans) (cdr ans)\n (let ((new-ans (apply op args)))\n (set args new-ans)\n new-ans))))))\n</code></pre>\n\n<p>This needs to be used like so:</p>\n\n<pre><code>(define fib (memoize (lambda (x)\n (if (&lt; x 2) x\n (+ (fib (- x 1)) (fib (- x 2)))))))\n</code></pre>\n\n<p>I'm sure that this can be ported to your favorite lexically scoped Lisp flavor with ease.</p>\n" }, { "answer_id": 2393414, "author": "Vatine", "author_id": 34771, "author_profile": "https://Stackoverflow.com/users/34771", "pm_score": 0, "selected": false, "text": "<p>I'd probably do something like:</p>\n\n<pre><code>(let ((memo (make-hash-table :test #'equal)))\n (defun collatz-steps (n)\n (or (gethash n memo)\n (setf (gethash n memo)\n (cond ((= n 1) 0)\n ((oddp n) (1+ (collatz-steps (+ 1 n n n))))\n (t (1+ (collatz-steps (/ n 2)))))))))\n</code></pre>\n\n<p>It's not Nice and Functional, but, then, it's not much hassle and it does work. Downside is that you don't get a handy unmemoized version to test with and clearing the cache is bordering on \"very difficult\".</p>\n" }, { "answer_id": 2393650, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 2, "selected": false, "text": "<p>Note a few things:</p>\n\n<pre><code>(defun foo (bar)\n ... (foo 3) ...)\n</code></pre>\n\n<p>Above is a function that has a call to itself.</p>\n\n<p>In Common Lisp the file compiler can assume that FOO does not change. It will NOT call an updated FOO later. If you change the function binding of FOO, then the call of the original function will still go to the old function.</p>\n\n<p><strong>So memoizing a self recursive function will NOT work in the general case. Especially not if you are using a good compiler.</strong></p>\n\n<p>You can work around it to go always through the symbol for example: (funcall 'foo 3)</p>\n\n<p>(DEFVAR ...) is a top-level form. Don't use it inside functions. If you have declared a variable, set it with SETQ or SETF later.</p>\n\n<p>For your problem, I'd just use a hash table to store the intermediate results.</p>\n" }, { "answer_id": 3494552, "author": "user421879", "author_id": 421879, "author_profile": "https://Stackoverflow.com/users/421879", "pm_score": 1, "selected": false, "text": "<p>This function is exactly the one Peter Norvig gives as an example of a function that seems like a good candidate for memoization, but which is not.</p>\n\n<p>See figure 3 (the function 'Hailstone') of his original paper on memoization (\"Using Automatic Memoization as a Software Engineering Tool in Real-World AI Systems\").</p>\n\n<p>So I'm guessing, even if you get the mechanics of memoization working, it won't really speed it up in this case.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8127/" ]
I'm a Lisp beginner. I'm trying to memoize a recursive function for calculating the number of terms in a [Collatz sequence](http://en.wikipedia.org/wiki/Collatz_conjecture) (for problem 14 in [Project Euler](http://projecteuler.net/index.php?section=problems&id=14)). My code as of yet is: ``` (defun collatz-steps (n) (if (= 1 n) 0 (if (evenp n) (1+ (collatz-steps (/ n 2))) (1+ (collatz-steps (1+ (* 3 n))))))) (defun p14 () (defvar m-collatz-steps (memoize #'collatz-steps)) (let ((maxsteps (funcall m-collatz-steps 2)) (n 2) (steps)) (loop for i from 1 to 1000000 do (setq steps (funcall m-collatz-steps i)) (cond ((> steps maxsteps) (setq maxsteps steps) (setq n i)) (t ()))) n)) (defun memoize (fn) (let ((cache (make-hash-table :test #'equal))) #'(lambda (&rest args) (multiple-value-bind (result exists) (gethash args cache) (if exists result (setf (gethash args cache) (apply fn args))))))) ``` The memoize function is the same as the one given in the [On Lisp](http://lib.store.yahoo.net/lib/paulgraham/onlisp.pdf) book. This code doesn't actually give any speedup compared to the non-memoized version. I believe it's due to the recursive calls calling the non-memoized version of the function, which sort of defeats the purpose. In that case, what is the correct way to do the memoization here? Is there any way to have all calls to the original function call the memoized version itself, removing the need for the special m-collatz-steps symbol? EDIT: Corrected the code to have ``` (defvar m-collatz-steps (memoize #'collatz-steps)) ``` which is what I had in my code. Before the edit I had erroneously put: ``` (defvar collatz-steps (memoize #'collatz-steps)) ``` Seeing that error gave me another idea, and I tried using this last defvar itself and changing the recursive calls to ``` (1+ (funcall collatz-steps (/ n 2))) (1+ (funcall collatz-steps (1+ (* 3 n)))) ``` This does seem to perform the memoization (speedup from about 60 seconds to 1.5 seconds), but requires changing the original function. Is there a cleaner solution which doesn't involve changing the original function?
I assume you're using Common-Lisp, which has separate namespaces for variable and function names. In order to memoize the function named by a symbol, you need to change its function binding, through the accessor `fdefinition': ``` (setf (fdefinition 'collatz-steps) (memoize #'collatz-steps)) (defun p14 () (let ((mx 0) (my 0)) (loop for x from 1 to 1000000 for y = (collatz-steps x) when (< my y) do (setf my y mx x)) mx)) ```
256,529
<p>I am building a WPF application. Inside that application I am using the XmlReader class to parse several local XML files. The code I have written <strong>works perfectly</strong> during debugging, but fails once I publish the application and install it.</p> <p>I have the XML documents as CONTENT in build action, and I have them set to COPY ALWAYS.I can confirm that the XML documents are being deployed in my build and are in tact in the application folder once installed.</p> <p>What further confuses me is that I am using the same XmlReader code to parse RSS feeds from external websites in this application without problem. It only fails on the local XML documents.</p> <p>Does anyone know why my XmlReader would fail to parse local XML documents once the application is published?</p> <p>Here is a small snippet of my XmlReader code for referance:</p> <pre><code>XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; try { settingsReader = XmlReader.Create("Resources/data/TriviaQuestions.xml", settings); nodeNum = 0; while (settingsReader.Read()) { switch (settingsReader.NodeType) { case XmlNodeType.Element: if (settingsReader.HasAttributes) { for (int i = 0; i &lt; settingsReader.AttributeCount; i++) { settingsReader.MoveToAttribute(i); _feeds[nodeNum] = settingsReader.Value.ToString(); } settingsReader.MoveToContent(); // Moves the reader back to the element node. } break; case XmlNodeType.Text: _questions[nodeNum] = settingsReader.Value; nodeNum++; break; } } settingsReader.Close(); } catch { } </code></pre> <p>Here is my XML</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Questions&gt; &lt;Question feed="http://entertainment.msn.com/rss/topboxoffice/"&gt;What movie has the top box office sales in the US right now?&lt;/Question&gt; &lt;Question feed="http://entertainment.msn.com/rss/topdvdrentals/"&gt;What is the top DVD rental in the US this week?&lt;/Question&gt; &lt;Question feed="http://entertainment.msn.com/rss/topalbums/"&gt;Which of the following albums is currently topping the charts?&lt;/Question&gt; &lt;/Questions&gt; </code></pre>
[ { "answer_id": 256576, "author": "Jeremy Wiebe", "author_id": 11807, "author_profile": "https://Stackoverflow.com/users/11807", "pm_score": 1, "selected": false, "text": "<p>Can you describe \"but fails once I publish the application and install it\" ?</p>\n\n<p>It would be helpful if you could describe what doesn't work, what the error is and provide exception information.</p>\n\n<hr>\n\n<p>Unrelated to your question, I cringe in horror every time I see empty catch blocks in production code!!</p>\n" }, { "answer_id": 258176, "author": "morechilli", "author_id": 5427, "author_profile": "https://Stackoverflow.com/users/5427", "pm_score": 3, "selected": true, "text": "<p>By your publish description I assume you are using clickonce to install the application.</p>\n\n<p>Clickonce has different default behavior for xml files - it assumes they are data files and places them in a different install location from your other files.</p>\n\n<p>Please double check that your xml files really are being installed where you think they are. </p>\n\n<p>In the publish settings you can change the setting for each xml file from data file to include. Your other files will already be set to include.</p>\n\n<p>Note that the publish settings are independent of the build settings for the file.</p>\n" }, { "answer_id": 259635, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 0, "selected": false, "text": "<p>Consider using IsolatedStorage to store your settings rather than in a relative Resources directory. This will give you a known location for different install scenarios (e.g., ClickOnce installs).</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30408/" ]
I am building a WPF application. Inside that application I am using the XmlReader class to parse several local XML files. The code I have written **works perfectly** during debugging, but fails once I publish the application and install it. I have the XML documents as CONTENT in build action, and I have them set to COPY ALWAYS.I can confirm that the XML documents are being deployed in my build and are in tact in the application folder once installed. What further confuses me is that I am using the same XmlReader code to parse RSS feeds from external websites in this application without problem. It only fails on the local XML documents. Does anyone know why my XmlReader would fail to parse local XML documents once the application is published? Here is a small snippet of my XmlReader code for referance: ``` XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; try { settingsReader = XmlReader.Create("Resources/data/TriviaQuestions.xml", settings); nodeNum = 0; while (settingsReader.Read()) { switch (settingsReader.NodeType) { case XmlNodeType.Element: if (settingsReader.HasAttributes) { for (int i = 0; i < settingsReader.AttributeCount; i++) { settingsReader.MoveToAttribute(i); _feeds[nodeNum] = settingsReader.Value.ToString(); } settingsReader.MoveToContent(); // Moves the reader back to the element node. } break; case XmlNodeType.Text: _questions[nodeNum] = settingsReader.Value; nodeNum++; break; } } settingsReader.Close(); } catch { } ``` Here is my XML ``` <?xml version="1.0" encoding="utf-8" ?> <Questions> <Question feed="http://entertainment.msn.com/rss/topboxoffice/">What movie has the top box office sales in the US right now?</Question> <Question feed="http://entertainment.msn.com/rss/topdvdrentals/">What is the top DVD rental in the US this week?</Question> <Question feed="http://entertainment.msn.com/rss/topalbums/">Which of the following albums is currently topping the charts?</Question> </Questions> ```
By your publish description I assume you are using clickonce to install the application. Clickonce has different default behavior for xml files - it assumes they are data files and places them in a different install location from your other files. Please double check that your xml files really are being installed where you think they are. In the publish settings you can change the setting for each xml file from data file to include. Your other files will already be set to include. Note that the publish settings are independent of the build settings for the file.
256,546
<p>Anyone know if there is already a validator for "type" strings?</p> <p>I want to make sure that the type attributes in my custom config are one of the following:</p> <pre> type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly" type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089" </pre> <p>Writing one is easy enough, I just don't want to reinvent the wheel.</p>
[ { "answer_id": 256764, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 0, "selected": false, "text": "<p>You'll get an error with resharper's Global Error Analysis if it can't find the namespace or class, but that's not always helpful if your referencing a plugin.</p>\n\n<p>probably the simpliest thing is to put your code to load the app domain in a try catch block.</p>\n\n<p>if the dll is in the bin it will be loaded on startup but it won't throw an error until you use it so if you just new up an instance of ContainingClass. You could pull the namespaces from the config and then try and use each class.</p>\n" }, { "answer_id": 258944, "author": "jon without an h", "author_id": 27578, "author_profile": "https://Stackoverflow.com/users/27578", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure there is nothing built into the framework for this.</p>\n\n<p>There are a couple of <a href=\"http://regexlib.com/Search.aspx?k=type+name&amp;c=-1&amp;m=-1&amp;ps=20\" rel=\"nofollow noreferrer\">results on regexlib.com</a>. Any of them should work for the scenario you described. However, bear in mind that none of them will properly support the syntax for specifying generic types. In order to properly handle this, a regular expression alone will not be sufficient - you will need to recursively process the same regular expression against the generic type arguments. For example, consider the following type names:</p>\n\n<pre><code>List&lt;&gt;\n\"System.Collections.Generic.List`1\"\n\nList&lt;string&gt;\n\"System.Collections.Generic.List`1[[System.String]]\"\n\nDictionary&lt;string, string&gt;\n\"System.Collections.Generic.Dictionary`2[[System.String],[System.String]]\"\n\nDictionary&lt;string, List&lt;string&gt;&gt;\n\"System.Collections.Generic.Dictionary`2[[System.String],[System.Collections.Generic.List`1[[System.String]]]]\"\n</code></pre>\n\n<p>For more information, see the MSDN documentation on <a href=\"http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx\" rel=\"nofollow noreferrer\">Type.AssemblyQualifiedName</a>.</p>\n" }, { "answer_id": 292768, "author": "Av Pinzur", "author_id": 26222, "author_profile": "https://Stackoverflow.com/users/26222", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what you mean by \"custom config\", but if you're still working within .NET's configuration framework (e.g., developing a custom <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx\" rel=\"nofollow noreferrer\">configurationSection</a>/<a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement.aspx\" rel=\"nofollow noreferrer\">configurationElement</a>), you can simply type the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationpropertyattribute.aspx\" rel=\"nofollow noreferrer\">property</a> as System.Type (instead of string), and .NET will do the validation automatically.</p>\n" }, { "answer_id": 293190, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 0, "selected": false, "text": "<p>Abraham Pinzur's suggestion is correct if you are writing a custom configuration section.</p>\n\n<p><code>Type.GetType(...)</code> allows you to do it by hand.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91911/" ]
Anyone know if there is already a validator for "type" strings? I want to make sure that the type attributes in my custom config are one of the following: ``` type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly" type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089" ``` Writing one is easy enough, I just don't want to reinvent the wheel.
I'm not sure what you mean by "custom config", but if you're still working within .NET's configuration framework (e.g., developing a custom [configurationSection](http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx)/[configurationElement](http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement.aspx)), you can simply type the [property](http://msdn.microsoft.com/en-us/library/system.configuration.configurationpropertyattribute.aspx) as System.Type (instead of string), and .NET will do the validation automatically.
256,554
<p>In particular, I'm editing the AutoCompletion.plist file for CSSEdit (if that even matters).</p> <p>My question is, are there any characters withing the STRING elements that need to be escaped? spaces? quotes?</p> <p>EDIT: Just to be clear, I'm not using CSSEdit to edit the file - rather the file is part of the CSSEdit package. I'm using TextMate to edit the file (although "Property List Editor.app" is another option) and it is in XML format. Here's a snippet from the AutoCompletion.plist file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;font-family&lt;/key&gt; &lt;array&gt; &lt;string&gt;Arial&lt;/string&gt; &lt;string&gt;Helvetica&lt;/string&gt; &lt;string&gt;Georgia&lt;/string&gt; &lt;string&gt;serif&lt;/string&gt; &lt;string&gt;sans-serif&lt;/string&gt; &lt;string&gt;cursive&lt;/string&gt; etc... </code></pre> <p>I'd like to add STRINGs with spaces and single quotes such as:</p> <pre><code>&lt;string&gt;Georgia, Times, 'Times New Roman', serif&lt;/string&gt; </code></pre> <p>But CSSEdit goes haywire when I edit the file as such</p>
[ { "answer_id": 256585, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 0, "selected": false, "text": "<p>There are 3 types of plists, and the escaping rules depend on type you are working with. The most common form are XML plists, which do require certain things to be escaped. In general you can use XML escaping rules within the string elements. If you are working with older NextStep style plists I believe much less needs to be escaped, but I would need to look up the details to be certain of what the rules are. The third type are binary, I am pretty confident you are not editing those with CSSEdit.</p>\n" }, { "answer_id": 257149, "author": "Brian Webster", "author_id": 23324, "author_profile": "https://Stackoverflow.com/users/23324", "pm_score": 5, "selected": true, "text": "<p>If you're editing an XML plist using a text editor of some sort, you'll need to escape characters just like in any XML. The basic characters to watch out for are:</p>\n<p>&lt; (less than), escaped as &amp;lt;</p>\n<p>&gt; (greater than), escaped as &amp;gt;</p>\n<p>&amp; (ampersand), escaped as &amp;amp;</p>\n<p>' (apostrophe), escaped as &amp;apos;</p>\n<p>&quot; (quote mark), escaped as &amp;quot;</p>\n<p>So in your example, you would want</p>\n<p><code>&lt;string&gt;Georgia, Times, &amp;apos;Times New Roman&amp;apos;, serif&lt;/string&gt;</code></p>\n<p>You can also use a tool such as Apple's Property List Editor, which is included with their free <a href=\"http://developer.apple.com/technology/tools.html\" rel=\"nofollow noreferrer\">Xcode developer tools</a>, or a third party product like <a href=\"http://www.fatcatsoftware.com/plisteditpro\" rel=\"nofollow noreferrer\">PlistEdit Pro</a>, both of which will take care of all the character escaping for you.</p>\n" }, { "answer_id": 257185, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 2, "selected": false, "text": "<p>You can use <code>plutil</code> to check the syntax of your plists. (Note that this won't validate whether the application will understand what you've done to its plist...)</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17252/" ]
In particular, I'm editing the AutoCompletion.plist file for CSSEdit (if that even matters). My question is, are there any characters withing the STRING elements that need to be escaped? spaces? quotes? EDIT: Just to be clear, I'm not using CSSEdit to edit the file - rather the file is part of the CSSEdit package. I'm using TextMate to edit the file (although "Property List Editor.app" is another option) and it is in XML format. Here's a snippet from the AutoCompletion.plist file: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>font-family</key> <array> <string>Arial</string> <string>Helvetica</string> <string>Georgia</string> <string>serif</string> <string>sans-serif</string> <string>cursive</string> etc... ``` I'd like to add STRINGs with spaces and single quotes such as: ``` <string>Georgia, Times, 'Times New Roman', serif</string> ``` But CSSEdit goes haywire when I edit the file as such
If you're editing an XML plist using a text editor of some sort, you'll need to escape characters just like in any XML. The basic characters to watch out for are: < (less than), escaped as &lt; > (greater than), escaped as &gt; & (ampersand), escaped as &amp; ' (apostrophe), escaped as &apos; " (quote mark), escaped as &quot; So in your example, you would want `<string>Georgia, Times, &apos;Times New Roman&apos;, serif</string>` You can also use a tool such as Apple's Property List Editor, which is included with their free [Xcode developer tools](http://developer.apple.com/technology/tools.html), or a third party product like [PlistEdit Pro](http://www.fatcatsoftware.com/plisteditpro), both of which will take care of all the character escaping for you.
256,557
<p>One of the things that seems to be necessary with use of STL is a way to specify local functions. Many of the functions that I would normally provide cannot be created using STL function object creation tools ( eg bind ), I have to hand roll my function object.</p> <p>Since the C++ standard forbids local types to be used as arguments in template instantiations the best I was able to use was to create a small library, ( just showing relevant parts )</p> <pre><code>// library header class MyFunctionBase&lt;R,T&gt; { public: virtual ~MyFunctionBase(); virtual R operator()(const T &amp;) const=0; }; class MyFunction&lt;R,T&gt; { MyFunctionBase&lt;R,T&gt; *b; public: ~MyFunction() { delete b; } virtual R operator()(const T &amp;) const { return (*b)(T); } }; // source file .... class func: public MyFunctionBase ... std::stl_alg(.... MyFunction(new funct)); </code></pre> <p>This has always seemed unwieldly to me. I guess to the people on the ISO committee believe so too and added a lambda to C++.</p> <p>In the meantime how have compilers addressed this problem? ( Especially Windows compilers. )</p> <p>A correction which might clarify a bit. Changelog: Nov 2 replaced to clarify Since the C++ standard forbids local classes as function objects</p>
[ { "answer_id": 256567, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "<p>The standard way is a \"functor\" - basically, a <code>struct</code> that supplies an <code>operator()</code></p>\n\n<p>For example:</p>\n\n<pre><code>struct MyMinFunctor {\n bool operator()(const int&amp; a, const int&amp; b) { return a &gt; b; }\n};\n\nvector&lt;int&gt; v;\nsort(v.begin(), v.end(), MyMinFunctor());\n</code></pre>\n\n<p>Because it is a struct/class, you can subclass any of the things like 'binary_operator' as well as maintain state for more advanced functors.</p>\n" }, { "answer_id": 257299, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "<p>With C++0x you can use lambda's (as you mentioned):</p>\n\n<pre><code>for_each(container.begin(), container.end(),\n [](auto item) {\n // do something with item\n }\n );\n</code></pre>\n\n<p>This is already available in MS Visual C++ 2010 (currently in Community Tech Preview) and GCC 4.3.x (with the -std=c++0x compiler flag). However, without lambda's, you just need to provide a type that:</p>\n\n<ol>\n<li>Is default constructible</li>\n<li>Is copy constructible</li>\n<li>Defines a function operator overload</li>\n</ol>\n\n<p>There are some algorithms that require binary function objects while there are some that require unary function objects. Refer your vendor's STL documentation to find out exactly which algorithms require binary function objects and which ones require unary function objects.</p>\n\n<p>One thing you might also want to look into are the newer implementations of <code>bind</code> and <code>function</code> in TR1 (based on Boost.Bind and Boost.Function).</p>\n" }, { "answer_id": 257326, "author": "user21714", "author_id": 21714, "author_profile": "https://Stackoverflow.com/users/21714", "pm_score": 2, "selected": true, "text": "<p>Boost.Bind, Boost.Function, and Boost.Lambda are your friends.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29178/" ]
One of the things that seems to be necessary with use of STL is a way to specify local functions. Many of the functions that I would normally provide cannot be created using STL function object creation tools ( eg bind ), I have to hand roll my function object. Since the C++ standard forbids local types to be used as arguments in template instantiations the best I was able to use was to create a small library, ( just showing relevant parts ) ``` // library header class MyFunctionBase<R,T> { public: virtual ~MyFunctionBase(); virtual R operator()(const T &) const=0; }; class MyFunction<R,T> { MyFunctionBase<R,T> *b; public: ~MyFunction() { delete b; } virtual R operator()(const T &) const { return (*b)(T); } }; // source file .... class func: public MyFunctionBase ... std::stl_alg(.... MyFunction(new funct)); ``` This has always seemed unwieldly to me. I guess to the people on the ISO committee believe so too and added a lambda to C++. In the meantime how have compilers addressed this problem? ( Especially Windows compilers. ) A correction which might clarify a bit. Changelog: Nov 2 replaced to clarify Since the C++ standard forbids local classes as function objects
Boost.Bind, Boost.Function, and Boost.Lambda are your friends.
256,564
<p>I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (<a href="http://twitpic.com/api.do" rel="nofollow noreferrer">http://twitpic.com/api.do</a>). For reference purposes, check out the code (<a href="http://pastebin.com/f4c498b6e" rel="nofollow noreferrer">http://pastebin.com/f4c498b6e</a>) and the error I'm getting (<a href="http://pastebin.com/mff11d31" rel="nofollow noreferrer">http://pastebin.com/mff11d31</a>).</p> <p>Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!).</p> <p>After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.</p>
[ { "answer_id": 256610, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://pycurl.sourceforge.net/doc/curlobject.html\" rel=\"nofollow noreferrer\">The pycurl doc</a> explicitly says:</p>\n\n<blockquote>\n <p>perform() -> None</p>\n</blockquote>\n\n<p>So the expected result is what you observe.</p>\n\n<p>looking at an example from the pycurl site:</p>\n\n<pre><code>import sys\nimport pycurl\n\nclass Test:\n def __init__(self):\n self.contents = ''\n\n def body_callback(self, buf):\n self.contents = self.contents + buf\n\nprint &gt;&gt;sys.stderr, 'Testing', pycurl.version\n\nt = Test()\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://curl.haxx.se/dev/')\nc.setopt(c.WRITEFUNCTION, t.body_callback)\nc.perform()\nc.close()\n\nprint t.contents\n</code></pre>\n\n<p>The interface requires a class instance - <code>Test()</code> - with a specific callback to save the content. Note the call <code>c.setopt(c.WRITEFUNCTION, t.body_callback)</code> - something like this is missing in your code, so you do not receive any data (<code>buf</code> in the example). The example shows how to access the content:</p>\n\n<pre><code>print t.contents\n</code></pre>\n" }, { "answer_id": 2351363, "author": "Alon Swartz", "author_id": 283106, "author_profile": "https://Stackoverflow.com/users/283106", "pm_score": 4, "selected": false, "text": "<p>Using a StringIO would be much cleaner, no point in using a dummy class like that if all you want is the response data...</p>\n\n<p>Something like this would suffice:</p>\n\n<pre><code>import pycurl\nimport cStringIO\n\nresponse = cStringIO.StringIO()\n\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://www.turnkeylinux.org')\nc.setopt(c.WRITEFUNCTION, response.write)\nc.perform()\nc.close()\n\nprint response.getvalue()\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33383/" ]
I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (<http://twitpic.com/api.do>). For reference purposes, check out the code (<http://pastebin.com/f4c498b6e>) and the error I'm getting (<http://pastebin.com/mff11d31>). Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!). After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.
[The pycurl doc](http://pycurl.sourceforge.net/doc/curlobject.html) explicitly says: > > perform() -> None > > > So the expected result is what you observe. looking at an example from the pycurl site: ``` import sys import pycurl class Test: def __init__(self): self.contents = '' def body_callback(self, buf): self.contents = self.contents + buf print >>sys.stderr, 'Testing', pycurl.version t = Test() c = pycurl.Curl() c.setopt(c.URL, 'http://curl.haxx.se/dev/') c.setopt(c.WRITEFUNCTION, t.body_callback) c.perform() c.close() print t.contents ``` The interface requires a class instance - `Test()` - with a specific callback to save the content. Note the call `c.setopt(c.WRITEFUNCTION, t.body_callback)` - something like this is missing in your code, so you do not receive any data (`buf` in the example). The example shows how to access the content: ``` print t.contents ```
256,566
<p>I'm trying to create a function in C# which will allow me to, when called, return a reference to a given class type. The only types of functions like this that I have seen are in UnrealScript and even then the functionality is hard coded into its compiler. I'm wondering if I can do this in C#. Here's what I mean (code snippet from UnrealScript source):</p> <pre><code>native(278) final function actor Spawn ( class&lt;actor&gt; SpawnClass, optional actor SpawnOwner, optional name SpawnTag, optional vector SpawnLocation, optional rotator SpawnRotation ); </code></pre> <p>Now in UScript you would call it like this...</p> <pre><code>local ActorChild myChildRef; //Ref to ActorChild which Extends 'actor' myChildRef = Spawn(class'ActorChild' ...); //rest of parameters taken out myChildRef.ChildMethod(); //method call to method existing inside class 'ActorChild' </code></pre> <p>Which will return a reference to an object of class 'ActorChild' and set it to variable 'myChildRef.' I need to do something similar within C#.</p> <p>I've looked into Generics but it seems that to use them, I need create an instace of the class where my function lies and pass the 'generic' parameter to it. This isn't very desirable however as I won't need to use the 'Spawn' function for certain classes but I would still need to add the generic parameter to the class whenever I use it.</p> <p>I guess a simplified question would be, how can I return a type that I do not know at compile time and when the different classes could be far too many to trap.</p> <p>Pseudo-Code (sticking to UScript class names, i.e. Actor):</p> <pre><code>//Function Sig public class&lt;Actor&gt; Create(class&lt;Actor&gt; CreatedClass) { return new CreatedClass; } //Function call ActorChild myChild = Create(class'ActorChild'); </code></pre> <p>Any ideas?</p> <p>EDIT: I would like to avoid explicit typecasts that would occur from the class calling Created. If I can typecast to the desired object within the Created method and return the 'unknown type' whatever that may be, I would be extremely happy.</p> <p>EDIT 2: Thanks for your answers.</p>
[ { "answer_id": 256586, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 0, "selected": false, "text": "<p>You can use the class System.Type to represent classes. To get references to type objects, you either use typeof (in a scope where the class is actually defined)</p>\n\n<pre><code>System.Type t = typeof(ActorChild);\n</code></pre>\n\n<p>or the Type.GetType function (if you only know the name of the type)</p>\n\n<pre><code>System.Type t = Type.GetType(\"NamespaceFoo.ActorChild\");\n</code></pre>\n\n<p>You can then use the reflection API to create an instance</p>\n\n<pre><code>public object Create(System.Type ClassToCreate)\n{\n return ClassToCreate.GetConstructor(Type.EmptyTypes).Invoke(null);\n}\n</code></pre>\n" }, { "answer_id": 256633, "author": "Alon L", "author_id": 30884, "author_profile": "https://Stackoverflow.com/users/30884", "pm_score": 0, "selected": false, "text": "<p>What you're trying to accomplish can be done quite easily with Reflection and something called Dynamic Method Invocation.</p>\n\n<p>Basically, you'll be using the Type object, the Activator.CreateInstance Method and some other nice classes like MethodInfo and ParameterInfo.</p>\n\n<p>Here's an example to get you started:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace Reflection\n{\n class SomeClass\n {\n private string StringPrimer = \"The parameter text is: \";\n public SomeClass(string text)\n {\n Console.WriteLine(StringPrimer + text);\n }\n public string getPrimer() //supplies the Primer in upper case, just for kicks\n {\n return StringPrimer.ToUpper();\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n SomeClass s = new SomeClass(\"this is an example of the classes normal hard-coded function.\\nNow try feeding in some text\");\n string t = Console.ReadLine();\n\n Console.WriteLine(\"Now feed in the class name (SomeClass in this case)\");\n Type myType = Type.GetType(\"Reflection.\"+Console.ReadLine()); //Stores info about the class.\n object myClass = Activator.CreateInstance(myType, new object[] { t }); //This dynamically calls SomeClass and sends in the text you enter as a parameter\n\n //Now lets get the string primer, using the getPrimer function, dynamically\n string primer = (string)myType.InvokeMember(\"getPrimer\",\n BindingFlags.InvokeMethod | BindingFlags.Default,\n null,\n myClass,\n null); //This method takes the name of the method, some Binding flags,\n //a binder object that I left null,\n //the object that the method will be called from (would have been null if the method was static)\n //and an object array of parameters, just like in the CreateInstance method.\n Console.WriteLine(primer);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 256636, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": true, "text": "<p>Rather than use a generic <em>class</em>, use a generic <em>method</em>:</p>\n\n<pre><code>public T Spawn&lt;T&gt;() where T : new()\n{\n return new T();\n}\n</code></pre>\n\n<p>Having said that, I assume you want to do more than just blindly create an instance, otherwise you could just call <code>new MyClass()</code> yourself.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to create a function in C# which will allow me to, when called, return a reference to a given class type. The only types of functions like this that I have seen are in UnrealScript and even then the functionality is hard coded into its compiler. I'm wondering if I can do this in C#. Here's what I mean (code snippet from UnrealScript source): ``` native(278) final function actor Spawn ( class<actor> SpawnClass, optional actor SpawnOwner, optional name SpawnTag, optional vector SpawnLocation, optional rotator SpawnRotation ); ``` Now in UScript you would call it like this... ``` local ActorChild myChildRef; //Ref to ActorChild which Extends 'actor' myChildRef = Spawn(class'ActorChild' ...); //rest of parameters taken out myChildRef.ChildMethod(); //method call to method existing inside class 'ActorChild' ``` Which will return a reference to an object of class 'ActorChild' and set it to variable 'myChildRef.' I need to do something similar within C#. I've looked into Generics but it seems that to use them, I need create an instace of the class where my function lies and pass the 'generic' parameter to it. This isn't very desirable however as I won't need to use the 'Spawn' function for certain classes but I would still need to add the generic parameter to the class whenever I use it. I guess a simplified question would be, how can I return a type that I do not know at compile time and when the different classes could be far too many to trap. Pseudo-Code (sticking to UScript class names, i.e. Actor): ``` //Function Sig public class<Actor> Create(class<Actor> CreatedClass) { return new CreatedClass; } //Function call ActorChild myChild = Create(class'ActorChild'); ``` Any ideas? EDIT: I would like to avoid explicit typecasts that would occur from the class calling Created. If I can typecast to the desired object within the Created method and return the 'unknown type' whatever that may be, I would be extremely happy. EDIT 2: Thanks for your answers.
Rather than use a generic *class*, use a generic *method*: ``` public T Spawn<T>() where T : new() { return new T(); } ``` Having said that, I assume you want to do more than just blindly create an instance, otherwise you could just call `new MyClass()` yourself.
256,625
<p>I have seen samples of closure from - <a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a &#39;Closure&#39;?</a></p> <p>Can anyone provide simple example of when to use closure?<br></p> <p><b>Specifically, scenarios in which closure makes sense?</b><Br></p> <p>Lets assume that the language doesn't have closure support, how would one still achieve similar thing?</p> <p>Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. <br>I am sorry, I do not understand functional languages yet.</p>
[ { "answer_id": 256630, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 4, "selected": false, "text": "<p>Typically, if one doesn't have closures, one must define a class to carry with it the equivalent of the closure's environment, and pass it around.</p>\n\n<p>For example, in a language like Lisp, one can define a function that returns a function (with a closed-over environment) to add some predefined amount to its argument thusly:</p>\n\n<pre><code>(defun make-adder (how-much)\n (lambda (x)\n (+ x how-much)))\n</code></pre>\n\n<p>and use it like this:</p>\n\n<pre><code>cl-user(2): (make-adder 5)\n#&lt;Interpreted Closure (:internal make-adder) @ #x10009ef272&gt;\ncl-user(3): (funcall * 3) ; calls the function you just made with the argument '3'.\n8\n</code></pre>\n\n<p>In a language without closures, you would do something like this:</p>\n\n<pre><code>public class Adder {\n private int howMuch;\n\n public Adder(int h) {\n howMuch = h;\n }\n\n public int doAdd(int x) {\n return x + howMuch;\n }\n}\n</code></pre>\n\n<p>and then use it like this:</p>\n\n<pre><code>Adder addFive = new Adder(5);\nint addedFive = addFive.doAdd(3);\n// addedFive is now 8.\n</code></pre>\n\n<p>The closure implicitly carries its environment with it; you seamlessly refer to that environment from inside the executing part (the lambda). Without closures you must make that environment explicit.</p>\n\n<p>That should explain to you when you would use closures: <em>all the time</em>. Most instances where a class is instantiated to carry with it some state from another part of the computation and apply it elsewhere are elegantly replaced by closures in languages which support them.</p>\n\n<p>One can implement an object system with closures.</p>\n" }, { "answer_id": 256643, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 1, "selected": false, "text": "<p>In Lua and Python it's a very natural thing to do when \"just coding\", because the moment you reference something that's not a parameter, you're making a closure. (so most of these will be quite dull as examples.)</p>\n\n<p>As for a concrete case, imagine an undo/redo system, where the steps are pairs of (undo(), redo()) closures. The more cumbersome ways of doing that might be to either: (a) Make unredoable classes have a special method with universally dorky arguments, or (b) subclass UnReDoOperation umpteen times.</p>\n\n<p>Another concrete example is infinite lists: Instead of working with genericized containers, you frob a function that retrieves the next element. (this is part of the power of iterators.) In this case you can either keep just little bit of state (the next integer, for the list-of-all-nonnegative-integers or similar) or a reference to a position in an actual container. Either way, it's a function that references something that is outside itself. (in the infinite-list case, the state variables must be closure variables, because otherwise they'd be clean for every call)</p>\n" }, { "answer_id": 256651, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 5, "selected": false, "text": "<p>I agree with a previous answer of \"all the time\". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking \"what is the scenario for a function?\" or \"what is the scenario for a loop?\" This isn't to make the original question sound dumb, rather it's to point out that there are constructs in languages that you don't define in terms of specific scenarios. You just use them all the time, for everything, it's second nature.</p>\n\n<p>This is somehow reminiscent of:</p>\n\n<blockquote>\n <p>The venerable master Qc Na was walking\n with his student, Anton. Hoping to\n prompt the master into a discussion,\n Anton said \"Master, I have heard that\n objects are a very good thing - is\n this true?\" Qc Na looked pityingly at\n his student and replied, \"Foolish\n pupil - objects are merely a poor\n man's closures.\" </p>\n \n <p>Chastised, Anton took his leave from\n his master and returned to his cell,\n intent on studying closures. He\n carefully read the entire \"Lambda: The\n Ultimate...\" series of papers and its\n cousins, and implemented a small\n Scheme interpreter with a\n closure-based object system. He\n learned much, and looked forward to\n informing his master of his progress.</p>\n \n <p>On his next walk with Qc Na, Anton\n attempted to impress his master by\n saying \"Master, I have diligently\n studied the matter, and now understand\n that objects are truly a poor man's\n closures.\" Qc Na responded by hitting\n Anton with his stick, saying \"When\n will you learn? Closures are a poor\n man's object.\" At that moment, Anton\n became enlightened.</p>\n</blockquote>\n\n<p>(<a href=\"http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html\" rel=\"noreferrer\">http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html</a>)</p>\n" }, { "answer_id": 256663, "author": "zvoase", "author_id": 31600, "author_profile": "https://Stackoverflow.com/users/31600", "pm_score": 4, "selected": false, "text": "<p>The most simple example of using closures is in something called currying. Basically, let's assume we have a function <code>f()</code> which, when called with two arguments <code>a</code> and <code>b</code>, adds them together. So, in Python, we have:</p>\n\n<pre><code>def f(a, b):\n return a + b\n</code></pre>\n\n<p>But let's say, for the sake of argument, that we only want to call <code>f()</code> with one argument at a time. So, instead of <code>f(2, 3)</code>, we want <code>f(2)(3)</code>. This can be done like so:</p>\n\n<pre><code>def f(a):\n def g(b): # Function-within-a-function\n return a + b # The value of a is present in the scope of g()\n return g # f() returns a one-argument function g()\n</code></pre>\n\n<p>Now, when we call <code>f(2)</code>, we get a new function, <code>g()</code>; this new function carries with it variables from the <em>scope</em> of <code>f()</code>, and so it is said to <em>close over</em> those variables, hence the term closure. When we call <code>g(3)</code>, the variable <code>a</code> (which is bound by the definition of <code>f</code>) is accessed by <code>g()</code>, returning <code>2 + 3 =&gt; 5</code></p>\n\n<p>This is useful in several scenarios. For example, if I had a function which accepted a large number of arguments, but only a few of them were useful to me, I could write a generic function like so:</p>\n\n<pre><code>def many_arguments(a, b, c, d, e, f, g, h, i):\n return # SOMETHING\n\ndef curry(function, **curry_args):\n # call is a closure which closes over the environment of curry.\n def call(*call_args):\n # Call the function with both the curry args and the call args, returning\n # the result.\n return function(*call_args, **curry_args)\n # Return the closure.\n return call\n\nuseful_function = curry(many_arguments, a=1, b=2, c=3, d=4, e=5, f=6)\n</code></pre>\n\n<p><code>useful_function</code> is now a function which only needs 3 arguments, instead of 9. I avoid having to repeat myself, and also have created a <em>generic</em> solution; if I write another many-argument function, I can use the <code>curry</code> tool again.</p>\n" }, { "answer_id": 256666, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do:</p>\n\n<pre><code>string name = // blah\nint value = // blah\nnew Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short\n</code></pre>\n\n<p>Compare that to creating a class with a name and value</p>\n\n<p>Or likewise with searching for a list (using a lambda this time):</p>\n\n<pre><code>Person person = list.Find(x=&gt;x.Age &gt; minAge &amp;&amp; x.Region == region);\n</code></pre>\n\n<p>Again - the alternative would be to write a class with two properties and a method:</p>\n\n<pre><code>internal sealed class PersonFinder\n{\n public PersonFinder(int minAge, string region)\n {\n this.minAge = minAge;\n this.region = region;\n }\n private readonly int minAge;\n private readonly string region;\n public bool IsMatch(Person person)\n {\n return person.Age &gt; minAge &amp;&amp; person.Region == region;\n }\n}\n...\nPerson person = list.Find(new PersonFinder(minAge,region).IsMatch);\n</code></pre>\n\n<p>This is <em>fairly</em> comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).</p>\n\n<p>The biggest caveat with C# captures is to watch the scope; for example:</p>\n\n<pre><code> for(int i = 0 ; i &lt; 10 ; i++) {\n ThreadPool.QueueUserWorkItem(delegate\n {\n Console.WriteLine(i);\n });\n }\n</code></pre>\n\n<p>This might not print what you expect, since the <em>variable</em> i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#:</p>\n\n<pre><code> for(int i = 0 ; i &lt; 10 ; i++) {\n int j = i;\n ThreadPool.QueueUserWorkItem(delegate\n {\n Console.WriteLine(j);\n });\n }\n</code></pre>\n\n<p>Here each j gets captured separately (i.e. a different compiler-generated class instance).</p>\n\n<p>Jon Skeet has a good blog entry covering C# and java closures <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/05/06/the-beauty-of-closures.aspx\" rel=\"noreferrer\">here</a>; or for more detail, see his book <a href=\"http://www.manning.com/skeet/\" rel=\"noreferrer\">C# in Depth</a>, which has an entire chapter on them.</p>\n" }, { "answer_id": 256682, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "<p>Here is an example from Python's standard library, inspect.py. It currently reads</p>\n\n<pre><code>def strseq(object, convert, join=joinseq):\n \"\"\"Recursively walk a sequence, stringifying each element.\"\"\"\n if type(object) in (list, tuple):\n return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))\n else:\n return convert(object)\n</code></pre>\n\n<p>This has, as parameters, a convert function and a join function, and recursively walks over lists and tuples. The recursion is implemented using map(), where the first parameter is a function. The code predates the support for closures in Python, so needs two additional default arguments, to pass convert and join into the recursive call. With closures, this reads</p>\n\n<pre><code>def strseq(object, convert, join=joinseq):\n \"\"\"Recursively walk a sequence, stringifying each element.\"\"\"\n if type(object) in (list, tuple):\n return join(map(lambda o: strseq(o, convert, join), object))\n else:\n return convert(object)\n</code></pre>\n\n<p>In OO languages, you typically don't use closures too often, as you can use objects to pass state - and bound methods, when your language has them. When Python didn't have closures, people said that Python emulates closures with objects, whereas Lisp emulates objects with closures. As an example from IDLE (ClassBrowser.py):</p>\n\n<pre><code>class ClassBrowser: # shortened\n def close(self, event=None):\n self.top.destroy()\n self.node.destroy()\n def init(self, flist):\n top.bind(\"&lt;Escape&gt;\", self.close)\n</code></pre>\n\n<p>Here, self.close is a parameter-less callback invoked when Escape is pressed. However, the close implementation does need parameters - namely self, and then self.top, self.node. If Python didn't have bound methods, you could write</p>\n\n<pre><code>class ClassBrowser:\n def close(self, event=None):\n self.top.destroy()\n self.node.destroy()\n def init(self, flist):\n top.bind(\"&lt;Escape&gt;\", lambda:self.close())\n</code></pre>\n\n<p>Here, the lambda would get \"self\" not from a parameter, but from the context.</p>\n" }, { "answer_id": 5423705, "author": "stu", "author_id": 12386, "author_profile": "https://Stackoverflow.com/users/12386", "pm_score": 1, "selected": false, "text": "<p>I'm told there are more uses in haskell, but I've only had the pleasure of using closures in javascript, and in javascript I don't much see the point. My first instinct was to scream \"oh no, not again\" at what a mess the implementation must be to make closures work. \nAfter I read about how closures were implemented (in javascript anyway), it doesn't seem quite so bad to me now and the implementation seems somewhat elegant, to me at least.</p>\n\n<p>But from that I realized \"closure\" isn't really the best word to describe the concept. I think it should better be named \"flying scope.\"</p>\n" }, { "answer_id": 19550098, "author": "BitMask777", "author_id": 509891, "author_profile": "https://Stackoverflow.com/users/509891", "pm_score": 1, "selected": false, "text": "<p>As one of the previous answers notes, you often find yourself using them without hardly noticing that you are.</p>\n\n<p>A case in point is that they are very commonly used in setting up UI event handling to gain code reuse while still allowing access to the UI context. Here's an example of how defining an anonymous handler function for a click event creates a closure that includes the <code>button</code> and <code>color</code> parameters of the <code>setColor()</code> function:</p>\n\n<pre><code>function setColor(button, color) {\n\n button.addEventListener(\"click\", function()\n {\n button.style.backgroundColor = color;\n }, false);\n}\n\nwindow.onload = function() {\n setColor(document.getElementById(\"StartButton\"), \"green\");\n setColor(document.getElementById(\"StopButton\"), \"red\");\n}\n</code></pre>\n\n<p>Note: for accuracy it's worth noting that the closure is not actually created until the <code>setColor()</code> function exits.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23574/" ]
I have seen samples of closure from - [What is a 'Closure'?](https://stackoverflow.com/questions/36636/what-is-a-closure) Can anyone provide simple example of when to use closure? **Specifically, scenarios in which closure makes sense?** Lets assume that the language doesn't have closure support, how would one still achieve similar thing? Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. I am sorry, I do not understand functional languages yet.
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do: ``` string name = // blah int value = // blah new Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short ``` Compare that to creating a class with a name and value Or likewise with searching for a list (using a lambda this time): ``` Person person = list.Find(x=>x.Age > minAge && x.Region == region); ``` Again - the alternative would be to write a class with two properties and a method: ``` internal sealed class PersonFinder { public PersonFinder(int minAge, string region) { this.minAge = minAge; this.region = region; } private readonly int minAge; private readonly string region; public bool IsMatch(Person person) { return person.Age > minAge && person.Region == region; } } ... Person person = list.Find(new PersonFinder(minAge,region).IsMatch); ``` This is *fairly* comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly). The biggest caveat with C# captures is to watch the scope; for example: ``` for(int i = 0 ; i < 10 ; i++) { ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(i); }); } ``` This might not print what you expect, since the *variable* i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#: ``` for(int i = 0 ; i < 10 ; i++) { int j = i; ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(j); }); } ``` Here each j gets captured separately (i.e. a different compiler-generated class instance). Jon Skeet has a good blog entry covering C# and java closures [here](http://msmvps.com/blogs/jon_skeet/archive/2008/05/06/the-beauty-of-closures.aspx); or for more detail, see his book [C# in Depth](http://www.manning.com/skeet/), which has an entire chapter on them.
256,628
<p>I'm trying to set up a loop where an animation runs a certain number of times, and a function is run before each iteration of the animation. The timing ends up being off, though -- it runs the callback n times, then runs the animation n times. For example:</p> <pre><code>for (var i=0;i&lt;3;i++) { console.log(i); $('#blerg').animate({top:'+=50px'},75,'linear', function(){log('animated')}); } </code></pre> <p>outputs</p> <pre><code>0 1 2 animated animated animated </code></pre> <p>I ran into this problem with scriptaculous before I switched to jquery, and discovered a "beforeSetup" animation callback. Is there a jquery equivalent?</p>
[ { "answer_id": 256645, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 2, "selected": false, "text": "<p>The animation is asynchronous. So the loops runs through pretty quickly, starting off three animations and outputting 1, 2 and 3. After a while the animations complete and output animated x 3. That would explain your output. </p>\n\n<p>How about some recursion?</p>\n\n<pre><code>do_animation(max_runs, total_runs) {\n log();\n if (total_runs &lt; max_runs) {\n $(foo).animate(..., do_animation(max_runs, ++total_runs));\n }\n}\n</code></pre>\n\n<p>do_animation(3, 0);</p>\n\n<p>Give that a try and let me know how it runs.</p>\n" }, { "answer_id": 256688, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>You could also try utilising the Queue function.</p>\n\n<p><a href=\"http://docs.jquery.com/Effects/queue#callback\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Effects/queue#callback</a></p>\n\n<p>Internally I recall animate uses the same execution queue, so this should work in theory ( untested ).</p>\n\n<pre><code>/* Safe Namespace + Onload : I do this everywhere */\njQuery(function($){ \n /* Calling this once instead of many times will save \n a lot of wasted calls to document.getElementById + processing garbage \n */\n var blerg = $('#blerg');\n var addStep = function( i )\n {\n blerg.queue(function(){ \n console.log(i);\n $(this).dequeue();\n }); \n blerg.animate({top:'+=50px'},75,'linear'); \n /* In theory, this works like the callback does */\n blerg.queue(function(){\n log('animated');\n $(this).dequeue();\n });\n };\n\n for (var i=0;i&lt;3;i++) \n {\n /* I call a function here, because that way you don't need to worry \n about the fact 'i' will reference the last value of 'i' when the code \n gets around to executing. */\n addStep(i); \n }\n});\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Kent, I don't quite understand why you need to explicitly put the callback in the \n queue. Not that you're wrong -- it doesn't work if the callback is an argument to \n animate() -- but I'm just curious. </p>\n</blockquote>\n\n<p>Its not necessary for the second case, but I thought it made for more consistent and somewhat neater code if one was going to endeavor to do more things in the callback phase ( for instance, another animation ). </p>\n\n<p>Then you would just put the next animate call after the second blerg.queue, </p>\n\n<p>Not to mention it has the added benefit of creating a bit of programmatic nicety in that the entire execution sequence is defined before it needs to be run, making the execution largely linear. </p>\n\n<p>So this makes the code still \"how you think it works\" and makes it still run \"how you need it to work\" without needing to worry about the whole asynchronicity of it all. ( Which makes for less buggy and more maintainable code )</p>\n" }, { "answer_id": 256707, "author": "Altay", "author_id": 33391, "author_profile": "https://Stackoverflow.com/users/33391", "pm_score": 0, "selected": false, "text": "<p>Both of those solutions worked like a charm! Thanks, MDCore and Kent!</p>\n\n<p>Kent, I don't quite understand why you need to explicitly put the callback in the queue. Not that you're wrong -- it doesn't work if the callback is an argument to animate() -- but I'm just curious. </p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33391/" ]
I'm trying to set up a loop where an animation runs a certain number of times, and a function is run before each iteration of the animation. The timing ends up being off, though -- it runs the callback n times, then runs the animation n times. For example: ``` for (var i=0;i<3;i++) { console.log(i); $('#blerg').animate({top:'+=50px'},75,'linear', function(){log('animated')}); } ``` outputs ``` 0 1 2 animated animated animated ``` I ran into this problem with scriptaculous before I switched to jquery, and discovered a "beforeSetup" animation callback. Is there a jquery equivalent?
The animation is asynchronous. So the loops runs through pretty quickly, starting off three animations and outputting 1, 2 and 3. After a while the animations complete and output animated x 3. That would explain your output. How about some recursion? ``` do_animation(max_runs, total_runs) { log(); if (total_runs < max_runs) { $(foo).animate(..., do_animation(max_runs, ++total_runs)); } } ``` do\_animation(3, 0); Give that a try and let me know how it runs.
256,634
<p>I have a problem. I am coding using VS2008. I am calling webservices from my JavaScript Page. An example</p> <pre><code>Services.ChangeDropDownLists.GetNowPlayingMoviesByLocationSVC( blah, OnSuccessMoviesByRegion, OnError, OnTimeOut ); </code></pre> <p>after execution, it goes to the function <code>OnSuccessMoviesByRegion</code>.</p> <p>But if I put the Services in a loop (a simple for loop)</p> <pre><code>Services.ChangeDropDownLists.GetNowPlayingMoviesByLocationSVC( blah[i], OnSuccessMoviesByRegion, OnError, OnTimeOut ); </code></pre> <p><code>OnSucessMoviesByRegion</code> function won't execute (but the service call executes n times successfully But I must have the function cos I am returning value through it.</p> <p>What am I missing? Is that the typical behaviour? Any alternatives?</p>
[ { "answer_id": 256632, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": true, "text": "<p>I would write it in <a href=\"http://www.antlr.org/\" rel=\"noreferrer\">ANTLR</a>. Write the grammar, let ANTLR generate a C# parser. You can ANTLR ask for a parse tree, and possibly the interpreter can already operate on the parse tree. Perhaps you'll have to convert the parse tree to some more abstract internal representation (although ANTLR already allows to leave out irrelevant punctuation when generating the tree).</p>\n" }, { "answer_id": 256635, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It might sound odd, but Game Scripting Mastery is a great resource for learning about parsing, compiling and interpreting code.</p>\n\n<p>You should really check it out:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1931841578\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Scripting-Mastery-Premier-Press-Development/dp/1931841578</a></p>\n" }, { "answer_id": 261065, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 2, "selected": false, "text": "<p>One way to do it is to examine the source code for an existing interpreter. I've written a javascript interpreter in the D programming language, you can download the source code from <a href=\"http://ftp.digitalmars.com/dmdscript.zip\" rel=\"nofollow noreferrer\">http://ftp.digitalmars.com/dmdscript.zip</a></p>\n\n<p>Walter Bright, Digital Mars</p>\n" }, { "answer_id": 261074, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>I'd recommend leveraging the DLR to do this, as this is exactly what it is designed for.</p>\n\n<p><a href=\"http://www.dotnetguru.org/us/dlrus/DLR2.htm\" rel=\"nofollow noreferrer\">Create Your Own Language ontop of the DLR</a></p>\n" }, { "answer_id": 261085, "author": "Daniel Plaisted", "author_id": 1509, "author_profile": "https://Stackoverflow.com/users/1509", "pm_score": 1, "selected": false, "text": "<p>Have you considered using <a href=\"http://www.codeplex.com/IronPython\" rel=\"nofollow noreferrer\">IronPython</a>? It's easy to use from .NET and it seems to meet all your requirements. I understand that python is fairly popular for scientific programming, so it's possible your users will already be familiar with it.</p>\n" }, { "answer_id": 362051, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.lua.org/\" rel=\"nofollow noreferrer\">Lua</a> was designed as an extensible interpreter for use by non-programmers. (The first users were Brazilian petroleum geologists although the <a href=\"http://www.wowprogramming.com/\" rel=\"nofollow noreferrer\">user base has broadened considerably</a> since then.) You can take Lua and easily add your scientific algorithms, visualizations, what have you. It's superbly well engineered and you can get on with the task at hand.</p>\n\n<p>Of course, if what you really want is the fun of building your own, then the other advice is reasonable.</p>\n" }, { "answer_id": 10762659, "author": "John F. Miller", "author_id": 163177, "author_profile": "https://Stackoverflow.com/users/163177", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The programming language that this interpreter will use should be simple, since it is targeting non- software developers.</p>\n</blockquote>\n\n<p>I'm going to chime in on this part of your question. A simple language is not what you really want to hand to non-software developers. Stripped down languages require more effort by the programmer. What you really want id a well designed and well implemented Domain Specific Language (DSL).</p>\n\n<p>In this sense I will second what Norman Ramsey recommends with Lua. It has an excellent reputation as a base for high quality DSLs. A well documented and useful DSL takes time and effort, but will save everyone time in the long run when domain experts can be brought up to speed quickly and require minimal support.</p>\n" }, { "answer_id": 44052941, "author": "Mann", "author_id": 2350203, "author_profile": "https://Stackoverflow.com/users/2350203", "pm_score": 0, "selected": false, "text": "<p>I am surprised no one has mentioned <a href=\"https://en.wikipedia.org/wiki/Xtext\" rel=\"nofollow noreferrer\">xtext</a> yet. It is available as <a href=\"https://eclipse.org/Xtext/index.html\" rel=\"nofollow noreferrer\">Eclipse plugin</a> and <a href=\"https://plugins.jetbrains.com/plugin/8074-xtext\" rel=\"nofollow noreferrer\">IntelliJ plugin</a>. It provides not just the parser like ANTLR but the whole pipeline (including parser, linker, typechecker, compiler) needed for a DSL. You can check it's source code on Github for understanding how, an interpreter/compiler works.</p>\n" }, { "answer_id": 56350813, "author": "Jonathan Wood", "author_id": 522663, "author_profile": "https://Stackoverflow.com/users/522663", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://github.com/SoftCircuits/Silk\" rel=\"nofollow noreferrer\">Silk</a> library has just been published to GitHub. It seems to do most of what you are asking. It is very easy to use. Just register the functions you want to make available to the script, compile the script to bytecode and execute it.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
I have a problem. I am coding using VS2008. I am calling webservices from my JavaScript Page. An example ``` Services.ChangeDropDownLists.GetNowPlayingMoviesByLocationSVC( blah, OnSuccessMoviesByRegion, OnError, OnTimeOut ); ``` after execution, it goes to the function `OnSuccessMoviesByRegion`. But if I put the Services in a loop (a simple for loop) ``` Services.ChangeDropDownLists.GetNowPlayingMoviesByLocationSVC( blah[i], OnSuccessMoviesByRegion, OnError, OnTimeOut ); ``` `OnSucessMoviesByRegion` function won't execute (but the service call executes n times successfully But I must have the function cos I am returning value through it. What am I missing? Is that the typical behaviour? Any alternatives?
I would write it in [ANTLR](http://www.antlr.org/). Write the grammar, let ANTLR generate a C# parser. You can ANTLR ask for a parse tree, and possibly the interpreter can already operate on the parse tree. Perhaps you'll have to convert the parse tree to some more abstract internal representation (although ANTLR already allows to leave out irrelevant punctuation when generating the tree).
256,647
<p>I want to see how long a function takes to run. What's the easiest way to do this in PLT-Scheme? Ideally I'd want to be able to do something like this:</p> <pre><code>&gt; (define (loopy times) (if (zero? times) 0 (loopy (sub1 times)))) &gt; (loopy 5000000) 0 ;(after about a second) &gt; (timed (loopy 5000000)) Took: 0.93 seconds 0 &gt; </code></pre> <p>It doesn't matter if I'd have to use some other syntax like <code>(timed loopy 5000000)</code> or <code>(timed '(loopy 5000000))</code>, or if it returns the time taken in a cons or something.</p>
[ { "answer_id": 256652, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<p>Found it...</p>\n\n<p>From the <a href=\"http://download.plt-scheme.org/doc/301/html/mzscheme/mzscheme-Z-H-15.html#node_sec_15.1.3\" rel=\"nofollow noreferrer\">online documentation</a>:</p>\n\n<blockquote>\n <ul>\n <li><code>(time-apply proc arg-list)</code> invokes the procedure proc with the arguments in arg-list. Four values are returned: a list containing the result(s) of applying proc, the number of milliseconds of CPU time required to obtain this result, the number of ``real'' milliseconds required for the result, and the number of milliseconds of CPU time (included in the first result) spent on garbage collection.</li>\n </ul>\n</blockquote>\n\n<p>Example usage:</p>\n\n<pre><code>&gt; (time-apply loopy '(5000000))\n(0)\n621\n887\n0\n</code></pre>\n" }, { "answer_id": 262916, "author": "soegaard", "author_id": 23567, "author_profile": "https://Stackoverflow.com/users/23567", "pm_score": 4, "selected": true, "text": "<p>The standard name for timing the execution of expressions in most Scheme implementations is \"time\". Here is an example from within DrRacket.</p>\n\n<blockquote>\n <p>(define (loopy times)\n (if (zero? times)\n 0\n (loopy (sub1 times)))) </p>\n \n <p>(time (loopy 5000000))\n cpu time: 1526 real time: 1657 gc time: 0\n 0</p>\n</blockquote>\n\n<p>If you use time to benchmark different implementations against each other,\nremember to use racket from the command line rather than benchmarking directly\nin DrRacket (DrRacket inserts debug code in order to give better error messages).</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
I want to see how long a function takes to run. What's the easiest way to do this in PLT-Scheme? Ideally I'd want to be able to do something like this: ``` > (define (loopy times) (if (zero? times) 0 (loopy (sub1 times)))) > (loopy 5000000) 0 ;(after about a second) > (timed (loopy 5000000)) Took: 0.93 seconds 0 > ``` It doesn't matter if I'd have to use some other syntax like `(timed loopy 5000000)` or `(timed '(loopy 5000000))`, or if it returns the time taken in a cons or something.
The standard name for timing the execution of expressions in most Scheme implementations is "time". Here is an example from within DrRacket. > > (define (loopy times) > (if (zero? times) > 0 > (loopy (sub1 times)))) > > > (time (loopy 5000000)) > cpu time: 1526 real time: 1657 gc time: 0 > 0 > > > If you use time to benchmark different implementations against each other, remember to use racket from the command line rather than benchmarking directly in DrRacket (DrRacket inserts debug code in order to give better error messages).
256,700
<p>What is a view in Oracle?</p>
[ { "answer_id": 256703, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 7, "selected": false, "text": "<p>A <strong>View in Oracle</strong> and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query</p>\n\n<pre><code>SELECT customerid, customername FROM customers WHERE countryid='US';\n</code></pre>\n\n<p>To create a view use the <strong>CREATE VIEW command</strong> as seen in this example</p>\n\n<pre><code>CREATE VIEW view_uscustomers\nAS\nSELECT customerid, customername FROM customers WHERE countryid='US';\n</code></pre>\n\n<p>This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this:</p>\n\n<pre><code>SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;\n</code></pre>\n\n<p>And Oracle will transform the query into this:</p>\n\n<pre><code>SELECT * \nFROM (select customerid, customername from customers WHERE countryid='US') \nWHERE customerid BETWEEN 100 AND 200\n</code></pre>\n\n<p><strong>Benefits of using Views</strong></p>\n\n<ul>\n<li>Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called it’s less likely to require parsing. </li>\n<li>Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to.</li>\n<li><a href=\"http://www.devx.com/tips/Tip/34429\" rel=\"noreferrer\">Predicate pushing</a></li>\n</ul>\n\n<p>You can find advanced topics in this article about \"<a href=\"http://www.oracle-dba-online.com/sql/create_and_manage_views.htm\" rel=\"noreferrer\">How to Create and Manage Views in Oracle</a>.\"</p>\n" }, { "answer_id": 258388, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 4, "selected": false, "text": "<p>If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.<br>\nSee <a href=\"http://download.oracle.com/docs/cd/B10501_01/server.920/a96567/repmview.htm\" rel=\"nofollow noreferrer\">materialized views</a></p>\n" }, { "answer_id": 4884830, "author": "jassi", "author_id": 601322, "author_profile": "https://Stackoverflow.com/users/601322", "pm_score": 2, "selected": false, "text": "<p>A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.</p>\n" }, { "answer_id": 5867837, "author": "shubham", "author_id": 735896, "author_profile": "https://Stackoverflow.com/users/735896", "pm_score": 2, "selected": false, "text": "<p>A view is simply any <code>SELECT</code> query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. To create a view, you use the SQL syntax:</p>\n\n<pre><code> CREATE OR REPLACE VIEW &lt;view_name&gt; AS\n SELECT &lt;any valid select query&gt;;\n</code></pre>\n" }, { "answer_id": 21180677, "author": "Nagappa L M", "author_id": 1523263, "author_profile": "https://Stackoverflow.com/users/1523263", "pm_score": 2, "selected": false, "text": "<p>regular view----->short name for a query,no additional space is used here</p>\n\n<p>Materialised view---->similar to creating table whose data will refresh periodically based on data query used for creating the view</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is a view in Oracle?
A **View in Oracle** and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query ``` SELECT customerid, customername FROM customers WHERE countryid='US'; ``` To create a view use the **CREATE VIEW command** as seen in this example ``` CREATE VIEW view_uscustomers AS SELECT customerid, customername FROM customers WHERE countryid='US'; ``` This command creates a new view called view\_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this: ``` SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200; ``` And Oracle will transform the query into this: ``` SELECT * FROM (select customerid, customername from customers WHERE countryid='US') WHERE customerid BETWEEN 100 AND 200 ``` **Benefits of using Views** * Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called it’s less likely to require parsing. * Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to. * [Predicate pushing](http://www.devx.com/tips/Tip/34429) You can find advanced topics in this article about "[How to Create and Manage Views in Oracle](http://www.oracle-dba-online.com/sql/create_and_manage_views.htm)."
256,702
<p>I have used something like the following to compose policies for my application:</p> <p>The policy classes look like this:</p> <pre><code>struct Policy { static void init(); static void cleanup(); //... }; template &lt;class CarT, class CdrT&gt; struct Cons { static void init() { CarT::init(); CdrT::init(); } static void cleanup() { CdrT::cleanup(); CarT::cleanup(); } //... }; </code></pre> <p>To compose policies:</p> <pre><code>typedef Cons&lt;Policy1, Cons&lt;Policy2, Cons&lt;Policy3, Policy4&gt; &gt; &gt; MyPolicy; </code></pre> <p>To use MyPolicy:</p> <pre><code>init_with&lt;MyPolicy&gt;(...); //... cleanup_with&lt;MyPolicy&gt;(...); </code></pre> <p>where they'd call:</p> <pre><code>MyPolicy::init_options(); // calls Policy1 to 4's init in order </code></pre> <p>and</p> <pre><code>MyPolicy::cleanup(); // calls Policy1 to 4's cleanup in reverse order </code></pre> <p>Essentially, Cons constructs a type list here. It's pretty straight forward. However the typedef cons line is kinda ugly. It'll be ideal to have policy combiner that can do this:</p> <pre><code>typedef CombinePolicy&lt;Policy1, Policy2, Policy3, Policy4&gt; MyPolicy; </code></pre> <p>Since we can have arbitrary number of policies, the CombinePolicy would need variadic template support in C++0x, which is only available experimentally in cutting edge compilers. However, it seems that boost:mpl library solved/worked around the problem by using a bunch preprocessing tricks. I <em>guess</em> I could use something like:</p> <pre><code>typedef mpl::list&lt;Policy, Policy2, Policy3, Policy4&gt; Policies; </code></pre> <p>and then calls:</p> <pre><code>init_with&lt;Policies&gt;(...); </code></pre> <p>which would then use:</p> <pre><code>typedef iter_fold&lt;Policies, begin&lt;Policies&gt;::type, some_magic_lambda_expression&gt;::type MyPolicy; </code></pre> <p>Obviously, I have a little trouble figuring out <em>some_magic_lambda_expression</em> here. I'm sure it's quite trivial for mpl experts here.</p> <p>Thanks in advance.</p>
[ { "answer_id": 256860, "author": "tabdamage", "author_id": 28022, "author_profile": "https://Stackoverflow.com/users/28022", "pm_score": 1, "selected": false, "text": "<p>I think your problem is rather runtime invocation than metafunctions, because you want to call the init functions on the actual runtime objects.</p>\n\n<p>You could try the runtime algorithms of mpl,\nlike : </p>\n\n<pre><code>for_each&lt;Policies&gt;(InitPolicy());\n</code></pre>\n\n<p>with </p>\n\n<pre><code>struct InitPolicy() {\n template&lt;class Policy&gt;\n void operator() (Policy&amp; p) { p.init_options(); }\n};\n</code></pre>\n" }, { "answer_id": 257270, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "<p>I think you're looking for something like:</p>\n\n<pre><code>typedef \n iter_fold&lt;\n Policies,\n begin&lt;Policies&gt;::type,\n Cons&lt;_1,_2&gt;\n &gt;::type\n MyType;\n</code></pre>\n\n<p>You also might want to look into <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/refmanual/inherit-linearly.html\" rel=\"nofollow noreferrer\">inherit_linearly&lt;></a> if you buld-in some sort of CRTP to invoke a base's functions hard-wired at compile time. </p>\n" }, { "answer_id": 260750, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 3, "selected": false, "text": "<p>Since no one answered the question satisfactorily, I spent sometime digging into the boost::mpl source. Man, it's not pretty with layers of macros and hundreds of lines of specialization classes. I now have more appreciation for the authors of the boost libraries to make meta programming easier and more portable for us. Hopefully C++0x will make library writers' life easier as well.</p>\n\n<p>Anyway, the solution turns out to be simple and elegant.</p>\n\n<p>First iter_fold is not what I want, as I couldn't figure out how to specify an iterator that can be deferenced to a null type. So I fiddled around with fold and find the following:</p>\n\n<pre><code>typedef fold&lt;Policies, Null, Cons&lt;_1, _2&gt; &gt;::type MyPolicy;\n</code></pre>\n\n<p>In order for this to work, I need to provide the Null type and a specialization for Cons:</p>\n\n<pre><code>struct Null { };\n\ntemplate&lt;class PolicyT&gt;\nstruct Cons&lt;Null, PolicyT&gt; {\n static void init() { PolicyT::init(); }\n static void cleanup() { PolicyT::cleanup(); }\n};\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28888/" ]
I have used something like the following to compose policies for my application: The policy classes look like this: ``` struct Policy { static void init(); static void cleanup(); //... }; template <class CarT, class CdrT> struct Cons { static void init() { CarT::init(); CdrT::init(); } static void cleanup() { CdrT::cleanup(); CarT::cleanup(); } //... }; ``` To compose policies: ``` typedef Cons<Policy1, Cons<Policy2, Cons<Policy3, Policy4> > > MyPolicy; ``` To use MyPolicy: ``` init_with<MyPolicy>(...); //... cleanup_with<MyPolicy>(...); ``` where they'd call: ``` MyPolicy::init_options(); // calls Policy1 to 4's init in order ``` and ``` MyPolicy::cleanup(); // calls Policy1 to 4's cleanup in reverse order ``` Essentially, Cons constructs a type list here. It's pretty straight forward. However the typedef cons line is kinda ugly. It'll be ideal to have policy combiner that can do this: ``` typedef CombinePolicy<Policy1, Policy2, Policy3, Policy4> MyPolicy; ``` Since we can have arbitrary number of policies, the CombinePolicy would need variadic template support in C++0x, which is only available experimentally in cutting edge compilers. However, it seems that boost:mpl library solved/worked around the problem by using a bunch preprocessing tricks. I *guess* I could use something like: ``` typedef mpl::list<Policy, Policy2, Policy3, Policy4> Policies; ``` and then calls: ``` init_with<Policies>(...); ``` which would then use: ``` typedef iter_fold<Policies, begin<Policies>::type, some_magic_lambda_expression>::type MyPolicy; ``` Obviously, I have a little trouble figuring out *some\_magic\_lambda\_expression* here. I'm sure it's quite trivial for mpl experts here. Thanks in advance.
Since no one answered the question satisfactorily, I spent sometime digging into the boost::mpl source. Man, it's not pretty with layers of macros and hundreds of lines of specialization classes. I now have more appreciation for the authors of the boost libraries to make meta programming easier and more portable for us. Hopefully C++0x will make library writers' life easier as well. Anyway, the solution turns out to be simple and elegant. First iter\_fold is not what I want, as I couldn't figure out how to specify an iterator that can be deferenced to a null type. So I fiddled around with fold and find the following: ``` typedef fold<Policies, Null, Cons<_1, _2> >::type MyPolicy; ``` In order for this to work, I need to provide the Null type and a specialization for Cons: ``` struct Null { }; template<class PolicyT> struct Cons<Null, PolicyT> { static void init() { PolicyT::init(); } static void cleanup() { PolicyT::cleanup(); } }; ```
256,719
<p>In most versions of windows, you can get to the menu by pressing the F10 key, thus avoiding having to use the mouse. This behaviour does not appear to be present in Windows Mobile 5.0, but is desirable as the device I am using will be more keyboard than touch screen driven. </p> <p>Is there a way of programmatically activating and using the menu on Windows Mobile 5.0, under C++ using either MFC or Windows API calls. I have tried setting the focus of the CFrameWnd and CCeCommandBar classes to no avail.</p>
[ { "answer_id": 256777, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": true, "text": "<p>After a number of attempts, the following appears to work;</p>\n\n<pre><code>void CMyFrame::OnFocusMenu()\n{\n PostMessage(WM_SYSCOMMAND,SC_KEYMENU,0);\n}\n</code></pre>\n\n<p>FWIW, none of the following did, where m_wndCommandBar is the CCeCommandBar toolbar containing the menu;</p>\n\n<pre><code>::SetActiveWindow(m_wndCommandBar.m_hWnd);\nm_wndCommandBar.PostMessage(WM_ACTIVATE,WA_ACTIVE,0);\nm_wndCommandBar.PostMessage(WM_LBUTTONDOWN,0,0);\nm_wndCommandBar.PostMessage(WM_LBUTTONUP,0,0);\nm_wndCommandBar.OnActivate(WA_ACTIVE, NULL, FALSE);\nm_wndCommandBar.SetFocus();\n</code></pre>\n" }, { "answer_id": 257522, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 0, "selected": false, "text": "<p>If by menu, you mean the soft keys, note that they are bound to F1 and F2 respectively.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22564/" ]
In most versions of windows, you can get to the menu by pressing the F10 key, thus avoiding having to use the mouse. This behaviour does not appear to be present in Windows Mobile 5.0, but is desirable as the device I am using will be more keyboard than touch screen driven. Is there a way of programmatically activating and using the menu on Windows Mobile 5.0, under C++ using either MFC or Windows API calls. I have tried setting the focus of the CFrameWnd and CCeCommandBar classes to no avail.
After a number of attempts, the following appears to work; ``` void CMyFrame::OnFocusMenu() { PostMessage(WM_SYSCOMMAND,SC_KEYMENU,0); } ``` FWIW, none of the following did, where m\_wndCommandBar is the CCeCommandBar toolbar containing the menu; ``` ::SetActiveWindow(m_wndCommandBar.m_hWnd); m_wndCommandBar.PostMessage(WM_ACTIVATE,WA_ACTIVE,0); m_wndCommandBar.PostMessage(WM_LBUTTONDOWN,0,0); m_wndCommandBar.PostMessage(WM_LBUTTONUP,0,0); m_wndCommandBar.OnActivate(WA_ACTIVE, NULL, FALSE); m_wndCommandBar.SetFocus(); ```
256,723
<p>We are using Subversion. We would like to </p> <pre><code>1. search across all commit messages ? 2. monitor the commits on certain important files ? 3. identify files that are never/rarely used ? 4. identify files that are most frequently changed ? 5. identify files that most developers have accessed ? 6. identify files that have been committed together many number of times ? </code></pre> <p>The usage of these data could be to weed out messages like <a href="https://stackoverflow.com/questions/216876/what-is-the-best-commit-message-you-have-ever-encountered#255762">these</a>, to refactor code and clean up the project of unused files. </p> <p>Please suggest tools to achieve the same.. </p> <p><b>EDIT:</b> We run SVN on Windows 2003.</p>
[ { "answer_id": 256727, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "<p>What platform are you using? On linux, a quick shell script using <code>sed</code> should do the trick.</p>\n" }, { "answer_id": 256749, "author": "Peter Mounce", "author_id": 20971, "author_profile": "https://Stackoverflow.com/users/20971", "pm_score": 1, "selected": false, "text": "<p>In .NET land, there is the <a href=\"http://sharpsvn.open.collab.net/\" rel=\"nofollow noreferrer\">SharpSvn</a> library that you could use. To achieve what you want, you would need to suck down all the log messages and parse them yourself, though.</p>\n" }, { "answer_id": 256784, "author": "alastairs", "author_id": 5296, "author_profile": "https://Stackoverflow.com/users/5296", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.statsvn.org/\" rel=\"nofollow noreferrer\" title=\"StatSVN\">StatSVN</a> should be able to do the majority of that for you. You'll need to set up a scheduled task to run it over your repository, however, or you can integrate it into an Ant build if you happen to use that. </p>\n\n<p>Some of the more complex tasks, such as number 6 in your list, will probably require a custom solution, however. Alternatively, as StatSVN is open source, you could make the required changes to that and submit them back to the project. </p>\n" }, { "answer_id": 256838, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 3, "selected": true, "text": "<p>Another tool worth looking at is <a href=\"http://www.viewvc.org/\" rel=\"nofollow noreferrer\">ViewVC</a>. The latest version has the option to maintain a commit database. This allows you to search across all commit messages and to see a list of changes to either a file or a files in a directory filtered by user, time or regular expression. It also supports RSS feeds which would enable some form of notification to individual files.</p>\n\n<p>For 3, 4 and 5 on your list StatSVN which is mentioned in the other answers should be able to do this. For a commercial solution there is <a href=\"http://www.atlassian.com/software/fisheye/\" rel=\"nofollow noreferrer\">FishEye</a> from Atlassian. </p>\n\n<p>On our repository we use a combination of ViewVC and StatSVN, the former used for repository browsing and searching commit messages with the latter for looking at statistics.</p>\n" }, { "answer_id": 257141, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 1, "selected": false, "text": "<p>You can do alot of it with the Subversion command line client and some scripting (Ruby or Python), but don't expect people here to write the code for you. The implementation details will depend on things like how often you want to run the stats and how large your repo is.</p>\n\n<p>When processing data from the Subversion command line client you may find it easier to use the --xml option (accepted by the \"log\" and \"info\" commands) which outputs the data in XML-format.</p>\n\n<pre><code>1. search across all commit messages ?\n</code></pre>\n\n<p>Run \"svn log -v --xml\" and run a text-search on the resulting XML (or parts of it). You can specify which set of commit messages you want to search.</p>\n\n<pre><code>2. monitor the commits on certain important files ?\n</code></pre>\n\n<p>This is implemented with commit-triggers. See the Subversion server documentation.</p>\n\n<pre><code>3. identify files that are never/rarely used ?\n4. identify files that are most frequently changed ? \n5. identify files that most developers have accessed ?\n6. identify files that have been committed together many number of times ?\n</code></pre>\n\n<p>These can all be implemented using the output from \"svn log --xml\" and post-processing of the resulting XML data.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
We are using Subversion. We would like to ``` 1. search across all commit messages ? 2. monitor the commits on certain important files ? 3. identify files that are never/rarely used ? 4. identify files that are most frequently changed ? 5. identify files that most developers have accessed ? 6. identify files that have been committed together many number of times ? ``` The usage of these data could be to weed out messages like [these](https://stackoverflow.com/questions/216876/what-is-the-best-commit-message-you-have-ever-encountered#255762), to refactor code and clean up the project of unused files. Please suggest tools to achieve the same.. **EDIT:** We run SVN on Windows 2003.
Another tool worth looking at is [ViewVC](http://www.viewvc.org/). The latest version has the option to maintain a commit database. This allows you to search across all commit messages and to see a list of changes to either a file or a files in a directory filtered by user, time or regular expression. It also supports RSS feeds which would enable some form of notification to individual files. For 3, 4 and 5 on your list StatSVN which is mentioned in the other answers should be able to do this. For a commercial solution there is [FishEye](http://www.atlassian.com/software/fisheye/) from Atlassian. On our repository we use a combination of ViewVC and StatSVN, the former used for repository browsing and searching commit messages with the latter for looking at statistics.
256,724
<p>In C++, is it safe to extend scope via a reference?</p> <p>In code, what I mean is: </p> <pre><code>MyCLass&amp; function badIdea() { MyClass obj1; ... return obj1; } </code></pre>
[ { "answer_id": 256741, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 1, "selected": false, "text": "<p>Please clarify what you do mean.</p>\n\n<p>Assuming you intend to do this:</p>\n\n<pre><code>int * p = NULL;\n{\n int y = 22;\n p = &amp;y;\n}\n*p = 77; // BOOM!\n</code></pre>\n\n<p>Then no, absolutely not, scope does not get extended by having a reference.</p>\n\n<p>You may want to look at smart pointers, e.g. from boost libraries: <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">clickety</a></p>\n" }, { "answer_id": 256744, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 6, "selected": true, "text": "<p>It is NOT safe to extend the scope via reference. Objects in C++ are not reference counted when obj1 goes out of scope it will be deleted, refering to the result of badIdea() will only get you into trouble</p>\n" }, { "answer_id": 256748, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": false, "text": "<p>The only place it's OK to extend a scope with a reference is with a <code>const</code> reference in <code>namespace</code> or function scope (not with class members).</p>\n\n<pre><code>const int &amp; cir = 1+1; // OK to use cir = 2 after this line \n</code></pre>\n\n<p>This trick is used in <a href=\"http://erdani.org/\" rel=\"noreferrer\">Andrei Alexandrescu's</a> very cool <a href=\"http://www.ddj.com/cpp/184403758\" rel=\"noreferrer\">scope guard</a> in order to capture a <code>const</code> reference to a base class of the concrete scope guard.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
In C++, is it safe to extend scope via a reference? In code, what I mean is: ``` MyCLass& function badIdea() { MyClass obj1; ... return obj1; } ```
It is NOT safe to extend the scope via reference. Objects in C++ are not reference counted when obj1 goes out of scope it will be deleted, refering to the result of badIdea() will only get you into trouble
256,728
<pre><code>function AddTheatres() { Services.AdminWebServices.AddTheatresSVC(oTheatres, OnSuccessTheatres, OnError, OnTimeOut); } function OnSuccessTheatres(result1) { Services.AdminWebServices.AddTicketPricesSVC(oTicketPrices, OnSuccessTicketPrices, OnError, OnTimeOut); //working } function OnSuccessTicketPrices(result2) { alert(result2); //not working } </code></pre> <p>Why is the alert not working? On Debugging the function calling <code>AddTicketPricesSVC</code> is returning correct value.</p>
[ { "answer_id": 256733, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": true, "text": "<p>Did you implement the OnError and OnTimeout handlers? Maybe there is a server error?</p>\n" }, { "answer_id": 256747, "author": "naveen", "author_id": 17447, "author_profile": "https://Stackoverflow.com/users/17447", "pm_score": 0, "selected": false, "text": "<pre><code>function OnError(error)\n{\n alert(error.get_message());\n}\nfunction OnTimeOut()\n{\n alert('System Time Out');\n}\n</code></pre>\n\n<p>This is the way to implement it right?</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
``` function AddTheatres() { Services.AdminWebServices.AddTheatresSVC(oTheatres, OnSuccessTheatres, OnError, OnTimeOut); } function OnSuccessTheatres(result1) { Services.AdminWebServices.AddTicketPricesSVC(oTicketPrices, OnSuccessTicketPrices, OnError, OnTimeOut); //working } function OnSuccessTicketPrices(result2) { alert(result2); //not working } ``` Why is the alert not working? On Debugging the function calling `AddTicketPricesSVC` is returning correct value.
Did you implement the OnError and OnTimeout handlers? Maybe there is a server error?
256,729
<p>I have a regular expression to match a persons name.</p> <p>So far I have ^([a-zA-Z\'\s]+)$ but id like to add a check to allow for a maximum of 4 spaces. How do I amend it to do this?</p> <p><strong>Edit:</strong> what i meant was 4 spaces anywhere in the string</p>
[ { "answer_id": 256735, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<h2> Screw the regex. </h2>\n\n<p>Using a regex here seems to be creating a problem for a solution instead of just solving a problem. </p>\n\n<p>This task should be 'easy' for even a novice programmer, and the novel idea of regex has polluted our minds!. </p>\n\n<pre><code>1: Get Input \n2: Trim White Space\n3: If this makes sence, trim out any 'bad' characters. \n4: Use the \"split\" utility provided by your language to break it into words\n5: Return the first 5 Words. \n</code></pre>\n\n<p>ROCKET SCIENCE. </p>\n\n<h3>replies</h3>\n\n<blockquote>\n <p>what do you mean screw the regex? your obviously a VB programmer. \n Regex is the most efficient way to work with strings. Learn them. </p>\n</blockquote>\n\n<p>No. Php, toyed a bit with ruby, now going manically into perl. </p>\n\n<p>There are some thing ( like this case ) where the regex based alternative is computationally and logically exponentially overly complex for the task. </p>\n\n<p>I've parse entire php source files with regex, I'm not exactly a novice in their use. </p>\n\n<p>But there are many cases, such as this, where you're employing a logging company to prune your rose bush. </p>\n\n<p>I could do all steps 2 to 5 with regex of course, but they would be simple and atomic regex, with no weird backtracking syntax or potential for recursive searching. </p>\n\n<p>The steps 1 to 5 I list above have a known scope, known range of input, and there's no ambiguity to how it functions. As to your regex, the fact you have to get contributions of others to write something so simple is proving the point. </p>\n\n<p>I see somebody marked my post as offensive, I am somewhat unhappy I can't mark this fact as offensive to me. ;) </p>\n\n<p>Proof Of Pudding: </p>\n\n<pre><code>sub getNames{\n my @args = @_;\n my $text = shift @args;\n my $num = shift @args;\n\n # Trim Whitespace from Head/End\n $text =~ s/^\\s*//;\n $text =~ s/\\s*$//;\n\n # Trim Bad Characters (??)\n $text =~ s/[^a-zA-Z\\'\\s]//g;\n\n # Tokenise By Space \n my @words = split( /\\s+/, $text );\n\n #return 0..n \n return @words[ 0 .. $num - 1 ];\n} ## end sub getNames\n\nprint join \",\", getNames \" Hello world this is a good test\", 5;\n&gt;&gt; Hello,world,this,is,a\n</code></pre>\n\n<p>If there is anything ambiguous to anybody how that works, I'll be glad to explain it to them. Noted that I'm still doing it with regexps. Other languages I would have used their native \"trim\" functions provided where possible. </p>\n\n<hr>\n\n<h2> Bollocks --> </h2>\n\n<p>I first tried this approach. This is your brain on regex. Kids, don't do regex. </p>\n\n<hr>\n\n<p>This might be a good start </p>\n\n<pre><code>/([^\\s]+\n (\\s[^\\s]+\n (\\s[^\\s]+\n (\\s[^\\s]+\n (\\s[^\\s]+|)\n |)\n |)\n |)\n )/ \n</code></pre>\n\n<p>( Linebroken for clarity )</p>\n\n<pre><code>/([^\\s]+(\\s[^\\s]+(\\s[^\\s]+(\\s[^\\s]+|)|)|))/ \n</code></pre>\n\n<p>( Actual )</p>\n\n<p>I've used <code>[^\\s]+</code> here instead of your A-Z combo for succintness, but the point is here the nested optional groups</p>\n\n<p>ie: </p>\n\n<pre><code>(Hello( this( is( example))))\n(Hello( this( is( example( two)))))\n(Hello( this( is( better( example))))) three\n(Hello( this( is()))))\n(Hello( this()))\n(Hello())\n</code></pre>\n\n<p>( Note: this, while being convoluted, has the benefit that it will match each name into its own group ) </p>\n\n<p>If you want readable code: </p>\n\n<pre><code> $word = '[^\\s]+'; \n $regex = \"/($word(\\s$word(\\s$word(\\s$word(\\s$word|)|)|)|)|)/\"; \n</code></pre>\n\n<p>( it anchors around the (capture|) mantra of \"get this, or get nothing\" ) </p>\n" }, { "answer_id": 256737, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p><code>^([a-zA-Z']+\\s){0,4}[a-zA-Z']+$</code></p>\n\n<p>This assumes you want 4 spaces <em>inside</em> this string (i.e. you have trimmed it)</p>\n\n<p>Edit: If you want 4 spaces anywhere I'd recommend not using regex - you'd be better off using a <code>substr_count</code> (or the equivalent in your language).</p>\n\n<p>I also agree with pipTheGeek that there are so many different ways of writing names that you're probably best off trusting the user to get their name right (although I have found that a lot of people don't bother using capital letters on ecommerce checkouts).</p>\n" }, { "answer_id": 256738, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 2, "selected": false, "text": "<p>@Sir Psycho : Be careful about your assumptions here. What about hyphenated names? Dotted names (e.g. Brian R. Bondy) and so on?</p>\n" }, { "answer_id": 256758, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 4, "selected": false, "text": "<p>Don't attempt to regex validate a name. People are allowed to call themselves what ever they like. This can include ANY character. Just because you live somewhere that only uses English doesn't mean that all the people who use your system will have English names. We have even had to make the name field in our system Unicode. It is the only Unicode type in the database.</p>\n\n<p>If you care, we actually split the name at \" \" and store each name part as a separate record, but we have some very specific requirements that mean this is a good idea.</p>\n\n<p>PS. My step mum has 5 spaces in her name.</p>\n" }, { "answer_id": 256789, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "<pre><code>^ # Start of string\n(?!\\S*(?:\\s\\S*){5}) # Negative look-ahead for five spaces.\n([a-zA-Z\\'\\s]+)$ # Original regex\n</code></pre>\n\n<p>Or in one line:</p>\n\n<pre><code>^(?!(?:\\S*\\s){5})([a-zA-Z\\'\\s]+)$\n</code></pre>\n\n<p>If there are five or more spaces in the string, five will be matched by the negative lookahead, and the whole match will fail. If there are four or less, the original regex will be matched.</p>\n" }, { "answer_id": 256805, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>Here's the answer that you're most likely looking for:</p>\n\n<pre><code>^[a-zA-Z']+(\\s[a-zA-Z']+){0,4}$\n</code></pre>\n\n<p>That says (in English): \"From start to finish, match one or more letters, there can also be a space followed by another 'name' up to four times.\"</p>\n\n<p>BTW: Why do you want them to have apostrophes anywhere in the name?</p>\n" }, { "answer_id": 17335836, "author": "Ketan.G", "author_id": 2526806, "author_profile": "https://Stackoverflow.com/users/2526806", "pm_score": -1, "selected": false, "text": "<p>Match multiple whitespace followed by two characters at the end of the line. </p>\n\n<p><strong>Related problem ----</strong></p>\n\n<p>From a string, remove trailing 2 characters preceded by multiple white spaces... For example, if the column contains this string - \n\" 'This is a long string with 2 chars at the end AB \" \nthen, AB should be removed while retaining the sentence.</p>\n\n<p><strong>Solution ----</strong></p>\n\n<p><code>select 'This is a long string with 2 chars at the end AB' as \"C1\",</code>\n <code>regexp_replace('This is a long string with 2 chars at the end AB',\n '[[[:space:]][a-zA-Z][a-zA-Z]]*$') as \"C2\" from dual;</code></p>\n\n<p><strong>Output ----</strong></p>\n\n<p><code>C1</code></p>\n\n<p><code>This is a long string with 2 chars at the end AB</code></p>\n\n<p><code>C2</code></p>\n\n<p><code>This is a long string with 2 chars at the end</code></p>\n\n<p><strong>Analysis ----</strong>\nregular expression specifies - match and replace zero or more occurences (*) of a space ([:space:]) followed by combination of two characters ([a-zA-Z][a-zA-Z]) at the end of the line. </p>\n\n<p>Hope this is useful.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
I have a regular expression to match a persons name. So far I have ^([a-zA-Z\'\s]+)$ but id like to add a check to allow for a maximum of 4 spaces. How do I amend it to do this? **Edit:** what i meant was 4 spaces anywhere in the string
Screw the regex. ----------------- Using a regex here seems to be creating a problem for a solution instead of just solving a problem. This task should be 'easy' for even a novice programmer, and the novel idea of regex has polluted our minds!. ``` 1: Get Input 2: Trim White Space 3: If this makes sence, trim out any 'bad' characters. 4: Use the "split" utility provided by your language to break it into words 5: Return the first 5 Words. ``` ROCKET SCIENCE. ### replies > > what do you mean screw the regex? your obviously a VB programmer. > Regex is the most efficient way to work with strings. Learn them. > > > No. Php, toyed a bit with ruby, now going manically into perl. There are some thing ( like this case ) where the regex based alternative is computationally and logically exponentially overly complex for the task. I've parse entire php source files with regex, I'm not exactly a novice in their use. But there are many cases, such as this, where you're employing a logging company to prune your rose bush. I could do all steps 2 to 5 with regex of course, but they would be simple and atomic regex, with no weird backtracking syntax or potential for recursive searching. The steps 1 to 5 I list above have a known scope, known range of input, and there's no ambiguity to how it functions. As to your regex, the fact you have to get contributions of others to write something so simple is proving the point. I see somebody marked my post as offensive, I am somewhat unhappy I can't mark this fact as offensive to me. ;) Proof Of Pudding: ``` sub getNames{ my @args = @_; my $text = shift @args; my $num = shift @args; # Trim Whitespace from Head/End $text =~ s/^\s*//; $text =~ s/\s*$//; # Trim Bad Characters (??) $text =~ s/[^a-zA-Z\'\s]//g; # Tokenise By Space my @words = split( /\s+/, $text ); #return 0..n return @words[ 0 .. $num - 1 ]; } ## end sub getNames print join ",", getNames " Hello world this is a good test", 5; >> Hello,world,this,is,a ``` If there is anything ambiguous to anybody how that works, I'll be glad to explain it to them. Noted that I'm still doing it with regexps. Other languages I would have used their native "trim" functions provided where possible. --- Bollocks --> ------------- I first tried this approach. This is your brain on regex. Kids, don't do regex. --- This might be a good start ``` /([^\s]+ (\s[^\s]+ (\s[^\s]+ (\s[^\s]+ (\s[^\s]+|) |) |) |) )/ ``` ( Linebroken for clarity ) ``` /([^\s]+(\s[^\s]+(\s[^\s]+(\s[^\s]+|)|)|))/ ``` ( Actual ) I've used `[^\s]+` here instead of your A-Z combo for succintness, but the point is here the nested optional groups ie: ``` (Hello( this( is( example)))) (Hello( this( is( example( two))))) (Hello( this( is( better( example))))) three (Hello( this( is())))) (Hello( this())) (Hello()) ``` ( Note: this, while being convoluted, has the benefit that it will match each name into its own group ) If you want readable code: ``` $word = '[^\s]+'; $regex = "/($word(\s$word(\s$word(\s$word(\s$word|)|)|)|)|)/"; ``` ( it anchors around the (capture|) mantra of "get this, or get nothing" )
256,754
<p>The situation is somewhat like-</p> <pre><code>var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false); </code></pre> <p>The problem is that the value of <code>someVar</code> is not visible inside the listener function of the <code>addEventListener</code>, where it is probably being treated as a new variable.</p>
[ { "answer_id": 256763, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 9, "selected": true, "text": "<p>There is absolutely nothing wrong with the code you've written. Both <code>some_function</code> and <code>someVar</code> should be accessible, in case they were available in the context where anonymous </p>\n\n<pre><code>function() { some_function(someVar); } \n</code></pre>\n\n<p>was created. </p>\n\n<p>Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same <code>someVar</code> variable next to the call to <code>addEventListener</code>)</p>\n\n<pre><code>var someVar; \nsomeVar = some_other_function();\nalert(someVar);\nsomeObj.addEventListener(\"click\", function(){\n some_function(someVar);\n}, false);\n</code></pre>\n" }, { "answer_id": 256945, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 3, "selected": false, "text": "<p><code>someVar</code> value should be accessible only in <code>some_function()</code> context, not from listener's.\nIf you like to have it within listener, you must do something like:</p>\n\n<pre><code>someObj.addEventListener(\"click\",\n function(){\n var newVar = someVar;\n some_function(someVar);\n },\n false);\n</code></pre>\n\n<p>and use <code>newVar</code> instead.</p>\n\n<p>The other way is to return <code>someVar</code> value from <code>some_function()</code> for using it further in listener (as a new local var):</p>\n\n<pre><code>var someVar = some_function(someVar);\n</code></pre>\n" }, { "answer_id": 3696345, "author": "Ganesh Krishnan", "author_id": 436620, "author_profile": "https://Stackoverflow.com/users/436620", "pm_score": 5, "selected": false, "text": "<p>You can add and remove eventlisteners with arguments by declaring a function as a variable.</p>\n\n<p><code>myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);</code></p>\n\n<p><code>newSrc</code> is the method with myaudio as parameter\n<code>funcName</code> is the function name variable</p>\n\n<p>You can remove the listener with \n <code>myaudio.removeEventListener('ended',func,false);</code></p>\n" }, { "answer_id": 8202901, "author": "DMike92", "author_id": 1056540, "author_profile": "https://Stackoverflow.com/users/1056540", "pm_score": 1, "selected": false, "text": "<p>Also try these (IE8 + Chrome. I dont know for FF):</p>\n\n<pre><code>function addEvent(obj, type, fn) {\n eval('obj.on'+type+'=fn');\n}\n\nfunction removeEvent(obj, type) {\n eval('obj.on'+type+'=null');\n}\n\n// Use :\n\nfunction someFunction (someArg) {alert(someArg);}\n\nvar object=document.getElementById('somObject_id') ;\nvar someArg=\"Hi there !\";\nvar func=function(){someFunction (someArg)};\n\n// mouseover is inactive\naddEvent (object, 'mouseover', func);\n// mouseover is now active\naddEvent (object, 'mouseover');\n// mouseover is inactive\n</code></pre>\n\n<p>Hope there is no typos :-)</p>\n" }, { "answer_id": 11515561, "author": "kta", "author_id": 539023, "author_profile": "https://Stackoverflow.com/users/539023", "pm_score": 3, "selected": false, "text": "<p>Use </p>\n\n<pre><code> el.addEventListener('click',\n function(){\n // this will give you the id value \n alert(this.id); \n },\nfalse);\n</code></pre>\n\n<p>And if you want to pass any custom value into this anonymous function then the easiest way to do it is </p>\n\n<pre><code> // this will dynamically create property a property\n // you can create anything like el.&lt;your variable&gt;\n el.myvalue = \"hello world\";\n el.addEventListener('click',\n function(){\n //this will show you the myvalue \n alert(el.myvalue);\n // this will give you the id value \n alert(this.id); \n },\nfalse);\n</code></pre>\n\n<p>Works perfectly in my project. Hope this will help</p>\n" }, { "answer_id": 11986895, "author": "Zaloz", "author_id": 1603177, "author_profile": "https://Stackoverflow.com/users/1603177", "pm_score": 9, "selected": false, "text": "<p>Why not just get the arguments from the target attribute of the event?</p>\n\n<p>Example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const someInput = document.querySelector('button');\r\nsomeInput.addEventListener('click', myFunc, false);\r\nsomeInput.myParam = 'This is my parameter';\r\nfunction myFunc(evt)\r\n{\r\n window.alert(evt.currentTarget.myParam);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button class=\"input\"&gt;Show parameter&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>JavaScript is a prototype-oriented language, remember!</p>\n" }, { "answer_id": 16595873, "author": "Brian Moore", "author_id": 623315, "author_profile": "https://Stackoverflow.com/users/623315", "pm_score": 7, "selected": false, "text": "<p>This question is old but I thought I'd offer an alternative using ES5's <code>.bind()</code> - for posterity. :)</p>\n<pre><code>function some_func(otherFunc, ev) {\n // magic happens\n}\nsomeObj.addEventListener(&quot;click&quot;, some_func.bind(null, some_other_func), false);\n</code></pre>\n<p>Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).</p>\n" }, { "answer_id": 21552207, "author": "eclos", "author_id": 3270790, "author_profile": "https://Stackoverflow.com/users/3270790", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind\" rel=\"noreferrer\">Function.prototype.bind()</a> is the way to bind a target function to a particular scope and optionally define the <code>this</code> object within the target function.</p>\n\n<pre><code>someObj.addEventListener(\"click\", some_function.bind(this), false);\n</code></pre>\n\n<p>Or to capture some of the lexical scope, for example in a loop:</p>\n\n<pre><code>someObj.addEventListener(\"click\", some_function.bind(this, arg1, arg2), false);\n</code></pre>\n\n<p>Finally, if the <code>this</code> parameter is not needed within the target function:</p>\n\n<pre><code>someObj.addEventListener(\"click\", some_function.bind(null, arg1, arg2), false);\n</code></pre>\n" }, { "answer_id": 23024673, "author": "Oleksandr Tkalenko", "author_id": 1027440, "author_profile": "https://Stackoverflow.com/users/1027440", "pm_score": 5, "selected": false, "text": "<p>You can just bind all necessary arguments with 'bind':</p>\n\n<pre><code>root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));\n</code></pre>\n\n<p>In this way you'll always get the <code>event</code>, <code>arg1</code>, and other stuff passed to <code>myPrettyHandler</code>.</p>\n\n<p><a href=\"http://passy.svbtle.com/partial-application-in-javascript-using-bind\" rel=\"noreferrer\">http://passy.svbtle.com/partial-application-in-javascript-using-bind</a></p>\n" }, { "answer_id": 23636295, "author": "fhuertas", "author_id": 3567642, "author_profile": "https://Stackoverflow.com/users/3567642", "pm_score": -1, "selected": false, "text": "<p>Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop </p>\n\n<pre><code>for (var key in catalog){\n document.getElementById(key).my_id = key\n document.getElementById(key).addEventListener('click', function(e) {\n editorContent.loadCatalogEntry(e.srcElement.my_id)\n }, false);\n}\n</code></pre>\n\n<p>It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers</p>\n\n<p>I found this solution using the <a href=\"https://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function#comment7616286_256763\">comment</a> posted by <a href=\"https://stackoverflow.com/users/279755/imatoria\">Imatoria</a> but I cannot mark it as useful because I do not have enough reputation :D</p>\n" }, { "answer_id": 24018543, "author": "Asik", "author_id": 1387002, "author_profile": "https://Stackoverflow.com/users/1387002", "pm_score": 1, "selected": false, "text": "<p>The following answer is correct but the below code is not working in IE8 if suppose you compressed the js file using yuicompressor. (In fact,still most of the US peoples using IE8)</p>\n\n<pre><code>var someVar; \nsomeVar = some_other_function();\nalert(someVar);\nsomeObj.addEventListener(\"click\",\n function(){\n some_function(someVar);\n },\n false);\n</code></pre>\n\n<p>So, we can fix the above issue as follows and it works fine in all browsers</p>\n\n<pre><code>var someVar, eventListnerFunc;\nsomeVar = some_other_function();\neventListnerFunc = some_function(someVar);\nsomeObj.addEventListener(\"click\", eventListnerFunc, false);\n</code></pre>\n\n<p>Hope, it would be useful for some one who is compressing the js file in production environment.</p>\n\n<p>Good Luck!!</p>\n" }, { "answer_id": 27908041, "author": "StanE", "author_id": 1854856, "author_profile": "https://Stackoverflow.com/users/1854856", "pm_score": 2, "selected": false, "text": "<p>There is a special variable inside all functions: <em>arguments</em>. You can pass your parameters as anonymous parameters and access them (by order) through the <em>arguments</em> variable.</p>\n\n<p>Example:</p>\n\n<pre><code>var someVar = some_other_function();\nsomeObj.addEventListener(\"click\", function(someVar){\n some_function(arguments[0]);\n}, false);\n</code></pre>\n" }, { "answer_id": 28633276, "author": "Hello World", "author_id": 2347534, "author_profile": "https://Stackoverflow.com/users/2347534", "pm_score": 4, "selected": false, "text": "<p>Here's yet another way (This one works inside for loops):</p>\n\n<pre><code>var someVar = some_other_function();\nsomeObj.addEventListener(\"click\", \n\nfunction(theVar){\n return function(){some_function(theVar)};\n}(someVar),\n\nfalse);\n</code></pre>\n" }, { "answer_id": 30732382, "author": "Šerg", "author_id": 4090695, "author_profile": "https://Stackoverflow.com/users/4090695", "pm_score": 0, "selected": false, "text": "<p>The following code worked fine for me (firefox):</p>\n\n<pre><code>for (var i=0; i&lt;3; i++) {\n element = new ... // create your element\n element.counter = i;\n element.addEventListener('click', function(e){\n console.log(this.counter);\n ... // another code with this element\n }, false);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>0\n1\n2\n</code></pre>\n" }, { "answer_id": 31195862, "author": "bob", "author_id": 1088866, "author_profile": "https://Stackoverflow.com/users/1088866", "pm_score": 2, "selected": false, "text": "<p>Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.</p>\n\n<p>Here's a nice little helper function you can use. Based on \"hello world's\" example above.)</p>\n\n<p>One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.</p>\n\n<pre><code>// Lambda closure chaos.\n//\n// Send an anonymous function to the listener, but execute it immediately.\n// This will cause the arguments are captured, which is useful when running \n// within loops.\n//\n// The anonymous function returns a closure, that will be executed when \n// the event triggers. And since the arguments were captured, any vars \n// that were sent in will be unique to the function.\n\nfunction addListenerWithArgs(elem, evt, func, vars){\n var f = function(ff, vv){\n return (function (){\n ff(vv);\n });\n }(func, vars);\n\n elem.addEventListener(evt, f);\n\n return f;\n}\n\n// Usage:\n\nfunction doSomething(withThis){\n console.log(\"withThis\", withThis);\n}\n\n// Capture the function so we can remove it later.\nvar storeFunc = addListenerWithArgs(someElem, \"click\", doSomething, \"foo\");\n\n// To remove the listener, use the normal routine:\nsomeElem.removeEventListener(\"click\", storeFunc);\n</code></pre>\n" }, { "answer_id": 32645073, "author": "Gennadiy Sherbakha", "author_id": 5349151, "author_profile": "https://Stackoverflow.com/users/5349151", "pm_score": 1, "selected": false, "text": "<pre><code> var EV = {\n ev: '',\n fn: '',\n elem: '',\n add: function () {\n this.elem.addEventListener(this.ev, this.fn, false);\n }\n };\n\n function cons() {\n console.log('some what');\n }\n\n EV.ev = 'click';\n EV.fn = cons;\n EV.elem = document.getElementById('body');\n EV.add();\n\n//If you want to add one more listener for load event then simply add this two lines of code:\n\n EV.ev = 'load';\n EV.add();\n</code></pre>\n" }, { "answer_id": 32930248, "author": "Felipe", "author_id": 4173568, "author_profile": "https://Stackoverflow.com/users/4173568", "pm_score": 3, "selected": false, "text": "<p>One way is doing this with an <strong>outer function</strong>:</p>\n\n<pre><code>elem.addEventListener('click', (function(numCopy) {\n return function() {\n alert(numCopy)\n };\n})(num));\n</code></pre>\n\n<p>This method of wrapping an anonymous function in parentheses and calling it right away is called an <strong>IIFE</strong> (Immediately-Invoked Function Expression)</p>\n\n<p>You can check an example with two parameters in <a href=\"http://codepen.io/froucher/pen/BoWwgz\" rel=\"noreferrer\">http://codepen.io/froucher/pen/BoWwgz</a>.</p>\n\n<pre><code>catimg.addEventListener('click', (function(c, i){\n return function() {\n c.meows++;\n i.textContent = c.name + '\\'s meows are: ' + c.meows;\n }\n})(cat, catmeows));\n</code></pre>\n" }, { "answer_id": 35212752, "author": "Nate", "author_id": 3549440, "author_profile": "https://Stackoverflow.com/users/3549440", "pm_score": 1, "selected": false, "text": "<p>The following approach worked well for me. Modified from <a href=\"https://github.com/loverajoel/jstips/blob/gh-pages/_posts/en/2016-01-16-passing-arguments-to-callback-functions.md\" rel=\"nofollow\">here</a>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function callback(theVar) {\r\n return function() {\r\n theVar();\r\n }\r\n}\r\n\r\nfunction some_other_function() {\r\n document.body.innerHTML += \"made it.\";\r\n}\r\n\r\nvar someVar = some_other_function;\r\ndocument.getElementById('button').addEventListener('click', callback(someVar));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n &lt;body&gt;\r\n &lt;button type=\"button\" id=\"button\"&gt;Click Me!&lt;/button&gt;\r\n &lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 35290817, "author": "Suneel Kumar", "author_id": 2301402, "author_profile": "https://Stackoverflow.com/users/2301402", "pm_score": 2, "selected": false, "text": "<p>I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly</p>\n\n<pre><code>for (var i = 0; i &lt; states_array.length; i++) {\n var link = document.getElementById('apply_'+states_array[i].state_id);\n link.my_id = i;\n link.addEventListener('click', function(e) { \n alert(e.target.my_id); \n some_function(states_array[e.target.my_id].css_url);\n });\n}\n</code></pre>\n" }, { "answer_id": 36786630, "author": "ahuigo", "author_id": 2140757, "author_profile": "https://Stackoverflow.com/users/2140757", "pm_score": 4, "selected": false, "text": "<p>You could pass somevar by value(not by reference) via a javascript feature known as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"noreferrer\">closure</a>:</p>\n\n<pre><code>var someVar='origin';\nfunc = function(v){\n console.log(v);\n}\ndocument.addEventListener('click',function(someVar){\n return function(){func(someVar)}\n}(someVar));\nsomeVar='changed'\n</code></pre>\n\n<p>Or you could write a common wrap function such as <code>wrapEventCallback</code>:</p>\n\n<pre><code>function wrapEventCallback(callback){\n var args = Array.prototype.slice.call(arguments, 1);\n return function(e){\n callback.apply(this, args)\n }\n}\nvar someVar='origin';\nfunc = function(v){\n console.log(v);\n}\ndocument.addEventListener('click',wrapEventCallback(func,someVar))\nsomeVar='changed'\n</code></pre>\n\n<p>Here <code>wrapEventCallback(func,var1,var2)</code> is like: </p>\n\n<pre><code>func.bind(null, var1,var2)\n</code></pre>\n" }, { "answer_id": 45696430, "author": "tomcek112", "author_id": 6691067, "author_profile": "https://Stackoverflow.com/users/6691067", "pm_score": 6, "selected": false, "text": "<p>Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"noreferrer\">currying.</a></p>\n\n<p>The code for that:</p>\n\n<pre><code>someObj.addEventListener('click', some_function(someVar));\n\nvar some_function = function(someVar) {\n return function curried_func(e) {\n // do something here\n }\n}\n</code></pre>\n\n<p>By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.</p>\n" }, { "answer_id": 50649380, "author": "Victor Behar", "author_id": 7768934, "author_profile": "https://Stackoverflow.com/users/7768934", "pm_score": 0, "selected": false, "text": "<p>You need:</p>\n\n<pre><code>newElem.addEventListener('click', {\n handleEvent: function (event) {\n clickImg(parameter);\n }\n});\n</code></pre>\n" }, { "answer_id": 53179059, "author": "fnclovers", "author_id": 8145426, "author_profile": "https://Stackoverflow.com/users/8145426", "pm_score": -1, "selected": false, "text": "<p>This solution may good for looking</p>\n\n<pre><code>var some_other_function = someVar =&gt; function() {\n}\n\nsomeObj.addEventListener('click', some_other_function(someVar));\n</code></pre>\n\n<p>or bind valiables will be also good</p>\n" }, { "answer_id": 54313715, "author": "developer82", "author_id": 2652208, "author_profile": "https://Stackoverflow.com/users/2652208", "pm_score": 3, "selected": false, "text": "<p>If I'm not mistaken using calling the function with <code>bind</code> actually creates a new function that is returned by the <code>bind</code> method. This will cause you problems later or if you would like to remove the event listener, as it's basically like an anonymous function:</p>\n\n<pre><code>// Possible:\nfunction myCallback() { /* code here */ }\nsomeObject.addEventListener('event', myCallback);\nsomeObject.removeEventListener('event', myCallback);\n\n// Not Possible:\nfunction myCallback() { /* code here */ }\nsomeObject.addEventListener('event', function() { myCallback });\nsomeObject.removeEventListener('event', /* can't remove anonymous function */);\n</code></pre>\n\n<p>So take that in mind.</p>\n\n<p>If you are using ES6 you could do the same as suggested but a bit cleaner:</p>\n\n<pre><code>someObject.addEventListener('event', () =&gt; myCallback(params));\n</code></pre>\n" }, { "answer_id": 54731362, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 3, "selected": false, "text": "<pre><code> $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));\n function save(data, keyword, name, comment, event) {\n</code></pre>\n\n<p>This is how I got event passed properly.</p>\n" }, { "answer_id": 55859799, "author": "Gon82", "author_id": 9212067, "author_profile": "https://Stackoverflow.com/users/9212067", "pm_score": 5, "selected": false, "text": "<p>nice one line alternative</p>\n\n<pre><code>element.addEventListener('dragstart',(evt) =&gt; onDragStart(param1, param2, param3, evt));\n</code></pre>\n\n<pre><code>function onDragStart(param1, param2, param3, evt) {\n\n //some action...\n\n}\n</code></pre>\n" }, { "answer_id": 55925153, "author": "Spoo", "author_id": 2415580, "author_profile": "https://Stackoverflow.com/users/2415580", "pm_score": 0, "selected": false, "text": "<p>Probably not optimal, but simple enough for those not super js savvy. Put the function that calls addEventListener into its own function. That way any function values passed into it maintain their own scope and you can iterate over that function as much as you want.</p>\n\n<p>Example I worked out with file reading as I needed to capture and render a preview of the image and filename. It took me awhile to avoid asynchronous issues when utilizing a multiple file upload type. I would accidentally see the same 'name' on all renders despite uploading different files.</p>\n\n<p>Originally, all the readFile() function was within the readFiles() function. This caused asynchronous scoping issues.</p>\n\n<pre><code> function readFiles(input) {\n if (input.files) {\n for(i=0;i&lt;input.files.length;i++) {\n\n var filename = input.files[i].name;\n\n if ( /\\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {\n readFile(input.files[i],filename);\n }\n }\n }\n } //end readFiles\n\n\n\n function readFile(file,filename) {\n var reader = new FileReader();\n\n reader.addEventListener(\"load\", function() { alert(filename);}, false);\n\n reader.readAsDataURL(file);\n\n } //end readFile\n</code></pre>\n" }, { "answer_id": 57889478, "author": "Bruce Tong", "author_id": 6131033, "author_profile": "https://Stackoverflow.com/users/6131033", "pm_score": 0, "selected": false, "text": "<p>just would like to add. if anyone is adding a function which updates checkboxes to an event listener, you would have to use <code>event.target</code> instead of <code>this</code> to update the checkboxes.</p>\n" }, { "answer_id": 59418293, "author": "hoogw", "author_id": 3521515, "author_profile": "https://Stackoverflow.com/users/3521515", "pm_score": 3, "selected": false, "text": "<p>In 2019, lots of api changes, the best answer no longer works, without fix bug.</p>\n\n<p>share some working code. </p>\n\n<p>Inspired by all above answer.</p>\n\n<pre><code> button_element = document.getElementById('your-button')\n\n button_element.setAttribute('your-parameter-name',your-parameter-value);\n\n button_element.addEventListener('click', your_function);\n\n\n function your_function(event)\n {\n //when click print the parameter value \n console.log(event.currentTarget.attributes.your-parameter-name.value;)\n }\n</code></pre>\n" }, { "answer_id": 61986436, "author": "AAYUSH SHAH", "author_id": 9082644, "author_profile": "https://Stackoverflow.com/users/9082644", "pm_score": -1, "selected": false, "text": "<p>I have very simplistic approach. This may work for others as it helped me.\nIt is...\nWhen you are having multiple elements/variables assigned a same function and you want to pass the reference, the simplest solution is...</p>\n\n<pre><code>function Name()\n{\n\nthis.methodName = \"Value\"\n\n}\n</code></pre>\n\n<p>That's it.\nIt worked for me. \n<strong><em>So simple.</em></strong></p>\n" }, { "answer_id": 63320750, "author": "Michael", "author_id": 14041506, "author_profile": "https://Stackoverflow.com/users/14041506", "pm_score": 1, "selected": false, "text": "<p>Since your event listener is 'click', you can:</p>\n<pre><code>someObj.setAttribute(&quot;onclick&quot;, &quot;function(parameter)&quot;);\n</code></pre>\n" }, { "answer_id": 67185345, "author": "Alvaro Gabriel Gomez", "author_id": 10797766, "author_profile": "https://Stackoverflow.com/users/10797766", "pm_score": 3, "selected": false, "text": "<p>one easy way to execute that may be this</p>\n<pre><code> window.addEventListener('click', (e) =&gt; functionHandler(e, ...args));\n</code></pre>\n<p>Works for me.</p>\n" }, { "answer_id": 70967292, "author": "leafsAsd", "author_id": 11042072, "author_profile": "https://Stackoverflow.com/users/11042072", "pm_score": 1, "selected": false, "text": "<p>I suggest you to do something like that:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var someVar = some_other_function();\nsomeObj.addEventListener(&quot;click&quot;, (event, param1 = someVar) =&gt; {\n some_function(param1);\n}, false);\n</code></pre>\n" }, { "answer_id": 72380138, "author": "Al Po", "author_id": 1224072, "author_profile": "https://Stackoverflow.com/users/1224072", "pm_score": 1, "selected": false, "text": "<p>Another workaround is by <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"nofollow noreferrer\">Using data attributes</a></p>\n<pre><code>function func(){\n console.log(this.dataset.someVar);\n div.removeEventListener(&quot;click&quot;, func);\n}\n \nvar div = document.getElementById(&quot;some-div&quot;);\ndiv.setAttribute(&quot;data-some-var&quot;, &quot;hello&quot;);\ndiv.addEventListener(&quot;click&quot;, func);\n</code></pre>\n<p><a href=\"https://jsfiddle.net/vir2alexport/76nr1gkv/\" rel=\"nofollow noreferrer\">jsfiddle</a></p>\n" }, { "answer_id": 74127970, "author": "Dejan Dozet", "author_id": 4541566, "author_profile": "https://Stackoverflow.com/users/4541566", "pm_score": 1, "selected": false, "text": "<p>The PERFECT SOLUTION for this is to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"nofollow noreferrer\">Closures</a> like this:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function makeSizer(size) {\n return function () {\n document.body.style.fontSize = `${size}px`;\n };\n}\n\n//pass parameters here and keep the reference in variables:\nconst size12 = makeSizer(12);\nconst size24 = makeSizer(24);\nconst size36 = makeSizer(36);\n\ndocument.getElementById('size-12').addEventListener(\"click\", size12);\ndocument.getElementById('size-24').addEventListener(\"click\", size24);\ndocument.getElementById('size-36').addEventListener(\"click\", size36);\n\ndocument.getElementById('remove-12').addEventListener(\"click\", ()=&gt;{\n document.getElementById('size-12').removeEventListener(\"click\", size12);\n alert(\"Now click on 'size 12' button and you will see that there is no event listener any more\");\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>test&lt;br/&gt;\n&lt;button id=\"size-12\"&gt;\nsize 12\n&lt;/button&gt;\n\n&lt;button id=\"size-24\"&gt;\nsize 24\n&lt;/button&gt;\n\n&lt;button id=\"size-36\"&gt;\nsize 36\n&lt;/button&gt;\n\n&lt;button id=\"remove-12\"&gt;\nremove 12\n&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>So basically you wrap a function inside another function and assign that to a variable that you can register as an event listener, but also unregister as well!</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30252/" ]
The situation is somewhat like- ``` var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false); ``` The problem is that the value of `someVar` is not visible inside the listener function of the `addEventListener`, where it is probably being treated as a new variable.
There is absolutely nothing wrong with the code you've written. Both `some_function` and `someVar` should be accessible, in case they were available in the context where anonymous ``` function() { some_function(someVar); } ``` was created. Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same `someVar` variable next to the call to `addEventListener`) ``` var someVar; someVar = some_other_function(); alert(someVar); someObj.addEventListener("click", function(){ some_function(someVar); }, false); ```
256,804
<p>Is there a way to execute SQL custom functions with Enterpise Library? I've tried Database.ExecuteScalar() but for some reason it returns null.</p> <p>This is my function:</p> <pre><code>Database db = DatabaseFactory.CreateDatabase("ConnectionString"); DbCommand cmd = db.GetStoredProcCommand("FunctionName"); db.AddInParameter(cmd, "Value1", DbType.String, Param1Value); db.AddInParameter(cmd, "Value2", DbType.String, Param2Value); return Convert.ToBoolean(db.ExecuteScalar(cmd)); </code></pre> <p>Here the db.ExecuteScalar(cmd) method returns null. This does not happen with Stored Procedures.</p> <p>By the way, im using version 4.0</p> <p>Thanks.</p>
[ { "answer_id": 256851, "author": "cstick", "author_id": 2735, "author_profile": "https://Stackoverflow.com/users/2735", "pm_score": 4, "selected": true, "text": "<p>You have to create a select statement which selects the result from the function and execute that.</p>\n\n<p>\"SELECT * FROM FunctionName(@Value1, @Value2)\"</p>\n\n<p>Or you can wrap your function call in a procedure and call the procedure, I prefer this.</p>\n" }, { "answer_id": 256898, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 2, "selected": false, "text": "<p>For scalar functions it would be</p>\n\n<pre><code>SELECT FuncName(@Param1)\n</code></pre>\n\n<p>whereas a Table-Valued Function would be</p>\n\n<pre><code>SELECT * FROM FuncName(@Param1)\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14533/" ]
Is there a way to execute SQL custom functions with Enterpise Library? I've tried Database.ExecuteScalar() but for some reason it returns null. This is my function: ``` Database db = DatabaseFactory.CreateDatabase("ConnectionString"); DbCommand cmd = db.GetStoredProcCommand("FunctionName"); db.AddInParameter(cmd, "Value1", DbType.String, Param1Value); db.AddInParameter(cmd, "Value2", DbType.String, Param2Value); return Convert.ToBoolean(db.ExecuteScalar(cmd)); ``` Here the db.ExecuteScalar(cmd) method returns null. This does not happen with Stored Procedures. By the way, im using version 4.0 Thanks.
You have to create a select statement which selects the result from the function and execute that. "SELECT \* FROM FunctionName(@Value1, @Value2)" Or you can wrap your function call in a procedure and call the procedure, I prefer this.
256,807
<p>Is there any way to check if a given index of an array exists? I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.</p> <p>I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++</p> <p>PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks</p>
[ { "answer_id": 256814, "author": "mdec", "author_id": 15534, "author_profile": "https://Stackoverflow.com/users/15534", "pm_score": 2, "selected": false, "text": "<p>My personal vote is for using a vector. They will resize dynamically, and as long as you don't do something stupid (like try and access an element that doesn't exist) they are quite friendly to use.</p>\n\n<p>As for tutorials the best thing I could point you towards is a <a href=\"http://www.google.com.au/search?q=C%2B%2B+vector+tutorial\" rel=\"nofollow noreferrer\">google search</a></p>\n" }, { "answer_id": 256825, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": 4, "selected": true, "text": "<p>In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs:</p>\n\n<pre><code>int i[10];\ni[10] = 2; // Legal but very dangerous! Writing on memory you don't know about\n</code></pre>\n\n<p>It seems that you want array-like behavior, but without all elements being filled. Traditionally, this is in the realms of hash-tables. Vectors are not such a good solution here as you will have empty elements taking up space, much better is something like a map, where you can test if an element exists by searching for it and interpreting the result:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n\n// Declare the map - integer keys, string values \nstd::map&lt;int, std::string&gt; a;\n\n// Add an item at an arbitrary location\na[2] = std::string(\"A string\");\n\n// Find a key that isn't present\nif(a.find(1) == a.end())\n{\n // This code will be run in this example\n std::cout &lt;&lt; \"Not found\" &lt;&lt; std::endl;\n}\nelse\n{\n std::cout &lt;&lt; \"Found\" &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>One word of warning: Use the above method to find if a key exists, rather than something like testing for a default value</p>\n\n<pre><code>if(a[2] == 0)\n{\n a[2] = myValueToPutIn;\n}\n</code></pre>\n\n<p>as the behavior of a map is to insert a default constructed object on the first access of that key value, if nothing is currently present.</p>\n" }, { "answer_id": 259452, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 1, "selected": false, "text": "<p>It sounds to me as though really a map is closest to what you want. You can use the Map class in the STL (standard template library)(<a href=\"http://www.cppreference.com/wiki/stl/map/start\" rel=\"nofollow noreferrer\">http://www.cppreference.com/wiki/stl/map/start</a>).</p>\n\n<p>Maps provide a container for objects which can be referenced by a key (your \"index\").</p>\n" }, { "answer_id": 31472020, "author": "MukeshD", "author_id": 2679111, "author_profile": "https://Stackoverflow.com/users/2679111", "pm_score": 2, "selected": false, "text": "<p>To do this without vectors, you can simply cross-check the index you are tying to access with the size of array. Like: <code>if(index &lt; array_size)</code> it is invalid index.</p>\n\n<p>In case the size is not known to you, you can find it using the <code>sizeof</code> operator.</p>\n\n<p>For example:</p>\n\n<pre><code>int arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};\nint arr_size = sizeof(arr)/sizeof(arr[0]);\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
Is there any way to check if a given index of an array exists? I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter. I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++ PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks
In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs: ``` int i[10]; i[10] = 2; // Legal but very dangerous! Writing on memory you don't know about ``` It seems that you want array-like behavior, but without all elements being filled. Traditionally, this is in the realms of hash-tables. Vectors are not such a good solution here as you will have empty elements taking up space, much better is something like a map, where you can test if an element exists by searching for it and interpreting the result: ``` #include <map> #include <string> // Declare the map - integer keys, string values std::map<int, std::string> a; // Add an item at an arbitrary location a[2] = std::string("A string"); // Find a key that isn't present if(a.find(1) == a.end()) { // This code will be run in this example std::cout << "Not found" << std::endl; } else { std::cout << "Found" << std::endl; } ``` One word of warning: Use the above method to find if a key exists, rather than something like testing for a default value ``` if(a[2] == 0) { a[2] = myValueToPutIn; } ``` as the behavior of a map is to insert a default constructed object on the first access of that key value, if nothing is currently present.
256,811
<p>How do you create non scrolling div that looks like the MS Office 2007 ribbon on a web page without two sets of scroll bars. One for the window and one for the div.</p>
[ { "answer_id": 256830, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 3, "selected": false, "text": "<p>Use a fixed position <code>&lt;div&gt;</code> element, that has 100% width and a high <code>z-index</code>.</p>\n\n<p>You'll also want to ensure that that the start of your scrolling content isn't obscured by the fixed <code>&lt;div&gt;</code>, until you start scrolling down, by putting this in another <code>&lt;div&gt;</code> and positioning this appropriately.</p>\n\n<pre><code>&lt;body&gt;\n &lt;div style=\"position: fixed; top: 0px; width:100%; height: 100px;\"&gt;\n HEader content goes here\n &lt;/div&gt;\n &lt;div style=\"margin-top: 100px;\"&gt;\n Main content goes here\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>Note the the height of the first <code>&lt;div&gt;</code>, and the top margin of the second, will need to be adjusted to suit your needs.</p>\n\n<p>P.S. This doesn't work in IE7, for some reason, but it's a good starting point, and I'm sure that you can work out some variation on this theme, that works in the way that you want it to.</p>\n" }, { "answer_id": 256870, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 0, "selected": false, "text": "<p>You could alternatively use </p>\n\n<pre><code>\n&lt;div style='position:absolute;top:0px:left:0px;'&gt;Text&lt/div&gt;;\n</code></pre>\n\n<p>It will jamm the div on the top of the page, but if your page scrolls down it will stay there. </p>\n" }, { "answer_id": 258404, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 0, "selected": false, "text": "<p>Belugabob has the right idea that what you are trying to do is fixed positioning, which IE 6 does not support.</p>\n\n<p>I modified an example from the bottom of <a href=\"http://www.howtocreate.co.uk/fixedPosition.html\" rel=\"nofollow noreferrer\">this tutorial</a> which should do what you want and support IE 6+ in addition to all the good browsers. It works because IE lets you put Javascript in style declarations:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n div#fixme {\n width: 100%; /* For all browsers */\n }\n body &gt; div#fixme {\n position: fixed; /* For good browsers */\n }\n&lt;/style&gt;\n\n&lt;!--[if gte IE 5.5]&gt;\n&lt;![if lt IE 7]&gt;\n&lt;style type=\"text/css\"&gt;\n div#fixme {\n /* IE5.5+/Win - this is more specific than the IE 5.0 version */\n right: auto; bottom: auto;\n left: expression( ( 0 - fixme.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );\n top: expression( ( 0 - fixme.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );\n }\n&lt;/style&gt;\n&lt;![endif]&gt;\n&lt;![endif]--&gt;\n\n&lt;body&gt;\n &lt;div id=\"fixme\"&gt; ...\n</code></pre>\n" }, { "answer_id": 258967, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head&gt;\n &lt;title&gt;Fixed Header/Full Page Content&lt;/title&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;\n &lt;style type=\"text/css\"&gt;\n body,\n div {\n margin: 0;\n padding: 0;\n }\n\n body {\n /* Disable scrollbars and ensure that the body fills the window */\n overflow: hidden;\n width: 100%;\n height: 100%;\n }\n\n #header {\n /* Provide scrollbars if needed and fix the header dimensions */\n overflow: auto;\n position: absolute;\n width: 100%;\n height: 200px;\n }\n\n #main {\n /* Provide scrollbars if needed, position below header, and derive height from top/bottom */\n overflow: auto;\n position: absolute;\n width: 100%;\n top: 200px;\n bottom: 0;\n }\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div id=\"header\"&gt;HEADER&lt;/div&gt;\n &lt;div id=\"main\"&gt;\n &lt;p&gt;FIRST&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;MAIN&lt;/p&gt;\n &lt;p&gt;LAST&lt;/p&gt;\n &lt;/div&gt;\n&lt;!--[if lt IE 7]&gt;\n &lt;script type=\"text/javascript\"&gt;\n var elMain = document.getElementById('main');\n\n setMainDims();\n document.body.onresize = setMainDims;\n\n function setMainDims() {\n elMain.style.height = (document.body.clientHeight - 200) + 'px';\n elMain.style.width = '99%'\n setTimeout(\"elMain.style.width = '100%'\", 0);\n }\n &lt;/script&gt;\n&lt;![endif]--&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Basically, what you are doing is removing the scrollbars from the body and applying scrollbars to elements inside the document. That is simple. The trick is to get the <code>#main</code> div to size to fill the space below the header. This is accomplished in most browsers by setting both the <code>top</code> and the <code>bottom</code> positions and leaving the <code>height</code> unset. The result is that the top of the div is fixed below the header and the bottom of the div will always stretch to the bottom of the screen.</p>\n\n<p>Of course there is always IE6 there to make sure that we earn our paychecks. Prior to version 7 IE wouldn't derive dimensions from conflicting absolute positions. <a href=\"http://www.alistapart.com/articles/conflictingabsolutepositions\" rel=\"noreferrer\">Some people</a> use IE's css expressions to solve this problem for IE6, but these expressions literally evaluate on every mousemove, so I'm simply resizing the <code>#main</code> div on the resize event and hiding that block of javascript from other browsers using a conditional comment.</p>\n\n<p>The lines setting the width to 99% and the setTimeout to set it back to 100% fixes a little rendering oddity in IE6 that causes the horizontal scrollbar to appear occasionally when you resize the window.</p>\n\n<p><em>Note: You must use a doctype and get IE out of quirks mode.</em></p>\n" }, { "answer_id": 261292, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 2, "selected": false, "text": "<p>I will probably be bashed by CSS purists here, but using a table with 100% width and height works in any browser, and does not require browser-specific CSS hacks.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you create non scrolling div that looks like the MS Office 2007 ribbon on a web page without two sets of scroll bars. One for the window and one for the div.
Try this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Fixed Header/Full Page Content</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> body, div { margin: 0; padding: 0; } body { /* Disable scrollbars and ensure that the body fills the window */ overflow: hidden; width: 100%; height: 100%; } #header { /* Provide scrollbars if needed and fix the header dimensions */ overflow: auto; position: absolute; width: 100%; height: 200px; } #main { /* Provide scrollbars if needed, position below header, and derive height from top/bottom */ overflow: auto; position: absolute; width: 100%; top: 200px; bottom: 0; } </style> </head> <body> <div id="header">HEADER</div> <div id="main"> <p>FIRST</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>MAIN</p> <p>LAST</p> </div> <!--[if lt IE 7]> <script type="text/javascript"> var elMain = document.getElementById('main'); setMainDims(); document.body.onresize = setMainDims; function setMainDims() { elMain.style.height = (document.body.clientHeight - 200) + 'px'; elMain.style.width = '99%' setTimeout("elMain.style.width = '100%'", 0); } </script> <![endif]--> </body> </html> ``` Basically, what you are doing is removing the scrollbars from the body and applying scrollbars to elements inside the document. That is simple. The trick is to get the `#main` div to size to fill the space below the header. This is accomplished in most browsers by setting both the `top` and the `bottom` positions and leaving the `height` unset. The result is that the top of the div is fixed below the header and the bottom of the div will always stretch to the bottom of the screen. Of course there is always IE6 there to make sure that we earn our paychecks. Prior to version 7 IE wouldn't derive dimensions from conflicting absolute positions. [Some people](http://www.alistapart.com/articles/conflictingabsolutepositions) use IE's css expressions to solve this problem for IE6, but these expressions literally evaluate on every mousemove, so I'm simply resizing the `#main` div on the resize event and hiding that block of javascript from other browsers using a conditional comment. The lines setting the width to 99% and the setTimeout to set it back to 100% fixes a little rendering oddity in IE6 that causes the horizontal scrollbar to appear occasionally when you resize the window. *Note: You must use a doctype and get IE out of quirks mode.*
256,822
<p>In RoR,how to validate a Chinese or a Japanese word for a posting form with utf8 code.</p> <p>In GBK code, it uses [\u4e00-\u9fa5]+ to validate Chinese words. In Php, it uses /^[\x{4e00}-\x{9fa5}]+$/u for utf-8 pages.</p>
[ { "answer_id": 256855, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": false, "text": "<p>Ruby 1.8 has poor support for UTF-8 strings. You need to write the bytes individually in the regular expression, rather then the full code:</p>\n\n<pre><code>&gt;&gt; \"acentuação\".scan(/\\xC3\\xA7/)\n=&gt; [\"ç\"] \n</code></pre>\n\n<p>To match the range you specified the expression will become a bit complicated:</p>\n\n<pre><code>/([\\x4E-\\x9E][\\x00-\\xFF])|(\\x9F[\\x00-\\xA5])/ # (untested)\n</code></pre>\n\n<p><a href=\"http://books.google.com.br/books?id=jcUbTcr5XWwC&amp;pg=PA50&amp;lpg=PA50&amp;source=web&amp;ots=fHClxbbxcy&amp;sig=up3TxmEM9C3N1K8hf-nnBQDzPUQ&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=6&amp;ct=result\" rel=\"noreferrer\">That will be improved in Ruby 1.9</a>, though.</p>\n\n<p><em>Edit:</em> As noted in the comments, the unicode characters \\u4E00-\\u9FA5 only map to the expression above in the UTF16-BE encoding. The UTF8 encoding is likely different. So you need to analyze the mapping carefully and see if you can come up with a byte-matching expression for Ruby 1.8.</p>\n" }, { "answer_id": 256873, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 1, "selected": false, "text": "<p>activeSupport has a UTF-8 handler</p>\n\n<p><a href=\"http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Handlers/UTF8Handler.html\" rel=\"nofollow noreferrer\">http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Handlers/UTF8Handler.html</a></p>\n\n<hr>\n\n<p>otherwise, look in ruby 1.9, encoding method for Regexp objects</p>\n" }, { "answer_id": 257633, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"https://github.com/stedolan/jq/wiki/Docs-for-Oniguruma-Regular-Expressions-(RE.txt)\" rel=\"nofollow noreferrer\" title=\"Oniguruma\">Oniguruma</a> regexp engine has proper support for Unicode. Ruby 1.9 uses Oniguruma by default. Ruby 1.8 can be recompiled to use it.</p>\n\n<p>With Oniguruma you can use the exact same regex as in PHP, including the /u modifier to force Ruby to treat the string as UTF-8.</p>\n" }, { "answer_id": 1971006, "author": "Jose Barrera", "author_id": 239738, "author_profile": "https://Stackoverflow.com/users/239738", "pm_score": 2, "selected": false, "text": "<p>This is what i have done:</p>\n\n<pre><code>%r{^[#{\"\\344\\270\\200\"}-#{\"\\351\\277\\277\"}]+$}\n</code></pre>\n\n<p>This is basically a regular expression with the octal values that represent the range between U+4E00 and U+9FFF, the most common Chinese and Japanese characters.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20191/" ]
In RoR,how to validate a Chinese or a Japanese word for a posting form with utf8 code. In GBK code, it uses [\u4e00-\u9fa5]+ to validate Chinese words. In Php, it uses /^[\x{4e00}-\x{9fa5}]+$/u for utf-8 pages.
Ruby 1.8 has poor support for UTF-8 strings. You need to write the bytes individually in the regular expression, rather then the full code: ``` >> "acentuação".scan(/\xC3\xA7/) => ["ç"] ``` To match the range you specified the expression will become a bit complicated: ``` /([\x4E-\x9E][\x00-\xFF])|(\x9F[\x00-\xA5])/ # (untested) ``` [That will be improved in Ruby 1.9](http://books.google.com.br/books?id=jcUbTcr5XWwC&pg=PA50&lpg=PA50&source=web&ots=fHClxbbxcy&sig=up3TxmEM9C3N1K8hf-nnBQDzPUQ&hl=en&sa=X&oi=book_result&resnum=6&ct=result), though. *Edit:* As noted in the comments, the unicode characters \u4E00-\u9FA5 only map to the expression above in the UTF16-BE encoding. The UTF8 encoding is likely different. So you need to analyze the mapping carefully and see if you can come up with a byte-matching expression for Ruby 1.8.
256,823
<p>The scenario is trying to adjust font size to get a nice graphic arrangement, or trying to decide where to break a caption/subtitle. a) In XL VBA is there a way to find out whether a text on a textbox, or caption on a label, still fits the control? b) Is there a way to know where was the text/caption broken on multiline control?</p>
[ { "answer_id": 256885, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>I'm sure there is no way to do this with the ordinary Excel controls on the Forms toolbar, not least because (as I understand it) they are simply drawings and not full Windows controls.</p>\n\n<p>The simplest approach may be to make a slightly conservative estimate of the maximum text length for each control, through a few tests, and use these to manage your line breaks.</p>\n" }, { "answer_id": 257458, "author": "jpinto3912", "author_id": 11567, "author_profile": "https://Stackoverflow.com/users/11567", "pm_score": 3, "selected": true, "text": "<p>I gave this a rest, gave it enough back-of-head time (which produces far better results than \"burp a non-answer ASAP, for credits\"), and...</p>\n\n<pre><code>Function TextWidth(aText As String, Optional aFont As NewFont) As Single\n Dim theFont As New NewFont\n Dim notSeenTBox As Control\n\n On Error Resume Next 'trap for aFont=Nothing\n theFont = aFont 'try assign\n\n If Err.Number Then 'can't use aFont because it's not instantiated/set\n theFont.Name = \"Tahoma\"\n theFont.Size = 8\n theFont.Bold = False\n theFont.Italic = False\n End If\n On Error GoTo ErrHandler\n\n 'make a TextBox, fiddle with autosize et al, retrive control width\n Set notSeenTBox = UserForms(0).Controls.Add(\"Forms.TextBox.1\", \"notSeen1\", False)\n notSeenTBox.MultiLine = False\n notSeenTBox.AutoSize = True 'the trick\n notSeenTBox.Font.Name = theFont.Name\n notSeenTBox.SpecialEffect = 0\n notSeenTBox.Width = 0 ' otherwise we get an offset (a \"\"feature\"\" from MS)\n notSeenTBox.Text = aText\n TextWidth = notSeenTBox.Width\n 'done with it, to scrap I say\n UserForms(0).Controls.Remove (\"notSeen1\")\n Exit Function\n\nErrHandler:\n TextWidth = -1\n MsgBox \"TextWidth failed: \" + Err.Description\nEnd Function\n</code></pre>\n\n<p>I feel I'm getting/got close to answer b), but I'll give it a second mind rest... because it works better than stating \"impossible\" in a flash.</p>\n" }, { "answer_id": 68120747, "author": "Wayne Hoff", "author_id": 16309261, "author_profile": "https://Stackoverflow.com/users/16309261", "pm_score": 0, "selected": false, "text": "<p>This can be achieved by taking advantage of the label or textbox's .AutoSize feature, and looping through font sizes until you reach the one that fits best.</p>\n<pre><code>Public Sub ResizeTextToFit(Ctrl As MSForms.Label) 'or TextBox\n \n Const FONT_SHRINKAGE_FACTOR As Single = 0.9 'For more accuracy, use .95 or .99\n \n Dim OrigWidth As Single\n Dim OrigHeight As Single\n Dim OrigLeft As Single\n Dim OrigTop As Single\n \n With Ctrl\n If .Caption = &quot;&quot; Then Exit Sub\n .AutoSize = False\n OrigWidth = .Width\n OrigHeight = .Height\n OrigLeft = .Left\n OrigTop = .Top\n Do\n .AutoSize = True\n If .Width &lt;= OrigWidth And .Height &lt;= OrigHeight Then\n Exit Do 'The font is small enough now\n .Font.Size = .Font.Size * FONT_SHRINKAGE_FACTOR\n .AutoSize = False\n Loop\n .AutoSize = False\n .Width = OrigWidth\n .Height = OrigHeight\n .Left = OrigLeft\n .Top = OrigTop\n End With\n\nEnd Sub\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11567/" ]
The scenario is trying to adjust font size to get a nice graphic arrangement, or trying to decide where to break a caption/subtitle. a) In XL VBA is there a way to find out whether a text on a textbox, or caption on a label, still fits the control? b) Is there a way to know where was the text/caption broken on multiline control?
I gave this a rest, gave it enough back-of-head time (which produces far better results than "burp a non-answer ASAP, for credits"), and... ``` Function TextWidth(aText As String, Optional aFont As NewFont) As Single Dim theFont As New NewFont Dim notSeenTBox As Control On Error Resume Next 'trap for aFont=Nothing theFont = aFont 'try assign If Err.Number Then 'can't use aFont because it's not instantiated/set theFont.Name = "Tahoma" theFont.Size = 8 theFont.Bold = False theFont.Italic = False End If On Error GoTo ErrHandler 'make a TextBox, fiddle with autosize et al, retrive control width Set notSeenTBox = UserForms(0).Controls.Add("Forms.TextBox.1", "notSeen1", False) notSeenTBox.MultiLine = False notSeenTBox.AutoSize = True 'the trick notSeenTBox.Font.Name = theFont.Name notSeenTBox.SpecialEffect = 0 notSeenTBox.Width = 0 ' otherwise we get an offset (a ""feature"" from MS) notSeenTBox.Text = aText TextWidth = notSeenTBox.Width 'done with it, to scrap I say UserForms(0).Controls.Remove ("notSeen1") Exit Function ErrHandler: TextWidth = -1 MsgBox "TextWidth failed: " + Err.Description End Function ``` I feel I'm getting/got close to answer b), but I'll give it a second mind rest... because it works better than stating "impossible" in a flash.
256,832
<p>I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop:</p> <pre><code>// Form has a menu containing a combobox added via SharpDevelop's GUI // --- Variables languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet(); // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add( lName ); for( int i=0; i&lt;languages.Length; i++ ) { DataRow lLang = lTable.NewRow(); lLang["Language"] = languages[i]; lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable); // --- Handling the combobox mnuActionLanguage.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; mnuActionLanguage.ComboBox.DisplayMember = "Language"; </code></pre> <p>One would assume to see some values in the dropdown, but it's empty. Please tell me what I'm doing wrong ;(</p> <p><em>EDIT: mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.</em></p> <p><strong>SOLUTION</strong></p> <pre><code>mnuActionLanguage.ComboBox.BindingContext = this.BindingContext; </code></pre> <p>at the end solved the problem!</p>
[ { "answer_id": 256840, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 0, "selected": false, "text": "<p>This line</p>\n\n<pre><code>mnuActionLanguage.ComboBox.DisplayMember = \"Lang.Language\";\n</code></pre>\n\n<p>is wrong. Change it to</p>\n\n<pre><code>mnuActionLanguage.ComboBox.DisplayMember = \"Language\";\n</code></pre>\n\n<p>and it will work (even without DataBind()).</p>\n" }, { "answer_id": 256854, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "<p>A few points:</p>\n\n<p>1) \"DataBind()\" is only for web apps (not windows apps).</p>\n\n<p>2) Your code looks very 'JAVAish' (not a bad thing, just an observation).</p>\n\n<p>Try this:</p>\n\n<pre><code>mnuActionLanguage.ComboBox.DataSource = languages;\n</code></pre>\n\n<p>If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.</p>\n" }, { "answer_id": 256864, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "<p>Are you applying a RowFilter to your DefaultView later in the code? This could change the results returned.</p>\n\n<p>I would also avoid using the string as the display member if you have a direct reference the the data column I would use the object properties:</p>\n\n<pre><code>mnuActionLanguage.ComboBox.DataSource = lTable.DefaultView;\nmnuActionLanguage.ComboBox.DisplayMember = lName.ColumnName;</code></pre>\n\n<p>I have tried this with a blank form and standard combo, and seems to work for me.</p>\n" }, { "answer_id": 256871, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 6, "selected": true, "text": "<p>You need to set the binding context of the ToolStripComboBox.ComboBox.</p>\n\n<p>Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.</p>\n\n<p>I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?</p>\n\n<p>If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.</p>\n\n<pre><code>var languages = new string[2];\nlanguages[0] = \"English\";\nlanguages[1] = \"German\";\n\nDataSet myDataSet = new DataSet();\n\n// --- Preparation\nDataTable lTable = new DataTable(\"Lang\");\nDataColumn lName = new DataColumn(\"Language\", typeof(string));\nlTable.Columns.Add(lName);\n\nfor (int i = 0; i &lt; languages.Length; i++)\n{\n DataRow lLang = lTable.NewRow();\n lLang[\"Language\"] = languages[i];\n lTable.Rows.Add(lLang);\n}\nmyDataSet.Tables.Add(lTable);\n\ntoolStripComboBox1.ComboBox.DataSource = myDataSet.Tables[\"Lang\"].DefaultView;\ntoolStripComboBox1.ComboBox.DisplayMember = \"Language\";\n\ntoolStripComboBox1.ComboBox.BindingContext = this.BindingContext;\n</code></pre>\n" }, { "answer_id": 5660011, "author": "Nidz", "author_id": 579496, "author_profile": "https://Stackoverflow.com/users/579496", "pm_score": 3, "selected": false, "text": "<pre><code>string strConn = \"Data Source=SEZSW08;Initial Catalog=Nidhi;Integrated Security=True\";\nSqlConnection Con = new SqlConnection(strConn);\nCon.Open();\nstring strCmd = \"select companyName from companyinfo where CompanyName='\" + cmbCompName.SelectedValue + \"';\";\nSqlDataAdapter da = new SqlDataAdapter(strCmd, Con);\nDataSet ds = new DataSet();\nCon.Close();\nda.Fill(ds);\ncmbCompName.DataSource = ds;\ncmbCompName.DisplayMember = \"CompanyName\";\ncmbCompName.ValueMember = \"CompanyName\";\n//cmbCompName.DataBind();\ncmbCompName.Enabled = true;\n</code></pre>\n" }, { "answer_id": 40449714, "author": "Masoud Siahkali", "author_id": 6687274, "author_profile": "https://Stackoverflow.com/users/6687274", "pm_score": 3, "selected": false, "text": "<p>For example, i created a table :</p>\n\n<pre><code>DataTable dt = new DataTable ();\ndt.Columns.Add(\"Title\", typeof(string));\ndt.Columns.Add(\"Value\", typeof(int));\n</code></pre>\n\n<p>Add recorde to table :</p>\n\n<pre><code>DataRow row = dt.NewRow();\nrow[\"Title\"] = \"Price\"\nrow[\"Value\"] = 2000;\ndt.Rows.Add(row);\n</code></pre>\n\n<p>or :</p>\n\n<pre><code>dt.Rows.Add(\"Price\",2000);\n</code></pre>\n\n<p>finally :</p>\n\n<pre><code>combo.DataSource = dt;\ncombo.DisplayMember = \"Title\";\ncombo.ValueMember = \"Value\";\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33429/" ]
I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop: ``` // Form has a menu containing a combobox added via SharpDevelop's GUI // --- Variables languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet(); // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add( lName ); for( int i=0; i<languages.Length; i++ ) { DataRow lLang = lTable.NewRow(); lLang["Language"] = languages[i]; lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable); // --- Handling the combobox mnuActionLanguage.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; mnuActionLanguage.ComboBox.DisplayMember = "Language"; ``` One would assume to see some values in the dropdown, but it's empty. Please tell me what I'm doing wrong ;( *EDIT: mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.* **SOLUTION** ``` mnuActionLanguage.ComboBox.BindingContext = this.BindingContext; ``` at the end solved the problem!
You need to set the binding context of the ToolStripComboBox.ComboBox. Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context. I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem? If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express. ``` var languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet(); // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add(lName); for (int i = 0; i < languages.Length; i++) { DataRow lLang = lTable.NewRow(); lLang["Language"] = languages[i]; lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable); toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; toolStripComboBox1.ComboBox.DisplayMember = "Language"; toolStripComboBox1.ComboBox.BindingContext = this.BindingContext; ```
256,859
<p>What, if any, is the performance difference between the following two loops?</p> <pre><code>for (Object o: objectArrayList) { o.DoSomething(); } </code></pre> <p>and </p> <pre><code>for (int i=0; i&lt;objectArrayList.size(); i++) { objectArrayList.get(i).DoSomething(); } </code></pre>
[ { "answer_id": 256861, "author": "Vijay Dev", "author_id": 27474, "author_profile": "https://Stackoverflow.com/users/27474", "pm_score": 9, "selected": true, "text": "<p>From Item 46 in <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321356683\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java</a> by Joshua Bloch :</p>\n\n<blockquote>\n <p>The for-each loop, introduced in\n release 1.5, gets rid of the clutter\n and the opportunity for error by\n hiding the iterator or index variable\n completely. The resulting idiom\n applies equally to collections and\n arrays:</p>\n\n<pre><code>// The preferred idiom for iterating over collections and arrays\nfor (Element e : elements) {\n doSomething(e);\n}\n</code></pre>\n \n <p>When you see the colon (:), read it as\n “in.” Thus, the loop above reads as\n “for each element e in elements.” Note\n that there is no performance penalty\n for using the for-each loop, even for\n arrays. In fact, it may offer a slight\n performance advantage over an ordinary\n for loop in some circumstances, as it\n computes the limit of the array index\n only once. While you can do this by\n hand (Item 45), programmers don’t\n always do so.</p>\n</blockquote>\n" }, { "answer_id": 256872, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>Even with something like an ArrayList or Vector, where \"get\" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.</p>\n" }, { "answer_id": 256879, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 2, "selected": false, "text": "<p>The only way to know for sure is to benchmark it, and even that is <a href=\"http://wikis.sun.com/display/HotSpotInternals/MicroBenchmarks\" rel=\"nofollow noreferrer\">not as simple as it may sound</a>. The JIT compiler can do very unexpected things to your code.</p>\n" }, { "answer_id": 256882, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": 4, "selected": false, "text": "<p>The for-each loop should generally be preferred. The \"get\" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the <a href=\"http://today.java.net/pub/a/today/2006/11/07/nuances-of-java-5-for-each-loop.html\" rel=\"nofollow noreferrer\">nuances of the for-each loop</a>.</p>\n\n<p>I think the article is now here: <a href=\"https://community.oracle.com/docs/DOC-983591\" rel=\"nofollow noreferrer\">new location</a></p>\n\n<p>The link shown here was dead. </p>\n" }, { "answer_id": 257009, "author": "P Arrayah", "author_id": 33459, "author_profile": "https://Stackoverflow.com/users/33459", "pm_score": 5, "selected": false, "text": "<p>All these loops do the exact same, I just want to show these before throwing in my two cents.</p>\n\n<p>First, the classic way of looping through List:</p>\n\n<pre><code>for (int i=0; i &lt; strings.size(); i++) { /* do something using strings.get(i) */ }\n</code></pre>\n\n<p>Second, the preferred way since it's less error prone (how many times have YOU done the \"oops, mixed the variables i and j in these loops within loops\" thing?).</p>\n\n<pre><code>for (String s : strings) { /* do something using s */ }\n</code></pre>\n\n<p>Third, the micro-optimized for loop:</p>\n\n<pre><code>int size = strings.size();\nfor (int i = -1; ++i &lt; size;) { /* do something using strings.get(i) */ }\n</code></pre>\n\n<p>Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.</p>\n\n<p>While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java <em>for-each loop</em> (some refer to it as <em>Iterator loop</em> and others as <em>for-in loop</em>) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.</p>\n\n<p>If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.</p>\n" }, { "answer_id": 257894, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 0, "selected": false, "text": "<p>It's always better to use the iterator instead of indexing. This is because iterator is most likely optimzied for the List implementation while indexed (calling get) might not be. For example LinkedList is a List but indexing through its elements will be slower than iterating using the iterator.</p>\n" }, { "answer_id": 258117, "author": "Fortyrunner", "author_id": 16828, "author_profile": "https://Stackoverflow.com/users/16828", "pm_score": 3, "selected": false, "text": "<p>foreach makes the intention of your code clearer and that is normally preferred over a very minor speed improvement - if any.</p>\n\n<p>Whenever I see an indexed loop I have to parse it a little longer to make sure it does what I <em>think</em> it does E.g. Does it start from zero, does it include or exclude the end point etc.?</p>\n\n<p>Most of my time seems to be spent reading code (that I wrote or someone else wrote) and clarity is almost always more important than performance. Its easy to dismiss performance these days because Hotspot does such an amazing job.</p>\n" }, { "answer_id": 580210, "author": "Sarmun", "author_id": 70173, "author_profile": "https://Stackoverflow.com/users/70173", "pm_score": 4, "selected": false, "text": "<p>Well, performance impact is mostly insignificant, but isn't zero. If you look at JavaDoc of <code>RandomAccess</code> interface:</p>\n\n<blockquote>\n <p>As a rule of thumb, a List\n implementation should implement this\n interface if, for typical instances of\n the class, this loop: </p>\n\n<pre><code>for (int i=0, n=list.size(); i &lt; n; i++)\n list.get(i);\n</code></pre>\n \n <p>runs faster than this loop: </p>\n\n<pre><code>for (Iterator i=list.iterator(); i.hasNext();)\n i.next();\n</code></pre>\n</blockquote>\n\n<p>And for-each loop is using version with iterator, so for <code>ArrayList</code> for example, for-each loop isn't fastest.</p>\n" }, { "answer_id": 12168053, "author": "Wibowit", "author_id": 492749, "author_profile": "https://Stackoverflow.com/users/492749", "pm_score": 2, "selected": false, "text": "<p>The following code:</p>\n\n<pre><code>import java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.List;\n\ninterface Function&lt;T&gt; {\n long perform(T parameter, long x);\n}\n\nclass MyArray&lt;T&gt; {\n\n T[] array;\n long x;\n\n public MyArray(int size, Class&lt;T&gt; type, long x) {\n array = (T[]) Array.newInstance(type, size);\n this.x = x;\n }\n\n public void forEach(Function&lt;T&gt; function) {\n for (T element : array) {\n x = function.perform(element, x);\n }\n }\n}\n\nclass Compute {\n int factor;\n final long constant;\n\n public Compute(int factor, long constant) {\n this.factor = factor;\n this.constant = constant;\n }\n\n public long compute(long parameter, long x) {\n return x * factor + parameter + constant;\n }\n}\n\npublic class Main {\n\n public static void main(String[] args) {\n List&lt;Long&gt; numbers = new ArrayList&lt;Long&gt;(50000000);\n for (int i = 0; i &lt; 50000000; i++) {\n numbers.add(i * i + 5L);\n }\n\n long x = 234553523525L;\n\n long time = System.currentTimeMillis();\n for (int i = 0; i &lt; numbers.size(); i++) {\n x += x * 7 + numbers.get(i) + 3;\n }\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(x);\n x = 0;\n time = System.currentTimeMillis();\n for (long i : numbers) {\n x += x * 7 + i + 3;\n }\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(x);\n x = 0;\n numbers = null;\n MyArray&lt;Long&gt; myArray = new MyArray&lt;Long&gt;(50000000, Long.class, 234553523525L);\n for (int i = 0; i &lt; 50000000; i++) {\n myArray.array[i] = i * i + 3L;\n }\n time = System.currentTimeMillis();\n myArray.forEach(new Function&lt;Long&gt;() {\n\n public long perform(Long parameter, long x) {\n return x * 8 + parameter + 5L;\n }\n });\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(myArray.x);\n myArray = null;\n myArray = new MyArray&lt;Long&gt;(50000000, Long.class, 234553523525L);\n for (int i = 0; i &lt; 50000000; i++) {\n myArray.array[i] = i * i + 3L;\n }\n time = System.currentTimeMillis();\n myArray.forEach(new Function&lt;Long&gt;() {\n\n public long perform(Long parameter, long x) {\n return new Compute(8, 5).compute(parameter, x);\n }\n });\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(myArray.x);\n }\n}\n</code></pre>\n\n<p>Gives following output on my system:</p>\n\n<pre><code>224\n-699150247503735895\n221\n-699150247503735895\n220\n-699150247503735895\n219\n-699150247503735895\n</code></pre>\n\n<p>I'm running Ubuntu 12.10 alpha with OracleJDK 1.7 update 6.</p>\n\n<p>In general HotSpot optimizes a lot of indirections and simple reduntant operations, so in general you shouldn't worry about them unless there are a lot of them in seqence or they are heavily nested.</p>\n\n<p>On the other hand, indexed get on LinkedList is much slower than calling next on iterator for LinkedList so you can avoid that performance hit while retaining readability when you use iterators (explicitly or implicitly in for-each loop).</p>\n" }, { "answer_id": 19802454, "author": "Changgeng", "author_id": 2958002, "author_profile": "https://Stackoverflow.com/users/2958002", "pm_score": 2, "selected": false, "text": "<p>By the variable name <code>objectArrayList</code>, I assume that is an instance of <code>java.util.ArrayList</code>. In that case, the performance difference would be unnoticeable.</p>\n\n<p>On the other hand, if it's an instance of <code>java.util.LinkedList</code>, the second approach will be much slower as the <code>List#get(int)</code> is an O(n) operation.</p>\n\n<p>So the first approach is always preferred unless the index is needed by the logic in the loop.</p>\n" }, { "answer_id": 26068201, "author": "Gary Gregory", "author_id": 686368, "author_profile": "https://Stackoverflow.com/users/686368", "pm_score": 3, "selected": false, "text": "<p>There appears to be a difference unfortunately.</p>\n\n<p>If you look at the generated bytes code for both kinds of loops, they are different.</p>\n\n<p>Here is an example from the Log4j source code.</p>\n\n<p>In /log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java we have a static inner class called Log4jMarker which defines:</p>\n\n<pre><code> /*\n * Called from add while synchronized.\n */\n private static boolean contains(final Marker parent, final Marker... localParents) {\n //noinspection ForLoopReplaceableByForEach\n for (final Marker marker : localParents) {\n if (marker == parent) {\n return true;\n }\n }\n return false;\n }\n</code></pre>\n\n<p>With standard loop:</p>\n\n<pre><code> private static boolean contains(org.apache.logging.log4j.Marker, org.apache.logging.log4j.Marker...);\n Code:\n 0: iconst_0\n 1: istore_2\n 2: aload_1\n 3: arraylength\n 4: istore_3\n 5: iload_2\n 6: iload_3\n 7: if_icmpge 29\n 10: aload_1\n 11: iload_2\n 12: aaload\n 13: astore 4\n 15: aload 4\n 17: aload_0\n 18: if_acmpne 23\n 21: iconst_1\n 22: ireturn\n 23: iinc 2, 1\n 26: goto 5\n 29: iconst_0\n 30: ireturn\n</code></pre>\n\n<p>With for-each:</p>\n\n<pre><code> private static boolean contains(org.apache.logging.log4j.Marker, org.apache.logging.log4j.Marker...);\n Code:\n 0: aload_1\n 1: astore_2\n 2: aload_2\n 3: arraylength\n 4: istore_3\n 5: iconst_0\n 6: istore 4\n 8: iload 4\n 10: iload_3\n 11: if_icmpge 34\n 14: aload_2\n 15: iload 4\n 17: aaload\n 18: astore 5\n 20: aload 5\n 22: aload_0\n 23: if_acmpne 28\n 26: iconst_1\n 27: ireturn\n 28: iinc 4, 1\n 31: goto 8\n 34: iconst_0\n 35: ireturn\n</code></pre>\n\n<p>What is up with THAT Oracle?</p>\n\n<p>I've tried this with Java 7 and 8 on Windows 7.</p>\n" }, { "answer_id": 34948680, "author": "Santosh", "author_id": 5730313, "author_profile": "https://Stackoverflow.com/users/5730313", "pm_score": 0, "selected": false, "text": "<pre><code>1. for(Object o: objectArrayList){\n o.DoSomthing();\n}\nand\n\n2. for(int i=0; i&lt;objectArrayList.size(); i++){\n objectArrayList.get(i).DoSomthing();\n}\n</code></pre>\n\n<p>Both does the same but for easy and safe programming use for-each, there are possibilities for error prone in 2nd way of using.</p>\n" }, { "answer_id": 38163145, "author": "TBridges42", "author_id": 1541763, "author_profile": "https://Stackoverflow.com/users/1541763", "pm_score": 2, "selected": false, "text": "<p>Here is a brief analysis of the difference put out by the Android development team:</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=MZOf3pOAM6A\" rel=\"nofollow\">https://www.youtube.com/watch?v=MZOf3pOAM6A</a></p>\n\n<p>The result is that there <em>is</em> a difference, and in very restrained environments with very large lists it could be a noticeable difference. In their testing, the for each loop took twice as long. However, their testing was over an arraylist of 400,000 integers. The actual difference per element in the array was 6 <em>microseconds</em>. I haven't tested and they didn't say, but I would expect the difference to be slightly larger using objects rather than primitives, but even still unless you are building library code where you have no idea the scale of what you will be asked to iterate over, I think the difference is not worth stressing about.</p>\n" }, { "answer_id": 44540213, "author": "neural", "author_id": 2102793, "author_profile": "https://Stackoverflow.com/users/2102793", "pm_score": 1, "selected": false, "text": "<p>It's weird that no one has mentioned the obvious - foreach allocates memory (in the form of an iterator), whereas a normal for loop does not allocate any memory. For games on Android, this is a problem, because it means that the garbage collector will run periodically. In a game you don't want the garbage collector to run... EVER. So don't use foreach loops in your draw (or render) method.</p>\n" }, { "answer_id": 45789947, "author": "Sreekanth Karumanaghat", "author_id": 1448316, "author_profile": "https://Stackoverflow.com/users/1448316", "pm_score": 0, "selected": false, "text": "<p>Accepted answer answers the question, apart from the exceptional case of ArrayList...</p>\n\n<p>Since most developers rely on ArrayList(atleast I believe so)</p>\n\n<p>So I am obligated to add the correct answer here.</p>\n\n<p>Straight from the developer documentation:-</p>\n\n<p>The enhanced for loop (also sometimes known as \"for-each\" loop) can be used for collections that implement the Iterable interface and for arrays. With collections, an iterator is allocated to make interface calls to hasNext() and next(). With an ArrayList, a hand-written counted loop is about 3x faster (with or without JIT), but for other collections the enhanced for loop syntax will be exactly equivalent to explicit iterator usage.</p>\n\n<p>There are several alternatives for iterating through an array:</p>\n\n<pre><code>static class Foo {\n int mSplat;\n}\n\nFoo[] mArray = ...\n\npublic void zero() {\n int sum = 0;\n for (int i = 0; i &lt; mArray.length; ++i) {\n sum += mArray[i].mSplat;\n }\n}\n\npublic void one() {\n int sum = 0;\n Foo[] localArray = mArray;\n int len = localArray.length;\n\n for (int i = 0; i &lt; len; ++i) {\n sum += localArray[i].mSplat;\n }\n}\n\npublic void two() {\n int sum = 0;\n for (Foo a : mArray) {\n sum += a.mSplat;\n }\n}\n</code></pre>\n\n<p>zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop.</p>\n\n<p>one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.</p>\n\n<p>two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.</p>\n\n<p>So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.</p>\n" }, { "answer_id": 69223378, "author": "Jerry Lundegaard", "author_id": 10656396, "author_profile": "https://Stackoverflow.com/users/10656396", "pm_score": 2, "selected": false, "text": "<p>Seems to me like the other answers are based on the incorrect benchmarks, that doesn't take Hotspot's compilation and optimization process into an account.</p>\n<h2><strong>Short answer</strong></h2>\n<p>Use enhanced-loop when possible, because most of the time it's the fastest.\nIf you cannot, pull the entire array into a local variable if possible:</p>\n<pre><code>int localArray = this.array;\nfor (int i = 0; i &lt; localArray.length; i++) { \n methodCall(localArray[i]); \n}\n</code></pre>\n<h2><strong>Long answer</strong></h2>\n<p>Now, usually there is no difference, because Hotspot is very good at optimizing and getting rid of checks that java needs to do.</p>\n<p>But sometimes some optimizations just cannot be done, usually because you have a virtual call inside a loop, that cannot be inlined.\nIn that case, some loops can really be faster than others.</p>\n<p>Few of the things that Java needs to do:</p>\n<ul>\n<li><em><strong>reload this.array</strong></em> - because it could be changed (by the call or another thread)</li>\n<li><strong>check whether <em>i</em> is in inside the bounds of the array</strong>, if not <em>throw IndexOutOfBoundsException</em></li>\n<li><strong>check whether an accessed object reference is null</strong>, if yes <em>throw NullPointerException</em></li>\n</ul>\n<p>Consider this c-style loop:</p>\n<pre><code>for (int i = 0; i &lt; this.array.length; i++) { //now java knows i &lt; this.array.length\n methodCall(this.array[i]);// no need to check\n}\n</code></pre>\n<p>By evaluating the loop condition <em><strong>i &lt; this.array.length</strong></em>, java knows that <em><strong>i</strong></em> <strong>must be</strong> inside of bounds (<em><strong>i</strong></em> is changed only <strong>after</strong> the call), so don't need to check it again in the next line.\nBut in this case java needs to reload <em><strong>this.array.length</strong></em>.</p>\n<p>You might be tempted to &quot;optimize&quot; the loop, by pulling the <em><strong>this.array.length</strong></em> value inside of the local variable:</p>\n<pre><code>int len = this.array.length;//len is now a local variable\nfor (int i = 0; i &lt; len; i++) { //no reload needed\n methodCall(this.array[i]); //now java will do the check\n}\n</code></pre>\n<p>Now java don't need to reload every single time, because a local variable can be cannot be changed by the methodCall and/or another thread. Local variables can be changed only inside the method itself, and java now can prove that variable <em><strong>len</strong></em> could not change.</p>\n<p>But now the loop condition <em><strong>i &lt; this.array.length</strong></em> changed to <em><strong>i &lt; len</strong></em>, and previous optimization fails, and java need to check whether the <em><strong>i</strong></em> in inside of bounds of <em><strong>this.array</strong></em>.</p>\n<p>A better optimization would be to pull entire array into a local variable:</p>\n<pre><code>ArrayType[] localArray = this.array;\nfor (int i = 0; i &lt; localArray.length; i++) { \n methodCall(localArray[i]); \n}\n</code></pre>\n<p>Now java don't need to reload the array, and the &quot;<em><strong>i</strong></em> in bounds&quot; check is also eliminated.</p>\n<p>And what about the enhanced-loop?\nWell, usually the compiler rewrites your enhanced loop into something like the last shown loop, if not even better.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
What, if any, is the performance difference between the following two loops? ``` for (Object o: objectArrayList) { o.DoSomething(); } ``` and ``` for (int i=0; i<objectArrayList.size(); i++) { objectArrayList.get(i).DoSomething(); } ```
From Item 46 in [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) by Joshua Bloch : > > The for-each loop, introduced in > release 1.5, gets rid of the clutter > and the opportunity for error by > hiding the iterator or index variable > completely. The resulting idiom > applies equally to collections and > arrays: > > > > ``` > // The preferred idiom for iterating over collections and arrays > for (Element e : elements) { > doSomething(e); > } > > ``` > > When you see the colon (:), read it as > “in.” Thus, the loop above reads as > “for each element e in elements.” Note > that there is no performance penalty > for using the for-each loop, even for > arrays. In fact, it may offer a slight > performance advantage over an ordinary > for loop in some circumstances, as it > computes the limit of the array index > only once. While you can do this by > hand (Item 45), programmers don’t > always do so. > > >
256,892
<p>How do i backup a SQL database using PHP.</p> <p>Is there a vendor agnostic way to do this that conforms to ANSI SQL?</p> <p>If not maybe you can list how to do it for each of the database vendors?</p>
[ { "answer_id": 256907, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 4, "selected": true, "text": "<p>Every database system comes with some program for dumping its contents.</p>\n\n<ul>\n<li>PostgreSQL: <a href=\"http://www.postgresql.org/docs/8.0/interactive/backup.html\" rel=\"noreferrer\"><code>pg_dump</code></a></li>\n<li>MySQL: <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html\" rel=\"noreferrer\"><code>mysqldump</code></a></li>\n<li>...</li>\n</ul>\n\n<p>You can simply call that program from PHP using <a href=\"http://php.net/manual/en/function.system.php\" rel=\"noreferrer\"><code>system()</code></a>\nor <a href=\"http://php.net/manual/en/function.shell-exec.php\" rel=\"noreferrer\"><code>shell_exec()</code></a>.</p>\n\n<p>For example, if you use PostgreSQL with enabled <a href=\"http://www.postgresql.org/docs/8.0/interactive/auth-methods.html#AUTH-IDENT\" rel=\"noreferrer\">Ident authentication</a> and want to dump the Database <code>test</code> directly as SQL text to the browser, it's as simple as:\n<code><pre>\n&lt;?php\nheader('Content-type: text/plain');\nsystem('pg_dump test');\n?&gt;\n</pre></code></p>\n\n<p>When using MySQL with database user and password stored into <a href=\"http://dev.mysql.com/doc/refman/5.0/en/option-files.html\" rel=\"noreferrer\"><code>~/.my.cnf</code></a>, it is also very simple:\n<code><pre>\n&lt;?php\nheader('Content-type: text/plain');\nsystem('mysqldump test');\n?&gt;\n</pre></code></p>\n\n<p>However, <b>don't do this:</b>\n<code><pre>\n&lt;?php\nheader('Content-type: text/plain');\nsystem('mysqldump -utestuser -p<b>testpassword</b> test');\n?&gt;\n</pre></code>\nbecause transmitting a password as command line argument is <a href=\"http://dev.mysql.com/doc/refman/5.0/en/password-security.html\" rel=\"noreferrer\">very insecure</a>.</p>\n" }, { "answer_id": 256913, "author": "kevtrout", "author_id": 1149, "author_profile": "https://Stackoverflow.com/users/1149", "pm_score": 1, "selected": false, "text": "<p>I love <a href=\"http://www.phpmybackuppro.net/\" rel=\"nofollow noreferrer\">phpmybackuppro</a></p>\n" }, { "answer_id": 256921, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": 0, "selected": false, "text": "<p>It's a pretty complicated process. I recommend you use phpmyadmin or similar.</p>\n" }, { "answer_id": 257668, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>Whilst backing up a database \"conformant to ANSI SQL\" is possible and admirable, you will still encounter portability issues. The most obvious is that whilst MySQL's dump/restore format is fairly fast, it achieves this principally by using a non-standard extension to SQL. So you can't just hand the dump to PostGresql: it won't work. In fact, PostGresql is also quite slow at handling a huge amount of INSERT statements. It's native dump format uses it's own custom SQL statement optimized for inserting a large amount of data at once.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
How do i backup a SQL database using PHP. Is there a vendor agnostic way to do this that conforms to ANSI SQL? If not maybe you can list how to do it for each of the database vendors?
Every database system comes with some program for dumping its contents. * PostgreSQL: [`pg_dump`](http://www.postgresql.org/docs/8.0/interactive/backup.html) * MySQL: [`mysqldump`](http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html) * ... You can simply call that program from PHP using [`system()`](http://php.net/manual/en/function.system.php) or [`shell_exec()`](http://php.net/manual/en/function.shell-exec.php). For example, if you use PostgreSQL with enabled [Ident authentication](http://www.postgresql.org/docs/8.0/interactive/auth-methods.html#AUTH-IDENT) and want to dump the Database `test` directly as SQL text to the browser, it's as simple as: ```` <?php header('Content-type: text/plain'); system('pg_dump test'); ?> ```` When using MySQL with database user and password stored into [`~/.my.cnf`](http://dev.mysql.com/doc/refman/5.0/en/option-files.html), it is also very simple: ```` <?php header('Content-type: text/plain'); system('mysqldump test'); ?> ```` However, **don't do this:** ```` <?php header('Content-type: text/plain'); system('mysqldump -utestuser -p**testpassword** test'); ?> ```` because transmitting a password as command line argument is [very insecure](http://dev.mysql.com/doc/refman/5.0/en/password-security.html).
256,915
<p>I'm building small web shop with asp.net mvc and Structuremap ioc/di. My Basket class uses session object for persistence, and I want use SM to create my basket object through IBasket interface. My basket implementation need HttpSessionStateBase (session state wrapper from mvc) in constructor, which is available inside Controller/Action. How do I register my IBasket implementation for SM?<br> This is my basket interface:</p> <pre><code>public interface IBasketService { BasketContent GetBasket(); void AddItem(Product productItem); void RemoveItem(Guid guid); } </code></pre> <p>And SM registration: </p> <pre><code>ForRequestedType(typeof (IBasketService)).TheDefaultIsConcreteType(typeof (StoreBasketService)); </code></pre> <p>But my StoreBasketService implementation has constructor: </p> <pre><code>public StoreBasketService(HttpSessionStateBase sessionState) </code></pre> <p>How do I provide HttpSessionStateBase object to SM, which is available only in controller?<br> This is my first use of SM IOC/DI, and cann't find solution/example in official documentation and web site ;)</p>
[ { "answer_id": 257496, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>If you absolutely have to have your StoreBasketService use the session, I'd be tempted to define an interface and wrapper around HttpSessionState instead of using HttpSessionStateBase so that you can register it with StructureMap as well.The wrapper would get the session state from the current context. Register the wrapper with StructureMap and then have your StoreBasketService take the interface as the argument to the constructor. Structure map should then know how to create an instance of the interface wrapper and inject it into your StoreBasketService class.</p>\n\n<p>Using an interface and wrapper will allow you to mock the wrapper in your unit tests, muc in the same way HttpSessionStateBase allows mocking the actual session.</p>\n\n<pre><code>public interface IHttpSessionStateWrapper\n{\n HttpSessionState GetSessionState();\n}\n\npublic class HttpSessionStateWrapper : IHttpSessionStateWrapper\n{\n public virtual HttpSessionState GetSessionState()\n {\n return HttpContext.Current.Session;\n }\n}\n\nForRquestedType(typeof(IHttpSessionStateWrapper))\n .TheDefaultIsConcreteType(typeof(IHttpSessionStateWrapper));\n</code></pre>\n\n<hr>\n\n<pre><code>public class StoreBasketService\n{\n HttpSessionState session;\n public StoreBasketService( IHttpSessionstateWrapper wrapper )\n {\n session = wrapper.GetSessionState();\n }\n\n // basket implementation ...\n}\n</code></pre>\n\n<p>However, you can have StructureMap actually store your basket in the session using <code>.CacheBy(InstanceScope.HttpContext)</code> when registering it. It may actually be better to have your StoreBasketService implement internal storage instead of storing things in the session -- then you lose the dependency on the session state entirely (from the perspective of your class) and your solution could be simpler. Your internal storage could be a <code>Dictionary&lt;Guid,Product&gt;</code> since this is how you access them via your interface.</p>\n\n<p>See also:</p>\n\n<p><a href=\"http://www.lostechies.com/blogs/chad_myers/archive/2008/07/15/structuremap-basic-scenario-usage.aspx\" rel=\"nofollow noreferrer\">http://www.lostechies.com/blogs/chad_myers/archive/2008/07/15/structuremap-basic-scenario-usage.aspx</a></p>\n\n<p><a href=\"http://www.lostechies.com/blogs/chad_myers/archive/2008/07/17/structuremap-medium-level-usage-scenarios.aspx\" rel=\"nofollow noreferrer\">http://www.lostechies.com/blogs/chad_myers/archive/2008/07/17/structuremap-medium-level-usage-scenarios.aspx</a></p>\n" }, { "answer_id": 349106, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I just started with StructureMap, and I do not get the results you are describing.\nI performed a simple test using a simple class, configuring Structuremap to cacheby HttpContext, and from what I can see, CacheBy.HttpContext means within the same request you will get the same instance... not within the same Session</p>\n\n<p>The constructor of my class, sets the date/time in a private field\nI have a button which gets 2 instances of MyClass with one second interval...\nIt then display the time of both instances in a label.</p>\n\n<p>Pressing the first time this button, object A and B are same instance, as their creation time is exactly the same, as expected.</p>\n\n<p>Clicking the button a second time, you would expect the creation time to not have changed if instances would be cached in session... however, in my test I get a new creation time ...</p>\n\n<p><strong>Structuremap configuration:</strong></p>\n\n<pre><code> ObjectFactory.Initialize(x=&gt;x.ForRequestedType&lt;MyClass&gt;(). CacheBy(InstanceScope.HttpContext));\n</code></pre>\n\n<p><strong>Button clicked event of test page</strong></p>\n\n<pre><code> protected void btnTest_Click(object sender, EventArgs e)\n {\n MyClass c = ObjectFactory.GetInstance&lt;MyClass&gt;();\n System.Threading.Thread.Sleep(1000);\n MyClass b = ObjectFactory.GetInstance&lt;MyClass&gt;();\n\n\n\n lblResult.Text = String.Format(\"cache by httpcontext First:{0} Second:{1} session id {2} \", c.GetTimeCreated(), b.GetTimeCreated(),Session.SessionID);\n }\n</code></pre>\n\n<p><strong>MyClass</strong></p>\n\n<pre><code>public class MyClass\n{\n private DateTime _timeCreated;\n public MyClass()\n {\n _timeCreated = DateTime.Now;\n }\n\n public string GetTimeCreated()\n {\n return _timeCreated.ToString(\"dd/MM/yyyy hh:mm:ss\");\n }\n}\n</code></pre>\n" }, { "answer_id": 349120, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You could also use one of the ObjectFactory.Inject methods to inject the HttpSessionStateBase into StructureMap. It would then invoke the constructor with the injected HttpSessionStateBase.</p>\n" }, { "answer_id": 350447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I just made my first attempt at creating an custom scope... build a small web application with it, and as far as I can see, it seems to work. This will cache the object inside the current user session and will return the same object as long as you remain inside the same session:</p>\n\n<pre><code>public class HttpSessionBuilder : CacheInterceptor\n{\n private readonly string _prefix = Guid.NewGuid().ToString();\n\n protected override CacheInterceptor clone()\n {\n return this;\n }\n\n private string getKey(string instanceKey, Type pluginType)\n {\n return string.Format(\"{0}:{1}:{2}\", pluginType.AssemblyQualifiedName, instanceKey, this._prefix);\n }\n\n public static bool HasContext()\n {\n return (HttpContext.Current.Session != null);\n }\n\n protected override bool isCached(string instanceKey, Type pluginType)\n {\n return HttpContext.Current.Session[this.getKey(instanceKey, pluginType)] != null;\n }\n\n protected override object retrieveFromCache(string instanceKey, Type pluginType)\n {\n return HttpContext.Current.Session[this.getKey(instanceKey, pluginType)];\n }\n\n protected override void storeInCache(string instanceKey, Type pluginType, object instance)\n {\n HttpContext.Current.Session.Add(this.getKey(instanceKey, pluginType), instance);\n }\n\n}\n</code></pre>\n\n<p>You have to configure the ObjectFactory as follows in the global.asax Application_start</p>\n\n<pre><code> ObjectFactory.Initialize(x=&gt;\n x.ForRequestedType&lt;MyClass&gt;().InterceptConstructionWith(new HttpSessionBuilder()));\n</code></pre>\n" }, { "answer_id": 370463, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 1, "selected": false, "text": "<pre><code>ForRequestedType&lt;IBasketService&gt;()\n .TheDefault.Is.OfConcreteType&lt;StoreBasketService&gt;()\n .WithCtorArg(\"sessionState\").EqualTo(HttpContext.Current.Session);\n</code></pre>\n\n<p>?? does that work?</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407/" ]
I'm building small web shop with asp.net mvc and Structuremap ioc/di. My Basket class uses session object for persistence, and I want use SM to create my basket object through IBasket interface. My basket implementation need HttpSessionStateBase (session state wrapper from mvc) in constructor, which is available inside Controller/Action. How do I register my IBasket implementation for SM? This is my basket interface: ``` public interface IBasketService { BasketContent GetBasket(); void AddItem(Product productItem); void RemoveItem(Guid guid); } ``` And SM registration: ``` ForRequestedType(typeof (IBasketService)).TheDefaultIsConcreteType(typeof (StoreBasketService)); ``` But my StoreBasketService implementation has constructor: ``` public StoreBasketService(HttpSessionStateBase sessionState) ``` How do I provide HttpSessionStateBase object to SM, which is available only in controller? This is my first use of SM IOC/DI, and cann't find solution/example in official documentation and web site ;)
If you absolutely have to have your StoreBasketService use the session, I'd be tempted to define an interface and wrapper around HttpSessionState instead of using HttpSessionStateBase so that you can register it with StructureMap as well.The wrapper would get the session state from the current context. Register the wrapper with StructureMap and then have your StoreBasketService take the interface as the argument to the constructor. Structure map should then know how to create an instance of the interface wrapper and inject it into your StoreBasketService class. Using an interface and wrapper will allow you to mock the wrapper in your unit tests, muc in the same way HttpSessionStateBase allows mocking the actual session. ``` public interface IHttpSessionStateWrapper { HttpSessionState GetSessionState(); } public class HttpSessionStateWrapper : IHttpSessionStateWrapper { public virtual HttpSessionState GetSessionState() { return HttpContext.Current.Session; } } ForRquestedType(typeof(IHttpSessionStateWrapper)) .TheDefaultIsConcreteType(typeof(IHttpSessionStateWrapper)); ``` --- ``` public class StoreBasketService { HttpSessionState session; public StoreBasketService( IHttpSessionstateWrapper wrapper ) { session = wrapper.GetSessionState(); } // basket implementation ... } ``` However, you can have StructureMap actually store your basket in the session using `.CacheBy(InstanceScope.HttpContext)` when registering it. It may actually be better to have your StoreBasketService implement internal storage instead of storing things in the session -- then you lose the dependency on the session state entirely (from the perspective of your class) and your solution could be simpler. Your internal storage could be a `Dictionary<Guid,Product>` since this is how you access them via your interface. See also: <http://www.lostechies.com/blogs/chad_myers/archive/2008/07/15/structuremap-basic-scenario-usage.aspx> <http://www.lostechies.com/blogs/chad_myers/archive/2008/07/17/structuremap-medium-level-usage-scenarios.aspx>
256,938
<p>I am writing a footer div that displays info from the database. The footer has a different background color than the rest of the page, and will have a height that depends on how much content the database throws to it. When I generate the content with php and call for a border around the footer div, the content appears and is, let's say, 400px high, but the div border appears as a 1px high rectangle at the top of the div.</p> <p>How do I get the height to auto-fit the content?</p> <pre><code>&lt;div id="footer"&gt; &lt;?php $an_array=array(); $tasks=mysql_query("select stuff from the db"); while($row=mysql_fetch_assoc($tasks)){ extract($taskrow); $an_array[]=$task; } $an_array=array_chunk($an_array,4); foreach($an_array as $dtkey=&gt;$dtval){ echo "&lt;dl&gt;"; foreach($dtval as $dtvkey=&gt;$dtvval){ echo "&lt;dt&gt;".$dtvval."&lt;/dt&gt;"; } echo "&lt;/dl&gt;"; } ?&gt; &lt;/div&gt; </code></pre> <p>This is what I get. The area below the red border should be filled with a color. <a href="http://www.kevtrout.com/tortus/div.png" rel="nofollow noreferrer">border image http://www.kevtrout.com/tortus/div.png</a></p> <p>By popular demand, here is the css:</p> <pre><code>#footer{ border-top: 10px solid #d8d8d8; background:#5b5b5b; /*overflow:auto;*///Added this after seeing your answers, it worked } dl.tr{ width: 255px; height:160px; background: #5b5b5b; margin:0px; float:left; padding: 10px; } dt.tr{ font-weight: normal; font-size: 14px; color: #d8d8d8; line-height: 28px; } </code></pre> <p>edit: I am using firefox on a mac</p>
[ { "answer_id": 256944, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 4, "selected": true, "text": "<p>Check your footer CSS... if you have overflow set to anything but auto/scroll, then the DIV won't grow.</p>\n\n<p>If not try using something other than DL/DT since DT's are inline elements, they won't push your div to fit content.*</p>\n\n<p>e.g. just try using a DIV instead, if the footer grows, you have your answer.</p>\n\n<p>(note: I revised order of suggestions)</p>\n\n<p>*(I realize spec-wise, that this <strong>Shouldn't</strong> be an issue, but there wasn't an indication of which browsers this was occuring in, thus I would not be at all surprised if IE was rendering differently than expected for example)</p>\n" }, { "answer_id": 256947, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<p>The browser doesn't care if your content is generated by PHP or comes from a static HTML file.</p>\n\n<p>The issue will most likely be in your CSS. Either the content you put in the footer has positioning properties (like float:left or position:absolute) that place them \"outside\" the div or the div has a fixed size and/or overflow properties set.</p>\n\n<p>I'd suggest posting your CSS file here or (if it's too large) put it up somewhere where we can take a look. The finished HTML (you could just save a static copy of the output if your system isn't online yet) wouldn't hurt either.</p>\n" }, { "answer_id": 256948, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 2, "selected": false, "text": "<p>Without seeing the CSS, my guess would be that your <code>&lt;dl&gt;</code>s are floated to get them side-by-side. The containing <code>&lt;div&gt;</code> then won't expand to contain them. If this is the case adding a <code>clear:both;</code> before the final <code>&lt;/div&gt;</code> should fix it, like this:</p>\n\n<pre><code>&lt;div style='clear:both;'&gt;&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 256965, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>By the way, your use of the <code>&lt;dl&gt;</code> element is wrong: you are missing the <code>&lt;dd&gt;</code> element. Items in the definition list always consist of one definition <em>term</em> and one or more <em>definitions</em> (which, in your code, are missing).</p>\n\n<p>Also, rather than using <code>&lt;div style='clear:both;'&gt;&lt;/div&gt;</code> as suggested by Steve, I'd suggest explicitly stating the height of your <code>&lt;dt&gt;</code> elements. This way, the floats don't have to be cleared.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1149/" ]
I am writing a footer div that displays info from the database. The footer has a different background color than the rest of the page, and will have a height that depends on how much content the database throws to it. When I generate the content with php and call for a border around the footer div, the content appears and is, let's say, 400px high, but the div border appears as a 1px high rectangle at the top of the div. How do I get the height to auto-fit the content? ``` <div id="footer"> <?php $an_array=array(); $tasks=mysql_query("select stuff from the db"); while($row=mysql_fetch_assoc($tasks)){ extract($taskrow); $an_array[]=$task; } $an_array=array_chunk($an_array,4); foreach($an_array as $dtkey=>$dtval){ echo "<dl>"; foreach($dtval as $dtvkey=>$dtvval){ echo "<dt>".$dtvval."</dt>"; } echo "</dl>"; } ?> </div> ``` This is what I get. The area below the red border should be filled with a color. [border image http://www.kevtrout.com/tortus/div.png](http://www.kevtrout.com/tortus/div.png) By popular demand, here is the css: ``` #footer{ border-top: 10px solid #d8d8d8; background:#5b5b5b; /*overflow:auto;*///Added this after seeing your answers, it worked } dl.tr{ width: 255px; height:160px; background: #5b5b5b; margin:0px; float:left; padding: 10px; } dt.tr{ font-weight: normal; font-size: 14px; color: #d8d8d8; line-height: 28px; } ``` edit: I am using firefox on a mac
Check your footer CSS... if you have overflow set to anything but auto/scroll, then the DIV won't grow. If not try using something other than DL/DT since DT's are inline elements, they won't push your div to fit content.\* e.g. just try using a DIV instead, if the footer grows, you have your answer. (note: I revised order of suggestions) \*(I realize spec-wise, that this **Shouldn't** be an issue, but there wasn't an indication of which browsers this was occuring in, thus I would not be at all surprised if IE was rendering differently than expected for example)
256,978
<p>Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum.</p> <p>I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.</p>
[ { "answer_id": 257073, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 3, "selected": false, "text": "<p>An easy but not so beautiful solution:</p>\n\n<p>Create an integer field with and set the mapping in the mapping file to the field. \nCreate a public property that uses the integer field.</p>\n\n<pre><code>private int myField;\npublic virtual MyEnum MyProperty\n{\n get { return (MyEnum)myField; }\n set { myField = value; }\n}\n</code></pre>\n" }, { "answer_id": 257810, "author": "Garo Yeriazarian", "author_id": 2655, "author_profile": "https://Stackoverflow.com/users/2655", "pm_score": 4, "selected": false, "text": "<p>You can use the enum type directly: <a href=\"http://web.archive.org/web/20100225131716/http://graysmatter.codivation.com/post/Justice-Grays-NHibernate-War-Stories-Dont-Use-Int-If-You-Mean-Enum.aspx\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20100225131716/http://graysmatter.codivation.com/post/Justice-Grays-NHibernate-War-Stories-Dont-Use-Int-If-You-Mean-Enum.aspx</a>. If your underlying type is a string, it should use the string representation, if it is numeric, it will just use the numeric representation.</p>\n\n<p>But your question wording sounds like you're looking for something different, not quite an enum. It seems that you want a lookup table without creating a separate entity class. I don't think this can be done without creating a separate entity class though.</p>\n" }, { "answer_id": 1530190, "author": "RhysC", "author_id": 17466, "author_profile": "https://Stackoverflow.com/users/17466", "pm_score": 2, "selected": false, "text": "<p>Try using a stategy pattern. Uou can then put logic into your inner classes. I use this quite alot espically when there is logic that should be contained in the \"enum\". For example the code below has the abstract IsReadyForSubmission() which is then implemented in each of the nested subclasses (only one shown). HTH</p>\n\n<pre><code>[Serializable]\npublic abstract partial class TimesheetStatus : IHasIdentity&lt;int&gt;\n{\n public static readonly TimesheetStatus NotEntered = new NotEnteredTimesheetStatus();\n public static readonly TimesheetStatus Draft = new DraftTimesheetStatus();\n public static readonly TimesheetStatus Submitted = new SubmittedTimesheetStatus();\n //etc\n\n public abstract int Id { get; protected set; }\n public abstract string Description { get; protected set; }\n public abstract bool IsReadyForSubmission();\n\n protected class NotEnteredTimesheetStatus: TimesheetStatus\n {\n private const string DESCRIPTION = \"NotEntered\";\n private const int ID = 0;\n public override int Id\n {\n get { return ID; }\n protected set { if (value != ID)throw new InvalidOperationException(\"ID for NotEnteredTimesheetStatus must be \" + ID); }\n }\n\n public override string Description\n {\n get { return DESCRIPTION; }\n protected set { if (value != DESCRIPTION)throw new InvalidOperationException(\"The description for NotEnteredTimesheetStatus must be \" + DESCRIPTION); }\n }\n public override bool IsReadyForSubmission()\n {\n return false;\n }\n\n }\n //etc\n}\n</code></pre>\n" }, { "answer_id": 1905268, "author": "Emad", "author_id": 18132, "author_profile": "https://Stackoverflow.com/users/18132", "pm_score": 7, "selected": false, "text": "<p>Why are you guys over complicating this? It is really simple.</p>\n\n<p>The mapping looks like this:</p>\n\n<pre><code>&lt;property name=\"OrganizationType\"&gt;&lt;/property&gt;\n</code></pre>\n\n<p>The model property looks like this:</p>\n\n<pre><code>public virtual OrganizationTypes OrganizationType { get; set; }\n</code></pre>\n\n<p>The Enum looks like this:</p>\n\n<pre><code>public enum OrganizationTypes\n{\n NonProfit = 1,\n ForProfit = 2\n}\n</code></pre>\n\n<p>NHibernate will automatically figure it all out. Why type more than you need????</p>\n" }, { "answer_id": 10605789, "author": "Jamie", "author_id": 1396824, "author_profile": "https://Stackoverflow.com/users/1396824", "pm_score": 2, "selected": false, "text": "<p>I am using NHibernate 3.2, and this works great:</p>\n\n<pre><code>type=\"NHibernate.Type.EnumStringType`1[[enum_full_type_name, enum_assembly]], NHibernate\"\n</code></pre>\n\n<p>Not sure when the generic EnumStringType got added, though. </p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956/" ]
Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum. I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.
Why are you guys over complicating this? It is really simple. The mapping looks like this: ``` <property name="OrganizationType"></property> ``` The model property looks like this: ``` public virtual OrganizationTypes OrganizationType { get; set; } ``` The Enum looks like this: ``` public enum OrganizationTypes { NonProfit = 1, ForProfit = 2 } ``` NHibernate will automatically figure it all out. Why type more than you need????
257,005
<p>I want to do this using the <code>Math.Round</code> function</p>
[ { "answer_id": 257011, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 7, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>twoDec = Math.Round(val, 2)\n</code></pre>\n" }, { "answer_id": 257017, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 10, "selected": false, "text": "<p>Here's some examples:</p>\n\n<pre><code>decimal a = 1.994444M;\n\nMath.Round(a, 2); //returns 1.99\n\ndecimal b = 1.995555M;\n\nMath.Round(b, 2); //returns 2.00\n</code></pre>\n\n<p>You might also want to look at bankers rounding / round-to-even with the following overload:</p>\n\n<pre><code>Math.Round(a, 2, MidpointRounding.ToEven);\n</code></pre>\n\n<p>There's more information on it <a href=\"http://en.wikipedia.org/wiki/Rounding#Round-to-even_method\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 257021, "author": "Kevin W Lee", "author_id": 26474, "author_profile": "https://Stackoverflow.com/users/26474", "pm_score": 2, "selected": false, "text": "<p>You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)</p>\n\n<p>You can read more <a href=\"http://msdn.microsoft.com/en-us/library/zy06z30k.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 257022, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<p>One thing you may want to check is the Rounding Mechanism of Math.Round:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx</a></p>\n\n<p>Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.</p>\n" }, { "answer_id": 257035, "author": "Foredecker", "author_id": 18256, "author_profile": "https://Stackoverflow.com/users/18256", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Rounding\" rel=\"noreferrer\">Wikipedia has a nice page</a> on rounding in general.</p>\n\n<p>All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the <a href=\"http://msdn.microsoft.com/en-us/library/zy06z30k(VS.95).aspx\" rel=\"noreferrer\">Math.Round()</a> (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use <a href=\"http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx\" rel=\"noreferrer\">round-to-even</a>. The <a href=\"http://msdn.microsoft.com/en-us/library/zx4t0t48(VS.95).aspx\" rel=\"noreferrer\">Ceiling()</a> and <a href=\"http://msdn.microsoft.com/en-us/library/e0b5f0xb(VS.95).aspx\" rel=\"noreferrer\">Floor()</a> methods are related.</p>\n\n<p>You can round with <a href=\"http://msdn.microsoft.com/en-us/library/0c899ak8(VS.95).aspx\" rel=\"noreferrer\">custom numeric formatting</a> as well.</p>\n\n<p>Note that <a href=\"http://msdn.microsoft.com/en-us/library/system.decimal.round(VS.71).aspx\" rel=\"noreferrer\">Decimal.Round()</a> uses a different method than Math.Round();</p>\n\n<p>Here is a <a href=\"http://blogs.msdn.com/ericlippert/archive/2003/09/26/bankers-rounding.aspx\" rel=\"noreferrer\">useful pos</a>t on the banker's rounding algorithm.\nSee one of Raymond's humorous <a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/01/26/360797.aspx\" rel=\"noreferrer\">posts here</a> about rounding...</p>\n" }, { "answer_id": 9403001, "author": "sadim", "author_id": 1226874, "author_profile": "https://Stackoverflow.com/users/1226874", "pm_score": 3, "selected": false, "text": "<p>This is for rounding to 2 decimal places in C#: </p>\n\n<pre><code>label8.Text = valor_cuota .ToString(\"N2\") ;\n</code></pre>\n\n<p>In VB.NET:</p>\n\n<pre><code> Imports System.Math\n round(label8.text,2)\n</code></pre>\n" }, { "answer_id": 9406108, "author": "Gleno", "author_id": 427673, "author_profile": "https://Stackoverflow.com/users/427673", "pm_score": 5, "selected": false, "text": "<p>Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that <code>string.Format(\"{0:0.00}\", number)</code> is a good approach.</p>\n" }, { "answer_id": 15650246, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 5, "selected": false, "text": "<p>If you'd like a string</p>\n\n<pre><code>&gt; (1.7289).ToString(\"#.##\")\n\"1.73\"\n</code></pre>\n\n<p>Or a decimal</p>\n\n<pre><code>&gt; Math.Round((Decimal)x, 2)\n1.73m\n</code></pre>\n\n<hr>\n\n<p>But remember! Rounding is not distributive, ie. <code>round(x*y) != round(x) * round(y)</code>. So don't do any rounding until the very end of a calculation, else you'll lose accuracy.</p>\n" }, { "answer_id": 33951496, "author": "Abhishek Jaiswal", "author_id": 5275530, "author_profile": "https://Stackoverflow.com/users/5275530", "pm_score": 1, "selected": false, "text": "<p>string a = \"10.65678\";</p>\n\n<p>decimal d = Math.Round(Convert.ToDouble(a.ToString()),2) </p>\n" }, { "answer_id": 34807727, "author": "Rae Lee", "author_id": 5113582, "author_profile": "https://Stackoverflow.com/users/5113582", "pm_score": 4, "selected": false, "text": "<p>// convert upto two decimal places</p>\n\n<pre><code>String.Format(\"{0:0.00}\", 140.6767554); // \"140.67\"\nString.Format(\"{0:0.00}\", 140.1); // \"140.10\"\nString.Format(\"{0:0.00}\", 140); // \"140.00\"\n\nDouble d = 140.6767554;\nDouble dc = Math.Round((Double)d, 2); // 140.67\n\ndecimal d = 140.6767554M;\ndecimal dc = Math.Round(d, 2); // 140.67\n</code></pre>\n\n<p>=========</p>\n\n<pre><code>// just two decimal places\nString.Format(\"{0:0.##}\", 123.4567); // \"123.46\"\nString.Format(\"{0:0.##}\", 123.4); // \"123.4\"\nString.Format(\"{0:0.##}\", 123.0); // \"123\"\n</code></pre>\n\n<p>can also combine \"0\" with \"#\".</p>\n\n<pre><code>String.Format(\"{0:0.0#}\", 123.4567) // \"123.46\"\nString.Format(\"{0:0.0#}\", 123.4) // \"123.4\"\nString.Format(\"{0:0.0#}\", 123.0) // \"123.0\"\n</code></pre>\n" }, { "answer_id": 44797890, "author": "Ruan", "author_id": 1713519, "author_profile": "https://Stackoverflow.com/users/1713519", "pm_score": 0, "selected": false, "text": "<pre><code> public double RoundDown(double number, int decimalPlaces)\n {\n return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);\n }\n</code></pre>\n" }, { "answer_id": 46502016, "author": "user3405179", "author_id": 3405179, "author_profile": "https://Stackoverflow.com/users/3405179", "pm_score": 2, "selected": false, "text": "<p><strong>Math.Floor(123456.646 * 100) / 100</strong>\nWould return 123456.64</p>\n" }, { "answer_id": 47071421, "author": "Guy P", "author_id": 1252723, "author_profile": "https://Stackoverflow.com/users/1252723", "pm_score": 3, "selected": false, "text": "<p>I know its an old question but please note for the following differences between <strong>Math round</strong> and <strong>String format round</strong>:</p>\n\n<pre><code>decimal d1 = (decimal)1.125;\nMath.Round(d1, 2).Dump(); // returns 1.12\nd1.ToString(\"#.##\").Dump(); // returns \"1.13\"\n\ndecimal d2 = (decimal)1.1251;\nMath.Round(d2, 2).Dump(); // returns 1.13\nd2.ToString(\"#.##\").Dump(); // returns \"1.13\"\n</code></pre>\n" }, { "answer_id": 56066728, "author": "fedesanp", "author_id": 2690533, "author_profile": "https://Stackoverflow.com/users/2690533", "pm_score": 3, "selected": false, "text": "<p>If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: <strong>0.75 * 0.95 = 0.7125</strong>. Right? Not in C#</p>\n\n<p>Let's see what happens if you want to round to the 3rd decimal:</p>\n\n<pre><code>double result = 0.75d * 0.95d; // result = 0.71249999999999991\ndouble result = 0.75f * 0.95f; // result = 0.71249997615814209\n\nresult = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok\nresult = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713\n</code></pre>\n\n<p>As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.</p>\n\n<p>This applies to negative numbers:</p>\n\n<pre><code>double result = -0.75 * 0.95; //result = -0.71249999999999991\nresult = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok\nresult = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713\n</code></pre>\n\n<p>So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:</p>\n\n<pre><code>double Redondea(double value, int precision, bool roundUp = true)\n{\n if ((decimal)value == 0.0m)\n return 0.0;\n\n double corrector = 1 / Math.Pow(10, precision + 2);\n\n if ((decimal)value &lt; 0.0m)\n {\n if (roundUp)\n return Math.Round(value, precision, MidpointRounding.ToEven);\n else\n return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);\n }\n else\n {\n if (roundUp)\n return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);\n else\n return Math.Round(value, precision, MidpointRounding.ToEven);\n }\n}\n</code></pre>\n\n<p>The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.</p>\n" }, { "answer_id": 57889973, "author": "Riyaz Hameed", "author_id": 1570636, "author_profile": "https://Stackoverflow.com/users/1570636", "pm_score": 3, "selected": false, "text": "<p>Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.</p>\n\n<pre><code>public static class DecimalExtensions\n{\n public static decimal WithTwoDecimalPoints(this decimal val)\n {\n return decimal.Parse(val.ToString(\"0.00\"));\n }\n}\n</code></pre>\n\n<p>Usage should be</p>\n\n<pre><code>var sampleDecimalValueV1 = 2.5m;\nConsole.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());\n\ndecimal sampleDecimalValueV1 = 2;\nConsole.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2.50\n2.00\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to do this using the `Math.Round` function
Here's some examples: ``` decimal a = 1.994444M; Math.Round(a, 2); //returns 1.99 decimal b = 1.995555M; Math.Round(b, 2); //returns 2.00 ``` You might also want to look at bankers rounding / round-to-even with the following overload: ``` Math.Round(a, 2, MidpointRounding.ToEven); ``` There's more information on it [here](http://en.wikipedia.org/wiki/Rounding#Round-to-even_method).
257,030
<p>Writing something like this using the <a href="http://loki-lib.sourceforge.net/" rel="nofollow noreferrer">loki library</a>,</p> <pre><code>typedef Functor&lt;void&gt; BitButtonPushHandler; </code></pre> <p>throws a compiler error, but this works</p> <pre><code>typedef Functor&lt;void,TYPELIST_1(Matrix3D*)&gt; Perspective; </code></pre> <blockquote> <p>Functor.h:530: error: '((Loki::FunctorHandler, int>*)this)->Loki::FunctorHandler, int>::f_' cannot be used as a function Functor.h:530: error: return-statement with a value, in function returning 'void'</p> </blockquote> <p>Anyone familiar with this library know how to get the first line working?</p>
[ { "answer_id": 257064, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": 3, "selected": true, "text": "<p>Looking at the source code, the Functor template definition is as follows:</p>\n\n<pre><code>template &lt;typename R = void, class TList = NullType,\n template&lt;class, class&gt; class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL&gt;\n class Functor{...};\n</code></pre>\n\n<p>As commented below, there are no template typedefs allowed, so all types (or accept all defaults) need to be specified.</p>\n\n<p>You can just define as follows and let the defaults do the work:</p>\n\n<pre><code>typedef Functor&lt;&gt; BitButtonPushHandler;\n</code></pre>\n\n<p>This compiles for me with a small test Functor class (not the actual Loki one), and I can use the typedef successfully.</p>\n" }, { "answer_id": 258156, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 0, "selected": false, "text": "<p>What I originally wrote worked... it was late, and I forgot about... </p>\n\n<pre><code>using namespace Loki; \n</code></pre>\n\n<p>...so sorry</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
Writing something like this using the [loki library](http://loki-lib.sourceforge.net/), ``` typedef Functor<void> BitButtonPushHandler; ``` throws a compiler error, but this works ``` typedef Functor<void,TYPELIST_1(Matrix3D*)> Perspective; ``` > > Functor.h:530: error: '((Loki::FunctorHandler, int>\*)this)->Loki::FunctorHandler, int>::f\_' cannot be used as a function > Functor.h:530: error: return-statement with a value, in function returning 'void' > > > Anyone familiar with this library know how to get the first line working?
Looking at the source code, the Functor template definition is as follows: ``` template <typename R = void, class TList = NullType, template<class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL> class Functor{...}; ``` As commented below, there are no template typedefs allowed, so all types (or accept all defaults) need to be specified. You can just define as follows and let the defaults do the work: ``` typedef Functor<> BitButtonPushHandler; ``` This compiles for me with a small test Functor class (not the actual Loki one), and I can use the typedef successfully.
257,047
<p>Where would i go to look for algorithms that take a 2d grid of values that are either 0 or 1 as input and then identifies all possible non-overlapping rectangles in it?</p> <p>In a more practical explanation: I am drawing a grid that is represented by a number of squares, and i wish to find a way to combine as many adjacent squares into rectangles as possible, in order to cut down on the time spent on cycling through each square and drawing it.</p> <p>Maximum efficiency is not needed, speed is more important.</p> <p>Addendum: Apparently what i am looking for seems to be a technique called Tesselation. Now i only need to find a good description for this specific case.</p> <p>Addendum 2: The boundary of the "1" squares will be irregular and in some cases not even connected, as the distribution of "1" squares will be completely random. I need these irregular shapes to be identified and split up into regular rectangles.</p> <p><strong>Correct answer:</strong> To get the best balance between speed and efficiency it is optimal to use the grid data to fill a quad-tree with each node having a status value of either empty/partly filled/filled.</p>
[ { "answer_id": 257069, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 0, "selected": false, "text": "<p>So you are looking for the rectangular boundary of the 'ON' squares?<br>\nDo you want the inner or outer bound?<br>\nie. Must the boundary only have 'ON' squares or do you want the rectangle to contain all the 'ON' squares in a group?</p>\n" }, { "answer_id": 257075, "author": "Peter Olsson", "author_id": 2703, "author_profile": "https://Stackoverflow.com/users/2703", "pm_score": 1, "selected": false, "text": "<p>As you are not looking for the minimum number of squares I would suggest using a compromise that still keeps your algorithm simple.</p>\n\n<p>What the best solution is depends on your data, but one simple alternative is to just collect boxes along one row. I.e:</p>\n\n<pre><code>0 0 1 1 1 0 0 0 1 1 1 1 0\n</code></pre>\n\n<p>Will result in:</p>\n\n<pre><code>skip 2\ndraw 3\nskip 3\ndraw 4\nskip 1\n</code></pre>\n\n<p>This will reduce the number of calls to draw box without any need of caching (i.e you can build your boxes on the fly).</p>\n\n<p>If you want to create bigger boxes I would suggest a backtracking algorithm there you find the first 1 and try to expand the box in all directions. Build a list of boxes and clear the 1:s as you have used them.</p>\n" }, { "answer_id": 257103, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 3, "selected": true, "text": "<p>I've done something similar for a quick-and-dirty voxel visualization of 3d boxes with OpenGL. </p>\n\n<p>I started from the top left box and stored the empty/filled flag. Then I tried to expand the rectangle to the right until I hit a box with a different flag. I did the same in the down direction.</p>\n\n<p>Draw the rectangle, if it is filled.</p>\n\n<p>If there are boxes remaing, recursivly repeat the procedure for all three remaing rectangles induced by the last rectangle, which are right, bottom and bottom right:</p>\n\n<pre><code>xxxx 1111\nxxxx 1111\nxxxx 1111\n\n2222 3333\n2222 3333\n2222 3333\n</code></pre>\n" }, { "answer_id": 713525, "author": "Joel in Gö", "author_id": 6091, "author_profile": "https://Stackoverflow.com/users/6091", "pm_score": 2, "selected": false, "text": "<p>Have a look at <a href=\"http://www.ddj.com/184410529\" rel=\"nofollow noreferrer\">this article from Dr Dobb's Portal</a> on finding a maximal rectangle in your situation. It is a very detailed discussion of an extremely efficient algorithm, and I think that repeating it iteratively would possibly solve your problem.</p>\n" }, { "answer_id": 35777827, "author": "gouessej", "author_id": 458157, "author_profile": "https://Stackoverflow.com/users/458157", "pm_score": 0, "selected": false, "text": "<p>I had to solve a similar problem, my algorithm supports jagged arrays, I have heavily tested and commented it but it's slower than joel-in-gö's suggestion :\n<a href=\"https://stackoverflow.com/a/13802336\">https://stackoverflow.com/a/13802336</a></p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145119/" ]
Where would i go to look for algorithms that take a 2d grid of values that are either 0 or 1 as input and then identifies all possible non-overlapping rectangles in it? In a more practical explanation: I am drawing a grid that is represented by a number of squares, and i wish to find a way to combine as many adjacent squares into rectangles as possible, in order to cut down on the time spent on cycling through each square and drawing it. Maximum efficiency is not needed, speed is more important. Addendum: Apparently what i am looking for seems to be a technique called Tesselation. Now i only need to find a good description for this specific case. Addendum 2: The boundary of the "1" squares will be irregular and in some cases not even connected, as the distribution of "1" squares will be completely random. I need these irregular shapes to be identified and split up into regular rectangles. **Correct answer:** To get the best balance between speed and efficiency it is optimal to use the grid data to fill a quad-tree with each node having a status value of either empty/partly filled/filled.
I've done something similar for a quick-and-dirty voxel visualization of 3d boxes with OpenGL. I started from the top left box and stored the empty/filled flag. Then I tried to expand the rectangle to the right until I hit a box with a different flag. I did the same in the down direction. Draw the rectangle, if it is filled. If there are boxes remaing, recursivly repeat the procedure for all three remaing rectangles induced by the last rectangle, which are right, bottom and bottom right: ``` xxxx 1111 xxxx 1111 xxxx 1111 2222 3333 2222 3333 2222 3333 ```
257,065
<p>The reason I am asking this is that I had accidentally done a <code>git commit -a</code> that included a file I did not yet want to commit. My solution was to do the following:</p> <pre><code>git reset --soft HEAD^ git reset -- file/with/changes_not_to_committed git commit -C HEAD@{1} </code></pre> <p>Here, I’ve rewound the branch by one commit while keeping the index and working tree, then pulled <code>file/with/changes_not_to_committed</code> from a yet older revision into the index, and then I committed the index using the commit message from the previous branch head commit. Neither <code>git-reset</code> invocation touches the working copy, so my modifications to <code>file/with/changes_not_to_committed</code> persist, but are no longer recorded in the <code>HEAD</code> revision.</p> <p>However, it would have been easier if I could pull <code>file/with/changes_not_to_committed</code> from the <code>HEAD^</code> revision right into the index <em>without touching the working copy</em>. Since the index otherwise already represents the state I want, I could then just amend the <code>HEAD</code> commit, producing a sequence like this:</p> <pre><code>git magic-pony HEAD^ file/with/changes_not_to_committed git commit --amend -C HEAD </code></pre> <p>This is <em>almost</em> what I would get by replacing <code>git-magic-pony</code> with <code>git-checkout</code>, except for the requirement that the working copy be left untouched and only the index updated. It seems there is no way to make <code>git-checkout</code> not touch both.</p> <p>My question is: does <code>git-magic-pony</code> exist, and if so, under what name?</p>
[ { "answer_id": 257105, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>It looks like you can do something like this using <a href=\"http://kernel.org/pub/software/scm/git-core/docs/git-update-index.html\" rel=\"nofollow noreferrer\"><code>git update-index</code></a>:</p>\n\n<pre><code>git update-index --cacheinfo 100644 5be7e154c284fb8de8ddca0bb18b72a73089df9b filename\n</code></pre>\n\n<p>You will need to get the mode (100644 above) and sha1 of the file you want to go back to (you can get this info all from <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-ls-tree.html\" rel=\"nofollow noreferrer\"><code>git ls-tree</code></a>). Then you can <code>git commit --amend</code> and your working copy will not be affected.</p>\n" }, { "answer_id": 257196, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "<p><del>So based on Greg Hewgill’s answer, <code>git-magic-pony</code> is a shell script I would write which looks like this:</del></p>\n\n<pre><code><del>#!/bin/sh\ngit ls-tree \"$@\" | while read mode type hash path ; do\n git update-index --cacheinfo $mode $hash \"$path\"\ndone</code></del></pre>\n" }, { "answer_id": 257976, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Right. When you want to move revisions from HEAD or another revision to the index, you use 'git reset REVISION -- file' - then, you'd use 'git commit --amend' to revise the commit. As it happens I'm currently working on a review aimed towards making it more obvious how files can be moved from A to B like that.</p>\n\n<p>Of course a much easier way is to crank up 'git-gui', click the 'amend last commit' button, then click on the icon by the file in the commit inventory section of the gui, and then 'commit'.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9410/" ]
The reason I am asking this is that I had accidentally done a `git commit -a` that included a file I did not yet want to commit. My solution was to do the following: ``` git reset --soft HEAD^ git reset -- file/with/changes_not_to_committed git commit -C HEAD@{1} ``` Here, I’ve rewound the branch by one commit while keeping the index and working tree, then pulled `file/with/changes_not_to_committed` from a yet older revision into the index, and then I committed the index using the commit message from the previous branch head commit. Neither `git-reset` invocation touches the working copy, so my modifications to `file/with/changes_not_to_committed` persist, but are no longer recorded in the `HEAD` revision. However, it would have been easier if I could pull `file/with/changes_not_to_committed` from the `HEAD^` revision right into the index *without touching the working copy*. Since the index otherwise already represents the state I want, I could then just amend the `HEAD` commit, producing a sequence like this: ``` git magic-pony HEAD^ file/with/changes_not_to_committed git commit --amend -C HEAD ``` This is *almost* what I would get by replacing `git-magic-pony` with `git-checkout`, except for the requirement that the working copy be left untouched and only the index updated. It seems there is no way to make `git-checkout` not touch both. My question is: does `git-magic-pony` exist, and if so, under what name?
Right. When you want to move revisions from HEAD or another revision to the index, you use 'git reset REVISION -- file' - then, you'd use 'git commit --amend' to revise the commit. As it happens I'm currently working on a review aimed towards making it more obvious how files can be moved from A to B like that. Of course a much easier way is to crank up 'git-gui', click the 'amend last commit' button, then click on the icon by the file in the commit inventory section of the gui, and then 'commit'.
257,078
<p>I understand that using the "===" compares type, so running the following code results in "not equal" because it's comparing a number type to a string type.</p> <pre><code>var a = 20; var b = "20"; if (a === b) { alert("They are equal"); } else { alert("They are not equal"); } </code></pre> <p>But I dont understand how using the "==" to compare only the value results in the "They are equal" message.</p> <pre><code>var a = 20; var b = "20"; if (a == b) { alert("They are equal"); } else { alert("They are not equal"); } </code></pre> <p>How are the values equal? Isn't the string "20" stored as the ASCII characters 50 and 48 (0110010 and 0110000 in binary) and 20 stored as the actual binary number 0010100?</p> <p>EDIT: Thanks everyone! I think all the responses are great and have helped me understand this much better.</p>
[ { "answer_id": 257083, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 5, "selected": true, "text": "<p>The <code>==</code> operator compares only the values of the variables. If the types are different, a conversion is operated. So the number 20 is converted to the string \"20\" and the result is compared. </p>\n\n<p>The <code>===</code> operator compares not only the values, but also the types, so no cast is operated. In this case <code>\"20\" !== 20</code></p>\n" }, { "answer_id": 257084, "author": "Gunnar Steinn", "author_id": 33468, "author_profile": "https://Stackoverflow.com/users/33468", "pm_score": 2, "selected": false, "text": "<p>The JavaScript engine sees the a as a number and casts the b to number before the valuation.</p>\n" }, { "answer_id": 257086, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 2, "selected": false, "text": "<p>Part of the definition of \"==\" is that the values will be converted to the same types before comparison, when possible. This is true of many loosely typed languages.</p>\n" }, { "answer_id": 257087, "author": "codeinthehole", "author_id": 32640, "author_profile": "https://Stackoverflow.com/users/32640", "pm_score": 0, "selected": false, "text": "<p>As far as I know JavaScript does automatic data type conversion on the fly - so maybe the variables are casted to equivalent types automatically.</p>\n" }, { "answer_id": 257088, "author": "Sean Schulte", "author_id": 33380, "author_profile": "https://Stackoverflow.com/users/33380", "pm_score": 2, "selected": false, "text": "<p>Javascript is designed such that a string containing numbers is considered \"equal\" to that number. The reason for that is simplicity of use for the case of users entering a number into an input field and the site validates it in JS -- you don't have to cast the entered string to a number before comparing.</p>\n\n<p>It simplifies a common use case, and the === operator still allows you to compare with the type considered as well.</p>\n" }, { "answer_id": 260360, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>When type conversion is needed, JavaScript converts String, Number, Boolean, or Object operands as follows.</p>\n\n<ul>\n<li>When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.</li>\n<li>If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.</li>\n<li>If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.</li>\n</ul>\n\n<p>The problem with the == comparison is that JavaScript version 1.2 doesn't perform type conversion, whereas versions 1.1 and 1.3 onwards do.</p>\n\n<p>The === comparison has been available since version 1.3, and is the best way to check of two variables match.</p>\n\n<p>If you need your code to be compatible with version 1.1, 1.2 and 1.3 versions of JavaScript code, you should ensure that the variables all match as if it was an === comparison that was being performed.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I understand that using the "===" compares type, so running the following code results in "not equal" because it's comparing a number type to a string type. ``` var a = 20; var b = "20"; if (a === b) { alert("They are equal"); } else { alert("They are not equal"); } ``` But I dont understand how using the "==" to compare only the value results in the "They are equal" message. ``` var a = 20; var b = "20"; if (a == b) { alert("They are equal"); } else { alert("They are not equal"); } ``` How are the values equal? Isn't the string "20" stored as the ASCII characters 50 and 48 (0110010 and 0110000 in binary) and 20 stored as the actual binary number 0010100? EDIT: Thanks everyone! I think all the responses are great and have helped me understand this much better.
The `==` operator compares only the values of the variables. If the types are different, a conversion is operated. So the number 20 is converted to the string "20" and the result is compared. The `===` operator compares not only the values, but also the types, so no cast is operated. In this case `"20" !== 20`
257,085
<p>I have a JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE:</p> <pre><code>var drop= function(id) { if(document.getElementById("select1").value == "Ficha de pediatria"){ top.location.href = "print.jsp?id="+id+"&amp;type=2"; } else if(document.getElementById("select1").value == "Ficha normal"){ top.location.href = "print.jsp?id="+id+"&amp;type=1"; } } &lt;select id="select1" name="select1" onChange="drop(id);return false;"&gt; &lt;option&gt;Imprimir:&lt;/option&gt; &lt;option&gt;Ficha de pediatria&lt;/option&gt; &lt;option&gt;Ficha normal&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I trimed this as it had more JSP code but it' remained the same. Anyone got any idea why it's not running on IE?</p>
[ { "answer_id": 257095, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>[EDIT] Sorry. I introduced an error with my first post by not carefully looking at how you are constructing your url. I shouldn't have removed the <code>id</code> parameter. I've updated the code and it should work now.</p>\n\n<p>Try this instead:</p>\n\n<pre><code>function drop(ctl,id)\n{\n var value = ctl.options[ctl.selectedIndex].value;\n\n if(value == \"Ficha de pediatria\"){\n window.top.location.href = \"print.jsp?id=\"+id+\"&amp;type=2\";\n }\n else if (value == \"Ficha normal\"){\n window.top.location.href = \"print.jsp?id=\"+id+\"&amp;type=1\";\n }\n}\n\n&lt;select id=\"select1\" name=\"select1\" onChange=\"drop(this,id);return false;\"&gt;\n&lt;option&gt;Imprimir:&lt;/option&gt;\n&lt;option&gt;Ficha de pediatria&lt;/option&gt;\n&lt;option&gt;Ficha normal&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>[EDIT] A bit of explanation...</p>\n\n<p>I think the issue is how it is accessing the DOM. I don't think that IE has a value property on a select. I think you have to get at it via the selected option. Also, I'm not sure that there is a top property in the global namespace, but you should be able to get at it via <code>window.top</code> to set the location. Finally, I made a slight improvement in that by specifying <code>this</code> as the argument, you can skip the element lookup and reference it directly from the control passed as the argument.</p>\n" }, { "answer_id": 257097, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": -1, "selected": false, "text": "<p>I see two possible reasons.</p>\n\n<p><strong>1</strong> - The way the function is declared. I've never seen it like that though I guess it works.</p>\n\n<p>Maybe try the following and see if it still does not work:</p>\n\n<pre><code>function drop(id)\n{\n // same code\n}\n</code></pre>\n\n<hr>\n\n<p><strong>2</strong> - The return false in IE does not always behave properly (trust me, it depends on the computer) So instead of returning false, try:</p>\n\n<pre><code>onChange=\"drop(id);event.returnValue=false;return false;\"\n</code></pre>\n\n<p>If possible create a method like this one:</p>\n\n<pre><code>function CrossBrowserFalse()\n{\n if(IE) // use whatever you want to detect IE\n {\n event.returnValue = false;\n }\n\n return false;\n}\n</code></pre>\n\n<p>and then in your methods you can use:</p>\n\n<pre><code>onChange=\"drop(id);return CrossBrowserFalse();\"\n</code></pre>\n\n<p>...yeah, IE is weird sometimes (often)</p>\n\n<hr>\n\n<p>If these two fail, at least make sure your drop function is called by putting some alerts in there or breakpoints if your IDE supports it for javascript.</p>\n" }, { "answer_id": 257279, "author": "kamens", "author_id": 1335, "author_profile": "https://Stackoverflow.com/users/1335", "pm_score": 1, "selected": false, "text": "<p>It's not that IE \"doesn't have .value\" of a &lt;select&gt; element, it's that you <strong>haven't specified any values for your &lt;option&gt; elements</strong>. Firefox, Safari, and co. are likely protecting you from this mistake. Nevertheless, your element should be constructed as:</p>\n\n<pre><code>&lt;select ...&gt;\n&lt;option value=\"Imprimir\"&gt;Imprimir:&lt;/option&gt;\n&lt;option value=\"Ficha de pediatria\"&gt;Ficha de pediatria&lt;/option&gt;\n&lt;option value=\"Ficha normal\"&gt;Ficha normal&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>...and you'll see more standard x-browser behavior for the &lt;select&gt;'s .value property.</p>\n" }, { "answer_id": 257321, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p>IE doesn't like the way you're grabbing the value of the select</p>\n\n<pre><code>document.getElementById(\"select1\").value\n</code></pre>\n\n<p>This is saying \"give me the text that's in the value attribute of the selected option in the select element with the id <em>select1</em>. Your options don't have any values. When Firefox and Safari encounter this ambiguity, they return the text of the selected option. When Internet Explorer encounters this ambiguity, it returns a blank string. Your javascript would work as is if you did something like </p>\n\n<pre><code>&lt;select id=\"select1\" name=\"select1\" onChange=\"drop(this,id);return false;\"&gt;\n &lt;option value=\"Imprimir:\"&gt;Imprimir:&lt;/option&gt;\n &lt;option value=\"Ficha de pediatria\"&gt;Ficha de pediatria&lt;/option&gt;\n &lt;option value=\"Ficha normal\"&gt;Ficha normal&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>If that's not possible, you'll want to grab the <em>text</em> of the option that's selected. </p>\n\n<pre><code>var theSelect = document.getElementById(\"select1\");\nvar theValue = theSelect.options[theSelect.selectedIndex].text\n</code></pre>\n\n<p>Finally, while not your direct question, a the hard coded <em>select1</em> isn't the best way to get at the select list. Consider using the this keyword</p>\n\n<pre><code>function foo(theSelect){\n alert(theSelect.options);\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>&lt;select id=\"whatever\" onchange=\"foo(this);\"&gt;\n...\n&lt;/select&gt;\n</code></pre>\n\n<p>This is a bit more generic, and you'll be able to use your function on a select with any ID. </p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
I have a JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE: ``` var drop= function(id) { if(document.getElementById("select1").value == "Ficha de pediatria"){ top.location.href = "print.jsp?id="+id+"&type=2"; } else if(document.getElementById("select1").value == "Ficha normal"){ top.location.href = "print.jsp?id="+id+"&type=1"; } } <select id="select1" name="select1" onChange="drop(id);return false;"> <option>Imprimir:</option> <option>Ficha de pediatria</option> <option>Ficha normal</option> </select> ``` I trimed this as it had more JSP code but it' remained the same. Anyone got any idea why it's not running on IE?
[EDIT] Sorry. I introduced an error with my first post by not carefully looking at how you are constructing your url. I shouldn't have removed the `id` parameter. I've updated the code and it should work now. Try this instead: ``` function drop(ctl,id) { var value = ctl.options[ctl.selectedIndex].value; if(value == "Ficha de pediatria"){ window.top.location.href = "print.jsp?id="+id+"&type=2"; } else if (value == "Ficha normal"){ window.top.location.href = "print.jsp?id="+id+"&type=1"; } } <select id="select1" name="select1" onChange="drop(this,id);return false;"> <option>Imprimir:</option> <option>Ficha de pediatria</option> <option>Ficha normal</option> </select> ``` [EDIT] A bit of explanation... I think the issue is how it is accessing the DOM. I don't think that IE has a value property on a select. I think you have to get at it via the selected option. Also, I'm not sure that there is a top property in the global namespace, but you should be able to get at it via `window.top` to set the location. Finally, I made a slight improvement in that by specifying `this` as the argument, you can skip the element lookup and reference it directly from the control passed as the argument.
257,091
<p>How do I clear the cin buffer in C++?</p>
[ { "answer_id": 257092, "author": "Gunnar Steinn", "author_id": 33468, "author_profile": "https://Stackoverflow.com/users/33468", "pm_score": 1, "selected": false, "text": "<p>The following should work:</p>\n\n<pre><code>cin.flush();\n</code></pre>\n\n<p>On some systems it's not available and then you can use:</p>\n\n<pre><code>cin.ignore(INT_MAX);\n</code></pre>\n" }, { "answer_id": 257098, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 8, "selected": true, "text": "<p>Possibly:</p>\n\n<pre><code>std::cin.ignore(INT_MAX);\n</code></pre>\n\n<p>This would read in and ignore everything until <code>EOF</code>. (you can also supply a second argument which is the character to read until (ex: <code>'\\n'</code> to ignore a single line).</p>\n\n<p>Also: You probably want to do a: <code>std::cin.clear();</code> before this too to reset the stream state.</p>\n" }, { "answer_id": 257182, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": false, "text": "<p>I would prefer the C++ size constraints over the C versions:</p>\n<pre><code>// Ignore to the end of Stream\nstd::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max())\n\n// Ignore to the end of line\nstd::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n')\n</code></pre>\n" }, { "answer_id": 257203, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 2, "selected": false, "text": "<p>I prefer:</p>\n\n<pre><code>cin.clear();\nfflush(stdin);\n</code></pre>\n\n<p>There's an example where cin.ignore just doesn't cut it, but I can't think of it at the moment. It was a while ago when I needed to use it (with Mingw).</p>\n\n<p>However, fflush(stdin) is undefined behavior according to the standard. fflush() is only meant for output streams. fflush(stdin) only seems to work as expected on Windows (with GCC and MS compilers at least) <a href=\"http://msdn.microsoft.com/en-us/library/9yky46tz(v=vs.71).aspx\" rel=\"nofollow noreferrer\">as an extension to the C standard</a>.</p>\n\n<p>So, if you use it, your code isn't going to be portable.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2979209/using-fflushstdin\">Using fflush(stdin)</a>.</p>\n\n<p>Also, see <a href=\"http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&amp;p=452568&amp;postcount=1\" rel=\"nofollow noreferrer\">http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&amp;p=452568&amp;postcount=1</a> for an alternative.</p>\n" }, { "answer_id": 538629, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>cin.ignore(cin.rdbuf()-&gt;in_avail());\n</code></pre>\n" }, { "answer_id": 1542777, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>int i;\n cout &lt;&lt; \"Please enter an integer value: \";\n\n // cin &gt;&gt; i; leaves '\\n' among possible other junk in the buffer. \n // '\\n' also happens to be the default delim character for getline() below.\n cin &gt;&gt; i; \n if (cin.fail()) \n {\n cout &lt;&lt; \"\\ncin failed - substituting: i=1;\\n\\n\";\n i = 1;\n }\n cin.clear(); cin.ignore(INT_MAX,'\\n'); \n\n cout &lt;&lt; \"The value you entered is: \" &lt;&lt; i &lt;&lt; \" and its double is \" &lt;&lt; i*2 &lt;&lt; \".\\n\\n\";\n\n string myString;\n cout &lt;&lt; \"What's your full name? (spaces inclded) \\n\";\n getline (cin, myString);\n cout &lt;&lt; \"\\nHello '\" &lt;&lt; myString &lt;&lt; \"'.\\n\\n\\n\";\n</code></pre>\n" }, { "answer_id": 23745035, "author": "jyggorath", "author_id": 2306552, "author_profile": "https://Stackoverflow.com/users/2306552", "pm_score": 5, "selected": false, "text": "<pre><code>cin.clear();\nfflush(stdin);\n</code></pre>\n\n<p>This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \\n, or something would remain in the buffer.</p>\n\n<p>EDIT:\nI found out that the previous solution made things worse. THIS one however, works:</p>\n\n<pre><code>cin.getline(temp, STRLEN);\nif (cin.fail()) {\n cin.clear();\n cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\\n');\n}\n</code></pre>\n" }, { "answer_id": 26817311, "author": "techcomp", "author_id": 3921632, "author_profile": "https://Stackoverflow.com/users/3921632", "pm_score": 1, "selected": false, "text": "<pre><code>#include &lt;stdio_ext.h&gt;\n</code></pre>\n\n<p>and then use function </p>\n\n<pre><code>__fpurge(stdin)\n</code></pre>\n" }, { "answer_id": 29155484, "author": "GuestPerson001", "author_id": 4691763, "author_profile": "https://Stackoverflow.com/users/4691763", "pm_score": 0, "selected": false, "text": "<p><code>cin.get()</code> seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).</p>\n" }, { "answer_id": 31872811, "author": "Bobul Mentol", "author_id": 5191247, "author_profile": "https://Stackoverflow.com/users/5191247", "pm_score": 2, "selected": false, "text": "<p>Another possible (manual) solution is</p>\n\n<pre><code>cin.clear();\nwhile (cin.get() != '\\n') \n{\n continue;\n}\n</code></pre>\n\n<p>I cannot use fflush or cin.flush() with CLion so this came handy.</p>\n" }, { "answer_id": 34518907, "author": "Ben", "author_id": 1727729, "author_profile": "https://Stackoverflow.com/users/1727729", "pm_score": 4, "selected": false, "text": "<p>I have found two solutions to this.</p>\n\n<p>The first, and simplest, is to use <code>std::getline()</code> for example:</p>\n\n<pre><code>std::getline(std::cin, yourString);\n</code></pre>\n\n<p>... that will discard the input stream when it gets to a new-line. Read more about this function <a href=\"http://www.cplusplus.com/reference/string/string/getline\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Another option that directly discards the stream is this...</p>\n\n<pre><code>#include &lt;limits&gt;\n// Possibly some other code here\ncin.clear();\ncin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\\n');\n</code></pre>\n\n<p>Good luck!</p>\n" }, { "answer_id": 46411174, "author": "Chaitanya Vaishampayan", "author_id": 7105441, "author_profile": "https://Stackoverflow.com/users/7105441", "pm_score": 2, "selected": false, "text": "<p>Easiest way:</p>\n\n<pre><code>cin.seekg(0,ios::end);\ncin.clear();\n</code></pre>\n\n<p>It just positions the cin pointer at the end of the stdin stream and cin.clear() clears all error flags such as the EOF flag.</p>\n" }, { "answer_id": 61894774, "author": "Amrit Malla", "author_id": 10755186, "author_profile": "https://Stackoverflow.com/users/10755186", "pm_score": 2, "selected": false, "text": "<p>It worked for me. I have used for loop with getline(). </p>\n\n<pre><code>cin.ignore()\n</code></pre>\n" }, { "answer_id": 72080307, "author": "shyed2001", "author_id": 11248174, "author_profile": "https://Stackoverflow.com/users/11248174", "pm_score": -1, "selected": false, "text": "<p>fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement.</p>\n<p>fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement.\nThe following should work:</p>\n<p>cin.flush();\nOn some systems it's not available and then you can use:</p>\n<p>cin.ignore(INT_MAX);\nBoth Windows and Linux define the behaviour of fflush() on an input stream,\nand even define it the same way (miracle of miracles).\nThe POSIX, C and C++ standards for fflush() do not define the behaviour,\nbut none of them prevent a system from defining it.\nIf you're coding for maximum portability, avoid fflush(stdin);\nif you're coding for platforms that define the behaviour, use it — but be aware that it is not portable\nportable code does not use fflush(stdin). Code that is tied to Microsoft's platform may use it and\nit may work as expected, but beware of the portability issues.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I clear the cin buffer in C++?
Possibly: ``` std::cin.ignore(INT_MAX); ``` This would read in and ignore everything until `EOF`. (you can also supply a second argument which is the character to read until (ex: `'\n'` to ignore a single line). Also: You probably want to do a: `std::cin.clear();` before this too to reset the stream state.
257,093
<p>Given the following table, how does one calculate the hourly mode, or value with the highest frequency by hour?</p> <pre><code>CREATE TABLE Values ( ValueID int NOT NULL, Value int NOT NULL, LogTime datetime NOT NULL ) </code></pre> <p>So far, I've come up with the following query.</p> <pre><code>SELECT count(*) AS Frequency, DatePart(yy, LogTime) as [Year], DatePart(mm, LogTime) as [Month], DatePart(dd, LogTime) as [Day], DatePart(hh, LogTime) as [Hour] FROM Values GROUP BY Value, DatePart(yy, LogTime), DatePart(mm, LogTime), DatePart(dd, LogTime), DatePart(hh, LogTime) </code></pre> <p>However, this yields the frequency of each distinct value by hour. How do I add a constraint to only return the value with the maximum frequency by hour?</p> <p>Thanks</p>
[ { "answer_id": 257181, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 1, "selected": false, "text": "<p>Nest the aggregates...</p>\n\n<pre><code>SELECT\n MAX(Frequency) AS [Mode],\n [Year],[Month],[Day],[Hour]\nFROM\n (SELECT\n COUNT(*) AS Frequency, \n DatePart(yy, LogTime) as [Year], \n DatePart(mm, LogTime) as [Month], \n DatePart(dd, LogTime) as [Day], \n DatePart(hh, LogTime) as [Hour]\n FROM \n Values \n GROUP BY \n Value, \n DatePart(yy, LogTime), \n DatePart(mm, LogTime), \n DatePart(dd, LogTime), \n DatePart(hh, LogTime)\n ) foo\nGROUP By\n [Year],[Month],[Day],[Hour]\n</code></pre>\n" }, { "answer_id": 257306, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>The following query may look odd... but it works and it gives you what you want. This query will give you the value that had the highest frequency in a particular \"hour\" (slice of time).</p>\n\n<p>I am <em>NOT</em> dividing into Year, Month, Day, etc... only hour (as you requested) even though you had those other fields in your example query.</p>\n\n<p>I chose to do \"MAX(Value)\" below, because the case can come up where more than one \"value\" tied for first place with the highest frequency by hour. You can choose to do MIN, or MAX or some other 'tiebreaker' if you want.</p>\n\n<pre><code>WITH GroupedValues (Value, Frequency, Hour) AS\n (SELECT\n Value,\n COUNT(*) AS Frequency,\n DATEPART(hh, LogTime) AS Hour\n FROM\n dbo.MyValues\n GROUP BY\n Value,\n DATEPART(hh, LogTime))\n\nSELECT\n MAX(Value) AS Value,\n a.Hour\nFROM\n GroupedValues a INNER JOIN\n (SELECT MAX(Frequency) AS MaxFrequency,\n Hour FROM GroupedValues GROUP BY Hour) b\n ON a.Frequency = b.MaxFrequency AND a.Hour = b.Hour\nGROUP BY\n a.Hour\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Given the following table, how does one calculate the hourly mode, or value with the highest frequency by hour? ``` CREATE TABLE Values ( ValueID int NOT NULL, Value int NOT NULL, LogTime datetime NOT NULL ) ``` So far, I've come up with the following query. ``` SELECT count(*) AS Frequency, DatePart(yy, LogTime) as [Year], DatePart(mm, LogTime) as [Month], DatePart(dd, LogTime) as [Day], DatePart(hh, LogTime) as [Hour] FROM Values GROUP BY Value, DatePart(yy, LogTime), DatePart(mm, LogTime), DatePart(dd, LogTime), DatePart(hh, LogTime) ``` However, this yields the frequency of each distinct value by hour. How do I add a constraint to only return the value with the maximum frequency by hour? Thanks
The following query may look odd... but it works and it gives you what you want. This query will give you the value that had the highest frequency in a particular "hour" (slice of time). I am *NOT* dividing into Year, Month, Day, etc... only hour (as you requested) even though you had those other fields in your example query. I chose to do "MAX(Value)" below, because the case can come up where more than one "value" tied for first place with the highest frequency by hour. You can choose to do MIN, or MAX or some other 'tiebreaker' if you want. ``` WITH GroupedValues (Value, Frequency, Hour) AS (SELECT Value, COUNT(*) AS Frequency, DATEPART(hh, LogTime) AS Hour FROM dbo.MyValues GROUP BY Value, DATEPART(hh, LogTime)) SELECT MAX(Value) AS Value, a.Hour FROM GroupedValues a INNER JOIN (SELECT MAX(Frequency) AS MaxFrequency, Hour FROM GroupedValues GROUP BY Hour) b ON a.Frequency = b.MaxFrequency AND a.Hour = b.Hour GROUP BY a.Hour ```
257,102
<p>In other words, can <code>fn()</code> know that it is being used as <code>$var = fn();</code> rather than as <code>fn();</code>?</p> <p>A use case would be to <code>echo</code> the return value in the latter case but to <code>return</code> it in the former.</p> <p>Can this be done without passing a parameter to the function to declare which way it is being used?</p>
[ { "answer_id": 257113, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 0, "selected": false, "text": "<p>No, there is no way to find it out. The unique thing you could do, is to grab the call stack (<a href=\"http://it2.php.net/debug_backtrace\" rel=\"nofollow noreferrer\">http://it2.php.net/debug_backtrace</a>) and inspect it. </p>\n" }, { "answer_id": 257114, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>No, it can't.</p>\n" }, { "answer_id": 257122, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 0, "selected": false, "text": "<p>It can't be easily done but, so what if you just passed an extra boolean variable to the function? That way, the end of the function would look like:</p>\n\n<pre><code>if (namespace) {\n return $output;\n} else {\n echo $output;\n}\n</code></pre>\n\n<p>Seems a pretty simple workaround.</p>\n" }, { "answer_id": 257184, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "<p>No, and it shouldn't. It's a pretty basic premise of the language that functions are unaware of the context in which they are used. This allows you to decompose your application, because each part (function) is completely isolated from its surroundings.</p>\n\n<p>That said, what you can do about this particular use-case, is to tturn on output buffering. By default <code>echo</code> will send data to stdout, but you can set a buffer, which will capture the output into a variable instead. For example:</p>\n\n<pre><code>function foo() {\n echo \"Hello World\";\n}\nfoo(); // will output \"Hello World\"\nob_start();\nfoo();\n$foo = ob_get_clean(); // will assign the string \"Hello World\" into the variable $foo\n</code></pre>\n\n<p>In addition to that, it is generally considered bad style to have functions output directly. You should generally return a string and leave it for the top level of your script to output. Ideally there should be just one single echo statement in your entire application.</p>\n" }, { "answer_id": 257191, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": "<p>Many PHP functions do this by passing a boolean value called $return which returns the value if $return is true, or prints the value if $return is false. A couple of examples are <a href=\"http://php.net/print_r\" rel=\"nofollow noreferrer\">print_r()</a> and <a href=\"http://php.net/highlight_file\" rel=\"nofollow noreferrer\">highlight_file()</a>.</p>\n\n<p>So your function would look like this:</p>\n\n<pre><code>function fn($return=false) {\n if ($return) {\n return 'blah';\n } else {\n echo 'blah';\n }\n}\n</code></pre>\n\n<p>Any other way will not be good programming style.</p>\n" }, { "answer_id": 257233, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>Just think about how the interpreter executes this statement:</p>\n\n<pre><code>$var = fn();\n</code></pre>\n\n<p>The interpreter evaluates operands right-to-left with the assignment operator, so first it will evaluate the expression on the right hand side (<code>fn()</code> in this case) and will then assign the result to <code>$var</code>. Every expression returns a value, and it's your choice of what to do with this value.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17964/" ]
In other words, can `fn()` know that it is being used as `$var = fn();` rather than as `fn();`? A use case would be to `echo` the return value in the latter case but to `return` it in the former. Can this be done without passing a parameter to the function to declare which way it is being used?
Many PHP functions do this by passing a boolean value called $return which returns the value if $return is true, or prints the value if $return is false. A couple of examples are [print\_r()](http://php.net/print_r) and [highlight\_file()](http://php.net/highlight_file). So your function would look like this: ``` function fn($return=false) { if ($return) { return 'blah'; } else { echo 'blah'; } } ``` Any other way will not be good programming style.
257,120
<p>I'm using TNMHTTP in Delphi to retrieve the code from a webpage. The code is relatively simple:</p> <pre><code>NMHTTP1 := TNMHTTP.Create(Self); NMHTTP1.InputFileMode := FALSE; NMHTTP1.OutputFileMode := FALSE; NMHTTP1.ReportLevel := Status_Basic; NMHTTP1.TimeOut := 3000; URL := 'http://www....'; NMHTTP1.Get(URL); S := NMHTTP1.Body; </code></pre> <p>I am catching exceptions in a try/except block, but that is not the problem.</p> <p>The problem is that on executing the NMHTTP1.Get method when the URL is a redirect, that method does not return and the program hangs. This is despite the fact that I've put a timeout of 3000 seconds in.</p> <p>So I see three possible ways of solving this (in order of easiest to hardest for me to modify my program): </p> <ol> <li><p>Do whatever is necessary to get the NMHTTP1.Get method to respond.</p></li> <li><p>Do some sort of check in advance of the NMHTTP1.Get statement to see if the URL is a redirect and get the URL it is redirecting to.</p></li> <li><p>Use another method to get a webpage using Delphi. When I wrote this, I used Delphi 4 and did not have Indy. I now have Delphi 2009, so I would be willing to use something that works in it (maybe INDY) if a simple #1 or #2 answer is not available.</p></li> </ol> <p>I would love to get an answer from someone that will work for me. Thanks in advance.</p>
[ { "answer_id": 257123, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 0, "selected": false, "text": "<p>The performance difference is negligible.</p>\n" }, { "answer_id": 257222, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": -1, "selected": false, "text": "<p>The performance is 0, because once wired up (once your application is compiled in memory), it never has to do it again. What I mean by that is, the ASP.NET framework isn't constantly itterating through every method by name to see if it should be wired up.</p>\n\n<p>But, I strongly suggest you turn it off, because it usually causes issues of double page loads or whatever (if you wire up an event yourself, but due to naming it a certain way, ASP.NET wires it up too).</p>\n\n<p>That's a feature that I wish was defaulted to off.</p>\n" }, { "answer_id": 259593, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 4, "selected": true, "text": "<p>The wireup isn't done at compile-time. It's done at runtime. As described in this article:</p>\n\n<p><a href=\"http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx\" rel=\"noreferrer\">http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx</a></p>\n\n<p>There IS a performance penalty because of the calls to CreateDelegate which must be made every time a page has been created. The performance hit is probably negligible, but it does exist.</p>\n" }, { "answer_id": 262176, "author": "Jon", "author_id": 4764, "author_profile": "https://Stackoverflow.com/users/4764", "pm_score": 3, "selected": false, "text": "<p>From MSDN article.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms973839.aspx\" rel=\"noreferrer\">Performance Tips and Tricks in .NET Applications</a></p>\n\n<p><strong>Avoid the Autoeventwireup Feature</strong></p>\n\n<p>Instead of relying on autoeventwireup, override the events from Page. For example, instead of writing a Page_Load() method, try overloading the public void OnLoad() method. This allows the run time from having to do a CreateDelegate() for every page.</p>\n\n<p>Knowledge Base article:</p>\n\n<p><a href=\"http://kbalertz.com/324151/AutoEventWireup-attribute-using-Visual.aspx\" rel=\"noreferrer\">How to use the AutoEventWireup attribute in an ASP.NET Web Form by using Visual C# .NET</a></p>\n\n<p><strong>When to avoid setting the value of the AutoEventWireup attribute to true</strong></p>\n\n<p><em>If performance is a key consideration, do not set the value of the AutoEventWireup attribute to true.</em> The AutoEventWireup attribute requires the ASP.NET page framework to make a call to the CreateDelegate function for every ASP.NET Web Form page. Instead of using automatic hookup, you must manually override the events from the page.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30176/" ]
I'm using TNMHTTP in Delphi to retrieve the code from a webpage. The code is relatively simple: ``` NMHTTP1 := TNMHTTP.Create(Self); NMHTTP1.InputFileMode := FALSE; NMHTTP1.OutputFileMode := FALSE; NMHTTP1.ReportLevel := Status_Basic; NMHTTP1.TimeOut := 3000; URL := 'http://www....'; NMHTTP1.Get(URL); S := NMHTTP1.Body; ``` I am catching exceptions in a try/except block, but that is not the problem. The problem is that on executing the NMHTTP1.Get method when the URL is a redirect, that method does not return and the program hangs. This is despite the fact that I've put a timeout of 3000 seconds in. So I see three possible ways of solving this (in order of easiest to hardest for me to modify my program): 1. Do whatever is necessary to get the NMHTTP1.Get method to respond. 2. Do some sort of check in advance of the NMHTTP1.Get statement to see if the URL is a redirect and get the URL it is redirecting to. 3. Use another method to get a webpage using Delphi. When I wrote this, I used Delphi 4 and did not have Indy. I now have Delphi 2009, so I would be willing to use something that works in it (maybe INDY) if a simple #1 or #2 answer is not available. I would love to get an answer from someone that will work for me. Thanks in advance.
The wireup isn't done at compile-time. It's done at runtime. As described in this article: <http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx> There IS a performance penalty because of the calls to CreateDelegate which must be made every time a page has been created. The performance hit is probably negligible, but it does exist.
257,152
<p>If I have two things which are hex, can I someone how append their binary together to get a value?</p> <p>In C++, say I have</p> <pre><code>unsigned char t = 0xc2; // 11000010 unsigned char q = 0xa3; // 10100011 </code></pre> <p>What I want is somehow, <code>1100001010100011</code>, is this possible using bit-wise operators?</p> <p>I want to extract the binary form of t and q and append them...</p>
[ { "answer_id": 257158, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": -1, "selected": false, "text": "<p>There is no append in binary/hex because you are dealing with Numbers (can you append 1 and 2 and not confuse the resulting 12 with the \"real\" 12?)</p>\n\n<p>You could delimit them with some special symbol, but you can't just \"concatenate\" them.</p>\n" }, { "answer_id": 257167, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 0, "selected": false, "text": "<p>Your example doesn't really work too well because the width (usually 8-bits) of the input values aren't defined. For example, why isn't your example: 0000000100000010, which would be truly appending 1 (00000001) and 2 (00000010) bit wise. </p>\n\n<p>If each value does have a fixed width <em>then</em> it can be answered with bit shifting and ORing values</p>\n\n<p>EDIT: if your \"width\" is defined the full width with all leading zero's removed, then it is possible to do with shifting and ORing, but more complicated.</p>\n" }, { "answer_id": 257172, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": -1, "selected": false, "text": "<p>Appending as an operation doesn't really make sense for numbers, regardless of what base they're in. Using . as the concatenation operator: in your example, 0x1 . 0x2 becomes 0x12 if you concat the hex, and 0b101 if you concat the binary. But 0x12 and 0b101 aren't the same value (in base 10, they're 18 and 5 respectively). In general, A O B (where A and B are numbers and O is an operator) should result in the same value no matter what base you're operating in.</p>\n" }, { "answer_id": 257199, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>Yes it's possible.</p>\n\n<p>Just use the left-bitshift operator, shifting to the left by 8, using at least a 16-bit integer. Then binary OR the 2nd value to the integer. </p>\n\n<pre><code>unsigned char t = 0xc2; // 11000010 \nunsigned char q = 0xa3; // 10100011\nunsigned short s = (((unsigned short)t)&lt;&lt;8) | q; //// 11000010 10100011\n</code></pre>\n\n<p>Alternatively putting both values in a union containing 2 chars (careful of big endian or small) would have the same bit level result. Another option is a char[2].</p>\n" }, { "answer_id": 257201, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "<p>Concatenating two chars:</p>\n\n<pre><code>unsigned char t = 0xc2; // 11000010\nunsigned char q = 0xa3; // 10100011\n\nint result = t; // Put into object that can hold the fully concatenated data;\nresult &lt;&lt;= 8; // Shift it left\nresult |= q; // Or the bottom bits into place;\n</code></pre>\n" }, { "answer_id": 257410, "author": "baash05", "author_id": 31325, "author_profile": "https://Stackoverflow.com/users/31325", "pm_score": 0, "selected": false, "text": "<p>I'd go with the char array.</p>\n\n<p>unsigned short s;\nchar * sPtr = &s;\nsPtr[0] = t; sPtr[1] = q;</p>\n\n<p>This doesn't really care about endian.. \nI'm not sure why you'd want to do this but this would work.</p>\n\n<p>The problem with the bit methods are that you're not sure what size you've got. \nIf you know the size.. I'd go with Brians answer</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
If I have two things which are hex, can I someone how append their binary together to get a value? In C++, say I have ``` unsigned char t = 0xc2; // 11000010 unsigned char q = 0xa3; // 10100011 ``` What I want is somehow, `1100001010100011`, is this possible using bit-wise operators? I want to extract the binary form of t and q and append them...
Yes it's possible. Just use the left-bitshift operator, shifting to the left by 8, using at least a 16-bit integer. Then binary OR the 2nd value to the integer. ``` unsigned char t = 0xc2; // 11000010 unsigned char q = 0xa3; // 10100011 unsigned short s = (((unsigned short)t)<<8) | q; //// 11000010 10100011 ``` Alternatively putting both values in a union containing 2 chars (careful of big endian or small) would have the same bit level result. Another option is a char[2].
257,157
<p>I am attempting to build a simple method that creates an XML file from a database in ruby on rails. I feel like my code is right but I am not seeing all of the users in the XML.<br> I am a complete newbie to RoR.</p> <p>Here's my code:</p> <pre><code>def create_file @users = User.find(:all) file = File.new('dir.xml','w') doc = Document.new make = Element.new "make" @users.each do |y| make.add_element "name" make.elements["name"].text = y.name make.add_element "description" make.elements["description"].text = y.description end doc.add_element make file.puts doc file.close end </code></pre> <p>And my XML output:</p> <pre><code>&lt;make&gt; &lt;name&gt;sammy&lt;/name&gt;&lt;description&gt;samsdescription&lt;/description&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;/make&gt; </code></pre> <p>I don't get why all the fields aren't populated. Why is just one of the database entires showing up? I really appreciate the help.</p>
[ { "answer_id": 257180, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": true, "text": "<p>There's a bug in your code. In each iteration you create an element with <a href=\"http://ruby-doc.org/stdlib/libdoc/rexml/rdoc/classes/REXML/Element.html#M003015\" rel=\"nofollow noreferrer\"><code>add_element</code></a> and then try to access that element with <a href=\"http://ruby-doc.org/stdlib/libdoc/rexml/rdoc/classes/REXML/Elements.html#M002900\" rel=\"nofollow noreferrer\"><code>Elements#[]</code></a>. But when you use a node name in <code>Elements#[]</code> it returns only the first matching node. So you are creating a node in every iteration but updating only the first one. Try to change the code to the following:</p>\n\n<pre><code>@users.each do |y|\n name_node = make.add_element \"name\"\n name_node.text = y.name\n desc_node = make.add_element \"description\"\n desc_node.text = y.description\nend\n</code></pre>\n\n<p>By the way, your XML structure is a bit strange. Wouldn't it be more clear if you wrapped every name/description pair inside another node (say, <em>user</em>) and then have many <em>user</em> nodes?</p>\n" }, { "answer_id": 257781, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>You ought to investigate <code>@users.to_xml</code> to see if it is something you could use instead of rolling your own solution. Read more about it in the <a href=\"http://api.rubyonrails.com/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000798\" rel=\"nofollow noreferrer\">Rails API docs</a>.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33344/" ]
I am attempting to build a simple method that creates an XML file from a database in ruby on rails. I feel like my code is right but I am not seeing all of the users in the XML. I am a complete newbie to RoR. Here's my code: ``` def create_file @users = User.find(:all) file = File.new('dir.xml','w') doc = Document.new make = Element.new "make" @users.each do |y| make.add_element "name" make.elements["name"].text = y.name make.add_element "description" make.elements["description"].text = y.description end doc.add_element make file.puts doc file.close end ``` And my XML output: ``` <make> <name>sammy</name><description>samsdescription</description> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> <name/><description/> </make> ``` I don't get why all the fields aren't populated. Why is just one of the database entires showing up? I really appreciate the help.
There's a bug in your code. In each iteration you create an element with [`add_element`](http://ruby-doc.org/stdlib/libdoc/rexml/rdoc/classes/REXML/Element.html#M003015) and then try to access that element with [`Elements#[]`](http://ruby-doc.org/stdlib/libdoc/rexml/rdoc/classes/REXML/Elements.html#M002900). But when you use a node name in `Elements#[]` it returns only the first matching node. So you are creating a node in every iteration but updating only the first one. Try to change the code to the following: ``` @users.each do |y| name_node = make.add_element "name" name_node.text = y.name desc_node = make.add_element "description" desc_node.text = y.description end ``` By the way, your XML structure is a bit strange. Wouldn't it be more clear if you wrapped every name/description pair inside another node (say, *user*) and then have many *user* nodes?
257,190
<p>Here is a simple scenario with table characters:</p> <pre><code>CharacterName GameTime Gold Live Foo 10 100 3 Foo 20 100 2 Foo 30 95 2 </code></pre> <p>How do I get this output for the query <code>SELECT Gold, Live FROM characters WHERE name = 'Foo' ORDER BY GameTime</code>:</p> <pre><code>Gold Live 100 3 0 -1 -5 0 </code></pre> <p>using MySQL stored procedure (or query) if it's even possible? I thought of using 2 arrays like how one would normally do in a server-side language, but MySQL doesn't have array types.</p> <p>While I'm aware it's probably easier to do in PHP (my server-side langauge), I want to know if it's possible to do in MySQL, just as a learning material.</p>
[ { "answer_id": 257213, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "<p>Do you have an ID on your Table.</p>\n\n<pre><code>GameID CharacterName GameTime Gold Live\n----------- ------------- ----------- ----------- -----------\n1 Foo 10 100 3\n2 Foo 20 100 2\n3 Foo 30 95 2\n</code></pre>\n\n<p>If so you could do a staggered join onto itself</p>\n\n<pre><code>SELECT\n c.CharacterName, \n CASE WHEN c_offset.Gold IS NOT NULL THEN c.Gold - c_offset.Gold ELSE c.Gold END AS Gold,\n CASE WHEN c_offset.Live IS NOT NULL THEN c.Live - c_offset.Live ELSE c.Live END AS Live\nFROM Characters c \n LEFT OUTER JOIN Characters c_offset\n ON c.GameID - 1 = c_offSet.GameID\nORDER BY\n c.GameTime\n</code></pre>\n\n<p>Essentially it joins each game row to the previous game row and does a diff between the values. That returns the following for me.</p>\n\n<pre><code>CharacterName Gold Live\n------------- ----------- -----------\nFoo 100 3\nFoo 0 -1\nFoo -5 0\n</code></pre>\n" }, { "answer_id": 257217, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": true, "text": "<p>One possible solution using a temporary table:</p>\n\n<pre><code>CREATE TABLE characters_by_gametime (\n id INTEGER AUTO_INCREMENT PRIMARY KEY,\n gold INTEGER,\n live INTEGER);\n\nINSERT INTO characters_by_gametime (gold, live)\nSELECT gold, live\nFROM characters\nORDER BY game_time;\n\nSELECT\n c1.id,\n c1.gold - IFNULL(c2.gold, 0) AS gold,\n c1.live - IFNULL(c2.live, 0) AS live\nFROM\n characters_by_gametime c1\n LEFT JOIN characters_by_gametime c2\n ON c1.id = c2.id + 1\nORDER BY\n c1.id;\n</code></pre>\n\n<p>Of course Eoin's solution is better if your <em>id</em> column follows the order you want in the output.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
Here is a simple scenario with table characters: ``` CharacterName GameTime Gold Live Foo 10 100 3 Foo 20 100 2 Foo 30 95 2 ``` How do I get this output for the query `SELECT Gold, Live FROM characters WHERE name = 'Foo' ORDER BY GameTime`: ``` Gold Live 100 3 0 -1 -5 0 ``` using MySQL stored procedure (or query) if it's even possible? I thought of using 2 arrays like how one would normally do in a server-side language, but MySQL doesn't have array types. While I'm aware it's probably easier to do in PHP (my server-side langauge), I want to know if it's possible to do in MySQL, just as a learning material.
One possible solution using a temporary table: ``` CREATE TABLE characters_by_gametime ( id INTEGER AUTO_INCREMENT PRIMARY KEY, gold INTEGER, live INTEGER); INSERT INTO characters_by_gametime (gold, live) SELECT gold, live FROM characters ORDER BY game_time; SELECT c1.id, c1.gold - IFNULL(c2.gold, 0) AS gold, c1.live - IFNULL(c2.live, 0) AS live FROM characters_by_gametime c1 LEFT JOIN characters_by_gametime c2 ON c1.id = c2.id + 1 ORDER BY c1.id; ``` Of course Eoin's solution is better if your *id* column follows the order you want in the output.
257,220
<h2>solution structure [Plain Winforms + VS 2008 Express Edition]</h2> <ul> <li>CoffeeMakerInterface (NS CoffeeMaker)</li> <li>CoffeeMakerSoftware (NS CoffeeMakerSoftware)</li> <li>TestCoffeeMaker (NS TestCoffeeMaker)</li> </ul> <p>CoffeeMakerSoftware proj references CoffeeMakerInterface. TestCoffeeMaker proj references CoffeeMakerInterface and CoffeeMakerSoftware.</p> <p>Now the thing that is driving me nuts. I can't get this to build. <strong>If I remove CoffeeMakerSoftware project reference from TestCoffeeMaker it builds (??!!).. as soon as I add the second project reference, it throws build errors</strong> claiming that types declared in first reference 'can't be found.. are you missing an assembly ref'</p> <p>At first I had the first 2 assemblies having the same namespace CoffeeMaker.. I then made them distinct (although I think having classes belonging to the same NS across assemblies should be possible) but even that doesn't seem to be it.</p> <p>Calling more eyeballs. Any pointers.. </p>
[ { "answer_id": 257336, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 0, "selected": false, "text": "<p>A few things to check:</p>\n\n<ul>\n<li>Ensure \"copy local\" is TRUE for all project references</li>\n<li>If any are set to false, check the GAC for old builds of your libraries</li>\n</ul>\n\n<p>If all this fails, remove all projects from the solution, create a new solution and add the projects back. Yeah, it's voodoo, but this has got me past silly mistakes before. ;-)</p>\n" }, { "answer_id": 258076, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "<p>I broke my 'Don't code when you're tired' dictum. I zipped it up, went to sleep and looked at it today.. found the issue by looking at the output window. <em>(FWIW everything was CopyLocal=True and nothing in GAC. This is Bob Martin's OOD problem from the Agile PPnP book.. coming up with good names was particularly hard)</em></p>\n\n<pre><code>1. CoffeeMaker &gt; CoffeeMakerInterfaces\n2. [X] &gt; CoffeeMaker &gt; CoffeeMakerSoftware\n3. [X] &gt; TestCoffeeMaker\n</code></pre>\n\n<p>That's how I added and renamed the projects in chronological order. Apparently renaming the Assembly via solution explorer, doesn't change the name of the produced binary or throw up a warning. As a result, #1 and #2 both were producing CoffeeMaker.dll as the output. \nAdding Reference#2 to the TestCoffeeMaker rendered all the types defined in reference#1 as unknown with the ever popular </p>\n\n<blockquote>\n <p>\"Error 2 The type or namespace name\n 'CoffeeMaker' could not be found (are\n you missing a using directive or an\n assembly reference?) C:\\Documents and\n Settings\\pillaigi\\Desktop\\CoffeeMaker\\TestCoffeeMaker\\FakeCoffeeMakerDevice.cs 4 7 TestCoffeeMaker\"</p>\n</blockquote>\n\n<p><strong>Solution: Open Project properties and examine if the \"Assembly name:\" in project properties for each (ref or otherwise) project is unique and doesn't clash.</strong></p>\n\n<p>Maybe not enough people do this.. the IDE or compiler could easily catch this one 'If referenced assemblies have the same binary name... please fix it.. you will anyway'\nI've done this to myself once before.. Making a BIG note to myself this time. Now excuse me while I wear my Dunce cap and sit in the corner. </p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
solution structure [Plain Winforms + VS 2008 Express Edition] ------------------------------------------------------------- * CoffeeMakerInterface (NS CoffeeMaker) * CoffeeMakerSoftware (NS CoffeeMakerSoftware) * TestCoffeeMaker (NS TestCoffeeMaker) CoffeeMakerSoftware proj references CoffeeMakerInterface. TestCoffeeMaker proj references CoffeeMakerInterface and CoffeeMakerSoftware. Now the thing that is driving me nuts. I can't get this to build. **If I remove CoffeeMakerSoftware project reference from TestCoffeeMaker it builds (??!!).. as soon as I add the second project reference, it throws build errors** claiming that types declared in first reference 'can't be found.. are you missing an assembly ref' At first I had the first 2 assemblies having the same namespace CoffeeMaker.. I then made them distinct (although I think having classes belonging to the same NS across assemblies should be possible) but even that doesn't seem to be it. Calling more eyeballs. Any pointers..
I broke my 'Don't code when you're tired' dictum. I zipped it up, went to sleep and looked at it today.. found the issue by looking at the output window. *(FWIW everything was CopyLocal=True and nothing in GAC. This is Bob Martin's OOD problem from the Agile PPnP book.. coming up with good names was particularly hard)* ``` 1. CoffeeMaker > CoffeeMakerInterfaces 2. [X] > CoffeeMaker > CoffeeMakerSoftware 3. [X] > TestCoffeeMaker ``` That's how I added and renamed the projects in chronological order. Apparently renaming the Assembly via solution explorer, doesn't change the name of the produced binary or throw up a warning. As a result, #1 and #2 both were producing CoffeeMaker.dll as the output. Adding Reference#2 to the TestCoffeeMaker rendered all the types defined in reference#1 as unknown with the ever popular > > "Error 2 The type or namespace name > 'CoffeeMaker' could not be found (are > you missing a using directive or an > assembly reference?) C:\Documents and > Settings\pillaigi\Desktop\CoffeeMaker\TestCoffeeMaker\FakeCoffeeMakerDevice.cs 4 7 TestCoffeeMaker" > > > **Solution: Open Project properties and examine if the "Assembly name:" in project properties for each (ref or otherwise) project is unique and doesn't clash.** Maybe not enough people do this.. the IDE or compiler could easily catch this one 'If referenced assemblies have the same binary name... please fix it.. you will anyway' I've done this to myself once before.. Making a BIG note to myself this time. Now excuse me while I wear my Dunce cap and sit in the corner.
257,229
<p>I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel.</p> <p>For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356". The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).</p>
[ { "answer_id": 257247, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": true, "text": "<p>You can use the Range object in VBA to set the value of a named cell, just like any other cell.</p>\n\n<pre><code>Range(\"C1\").Value = Inputbox(\"Which job number would you like to add to the list?)\n</code></pre>\n\n<p>Where \"C1\" is the name of the cell you want to update.</p>\n\n<p>My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.</p>\n" }, { "answer_id": 257253, "author": "rbrayb", "author_id": 9922, "author_profile": "https://Stackoverflow.com/users/9922", "pm_score": 0, "selected": false, "text": "<p>I've done this kind of thing with a form that contains a TextBox.</p>\n\n<p>So if you wanted to put this in say cell <code>H1</code>, then use:</p>\n\n<p><code>ActiveSheet.Range(\"H1\").Value = txtBoxName.Text</code></p>\n" }, { "answer_id": 257706, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 2, "selected": false, "text": "<p>I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg \"H1\" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell. </p>\n\n<p>So</p>\n\n<pre><code>Range(\"RefNo\") = InputBox(\"....\") \n</code></pre>\n\n<p>is safer than</p>\n\n<pre><code>Range(\"H1\") = InputBox(\"....\") \n</code></pre>\n\n<p>You can set the value of several cells, too.</p>\n\n<pre><code>Range(\"Results\").Resize(10,3) = arrResults()\n</code></pre>\n\n<p>where arrResults is an array of at least 10 rows &amp; 3 columns (and can be any type). If you use this, put this </p>\n\n<pre><code>Option Base 1\n</code></pre>\n\n<p>at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).</p>\n" }, { "answer_id": 35447038, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>When asking a user for a response to put into a cell using the <a href=\"https://msdn.microsoft.com/en-us/library/office/aa195768%28v=office.11%29.aspx\" rel=\"nofollow\">InputBox method</a>, there are usually three things that can happen¹.</p>\n\n<ol>\n<li>The user types something in and clicks <kbd>OK</kbd>. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.</li>\n<li>The user clicks <kbd>Cancel</kbd>, presses <kbd>Esc</kbd> or clicks <kbd><strong>×</strong></kbd> (Close). The return value is a boolean <strong>False</strong>. This should be accounted for.</li>\n<li>The user does <strong>not</strong> type anything in but clicks <kbd>OK</kbd> regardless. The return value is a zero-length string.</li>\n</ol>\n\n<p>If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a <a href=\"https://msdn.microsoft.com/en-us/library/office/gg278665.aspx\" rel=\"nofollow\">Select Case statement</a>.</p>\n\n<pre><code> Dim returnVal As Variant\n\n returnVal = InputBox(Prompt:=\"Type a value:\", Title:=\"Test Data\")\n\n 'if the user clicked Cancel, Close or Esc the False\n 'is translated to the variant as a vbNullString\n Select Case True\n Case Len(returnVal) = 0\n 'no value but user clicked OK - clear the target cell\n Range(\"A2\").ClearContents\n Case Else\n 'returned a value with OK, save it\n Range(\"A2\") = returnVal\n End Select\n</code></pre>\n\n<hr>\n\n<p>¹ <sub>There is a fourth scenario when a specific type of <strong><a href=\"https://msdn.microsoft.com/en-us/library/office/aa195768%28v=office.11%29.aspx\" rel=\"nofollow\">InputBox method</a></strong> is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.</sub></p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22284/" ]
I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel. For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356". The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).
You can use the Range object in VBA to set the value of a named cell, just like any other cell. ``` Range("C1").Value = Inputbox("Which job number would you like to add to the list?) ``` Where "C1" is the name of the cell you want to update. My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.
257,250
<p>I'm relatively new to jQuery, but so far what I've seen I like. What I want is for a div (or any element) to be across the top of the page as if "position: fixed" worked in every browser.</p> <p>I do not want something complicated. I do not want giant CSS hacks. I would prefer if just using jQuery (version 1.2.6) is good enough, but if I need jQuery-UI-core, then that's fine too.</p> <p>I've tried $("#topBar").scrollFollow(); &lt;-- but that goes slow... I want something to appear really fixed.</p>
[ { "answer_id": 257972, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 7, "selected": true, "text": "<p>Using this HTML:</p>\n\n<pre><code>&lt;div id=\"myElement\" style=\"position: absolute\"&gt;This stays at the top&lt;/div&gt;\n</code></pre>\n\n<p>This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.</p>\n\n<pre><code>$(window).scroll(function() {\n $('#myElement').css('top', $(this).scrollTop() + \"px\");\n});\n</code></pre>\n\n<hr>\n\n<p>As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's <a href=\"http://benalman.com/projects/jquery-throttle-debounce-plugin/\" rel=\"noreferrer\">debounce/throttle</a> plugin to reduce overhead.</p>\n" }, { "answer_id": 258331, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": false, "text": "<p>Beautiful! Your solution was 99%... instead of \"this.scrollY\", I used \"$(window).scrollTop()\". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).</p>\n\n<p>The reason I wanted that version in particular is because that's what ships with MVC currently.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"#topBar\").css(\"position\", \"absolute\");\n});\n\n$(window).scroll(function() {\n $(\"#topBar\").css(\"top\", $(window).scrollTop() + \"px\");\n});\n</code></pre>\n" }, { "answer_id": 1284248, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In a project, my client would like a floating box in another div, so I use margin-top CSS property rather than top in order to my floating box stay in its parent.</p>\n" }, { "answer_id": 2560377, "author": "Schmoove", "author_id": 306871, "author_profile": "https://Stackoverflow.com/users/306871", "pm_score": 3, "selected": false, "text": "<p>For those browsers that do support \"position: fixed\" you can simply use javascript (jQuery) to change the position to \"fixed\" when scrolling. This eliminates the jumpiness when scrolling with the $(window).scroll(function()) solutions listed here.</p>\n\n<p>Ben Nadel demonstrates this in his tutorial:\n<a href=\"http://www.bennadel.com/blog/1810-Creating-A-Sometimes-Fixed-Position-Element-With-jQuery.htm\" rel=\"noreferrer\">Creating A Sometimes-Fixed-Position Element With jQuery</a></p>\n" }, { "answer_id": 3756951, "author": "tbranyen", "author_id": 282175, "author_profile": "https://Stackoverflow.com/users/282175", "pm_score": 1, "selected": false, "text": "<p>For anyone still looking for an easy solution in IE 6. I created a plugin that handles the IE 6 position: fixed problem and is very easy to use: <a href=\"http://www.fixedie.com/\" rel=\"nofollow noreferrer\">http://www.fixedie.com/</a></p>\n\n<p>I wrote it in an attempt to mimic the simplicity of belatedpng, where the only changes necessary are adding the script and invoking it.</p>\n" }, { "answer_id": 11620903, "author": "Mac Attack", "author_id": 406914, "author_profile": "https://Stackoverflow.com/users/406914", "pm_score": 2, "selected": false, "text": "<p><strong>HTML/CSS Approach</strong></p>\n\n<p>If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <code>&lt;div&gt;</code> and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:</p>\n\n<p><a href=\"http://jsfiddle.net/rncVe/5/\" rel=\"nofollow\" title=\"JS Fiddle\">JS Fiddle</a></p>\n\n<p>HTML</p>\n\n<pre><code>&lt;div id=\"wrapper\"&gt;\n &lt;div id=\"fixed\"&gt;\n [Fixed Content]\n &lt;/div&gt;&lt;!-- /fixed --&gt;\n &lt;div id=\"scroller\"&gt;\n [Scrolling Content]\n &lt;/div&gt;&lt;!-- /scroller --&gt;\n&lt;/div&gt;&lt;!-- /wrapper --&gt;\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>#wrapper { position: relative; }\n#fixed { position: fixed; top: 0; right: 0; }\n#scroller { height: 100px; overflow: auto; }\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>//Compensate for the scrollbar (otherwise #fixed will be positioned over it).\n$(function() {\n //Determine the difference in widths between\n //the wrapper and the scroller. This value is\n //the width of the scroll bar (if any).\n var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;\n\n //Set the right offset\n $('#fixed').css('right', offset + 'px');​\n});\n</code></pre>\n\n<p>Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11917/" ]
I'm relatively new to jQuery, but so far what I've seen I like. What I want is for a div (or any element) to be across the top of the page as if "position: fixed" worked in every browser. I do not want something complicated. I do not want giant CSS hacks. I would prefer if just using jQuery (version 1.2.6) is good enough, but if I need jQuery-UI-core, then that's fine too. I've tried $("#topBar").scrollFollow(); <-- but that goes slow... I want something to appear really fixed.
Using this HTML: ``` <div id="myElement" style="position: absolute">This stays at the top</div> ``` This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled. ``` $(window).scroll(function() { $('#myElement').css('top', $(this).scrollTop() + "px"); }); ``` --- As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's [debounce/throttle](http://benalman.com/projects/jquery-throttle-debounce-plugin/) plugin to reduce overhead.
257,251
<p>I swear I've seen someone do this, but I can't find it in the various lists of shortcuts.</p> <p>Given:</p> <pre><code>String s = "A very long ............................ String"; </code></pre> <p>Is there an Eclipse shortcut to turn it into:</p> <pre><code>String s = "A very long ............................ " + "String"; </code></pre>
[ { "answer_id": 257252, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Yup - just hit return when your cursor is in the middle of the string.</p>\n\n<p>Admittedly that puts the + at the end of the first line instead of the start of the second, which is irritating if your style guide demands the latter, but if you're not fussy it's great :)</p>\n" }, { "answer_id": 257278, "author": "Fylke", "author_id": 30059, "author_profile": "https://Stackoverflow.com/users/30059", "pm_score": 1, "selected": false, "text": "<p>All the formatting templates in Eclipse will put the plus on the next row (which <em>I</em> find really annoying), so you can simply apply the code formatter and the plus will end up on the next row.</p>\n" }, { "answer_id": 257652, "author": "John Stoneham", "author_id": 2040146, "author_profile": "https://Stackoverflow.com/users/2040146", "pm_score": 0, "selected": false, "text": "<p>There may be a Quick Fix (<kbd>Ctrl</kbd> + <kbd>1</kbd>) for this as well.</p>\n\n<p>I was amazed in 3.4 to discover that there are Quick Fixes to transform +-based string concats into uses of <code>StringBuilder</code> or <code>MessageFormat</code>. Brilliant!</p>\n" }, { "answer_id": 26861386, "author": "Tomáš Záluský", "author_id": 653539, "author_profile": "https://Stackoverflow.com/users/653539", "pm_score": 0, "selected": false, "text": "<p>Also you can format code using regular expression. Select expression, press Ctrl+F and use:</p>\n\n<p>Find: <code>\"\\s*?\\+\\s*?\\R(\\s*?)\"</code></p>\n\n<p>Replace with: <code>\"\\R$1\\+ \"</code></p>\n\n<p>&#9745; Regular expressions </p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
I swear I've seen someone do this, but I can't find it in the various lists of shortcuts. Given: ``` String s = "A very long ............................ String"; ``` Is there an Eclipse shortcut to turn it into: ``` String s = "A very long ............................ " + "String"; ```
Yup - just hit return when your cursor is in the middle of the string. Admittedly that puts the + at the end of the first line instead of the start of the second, which is irritating if your style guide demands the latter, but if you're not fussy it's great :)
257,255
<p>I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.</p> <p>for example, if i have this form:</p> <pre><code>&lt;form id="someform"&gt; &lt;select name="option1"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;select name="option2"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>I'd like to be able to take a param string like this: <code>option1=2&amp;option2=1</code></p> <p>And then have the correct things selected based on the options in the query string.</p> <p>I have a sort of ugly solution where I go through children of the form and check if they match the various keys, then set the values, but I really don't like it.</p> <p>I'd like a cleaner, <strong>generic</strong> way of doing it that would work for any form (assuming the param string had all the right keys).</p> <p>I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it.</p> <p>EDIT: this is what I've come up with so far (using prototype for <code>Form.getElements(form)</code>)</p> <pre><code>function setFormOptions(formId, params) { params = params.split('&amp;'); params.each(function(pair) { pair = pair.split('='); var key = pair[0]; var val = pair[1]; Form.getElements(form).each(function(element) { if(element.name == key) { element.value = val; } }); }); } </code></pre> <p>I feel that it could still be faster/cleaner however.</p>
[ { "answer_id": 257287, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "<p>You said you're already going through the elements and setting the values. However, maybe this is cleaner that what you have?</p>\n\n<pre><code>function setFormSelectValues(form, dataset) {\n var sel = form.getElementsByTagName(\"select\");\n dataset.replace(/([^=&amp;]+)=([^&amp;]*)/g, function(match, name, value){\n for (var i = 0; i &lt; sel.length; ++i) {\n if (sel[i].name == name) {\n sel[i].value = value;\n }\n }\n }); \n}\n</code></pre>\n\n<p>You could then adapt that to more than just select elements if needed.</p>\n" }, { "answer_id": 257322, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>Event.observe(window, 'load', function() {\n var loc = window.location.search.substr(1).split('&amp;');\n\n loc.each(function(param) {\n param = param.split('=');\n key = param[0];\n val = param[1];\n\n $(key).value = val;\n });\n});\n</code></pre>\n\n<p>The above code assumes that you assign id values as well as names to each form element. It takes parameters in the form:</p>\n\n<pre>?key=value&key=value</pre>\n\n<p>or</p>\n\n<pre>?option1=1&option2=2</pre> \n\n<hr>\n\n<p>If you want to keep it at just names for the elements, then try instead of the above:</p>\n\n<pre><code>Event.observe(window, 'load', function() {\n var loc = window.location.search.substr(1).split('&amp;');\n\n loc.each(function(param) {\n param = param.split('=');\n key = param[0].split('_');\n\n type = key[0];\n key = key[1];\n val = param[1];\n\n $$(type + '[name=\"' + key + '\"]').each(function(ele) {\n ele.value = val;\n });\n});\n</code></pre>\n\n<p>This code takes parameters in the form of:</p>\n\n<pre>?type_key=value&type_key=value</pre>\n\n<p>or</p>\n\n<pre>?select_option1=1&select_option2=2</pre>\n" }, { "answer_id": 257401, "author": "adgoudz", "author_id": 30527, "author_profile": "https://Stackoverflow.com/users/30527", "pm_score": 4, "selected": true, "text": "<p>If you're using Prototype, this is easy. First, you can use the <a href=\"http://prototypejs.org/api/string/toQueryParams\" rel=\"nofollow noreferrer\">toQueryParams</a> method on the String object to get a Javascript object with name/value pairs for each parameter.</p>\n\n<p>Second, you can use the Form.Elements.setValue method (doesn't seem to be documented) to translate each query string value to an actual form input state (e.g. check a checkbox when the query string value is \"on\"). Using the name.value=value technique only works for text and select (one, not many) inputs. Using the Prototype method adds support for checkbox and select (multiple) inputs.</p>\n\n<p>As for a simple function to populate what you have, this works well and it isn't complicated.</p>\n\n<pre><code>function populateForm(queryString) {\n var params = queryString.toQueryParams();\n Object.keys(params).each(function(key) {\n Form.Element.setValue($(\"someform\")[key], params[key]);\n });\n}\n</code></pre>\n\n<p>This uses the <a href=\"http://prototypejs.org/api/object/keys\" rel=\"nofollow noreferrer\">Object.keys</a> and the <a href=\"http://prototypejs.org/api/array/each\" rel=\"nofollow noreferrer\">each</a> methods to iterate over each query string parameter and set the matching form input (using the input name attribute) to the matching value in the query params object.</p>\n\n<p><strong>Edit:</strong> Note that you do not need to have id attributes on your form elements for this solution to work.</p>\n" }, { "answer_id": 283923, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 0, "selected": false, "text": "<p>Three lines of code in <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">prototype.js</a>:</p>\n\n<pre><code>$H(query.toQueryParams()).each(function(pair) {\n $(\"form\")[pair.key].setValue(pair.value);\n});\n</code></pre>\n" }, { "answer_id": 3815859, "author": "Anoop", "author_id": 460942, "author_profile": "https://Stackoverflow.com/users/460942", "pm_score": 0, "selected": false, "text": "<p>You can get form data in JavaScript object using <a href=\"http://javascriptmanagement.blogspot.com/2011/06/form-management.html\" rel=\"nofollow\" > formManager </a> .</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12983/" ]
I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript. for example, if i have this form: ``` <form id="someform"> <select name="option1"> <option value="1">1</option> <option value="2">2</option> </select> <select name="option2"> <option value="1">1</option> <option value="2">2</option> </select> </form> ``` I'd like to be able to take a param string like this: `option1=2&option2=1` And then have the correct things selected based on the options in the query string. I have a sort of ugly solution where I go through children of the form and check if they match the various keys, then set the values, but I really don't like it. I'd like a cleaner, **generic** way of doing it that would work for any form (assuming the param string had all the right keys). I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it. EDIT: this is what I've come up with so far (using prototype for `Form.getElements(form)`) ``` function setFormOptions(formId, params) { params = params.split('&'); params.each(function(pair) { pair = pair.split('='); var key = pair[0]; var val = pair[1]; Form.getElements(form).each(function(element) { if(element.name == key) { element.value = val; } }); }); } ``` I feel that it could still be faster/cleaner however.
If you're using Prototype, this is easy. First, you can use the [toQueryParams](http://prototypejs.org/api/string/toQueryParams) method on the String object to get a Javascript object with name/value pairs for each parameter. Second, you can use the Form.Elements.setValue method (doesn't seem to be documented) to translate each query string value to an actual form input state (e.g. check a checkbox when the query string value is "on"). Using the name.value=value technique only works for text and select (one, not many) inputs. Using the Prototype method adds support for checkbox and select (multiple) inputs. As for a simple function to populate what you have, this works well and it isn't complicated. ``` function populateForm(queryString) { var params = queryString.toQueryParams(); Object.keys(params).each(function(key) { Form.Element.setValue($("someform")[key], params[key]); }); } ``` This uses the [Object.keys](http://prototypejs.org/api/object/keys) and the [each](http://prototypejs.org/api/array/each) methods to iterate over each query string parameter and set the matching form input (using the input name attribute) to the matching value in the query params object. **Edit:** Note that you do not need to have id attributes on your form elements for this solution to work.
257,259
<pre><code>void addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -&gt; data = n; temp -&gt; link = head; head = temp; } </code></pre> <p>The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list. Generally the correct versions are like,</p> <pre><code>void addNewNode (struct node **head, int n); void addNewNode (struct node * &amp;head, int n); </code></pre> <p>I worked out another but simple function for the purpose which worked fine.</p> <pre><code>struct node* addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -&gt; data = n; temp -&gt; link = head; return temp; } </code></pre> <p>But I haven't seen this being used or discussed in code and tutorials and thus I am curious to know if this approach has some flaw.</p>
[ { "answer_id": 257264, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "<p>The flaw is that you're relying on the caller to perform the last step of updating the head pointer to the list.</p>\n\n<p>If the caller neglects to do this, the compiler will not complain, and for all intents and purposes the list will appear to not have changed (and you'll have leaked the memory for a node).</p>\n" }, { "answer_id": 257266, "author": "sergtk", "author_id": 13441, "author_profile": "https://Stackoverflow.com/users/13441", "pm_score": 0, "selected": false, "text": "<p>I see no problems in any of the mentioned correct code. \nTo change or not to change the head is a matter of design - and how to return modified list. \nGood interface is implemented in std::list&lt;> as an example where OOP is used, such approach is free of potential problems. head pointer is hidden and you can modify it as you want, and since caller do not store head explicitly, its reference to the list is always correct.</p>\n\n<p>one things which looks ugly (when you use C++, not C) is a malloc, better to use 'new'.</p>\n" }, { "answer_id": 257267, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "<p>Your approach is incompatible with the idea that <code>addNode</code> is a method on the list, more commonly used in OO languages.</p>\n\n<p>Personally I think</p>\n\n<pre><code>list.add(element)\n</code></pre>\n\n<p>is a huge lot more intuitive than</p>\n\n<pre><code>list = add(list, element)\n</code></pre>\n\n<p>Dozens of \"collections\" libraries can't be wrong...</p>\n" }, { "answer_id": 257268, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>This is how linked lists work in most functional languages. For example, in ML you might do something like this:</p>\n\n<pre><code>val ls = [1, 2, 3, 4]\nval newList = 0 :: ls\n</code></pre>\n\n<p>The <code>::</code> syntax is actually a function which takes two parameters (<code>0</code> and <code>ls</code>) and returns a new list which has <code>0</code> as the first element. Lists in ML are actually defined as list nodes, so <code>::</code> is actually written very similarly to the <code>addNewNode</code> function you proposed.</p>\n\n<p>In other words: congratulations, you have created an immutable linked list implementation in C! Understanding this is actually a fairly important first step to functional languages, so it's really a good thing to know.</p>\n" }, { "answer_id": 259076, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 1, "selected": false, "text": "<p>Afaik, that's the way how the lists in glib work and I'm sure the gtk folks weren't the first that use that way, so I wouldn't call it a new approach. I personally prefer to have a base structure, that holds the node count, first- and last-pointer.</p>\n" }, { "answer_id": 259115, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "<p>This is not new. As pointed out by quinmars, glib has done it like this for over 10 years. It's a great idea, so congratulations for figuring it out.</p>\n\n<p>One nitpick about your code, though: don't cast the return value of <code>malloc()</code> in C, and don't repeat the type name in the use of <code>sizeof</code>. Your allocation line should read like this:</p>\n\n<pre><code>struct node* temp = malloc(sizeof *temp);\n</code></pre>\n\n<p>See? Shorter, tighter, easier to read, harder to mess up. Better! :)</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
``` void addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -> data = n; temp -> link = head; head = temp; } ``` The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list. Generally the correct versions are like, ``` void addNewNode (struct node **head, int n); void addNewNode (struct node * &head, int n); ``` I worked out another but simple function for the purpose which worked fine. ``` struct node* addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -> data = n; temp -> link = head; return temp; } ``` But I haven't seen this being used or discussed in code and tutorials and thus I am curious to know if this approach has some flaw.
The flaw is that you're relying on the caller to perform the last step of updating the head pointer to the list. If the caller neglects to do this, the compiler will not complain, and for all intents and purposes the list will appear to not have changed (and you'll have leaked the memory for a node).
257,286
<p>in C++ I have two chars holding hex values e.g.:</p> <pre><code>char t = 0x4; char q = 0x4; </code></pre> <p>How would i compare if the two values held in the char are the same?? I tried</p> <pre><code>if (t == q) // should give me true </code></pre> <p>but no, any help, thanks!</p>
[ { "answer_id": 257291, "author": "BobS", "author_id": 33481, "author_profile": "https://Stackoverflow.com/users/33481", "pm_score": -1, "selected": false, "text": "<p>Ah, I found the solution:</p>\n\n<pre><code>if (t &amp; q)\n</code></pre>\n" }, { "answer_id": 257304, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>A char is just an 8-bit integer. It doesn't matter if you initialized it with hex or decimal literal, in either case the value of the char will be the same afterwards. </p>\n\n<p>So: </p>\n\n<pre><code>char t = 0x4;\nchar q = 0x4;\nif(t == q)\n{\n //They are the same\n}\n</code></pre>\n\n<p>It is equivalent to:</p>\n\n<pre><code>char t = 4;\nchar q = 4;\nif(t == q)\n{\n //They are the same\n}\n</code></pre>\n\n<p>You mentioned that the above is not true, but you must have an error in your code or t and q must not be the same. </p>\n\n<p><strong>What you suggested...</strong></p>\n\n<blockquote>\n <p>if (t == q) // should give me true\n but no, any help, thanks!</p>\n</blockquote>\n\n<p><strong>is not correct. Why?</strong></p>\n\n<p>t &amp; q does a bitwise compare, returning a value where both aligned bits are 1. </p>\n\n<p>The term \"if(t&amp;q)\" would return true as long as any of the bits of t and q are in common. </p>\n\n<p>so if t = 3 which is in binary 00000011 and q = 1 which is in binary 00000001 then (t&amp;q) would return true even know they are not equal. </p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
in C++ I have two chars holding hex values e.g.: ``` char t = 0x4; char q = 0x4; ``` How would i compare if the two values held in the char are the same?? I tried ``` if (t == q) // should give me true ``` but no, any help, thanks!
A char is just an 8-bit integer. It doesn't matter if you initialized it with hex or decimal literal, in either case the value of the char will be the same afterwards. So: ``` char t = 0x4; char q = 0x4; if(t == q) { //They are the same } ``` It is equivalent to: ``` char t = 4; char q = 4; if(t == q) { //They are the same } ``` You mentioned that the above is not true, but you must have an error in your code or t and q must not be the same. **What you suggested...** > > if (t == q) // should give me true > but no, any help, thanks! > > > **is not correct. Why?** t & q does a bitwise compare, returning a value where both aligned bits are 1. The term "if(t&q)" would return true as long as any of the bits of t and q are in common. so if t = 3 which is in binary 00000011 and q = 1 which is in binary 00000001 then (t&q) would return true even know they are not equal.
257,288
<p>Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?</p> <p>Here's a simple example of what I would want to write:</p> <pre><code>template&lt;class T&gt; std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T-&gt;toString)) return obj-&gt;toString(); else return "toString not defined"; } </code></pre> <p>So, if <code>class T</code> has <code>toString()</code> defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.</p>
[ { "answer_id": 257315, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>This is what type traits are there for. Unfortunately, they have to be defined manually. In your case, imagine the following:</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct response_trait {\n static bool const has_tostring = false;\n};\n\ntemplate &lt;&gt;\nstruct response_trait&lt;your_type_with_tostring&gt; {\n static bool const has_tostring = true;\n}\n</code></pre>\n" }, { "answer_id": 257382, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 10, "selected": true, "text": "<p>Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:</p>\n<pre><code>#include &lt;iostream&gt;\n\nstruct Hello\n{\n int helloworld() { return 0; }\n};\n\nstruct Generic {}; \n\n// SFINAE test\ntemplate &lt;typename T&gt;\nclass has_helloworld\n{\n typedef char one;\n struct two { char x[2]; };\n\n template &lt;typename C&gt; static one test( decltype(&amp;C::helloworld) ) ;\n template &lt;typename C&gt; static two test(...); \n\npublic:\n enum { value = sizeof(test&lt;T&gt;(0)) == sizeof(char) };\n};\n \nint main(int argc, char *argv[])\n{\n std::cout &lt;&lt; has_helloworld&lt;Hello&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; has_helloworld&lt;Generic&gt;::value &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n<p>I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.</p>\n" }, { "answer_id": 261262, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>Now this was a <em>nice</em> little puzzle - great question!</p>\n\n<p>Here's an alternative to <a href=\"https://stackoverflow.com/questions/257288/possible-for-c-template-to-check-for-a-functions-existence#257382\">Nicola Bonelli's solution</a> that does not rely on the non-standard <code>typeof</code> operator.</p>\n\n<p>Unfortunately, it does not work on GCC (MinGW) 3.4.5 or Digital Mars 8.42n, but it does work on all versions of MSVC (including VC6) and on Comeau C++.</p>\n\n<p>The longer comment block has the details on how it works (or is supposed to work). As it says, I'm not sure which behavior is standards compliant - I'd welcome commentary on that.</p>\n\n<hr>\n\n<p>update - 7 Nov 2008:</p>\n\n<p>It looks like while this code is syntactically correct, the behavior that MSVC and Comeau C++ show does not follow the standard (thanks to <a href=\"https://stackoverflow.com/users/4727/leon-timmermans\">Leon Timmermans</a> and <a href=\"https://stackoverflow.com/users/34509/litb\">litb</a> for pointing me in the right direction). The C++03 standard says the following:</p>\n\n<blockquote>\n <p>14.6.2 Dependent names [temp.dep]</p>\n \n <p>Paragraph 3</p>\n \n <p>In the definition of a class template\n or a member of a class template, if a\n base class of the class template\n depends on a template-parameter, the\n base class scope is not examined\n during unqualified name lookup either\n at the point of definition of the\n class template or member or during an\n instantiation of the class template or\n member.</p>\n</blockquote>\n\n<p>So, it looks like that when MSVC or Comeau consider the <code>toString()</code> member function of <code>T</code> performing name lookup at the call site in <code>doToString()</code> when the template is instantiated, that is incorrect (even though it's actually the behavior I was looking for in this case).</p>\n\n<p>The behavior of GCC and Digital Mars looks to be correct - in both cases the non-member <code>toString()</code> function is bound to the call.</p>\n\n<p>Rats - I thought I might have found a clever solution, instead I uncovered a couple compiler bugs...</p>\n\n<hr>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nstruct Hello\n{\n std::string toString() {\n return \"Hello\";\n }\n};\n\nstruct Generic {};\n\n\n// the following namespace keeps the toString() method out of\n// most everything - except the other stuff in this\n// compilation unit\n\nnamespace {\n std::string toString()\n {\n return \"toString not defined\";\n }\n\n template &lt;typename T&gt;\n class optionalToStringImpl : public T\n {\n public:\n std::string doToString() {\n\n // in theory, the name lookup for this call to \n // toString() should find the toString() in \n // the base class T if one exists, but if one \n // doesn't exist in the base class, it'll \n // find the free toString() function in \n // the private namespace.\n //\n // This theory works for MSVC (all versions\n // from VC6 to VC9) and Comeau C++, but\n // does not work with MinGW 3.4.5 or \n // Digital Mars 8.42n\n //\n // I'm honestly not sure what the standard says \n // is the correct behavior here - it's sort \n // of like ADL (Argument Dependent Lookup - \n // also known as Koenig Lookup) but without\n // arguments (except the implied \"this\" pointer)\n\n return toString();\n }\n };\n}\n\ntemplate &lt;typename T&gt;\nstd::string optionalToString(T &amp; obj)\n{\n // ugly, hacky cast...\n optionalToStringImpl&lt;T&gt;* temp = reinterpret_cast&lt;optionalToStringImpl&lt;T&gt;*&gt;( &amp;obj);\n\n return temp-&gt;doToString();\n}\n\n\n\nint\nmain(int argc, char *argv[])\n{\n Hello helloObj;\n Generic genericObj;\n\n std::cout &lt;&lt; optionalToString( helloObj) &lt;&lt; std::endl;\n std::cout &lt;&lt; optionalToString( genericObj) &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 264088, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": false, "text": "<p>C++ allows <a href=\"http://en.wikipedia.org/wiki/SFINAE\" rel=\"noreferrer\">SFINAE</a> to be used for this (notice that with C++11 features this is simplier because it supports extended SFINAE on nearly arbitrary expressions - the below was crafted to work with common C++03 compilers):</p>\n<pre><code>#define HAS_MEM_FUNC(func, name) \\\n template&lt;typename T, typename Sign&gt; \\\n struct name { \\\n typedef char yes[1]; \\\n typedef char no [2]; \\\n template &lt;typename U, U&gt; struct type_check; \\\n template &lt;typename _1&gt; static yes &amp;chk(type_check&lt;Sign, &amp;_1::func &gt; *); \\\n template &lt;typename &gt; static no &amp;chk(...); \\\n static bool const value = sizeof(chk&lt;T&gt;(0)) == sizeof(yes); \\\n }\n</code></pre>\n<p>The above template and macro tries to instantiate a template, giving it a member function pointer type, and the actual member function pointer. If the types do not fit, SFINAE causes the template to be ignored. Usage like this:</p>\n<pre><code>HAS_MEM_FUNC(toString, has_to_string);\n\ntemplate&lt;typename T&gt; void\ndoSomething() {\n if(has_to_string&lt;T, std::string(T::*)()&gt;::value) {\n ...\n } else {\n ...\n }\n}\n</code></pre>\n<p>But note that you cannot just call that <code>toString</code> function in that <code>if</code> branch. Since the compiler will check for validity in both branches, that would fail for cases the function doesn't exist. One way is to use SFINAE once again (<code>enable_if</code> can be obtained from boost, too):</p>\n<pre><code>template&lt;bool C, typename T = void&gt;\nstruct enable_if {\n typedef T type;\n};\n\ntemplate&lt;typename T&gt;\nstruct enable_if&lt;false, T&gt; { };\n\nHAS_MEM_FUNC(toString, has_to_string);\n\ntemplate&lt;typename T&gt; \ntypename enable_if&lt;has_to_string&lt;T, \n std::string(T::*)()&gt;::value, std::string&gt;::type\ndoSomething(T * t) {\n /* something when T has toString ... */\n return t-&gt;toString();\n}\n\ntemplate&lt;typename T&gt; \ntypename enable_if&lt;!has_to_string&lt;T, \n std::string(T::*)()&gt;::value, std::string&gt;::type\ndoSomething(T * t) {\n /* something when T doesnt have toString ... */\n return &quot;T::toString() does not exist.&quot;;\n}\n</code></pre>\n<p>Have fun using it. The advantage of it is that it also works for overloaded member functions, and also for <code>const</code> member functions (remember using <code>std::string(T::*)() const</code> as the member function pointer type then!).</p>\n" }, { "answer_id": 502552, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The standard C++ solution presented here by litb will not work as expected if the method happens to be defined in a base class. </p>\n\n<p>For a solution that handles this situation refer to :</p>\n\n<p>In Russian :\n<a href=\"http://www.rsdn.ru/forum/message/2759773.1.aspx\" rel=\"noreferrer\">http://www.rsdn.ru/forum/message/2759773.1.aspx</a> </p>\n\n<p>English Translation by Roman.Perepelitsa : \n<a href=\"http://groups.google.com/group/comp.lang.c++.moderated/tree/browse_frm/thread/4f7c7a96f9afbe44/c95a7b4c645e449f?pli=1\" rel=\"noreferrer\">http://groups.google.com/group/comp.lang.c++.moderated/tree/browse_frm/thread/4f7c7a96f9afbe44/c95a7b4c645e449f?pli=1</a> </p>\n\n<p>It is insanely clever. However one issue with this solutiion is that gives compiler errors if the type being tested is one that cannot be used as a base class (e.g. primitive types)</p>\n\n<p>In Visual Studio, I noticed that if working with method having no arguments, an extra pair of redundant ( ) needs to be inserted around the argments to deduce( ) in the sizeof expression.</p>\n" }, { "answer_id": 3102261, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 2, "selected": false, "text": "<p>Strange nobody suggested the following nice trick I saw once on this very site :</p>\n\n<pre><code>template &lt;class T&gt;\nstruct has_foo\n{\n struct S { void foo(...); };\n struct derived : S, T {};\n\n template &lt;typename V, V&gt; struct W {};\n\n template &lt;typename X&gt;\n char (&amp;test(W&lt;void (X::*)(), &amp;X::foo&gt; *))[1];\n\n template &lt;typename&gt;\n char (&amp;test(...))[2];\n\n static const bool value = sizeof(test&lt;derived&gt;(0)) == 1;\n};\n</code></pre>\n\n<p>You have to make sure T is a class. It seems that ambiguity in the lookup of foo is a substitution failure. I made it work on gcc, not sure if it is standard though.</p>\n" }, { "answer_id": 3627243, "author": "FireAphis", "author_id": 102834, "author_profile": "https://Stackoverflow.com/users/102834", "pm_score": 6, "selected": false, "text": "<p>Though this question is two years old, I'll dare to add my answer. Hopefully it will clarify the previous, indisputably excellent, solution. I took the very helpful answers of Nicola Bonelli and Johannes Schaub and merged them into a solution that is, IMHO, more readable, clear and does not require the <code>typeof</code> extension:</p>\n\n<pre><code>template &lt;class Type&gt;\nclass TypeHasToString\n{\n // This type won't compile if the second template parameter isn't of type T,\n // so I can put a function pointer type in the first parameter and the function\n // itself in the second thus checking that the function has a specific signature.\n template &lt;typename T, T&gt; struct TypeCheck;\n\n typedef char Yes;\n typedef long No;\n\n // A helper struct to hold the declaration of the function pointer.\n // Change it if the function signature changes.\n template &lt;typename T&gt; struct ToString\n {\n typedef void (T::*fptr)();\n };\n\n template &lt;typename T&gt; static Yes HasToString(TypeCheck&lt; typename ToString&lt;T&gt;::fptr, &amp;T::toString &gt;*);\n template &lt;typename T&gt; static No HasToString(...);\n\npublic:\n static bool const value = (sizeof(HasToString&lt;Type&gt;(0)) == sizeof(Yes));\n};\n</code></pre>\n\n<p>I checked it with gcc 4.1.2.\nThe credit goes mainly to Nicola Bonelli and Johannes Schaub, so give them a vote up if my answer helps you :)</p>\n" }, { "answer_id": 4810386, "author": "nob", "author_id": 335385, "author_profile": "https://Stackoverflow.com/users/335385", "pm_score": 3, "selected": false, "text": "<p>MSVC has the __if_exists and __if_not_exists keywords (<a href=\"http://msdn.microsoft.com/en-us/library/x7wy9xh3(VS.80).aspx\" rel=\"noreferrer\">Doc</a>). Together with the typeof-SFINAE approach of Nicola I could create a check for GCC and MSVC like the OP looked for.</p>\n\n<p><strong>Update:</strong> Source can be found <a href=\"https://github.com/nob13/sfserialization/blob/master/sfserialization/isdefault.h\" rel=\"noreferrer\">Here</a></p>\n" }, { "answer_id": 6324863, "author": "Brett Rossier", "author_id": 376331, "author_profile": "https://Stackoverflow.com/users/376331", "pm_score": 3, "selected": false, "text": "<p>Here are some usage snippets:\n*The guts for all this are farther down</p>\n\n<p><strong>Check for member <code>x</code> in a given class. Could be var, func, class, union, or enum:</strong></p>\n\n<pre><code>CREATE_MEMBER_CHECK(x);\nbool has_x = has_member_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member function <code>void x()</code>:</strong></p>\n\n<pre><code>//Func signature MUST have T as template variable here... simpler this way :\\\nCREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);\nbool has_func_sig_void__x = has_member_func_void__x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member variable <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_VAR_CHECK(x);\nbool has_var_x = has_member_var_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member class <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_CLASS_CHECK(x);\nbool has_class_x = has_member_class_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member union <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_UNION_CHECK(x);\nbool has_union_x = has_member_union_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for member enum <code>x</code>:</strong></p>\n\n<pre><code>CREATE_MEMBER_ENUM_CHECK(x);\nbool has_enum_x = has_member_enum_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Check for any member function <code>x</code> regardless of signature:</strong></p>\n\n<pre><code>CREATE_MEMBER_CHECK(x);\nCREATE_MEMBER_VAR_CHECK(x);\nCREATE_MEMBER_CLASS_CHECK(x);\nCREATE_MEMBER_UNION_CHECK(x);\nCREATE_MEMBER_ENUM_CHECK(x);\nCREATE_MEMBER_FUNC_CHECK(x);\nbool has_any_func_x = has_member_func_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>CREATE_MEMBER_CHECKS(x); //Just stamps out the same macro calls as above.\nbool has_any_func_x = has_member_func_x&lt;class_to_check_for_x&gt;::value;\n</code></pre>\n\n<p><strong>Details and core:</strong></p>\n\n<pre><code>/*\n - Multiple inheritance forces ambiguity of member names.\n - SFINAE is used to make aliases to member names.\n - Expression SFINAE is used in just one generic has_member that can accept\n any alias we pass it.\n*/\n\n//Variadic to force ambiguity of class members. C++11 and up.\ntemplate &lt;typename... Args&gt; struct ambiguate : public Args... {};\n\n//Non-variadic version of the line above.\n//template &lt;typename A, typename B&gt; struct ambiguate : public A, public B {};\n\ntemplate&lt;typename A, typename = void&gt;\nstruct got_type : std::false_type {};\n\ntemplate&lt;typename A&gt;\nstruct got_type&lt;A&gt; : std::true_type {\n typedef A type;\n};\n\ntemplate&lt;typename T, T&gt;\nstruct sig_check : std::true_type {};\n\ntemplate&lt;typename Alias, typename AmbiguitySeed&gt;\nstruct has_member {\n template&lt;typename C&gt; static char ((&amp;f(decltype(&amp;C::value))))[1];\n template&lt;typename C&gt; static char ((&amp;f(...)))[2];\n\n //Make sure the member name is consistently spelled the same.\n static_assert(\n (sizeof(f&lt;AmbiguitySeed&gt;(0)) == 1)\n , \"Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified.\"\n );\n\n static bool const value = sizeof(f&lt;Alias&gt;(0)) == 2;\n};\n</code></pre>\n\n<p><em><strong>Macros (El Diablo!):</em></strong></p>\n\n<p><strong>CREATE_MEMBER_CHECK:</strong></p>\n\n<pre><code>//Check for any member with given name, whether var, func, class, union, enum.\n#define CREATE_MEMBER_CHECK(member) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct Alias_##member; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct Alias_##member &lt; \\\n T, std::integral_constant&lt;bool, got_type&lt;decltype(&amp;T::member)&gt;::value&gt; \\\n&gt; { static const decltype(&amp;T::member) value; }; \\\n \\\nstruct AmbiguitySeed_##member { char member; }; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_##member { \\\n static const bool value \\\n = has_member&lt; \\\n Alias_##member&lt;ambiguate&lt;T, AmbiguitySeed_##member&gt;&gt; \\\n , Alias_##member&lt;AmbiguitySeed_##member&gt; \\\n &gt;::value \\\n ; \\\n}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_VAR_CHECK:</strong></p>\n\n<pre><code>//Check for member variable with given name.\n#define CREATE_MEMBER_VAR_CHECK(var_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_var_##var_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_var_##var_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , !std::is_member_function_pointer&lt;decltype(&amp;T::var_name)&gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_FUNC_SIG_CHECK:</strong></p>\n\n<pre><code>//Check for member function with given name AND signature.\n#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_func_##templ_postfix : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_func_##templ_postfix&lt; \\\n T, std::integral_constant&lt; \\\n bool \\\n , sig_check&lt;func_sig, &amp;T::func_name&gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_CLASS_CHECK:</strong></p>\n\n<pre><code>//Check for member class with given name.\n#define CREATE_MEMBER_CLASS_CHECK(class_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_class_##class_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_class_##class_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , std::is_class&lt; \\\n typename got_type&lt;typename T::class_name&gt;::type \\\n &gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_UNION_CHECK:</strong></p>\n\n<pre><code>//Check for member union with given name.\n#define CREATE_MEMBER_UNION_CHECK(union_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_union_##union_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_union_##union_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , std::is_union&lt; \\\n typename got_type&lt;typename T::union_name&gt;::type \\\n &gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_ENUM_CHECK:</strong></p>\n\n<pre><code>//Check for member enum with given name.\n#define CREATE_MEMBER_ENUM_CHECK(enum_name) \\\n \\\ntemplate&lt;typename T, typename = std::true_type&gt; \\\nstruct has_member_enum_##enum_name : std::false_type {}; \\\n \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_enum_##enum_name&lt; \\\n T \\\n , std::integral_constant&lt; \\\n bool \\\n , std::is_enum&lt; \\\n typename got_type&lt;typename T::enum_name&gt;::type \\\n &gt;::value \\\n &gt; \\\n&gt; : std::true_type {}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_FUNC_CHECK:</strong></p>\n\n<pre><code>//Check for function with given name, any signature.\n#define CREATE_MEMBER_FUNC_CHECK(func) \\\ntemplate&lt;typename T&gt; \\\nstruct has_member_func_##func { \\\n static const bool value \\\n = has_member_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_var_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_class_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_union_##func&lt;T&gt;::value \\\n &amp;&amp; !has_member_enum_##func&lt;T&gt;::value \\\n ; \\\n}\n</code></pre>\n\n<p><strong>CREATE_MEMBER_CHECKS:</strong></p>\n\n<pre><code>//Create all the checks for one member. Does NOT include func sig checks.\n#define CREATE_MEMBER_CHECKS(member) \\\nCREATE_MEMBER_CHECK(member); \\\nCREATE_MEMBER_VAR_CHECK(member); \\\nCREATE_MEMBER_CLASS_CHECK(member); \\\nCREATE_MEMBER_UNION_CHECK(member); \\\nCREATE_MEMBER_ENUM_CHECK(member); \\\nCREATE_MEMBER_FUNC_CHECK(member)\n</code></pre>\n" }, { "answer_id": 8755981, "author": "kispaljr", "author_id": 667409, "author_profile": "https://Stackoverflow.com/users/667409", "pm_score": 3, "selected": false, "text": "<p>I wrote an answer to this in another thread that (unlike the solutions above) also checks inherited member functions:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions/8752988#8752988\">SFINAE to check for inherited member functions</a></p>\n\n<p>Here are some example from that solution:</p>\n\n<h2>Example1:</h2>\n\n<p>We are checking for a member with the following signature: \n<code>T::const_iterator begin() const</code></p>\n\n<pre><code>template&lt;class T&gt; struct has_const_begin\n{\n typedef char (&amp;Yes)[1];\n typedef char (&amp;No)[2];\n\n template&lt;class U&gt; \n static Yes test(U const * data, \n typename std::enable_if&lt;std::is_same&lt;\n typename U::const_iterator, \n decltype(data-&gt;begin())\n &gt;::value&gt;::type * = 0);\n static No test(...);\n static const bool value = sizeof(Yes) == sizeof(has_const_begin::test((typename std::remove_reference&lt;T&gt;::type*)0));\n};\n</code></pre>\n\n<p>Please notice that it even checks the constness of the method, and works with primitive types, as well. (I mean <code>has_const_begin&lt;int&gt;::value</code> is false and doesn't cause a compile-time error.) </p>\n\n<h2>Example 2</h2>\n\n<p>Now we are looking for the signature: <code>void foo(MyClass&amp;, unsigned)</code></p>\n\n<pre><code>template&lt;class T&gt; struct has_foo\n{\n typedef char (&amp;Yes)[1];\n typedef char (&amp;No)[2];\n\n template&lt;class U&gt;\n static Yes test(U * data, MyClass* arg1 = 0,\n typename std::enable_if&lt;std::is_void&lt;\n decltype(data-&gt;foo(*arg1, 1u))\n &gt;::value&gt;::type * = 0);\n static No test(...);\n static const bool value = sizeof(Yes) == sizeof(has_foo::test((typename std::remove_reference&lt;T&gt;::type*)0));\n};\n</code></pre>\n\n<p>Please notice that MyClass doesn't has to be default constructible or to satisfy any special concept. The technique works with template members, as well.</p>\n\n<p>I am eagerly waiting opinions regarding this.</p>\n" }, { "answer_id": 9154394, "author": "Xeo", "author_id": 500104, "author_profile": "https://Stackoverflow.com/users/500104", "pm_score": 8, "selected": false, "text": "<p>This question is old, but with C++11 we got a new way to check for a functions existence (or existence of any non-type member, really), relying on SFINAE again:</p>\n\n<pre><code>template&lt;class T&gt;\nauto serialize_imp(std::ostream&amp; os, T const&amp; obj, int)\n -&gt; decltype(os &lt;&lt; obj, void())\n{\n os &lt;&lt; obj;\n}\n\ntemplate&lt;class T&gt;\nauto serialize_imp(std::ostream&amp; os, T const&amp; obj, long)\n -&gt; decltype(obj.stream(os), void())\n{\n obj.stream(os);\n}\n\ntemplate&lt;class T&gt;\nauto serialize(std::ostream&amp; os, T const&amp; obj)\n -&gt; decltype(serialize_imp(os, obj, 0), void())\n{\n serialize_imp(os, obj, 0);\n}\n</code></pre>\n\n<p>Now onto some explanations. First thing, I use <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2634.html\" rel=\"noreferrer\">expression SFINAE</a> to exclude the <code>serialize(_imp)</code> functions from overload resolution, if the first expression inside <code>decltype</code> isn't valid (aka, the function doesn't exist).</p>\n\n<p>The <code>void()</code> is used to make the return type of all those functions <code>void</code>.</p>\n\n<p>The <code>0</code> argument is used to prefer the <code>os &lt;&lt; obj</code> overload if both are available (literal <code>0</code> is of type <code>int</code> and as such the first overload is a better match).</p>\n\n<hr>\n\n<p>Now, you probably want a trait to check if a function exists. Luckily, it's easy to write that. Note, though, that you need to write a trait <em>yourself</em> for every different function name you might want.</p>\n\n<pre><code>#include &lt;type_traits&gt;\n\ntemplate&lt;class&gt;\nstruct sfinae_true : std::true_type{};\n\nnamespace detail{\n template&lt;class T, class A0&gt;\n static auto test_stream(int)\n -&gt; sfinae_true&lt;decltype(std::declval&lt;T&gt;().stream(std::declval&lt;A0&gt;()))&gt;;\n template&lt;class, class A0&gt;\n static auto test_stream(long) -&gt; std::false_type;\n} // detail::\n\ntemplate&lt;class T, class Arg&gt;\nstruct has_stream : decltype(detail::test_stream&lt;T, Arg&gt;(0)){};\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/cd139d95d214c5c3\" rel=\"noreferrer\">Live example.</a></p>\n\n<p>And on to explanations. First, <code>sfinae_true</code> is a helper type, and it basically amounts to the same as writing <code>decltype(void(std::declval&lt;T&gt;().stream(a0)), std::true_type{})</code>. The advantage is simply that it's shorter.<br>\nNext, the <code>struct has_stream : decltype(...)</code> inherits from either <code>std::true_type</code> or <code>std::false_type</code> in the end, depending on whether the <code>decltype</code> check in <code>test_stream</code> fails or not.<br>\nLast, <code>std::declval</code> gives you a \"value\" of whatever type you pass, without you needing to know how you can construct it. Note that this is only possible inside an unevaluated context, such as <code>decltype</code>, <code>sizeof</code> and others.</p>\n\n<hr>\n\n<p>Note that <code>decltype</code> is not necessarily needed, as <code>sizeof</code> (and all unevaluated contexts) got that enhancement. It's just that <code>decltype</code> already delivers a type and as such is just cleaner. Here's a <code>sizeof</code> version of one of the overloads:</p>\n\n<pre><code>template&lt;class T&gt;\nvoid serialize_imp(std::ostream&amp; os, T const&amp; obj, int,\n int(*)[sizeof((os &lt;&lt; obj),0)] = 0)\n{\n os &lt;&lt; obj;\n}\n</code></pre>\n\n<p>The <code>int</code> and <code>long</code> parameters are still there for the same reason. The array pointer is used to provide a context where <code>sizeof</code> can be used.</p>\n" }, { "answer_id": 17534399, "author": "user1095108", "author_id": 1095108, "author_profile": "https://Stackoverflow.com/users/1095108", "pm_score": 2, "selected": false, "text": "<p>How about this solution?</p>\n\n<pre><code>#include &lt;type_traits&gt;\n\ntemplate &lt;typename U, typename = void&gt; struct hasToString : std::false_type { };\n\ntemplate &lt;typename U&gt;\nstruct hasToString&lt;U,\n typename std::enable_if&lt;bool(sizeof(&amp;U::toString))&gt;::type\n&gt; : std::true_type { };\n</code></pre>\n" }, { "answer_id": 19815793, "author": "Shubham", "author_id": 2712152, "author_profile": "https://Stackoverflow.com/users/2712152", "pm_score": 3, "selected": false, "text": "<p>I modified the solution provided in <a href=\"https://stackoverflow.com/a/264088/2712152\">https://stackoverflow.com/a/264088/2712152</a> to make it a bit more general. Also since it doesn't use any of the new C++11 features we can use it with old compilers and should also work with msvc. But the compilers should enable C99 to use this since it uses variadic macros.</p>\n\n<p>The following macro can be used to check if a particular class has a particular typedef or not.</p>\n\n<pre><code>/** \n * @class : HAS_TYPEDEF\n * @brief : This macro will be used to check if a class has a particular\n * typedef or not.\n * @param typedef_name : Name of Typedef\n * @param name : Name of struct which is going to be run the test for\n * the given particular typedef specified in typedef_name\n */\n#define HAS_TYPEDEF(typedef_name, name) \\\n template &lt;typename T&gt; \\\n struct name { \\\n typedef char yes[1]; \\\n typedef char no[2]; \\\n template &lt;typename U&gt; \\\n struct type_check; \\\n template &lt;typename _1&gt; \\\n static yes&amp; chk(type_check&lt;typename _1::typedef_name&gt;*); \\\n template &lt;typename&gt; \\\n static no&amp; chk(...); \\\n static bool const value = sizeof(chk&lt;T&gt;(0)) == sizeof(yes); \\\n }\n</code></pre>\n\n<p>The following macro can be used to check if a particular class has a particular member function or not with any given number of arguments.</p>\n\n<pre><code>/** \n * @class : HAS_MEM_FUNC\n * @brief : This macro will be used to check if a class has a particular\n * member function implemented in the public section or not. \n * @param func : Name of Member Function\n * @param name : Name of struct which is going to be run the test for\n * the given particular member function name specified in func\n * @param return_type: Return type of the member function\n * @param ellipsis(...) : Since this is macro should provide test case for every\n * possible member function we use variadic macros to cover all possibilities\n */\n#define HAS_MEM_FUNC(func, name, return_type, ...) \\\n template &lt;typename T&gt; \\\n struct name { \\\n typedef return_type (T::*Sign)(__VA_ARGS__); \\\n typedef char yes[1]; \\\n typedef char no[2]; \\\n template &lt;typename U, U&gt; \\\n struct type_check; \\\n template &lt;typename _1&gt; \\\n static yes&amp; chk(type_check&lt;Sign, &amp;_1::func&gt;*); \\\n template &lt;typename&gt; \\\n static no&amp; chk(...); \\\n static bool const value = sizeof(chk&lt;T&gt;(0)) == sizeof(yes); \\\n }\n</code></pre>\n\n<p>We can use the above 2 macros to perform the checks for has_typedef and has_mem_func as:</p>\n\n<pre><code>class A {\npublic:\n typedef int check;\n void check_function() {}\n};\n\nclass B {\npublic:\n void hello(int a, double b) {}\n void hello() {}\n};\n\nHAS_MEM_FUNC(check_function, has_check_function, void, void);\nHAS_MEM_FUNC(hello, hello_check, void, int, double);\nHAS_MEM_FUNC(hello, hello_void_check, void, void);\nHAS_TYPEDEF(check, has_typedef_check);\n\nint main() {\n std::cout &lt;&lt; \"Check Function A:\" &lt;&lt; has_check_function&lt;A&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Check Function B:\" &lt;&lt; has_check_function&lt;B&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Hello Function A:\" &lt;&lt; hello_check&lt;A&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Hello Function B:\" &lt;&lt; hello_check&lt;B&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Hello void Function A:\" &lt;&lt; hello_void_check&lt;A&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Hello void Function B:\" &lt;&lt; hello_void_check&lt;B&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Check Typedef A:\" &lt;&lt; has_typedef_check&lt;A&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Check Typedef B:\" &lt;&lt; has_typedef_check&lt;B&gt;::value &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 21063089, "author": "Hui", "author_id": 3185134, "author_profile": "https://Stackoverflow.com/users/3185134", "pm_score": 1, "selected": false, "text": "<p>Here is my version that handles all possible member function overloads with arbitrary arity, including template member functions, possibly with default arguments. It distinguishes 3 mutually exclusive scenarios when making a member function call to some class type, with given arg types: (1) valid, or (2) ambiguous, or (3) non-viable. Example usage:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n\nHAS_MEM(bar)\nHAS_MEM_FUN_CALL(bar)\n\nstruct test\n{\n void bar(int);\n void bar(double);\n void bar(int,double);\n\n template &lt; typename T &gt;\n typename std::enable_if&lt; not std::is_integral&lt;T&gt;::value &gt;::type\n bar(const T&amp;, int=0){}\n\n template &lt; typename T &gt;\n typename std::enable_if&lt; std::is_integral&lt;T&gt;::value &gt;::type\n bar(const std::vector&lt;T&gt;&amp;, T*){}\n\n template &lt; typename T &gt;\n int bar(const std::string&amp;, int){}\n};\n</code></pre>\n\n<p>Now you can use it like this:</p>\n\n<pre><code>int main(int argc, const char * argv[])\n{\n static_assert( has_mem_bar&lt;test&gt;::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar&lt;test(char const*,long)&gt;::value , \"\");\n static_assert( has_valid_mem_fun_call_bar&lt;test(std::string&amp;,long)&gt;::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar&lt;test(std::vector&lt;int&gt;, int*)&gt;::value , \"\");\n static_assert( has_no_viable_mem_fun_call_bar&lt;test(std::vector&lt;double&gt;, double*)&gt;::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar&lt;test(int)&gt;::value , \"\");\n static_assert( std::is_same&lt;void,result_of_mem_fun_call_bar&lt;test(int)&gt;::type&gt;::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar&lt;test(int,double)&gt;::value , \"\");\n static_assert( not has_valid_mem_fun_call_bar&lt;test(int,double,int)&gt;::value , \"\");\n\n static_assert( not has_ambiguous_mem_fun_call_bar&lt;test(double)&gt;::value , \"\");\n static_assert( has_ambiguous_mem_fun_call_bar&lt;test(unsigned)&gt;::value , \"\");\n\n static_assert( has_viable_mem_fun_call_bar&lt;test(unsigned)&gt;::value , \"\");\n static_assert( has_viable_mem_fun_call_bar&lt;test(int)&gt;::value , \"\");\n\n static_assert( has_no_viable_mem_fun_call_bar&lt;test(void)&gt;::value , \"\");\n\n return 0;\n}\n</code></pre>\n\n<p>Here is the code, written in c++11, however, you can easily port it (with minor tweaks) to non-c++11 that has typeof extensions (e.g. gcc). You can replace the HAS_MEM macro with your own.</p>\n\n<pre><code>#pragma once\n\n#if __cplusplus &gt;= 201103\n\n#include &lt;utility&gt;\n#include &lt;type_traits&gt;\n\n#define HAS_MEM(mem) \\\n \\\ntemplate &lt; typename T &gt; \\\nstruct has_mem_##mem \\\n{ \\\n struct yes {}; \\\n struct no {}; \\\n \\\n struct ambiguate_seed { char mem; }; \\\n template &lt; typename U &gt; struct ambiguate : U, ambiguate_seed {}; \\\n \\\n template &lt; typename U, typename = decltype(&amp;U::mem) &gt; static constexpr no test(int); \\\n template &lt; typename &gt; static constexpr yes test(...); \\\n \\\n static bool constexpr value = std::is_same&lt;decltype(test&lt; ambiguate&lt;T&gt; &gt;(0)),yes&gt;::value ; \\\n typedef std::integral_constant&lt;bool,value&gt; type; \\\n};\n\n\n#define HAS_MEM_FUN_CALL(memfun) \\\n \\\ntemplate &lt; typename Signature &gt; \\\nstruct has_valid_mem_fun_call_##memfun; \\\n \\\ntemplate &lt; typename T, typename... Args &gt; \\\nstruct has_valid_mem_fun_call_##memfun&lt; T(Args...) &gt; \\\n{ \\\n struct yes {}; \\\n struct no {}; \\\n \\\n template &lt; typename U, bool = has_mem_##memfun&lt;U&gt;::value &gt; \\\n struct impl \\\n { \\\n template &lt; typename V, typename = decltype(std::declval&lt;V&gt;().memfun(std::declval&lt;Args&gt;()...)) &gt; \\\n struct test_result { using type = yes; }; \\\n \\\n template &lt; typename V &gt; static constexpr typename test_result&lt;V&gt;::type test(int); \\\n template &lt; typename &gt; static constexpr no test(...); \\\n \\\n static constexpr bool value = std::is_same&lt;decltype(test&lt;U&gt;(0)),yes&gt;::value; \\\n using type = std::integral_constant&lt;bool, value&gt;; \\\n }; \\\n \\\n template &lt; typename U &gt; \\\n struct impl&lt;U,false&gt; : std::false_type {}; \\\n \\\n static constexpr bool value = impl&lt;T&gt;::value; \\\n using type = std::integral_constant&lt;bool, value&gt;; \\\n}; \\\n \\\ntemplate &lt; typename Signature &gt; \\\nstruct has_ambiguous_mem_fun_call_##memfun; \\\n \\\ntemplate &lt; typename T, typename... Args &gt; \\\nstruct has_ambiguous_mem_fun_call_##memfun&lt; T(Args...) &gt; \\\n{ \\\n struct ambiguate_seed { void memfun(...); }; \\\n \\\n template &lt; class U, bool = has_mem_##memfun&lt;U&gt;::value &gt; \\\n struct ambiguate : U, ambiguate_seed \\\n { \\\n using ambiguate_seed::memfun; \\\n using U::memfun; \\\n }; \\\n \\\n template &lt; class U &gt; \\\n struct ambiguate&lt;U,false&gt; : ambiguate_seed {}; \\\n \\\n static constexpr bool value = not has_valid_mem_fun_call_##memfun&lt; ambiguate&lt;T&gt;(Args...) &gt;::value; \\\n using type = std::integral_constant&lt;bool, value&gt;; \\\n}; \\\n \\\ntemplate &lt; typename Signature &gt; \\\nstruct has_viable_mem_fun_call_##memfun; \\\n \\\ntemplate &lt; typename T, typename... Args &gt; \\\nstruct has_viable_mem_fun_call_##memfun&lt; T(Args...) &gt; \\\n{ \\\n static constexpr bool value = has_valid_mem_fun_call_##memfun&lt;T(Args...)&gt;::value \\\n or has_ambiguous_mem_fun_call_##memfun&lt;T(Args...)&gt;::value; \\\n using type = std::integral_constant&lt;bool, value&gt;; \\\n}; \\\n \\\ntemplate &lt; typename Signature &gt; \\\nstruct has_no_viable_mem_fun_call_##memfun; \\\n \\\ntemplate &lt; typename T, typename... Args &gt; \\\nstruct has_no_viable_mem_fun_call_##memfun &lt; T(Args...) &gt; \\\n{ \\\n static constexpr bool value = not has_viable_mem_fun_call_##memfun&lt;T(Args...)&gt;::value; \\\n using type = std::integral_constant&lt;bool, value&gt;; \\\n}; \\\n \\\ntemplate &lt; typename Signature &gt; \\\nstruct result_of_mem_fun_call_##memfun; \\\n \\\ntemplate &lt; typename T, typename... Args &gt; \\\nstruct result_of_mem_fun_call_##memfun&lt; T(Args...) &gt; \\\n{ \\\n using type = decltype(std::declval&lt;T&gt;().memfun(std::declval&lt;Args&gt;()...)); \\\n};\n\n#endif\n</code></pre>\n\n<hr>\n" }, { "answer_id": 22014784, "author": "Morwenn", "author_id": 1364752, "author_profile": "https://Stackoverflow.com/users/1364752", "pm_score": 7, "selected": false, "text": "<h2>C++20 - <code>requires</code> expressions</h2>\n<p>With C++20 come concepts and assorted tools such as <a href=\"https://en.cppreference.com/w/cpp/language/constraints\" rel=\"noreferrer\"><code>requires</code> expressions</a> which are a built-in way to check for a function existence. With them you could rewrite your <code>optionalToString</code> function as follows:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template&lt;class T&gt;\nstd::string optionalToString(T* obj)\n{\n constexpr bool has_toString = requires(const T&amp; t) {\n t.toString();\n };\n\n if constexpr (has_toString)\n return obj-&gt;toString();\n else\n return &quot;toString not defined&quot;;\n}\n</code></pre>\n<h2>Pre-C++20 - Detection toolkit</h2>\n<p><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf\" rel=\"noreferrer\">N4502</a> proposes a detection toolkit for inclusion into the C++17 standard library that eventually made it into the library fundamentals TS v2. It most likely won't ever get into the standard because it has been subsumed by <code>requires</code> expressions since, but it still solves the problem in a somewhat elegant manner. The toolkit introduces some metafunctions, including <a href=\"http://en.cppreference.com/w/cpp/experimental/is_detected\" rel=\"noreferrer\"><code>std::is_detected</code></a> which can be used to easily write type or function detection metafunctions on the top of it. Here is how you could use it:</p>\n<pre><code>template&lt;typename T&gt;\nusing toString_t = decltype( std::declval&lt;T&amp;&gt;().toString() );\n\ntemplate&lt;typename T&gt;\nconstexpr bool has_toString = std::is_detected_v&lt;toString_t, T&gt;;\n</code></pre>\n<p>Note that the example above is untested. The detection toolkit is not available in standard libraries yet but the proposal contains a full implementation that you can easily copy if you really need it. It plays nice with the C++17 feature <code>if constexpr</code>:</p>\n<pre><code>template&lt;class T&gt;\nstd::string optionalToString(T* obj)\n{\n if constexpr (has_toString&lt;T&gt;)\n return obj-&gt;toString();\n else\n return &quot;toString not defined&quot;;\n}\n</code></pre>\n<h2>C++14 - Boost.Hana</h2>\n<p>Boost.Hana apparently builds upon this specific example and provides a solution for C++14 in its documentation, so I'm going to quote it directly:</p>\n<blockquote>\n<p>[...] Hana provides a <code>is_valid</code> function that can be combined with C++14 generic lambdas to obtain a much cleaner implementation of the same thing:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto has_toString = hana::is_valid([](auto&amp;&amp; obj) -&gt; decltype(obj.toString()) { });\n</code></pre>\n<p>This leaves us with a function object <code>has_toString</code> which returns whether the given expression is valid on the argument we pass to it. The result is returned as an <code>IntegralConstant</code>, so constexpr-ness is not an issue here because the result of the function is represented as a type anyway. Now, in addition to being less verbose (that's a one liner!), the intent is much clearer. Other benefits are the fact that <code>has_toString</code> can be passed to higher order algorithms and it can also be defined at function scope, so there is no need to pollute the namespace scope with implementation details.</p>\n</blockquote>\n<h2>Boost.TTI</h2>\n<p>Another somewhat idiomatic toolkit to perform such a check - even though less elegant - is <a href=\"http://www.boost.org/doc/libs/1_55_0/libs/tti/doc/html/index.html\" rel=\"noreferrer\">Boost.TTI</a>, introduced in Boost 1.54.0. For your example, you would have to use the macro <code>BOOST_TTI_HAS_MEMBER_FUNCTION</code>. Here is how you could use it:</p>\n<pre><code>#include &lt;boost/tti/has_member_function.hpp&gt;\n\n// Generate the metafunction\nBOOST_TTI_HAS_MEMBER_FUNCTION(toString)\n\n// Check whether T has a member function toString\n// which takes no parameter and returns a std::string\nconstexpr bool foo = has_member_function_toString&lt;T, std::string&gt;::value;\n</code></pre>\n<p>Then, you could use the <code>bool</code> to create a SFINAE check.</p>\n<p><em>Explanation</em></p>\n<p>The macro <code>BOOST_TTI_HAS_MEMBER_FUNCTION</code> generates the metafunction <code>has_member_function_toString</code> which takes the checked type as its first template parameter. The second template parameter corresponds to the return type of the member function, and the following parameters correspond to the types of the function's parameters. The member <code>value</code> contains <code>true</code> if the class <code>T</code> has a member function <code>std::string toString()</code>.</p>\n<p>Alternatively, <code>has_member_function_toString</code> can take a member function pointer as a template parameter. Therefore, it is possible to replace <code>has_member_function_toString&lt;T, std::string&gt;::value</code> by <code>has_member_function_toString&lt;std::string T::* ()&gt;::value</code>.</p>\n" }, { "answer_id": 23996349, "author": "Yakk - Adam Nevraumont", "author_id": 1774667, "author_profile": "https://Stackoverflow.com/users/1774667", "pm_score": 4, "selected": false, "text": "<p>This is a C++11 solution for the general problem if \"If I did X, would it compile?\"</p>\n\n<pre><code>template&lt;class&gt; struct type_sink { typedef void type; }; // consumes a type, and makes it `void`\ntemplate&lt;class T&gt; using type_sink_t = typename type_sink&lt;T&gt;::type;\ntemplate&lt;class T, class=void&gt; struct has_to_string : std::false_type {}; \\\ntemplate&lt;class T&gt; struct has_to_string&lt;\n T,\n type_sink_t&lt; decltype( std::declval&lt;T&gt;().toString() ) &gt;\n&gt;: std::true_type {};\n</code></pre>\n\n<p>Trait <code>has_to_string</code> such that <code>has_to_string&lt;T&gt;::value</code> is <code>true</code> if and only if <code>T</code> has a method <code>.toString</code> that can be invoked with 0 arguments in this context.</p>\n\n<p>Next, I'd use tag dispatching:</p>\n\n<pre><code>namespace details {\n template&lt;class T&gt;\n std::string optionalToString_helper(T* obj, std::true_type /*has_to_string*/) {\n return obj-&gt;toString();\n }\n template&lt;class T&gt;\n std::string optionalToString_helper(T* obj, std::false_type /*has_to_string*/) {\n return \"toString not defined\";\n }\n}\ntemplate&lt;class T&gt;\nstd::string optionalToString(T* obj) {\n return details::optionalToString_helper( obj, has_to_string&lt;T&gt;{} );\n}\n</code></pre>\n\n<p>which tends to be more maintainable than complex SFINAE expressions.</p>\n\n<p>You can write these traits with a macro if you find yourself doing it alot, but they are relatively simple (a few lines each) so maybe not worth it:</p>\n\n<pre><code>#define MAKE_CODE_TRAIT( TRAIT_NAME, ... ) \\\ntemplate&lt;class T, class=void&gt; struct TRAIT_NAME : std::false_type {}; \\\ntemplate&lt;class T&gt; struct TRAIT_NAME&lt; T, type_sink_t&lt; decltype( __VA_ARGS__ ) &gt; &gt;: std::true_type {};\n</code></pre>\n\n<p>what the above does is create a macro <code>MAKE_CODE_TRAIT</code>. You pass it the name of the trait you want, and some code that can test the type <code>T</code>. Thus:</p>\n\n<pre><code>MAKE_CODE_TRAIT( has_to_string, std::declval&lt;T&gt;().toString() )\n</code></pre>\n\n<p>creates the above traits class.</p>\n\n<p>As an aside, the above technique is part of what MS calls \"expression SFINAE\", and their 2013 compiler fails pretty hard.</p>\n\n<p>Note that in C++1y the following syntax is possible:</p>\n\n<pre><code>template&lt;class T&gt;\nstd::string optionalToString(T* obj) {\n return compiled_if&lt; has_to_string &gt;(*obj, [&amp;](auto&amp;&amp; obj) {\n return obj.toString();\n }) *compiled_else ([&amp;]{ \n return \"toString not defined\";\n });\n}\n</code></pre>\n\n<p>which is an inline compilation conditional branch that abuses lots of C++ features. Doing so is probably not worth it, as the benefit (of code being inline) is not worth the cost (of next to nobody understanding how it works), but the existence of that above solution may be of interest.</p>\n" }, { "answer_id": 30848101, "author": "akim", "author_id": 1353549, "author_profile": "https://Stackoverflow.com/users/1353549", "pm_score": 5, "selected": false, "text": "<p>Well, this question has a long list of answers already, but I would like to emphasize the comment from Morwenn: there is a proposal for C++17 that makes it really much simpler. See <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf\" rel=\"noreferrer\" title=\"Proposing Standard Library Support for the C++ Detection Idiom, v2\">N4502</a> for details, but as a self-contained example consider the following.</p>\n\n<p>This part is the constant part, put it in a header.</p>\n\n<pre><code>// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf.\ntemplate &lt;typename...&gt;\nusing void_t = void;\n\n// Primary template handles all types not supporting the operation.\ntemplate &lt;typename, template &lt;typename&gt; class, typename = void_t&lt;&gt;&gt;\nstruct detect : std::false_type {};\n\n// Specialization recognizes/validates only types supporting the archetype.\ntemplate &lt;typename T, template &lt;typename&gt; class Op&gt;\nstruct detect&lt;T, Op, void_t&lt;Op&lt;T&gt;&gt;&gt; : std::true_type {};\n</code></pre>\n\n<p>then there is the variable part, where you specify what you are looking for (a type, a member type, a function, a member function etc.). In the case of the OP:</p>\n\n<pre><code>template &lt;typename T&gt;\nusing toString_t = decltype(std::declval&lt;T&gt;().toString());\n\ntemplate &lt;typename T&gt;\nusing has_toString = detect&lt;T, toString_t&gt;;\n</code></pre>\n\n<p>The following example, taken from <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf\" rel=\"noreferrer\" title=\"Proposing Standard Library Support for the C++ Detection Idiom, v2\">N4502</a>, shows a more elaborate probe:</p>\n\n<pre><code>// Archetypal expression for assignment operation.\ntemplate &lt;typename T&gt;\nusing assign_t = decltype(std::declval&lt;T&amp;&gt;() = std::declval&lt;T const &amp;&gt;())\n\n// Trait corresponding to that archetype.\ntemplate &lt;typename T&gt;\nusing is_assignable = detect&lt;T, assign_t&gt;;\n</code></pre>\n\n<p>Compared to the other implementations described above, this one is fairly simple: a reduced set of tools (<code>void_t</code> and <code>detect</code>) suffices, no need for hairy macros. Besides, it was reported (see <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf\" rel=\"noreferrer\" title=\"Proposing Standard Library Support for the C++ Detection Idiom, v2\">N4502</a>) that it is measurably more efficient (compile-time and compiler memory consumption) than previous approaches.</p>\n\n<p>Here is a <a href=\"http://coliru.stacked-crooked.com/a/7eae9c76232a2d20\" rel=\"noreferrer\" title=\"Detection idiom\">live example</a>. It works fine with Clang, but unfortunately, GCC versions before 5.1 followed a different interpretation of the C++11 standard which caused <code>void_t</code> to not work as expected. Yakk already provided the work-around: use the following definition of <code>void_t</code> (<a href=\"https://stackoverflow.com/questions/28967003/void-t-in-parameter-list-works-but-not-as-return-type/28967049#28967049\">void_t in parameter list works but not as return type</a>):</p>\n\n<pre><code>#if __GNUC__ &lt; 5 &amp;&amp; ! defined __clang__\n// https://stackoverflow.com/a/28967049/1353549\ntemplate &lt;typename...&gt;\nstruct voider\n{\n using type = void;\n};\ntemplate &lt;typename...Ts&gt;\nusing void_t = typename voider&lt;Ts...&gt;::type;\n#else\ntemplate &lt;typename...&gt;\nusing void_t = void;\n#endif\n</code></pre>\n" }, { "answer_id": 31860104, "author": "Aaron McDaid", "author_id": 146041, "author_profile": "https://Stackoverflow.com/users/146041", "pm_score": 5, "selected": false, "text": "<p>A simple solution for C++11:</p>\n\n<pre><code>template&lt;class T&gt;\nauto optionalToString(T* obj)\n -&gt; decltype( obj-&gt;toString() )\n{\n return obj-&gt;toString();\n}\nauto optionalToString(...) -&gt; string\n{\n return \"toString not defined\";\n}\n</code></pre>\n\n<p>Update, 3 years later: (and this is untested). To test for the existence, I think this will work:</p>\n\n<pre><code>template&lt;class T&gt;\nconstexpr auto test_has_toString_method(T* obj)\n -&gt; decltype( obj-&gt;toString() , std::true_type{} )\n{\n return obj-&gt;toString();\n}\nconstexpr auto test_has_toString_method(...) -&gt; std::false_type\n{\n return \"toString not defined\";\n}\n</code></pre>\n" }, { "answer_id": 33328621, "author": "user3296587", "author_id": 3296587, "author_profile": "https://Stackoverflow.com/users/3296587", "pm_score": 2, "selected": false, "text": "<p>There are a lot of answers here, but I failed, to find a version, that performs <em>real</em> method resolution ordering, while not using any of the newer c++ features (only using c++98 features).<br>\nNote: This version is tested and working with vc++2013, g++ 5.2.0 and the onlline compiler.<br></p>\n\n<p>So I came up with a version, that only uses sizeof():</p>\n\n<pre><code>template&lt;typename T&gt; T declval(void);\n\nstruct fake_void { };\ntemplate&lt;typename T&gt; T &amp;operator,(T &amp;,fake_void);\ntemplate&lt;typename T&gt; T const &amp;operator,(T const &amp;,fake_void);\ntemplate&lt;typename T&gt; T volatile &amp;operator,(T volatile &amp;,fake_void);\ntemplate&lt;typename T&gt; T const volatile &amp;operator,(T const volatile &amp;,fake_void);\n\nstruct yes { char v[1]; };\nstruct no { char v[2]; };\ntemplate&lt;bool&gt; struct yes_no:yes{};\ntemplate&lt;&gt; struct yes_no&lt;false&gt;:no{};\n\ntemplate&lt;typename T&gt;\nstruct has_awesome_member {\n template&lt;typename U&gt; static yes_no&lt;(sizeof((\n declval&lt;U&gt;().awesome_member(),fake_void()\n ))!=0)&gt; check(int);\n template&lt;typename&gt; static no check(...);\n enum{value=sizeof(check&lt;T&gt;(0)) == sizeof(yes)};\n};\n\n\nstruct foo { int awesome_member(void); };\nstruct bar { };\nstruct foo_void { void awesome_member(void); };\nstruct wrong_params { void awesome_member(int); };\n\nstatic_assert(has_awesome_member&lt;foo&gt;::value,\"\");\nstatic_assert(!has_awesome_member&lt;bar&gt;::value,\"\");\nstatic_assert(has_awesome_member&lt;foo_void&gt;::value,\"\");\nstatic_assert(!has_awesome_member&lt;wrong_params&gt;::value,\"\");\n</code></pre>\n\n<p>Live demo (with extended return type checking and vc++2010 workaround): <a href=\"http://cpp.sh/5b2vs\" rel=\"nofollow noreferrer\">http://cpp.sh/5b2vs</a></p>\n\n<p>No source, as I came up with it myself.</p>\n\n<p>When running the Live demo on the g++ compiler, please note that array sizes of 0 are allowed, meaning that the static_assert used will not trigger a compiler error, even when it fails.<br>\nA commonly used work-around is to replace the 'typedef' in the macro with 'extern'.</p>\n" }, { "answer_id": 34801904, "author": "Paul Fultz II", "author_id": 375343, "author_profile": "https://Stackoverflow.com/users/375343", "pm_score": 1, "selected": false, "text": "<p>You can skip all the metaprogramming in C++14, and just write this using <a href=\"http://fit.readthedocs.io/en/latest/include/fit/conditional.html\" rel=\"nofollow noreferrer\"><code>fit::conditional</code></a> from the <a href=\"https://github.com/pfultz2/Fit\" rel=\"nofollow noreferrer\">Fit</a> library:</p>\n\n<pre><code>template&lt;class T&gt;\nstd::string optionalToString(T* x)\n{\n return fit::conditional(\n [](auto* obj) -&gt; decltype(obj-&gt;toString()) { return obj-&gt;toString(); },\n [](auto*) { return \"toString not defined\"; }\n )(x);\n}\n</code></pre>\n\n<p>You can also create the function directly from the lambdas as well:</p>\n\n<pre><code>FIT_STATIC_LAMBDA_FUNCTION(optionalToString) = fit::conditional(\n [](auto* obj) -&gt; decltype(obj-&gt;toString(), std::string()) { return obj-&gt;toString(); },\n [](auto*) -&gt; std::string { return \"toString not defined\"; }\n);\n</code></pre>\n\n<p>However, if you are using a compiler that doesn't support generic lambdas, you will have to write separate function objects:</p>\n\n<pre><code>struct withToString\n{\n template&lt;class T&gt;\n auto operator()(T* obj) const -&gt; decltype(obj-&gt;toString(), std::string())\n {\n return obj-&gt;toString();\n }\n};\n\nstruct withoutToString\n{\n template&lt;class T&gt;\n std::string operator()(T*) const\n {\n return \"toString not defined\";\n }\n};\n\nFIT_STATIC_FUNCTION(optionalToString) = fit::conditional(\n withToString(),\n withoutToString()\n);\n</code></pre>\n" }, { "answer_id": 37142300, "author": "anton_rh", "author_id": 5447906, "author_profile": "https://Stackoverflow.com/users/5447906", "pm_score": 2, "selected": false, "text": "<p>The generic template that can be used for checking if some \"feature\" is supported by the type:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n\ntemplate &lt;template &lt;typename&gt; class TypeChecker, typename Type&gt;\nstruct is_supported\n{\n // these structs are used to recognize which version\n // of the two functions was chosen during overload resolution\n struct supported {};\n struct not_supported {};\n\n // this overload of chk will be ignored by SFINAE principle\n // if TypeChecker&lt;Type_&gt; is invalid type\n template &lt;typename Type_&gt;\n static supported chk(typename std::decay&lt;TypeChecker&lt;Type_&gt;&gt;::type *);\n\n // ellipsis has the lowest conversion rank, so this overload will be\n // chosen during overload resolution only if the template overload above is ignored\n template &lt;typename Type_&gt;\n static not_supported chk(...);\n\n // if the template overload of chk is chosen during\n // overload resolution then the feature is supported\n // if the ellipses overload is chosen the the feature is not supported\n static constexpr bool value = std::is_same&lt;decltype(chk&lt;Type&gt;(nullptr)),supported&gt;::value;\n};\n</code></pre>\n\n<p>The template that checks whether there is a method <code>foo</code> that is compatible with signature <code>double(const char*)</code></p>\n\n<pre><code>// if T doesn't have foo method with the signature that allows to compile the bellow\n// expression then instantiating this template is Substitution Failure (SF)\n// which Is Not An Error (INAE) if this happens during overload resolution\ntemplate &lt;typename T&gt;\nusing has_foo = decltype(double(std::declval&lt;T&gt;().foo(std::declval&lt;const char*&gt;())));\n</code></pre>\n\n<p>Examples</p>\n\n<pre><code>// types that support has_foo\nstruct struct1 { double foo(const char*); }; // exact signature match\nstruct struct2 { int foo(const std::string &amp;str); }; // compatible signature\nstruct struct3 { float foo(...); }; // compatible ellipsis signature\nstruct struct4 { template &lt;typename T&gt;\n int foo(T t); }; // compatible template signature\n\n// types that do not support has_foo\nstruct struct5 { void foo(const char*); }; // returns void\nstruct struct6 { std::string foo(const char*); }; // std::string can't be converted to double\nstruct struct7 { double foo( int *); }; // const char* can't be converted to int*\nstruct struct8 { double bar(const char*); }; // there is no foo method\n\nint main()\n{\n std::cout &lt;&lt; std::boolalpha;\n\n std::cout &lt;&lt; is_supported&lt;has_foo, int &gt;::value &lt;&lt; std::endl; // false\n std::cout &lt;&lt; is_supported&lt;has_foo, double &gt;::value &lt;&lt; std::endl; // false\n\n std::cout &lt;&lt; is_supported&lt;has_foo, struct1&gt;::value &lt;&lt; std::endl; // true\n std::cout &lt;&lt; is_supported&lt;has_foo, struct2&gt;::value &lt;&lt; std::endl; // true\n std::cout &lt;&lt; is_supported&lt;has_foo, struct3&gt;::value &lt;&lt; std::endl; // true\n std::cout &lt;&lt; is_supported&lt;has_foo, struct4&gt;::value &lt;&lt; std::endl; // true\n\n std::cout &lt;&lt; is_supported&lt;has_foo, struct5&gt;::value &lt;&lt; std::endl; // false\n std::cout &lt;&lt; is_supported&lt;has_foo, struct6&gt;::value &lt;&lt; std::endl; // false\n std::cout &lt;&lt; is_supported&lt;has_foo, struct7&gt;::value &lt;&lt; std::endl; // false\n std::cout &lt;&lt; is_supported&lt;has_foo, struct8&gt;::value &lt;&lt; std::endl; // false\n\n return 0;\n}\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/83c6a631ed42cea4\" rel=\"nofollow\">http://coliru.stacked-crooked.com/a/83c6a631ed42cea4</a></p>\n" }, { "answer_id": 47064058, "author": "tereshkd", "author_id": 2584542, "author_profile": "https://Stackoverflow.com/users/2584542", "pm_score": 0, "selected": false, "text": "<p>Here is an example of the working code.</p>\n\n<pre><code>template&lt;typename T&gt;\nusing toStringFn = decltype(std::declval&lt;const T&gt;().toString());\n\ntemplate &lt;class T, toStringFn&lt;T&gt;* = nullptr&gt;\nstd::string optionalToString(const T* obj, int)\n{\n return obj-&gt;toString();\n}\n\ntemplate &lt;class T&gt;\nstd::string optionalToString(const T* obj, long)\n{\n return \"toString not defined\";\n}\n\nint main()\n{\n A* a;\n B* b;\n\n std::cout &lt;&lt; optionalToString(a, 0) &lt;&lt; std::endl; // This is A\n std::cout &lt;&lt; optionalToString(b, 0) &lt;&lt; std::endl; // toString not defined\n}\n</code></pre>\n\n<p><code>toStringFn&lt;T&gt;* = nullptr</code> will enable the function which takes extra <code>int</code> argument which has a priority over function which takes <code>long</code> when called with <code>0</code>.</p>\n\n<p>You can use the same principle for the functions which returns <code>true</code> if function is implemented.</p>\n\n<pre><code>template &lt;typename T&gt;\nconstexpr bool toStringExists(long)\n{\n return false;\n}\n\ntemplate &lt;typename T, toStringFn&lt;T&gt;* = nullptr&gt;\nconstexpr bool toStringExists(int)\n{\n return true;\n}\n\n\nint main()\n{\n A* a;\n B* b;\n\n std::cout &lt;&lt; toStringExists&lt;A&gt;(0) &lt;&lt; std::endl; // true\n std::cout &lt;&lt; toStringExists&lt;B&gt;(0) &lt;&lt; std::endl; // false\n}\n</code></pre>\n" }, { "answer_id": 48384508, "author": "Paul Belanger", "author_id": 3349368, "author_profile": "https://Stackoverflow.com/users/3349368", "pm_score": 3, "selected": false, "text": "<p>An example using SFINAE and template partial specialization, by writing a <code>Has_foo</code> concept check: </p>\n\n<pre><code>#include &lt;type_traits&gt;\nstruct A{};\n\nstruct B{ int foo(int a, int b);};\n\nstruct C{void foo(int a, int b);};\n\nstruct D{int foo();};\n\nstruct E: public B{};\n\n// available in C++17 onwards as part of &lt;type_traits&gt;\ntemplate&lt;typename...&gt;\nusing void_t = void;\n\ntemplate&lt;typename T, typename = void&gt; struct Has_foo: std::false_type{};\n\ntemplate&lt;typename T&gt; \nstruct Has_foo&lt;T, void_t&lt;\n std::enable_if_t&lt;\n std::is_same&lt;\n int, \n decltype(std::declval&lt;T&gt;().foo((int)0, (int)0))\n &gt;::value\n &gt;\n&gt;&gt;: std::true_type{};\n\n\nstatic_assert(not Has_foo&lt;A&gt;::value, \"A does not have a foo\");\nstatic_assert(Has_foo&lt;B&gt;::value, \"B has a foo\");\nstatic_assert(not Has_foo&lt;C&gt;::value, \"C has a foo with the wrong return. \");\nstatic_assert(not Has_foo&lt;D&gt;::value, \"D has a foo with the wrong arguments. \");\nstatic_assert(Has_foo&lt;E&gt;::value, \"E has a foo since it inherits from B\");\n</code></pre>\n" }, { "answer_id": 53987441, "author": "Yigal Eilam", "author_id": 5925184, "author_profile": "https://Stackoverflow.com/users/5925184", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem:</p>\n\n<p>A template class that may be derived from few base classes, some that have a certain member and others that do not.</p>\n\n<p>I solved it similarly to the \"typeof\" (Nicola Bonelli's) answer, but with decltype so it compiles and runs correctly on MSVS:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nstruct Generic {}; \nstruct HasMember \n{\n HasMember() : _a(1) {};\n int _a;\n}; \n\n// SFINAE test\ntemplate &lt;typename T&gt;\nclass S : public T\n{\npublic:\n std::string foo (std::string b)\n {\n return foo2&lt;T&gt;(b,0);\n }\n\nprotected:\n template &lt;typename T&gt; std::string foo2 (std::string b, decltype (T::_a))\n {\n return b + std::to_string(T::_a);\n }\n template &lt;typename T&gt; std::string foo2 (std::string b, ...)\n {\n return b + \"No\";\n }\n};\n\nint main(int argc, char *argv[])\n{\n S&lt;HasMember&gt; d1;\n S&lt;Generic&gt; d2;\n\n std::cout &lt;&lt; d1.foo(\"HasMember: \") &lt;&lt; std::endl;\n std::cout &lt;&lt; d2.foo(\"Generic: \") &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 54867112, "author": "Abhishek", "author_id": 5321262, "author_profile": "https://Stackoverflow.com/users/5321262", "pm_score": -1, "selected": false, "text": "<pre><code>template&lt;class T&gt;\nauto optionalToString(T* obj)\n-&gt;decltype( obj-&gt;toString(), std::string() )\n{\n return obj-&gt;toString();\n}\n\ntemplate&lt;class T&gt;\nauto optionalToString(T* obj)\n-&gt;decltype( std::string() )\n{\n throw \"Error!\";\n}\n</code></pre>\n" }, { "answer_id": 61034367, "author": "Bernd", "author_id": 9099261, "author_profile": "https://Stackoverflow.com/users/9099261", "pm_score": 4, "selected": false, "text": "<p>With C++ 20 you can write the following:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template&lt;typename T&gt;\nconcept has_toString = requires(const T&amp; t) {\n t.toString();\n};\n\ntemplate&lt;typename T&gt;\nstd::string optionalToString(const T&amp; obj)\n{\n if constexpr (has_toString&lt;T&gt;)\n return obj.toString();\n else\n return \"toString not defined\";\n}\n</code></pre>\n" }, { "answer_id": 62292282, "author": "Dmytro Ovdiienko", "author_id": 1145526, "author_profile": "https://Stackoverflow.com/users/1145526", "pm_score": 4, "selected": false, "text": "<p>Yet another way to do it in C++17 (inspired by <code>boost:hana</code>).</p>\n<p>This solution does not require <code>has_something&lt;T&gt;</code> SFINAE type traits classes.</p>\n<h3>Solution</h3>\n<pre class=\"lang-cpp prettyprint-override\"><code>////////////////////////////////////////////\n// has_member implementation\n////////////////////////////////////////////\n\n#include &lt;type_traits&gt;\n\ntemplate&lt;typename T, typename F&gt;\nconstexpr auto has_member_impl(F&amp;&amp; f) -&gt; decltype(f(std::declval&lt;T&gt;()), true)\n{\n return true;\n}\n\ntemplate&lt;typename&gt;\nconstexpr bool has_member_impl(...) { return false; }\n\n#define has_member(T, EXPR) \\\n has_member_impl&lt;T&gt;( [](auto&amp;&amp; obj)-&gt;decltype(obj.EXPR){} )\n\n</code></pre>\n<h3>Test</h3>\n<pre class=\"lang-cpp prettyprint-override\"><code>////////////////////////////////////////////\n// Test\n////////////////////////////////////////////\n\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nstruct Example {\n int Foo;\n void Bar() {}\n std::string toString() { return &quot;Hello from Example::toString()!&quot;; }\n};\n\nstruct Example2 {\n int X;\n};\n\ntemplate&lt;class T&gt;\nstd::string optionalToString(T* obj)\n{\n if constexpr(has_member(T, toString()))\n return obj-&gt;toString();\n else\n return &quot;toString not defined&quot;;\n}\n\nint main() {\n static_assert(has_member(Example, Foo), \n &quot;Example class must have Foo member&quot;);\n static_assert(has_member(Example, Bar()), \n &quot;Example class must have Bar() member function&quot;);\n static_assert(!has_member(Example, ZFoo), \n &quot;Example class must not have ZFoo member.&quot;);\n static_assert(!has_member(Example, ZBar()), \n &quot;Example class must not have ZBar() member function&quot;);\n\n Example e1;\n Example2 e2;\n\n std::cout &lt;&lt; &quot;e1: &quot; &lt;&lt; optionalToString(&amp;e1) &lt;&lt; &quot;\\n&quot;;\n std::cout &lt;&lt; &quot;e1: &quot; &lt;&lt; optionalToString(&amp;e2) &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n" }, { "answer_id": 63630013, "author": "Sean", "author_id": 12854372, "author_profile": "https://Stackoverflow.com/users/12854372", "pm_score": 2, "selected": false, "text": "<p>My take: to universally determine if something is callable without making verbose type traits for each and every one, or using experimental features, or long code:</p>\n<pre><code>template&lt;typename Callable, typename... Args, typename = decltype(declval&lt;Callable&gt;()(declval&lt;Args&gt;()...))&gt;\nstd::true_type isCallableImpl(Callable, Args...) { return {}; }\n\nstd::false_type isCallableImpl(...) { return {}; }\n\ntemplate&lt;typename... Args, typename Callable&gt;\nconstexpr bool isCallable(Callable callable) {\n return decltype(isCallableImpl(callable, declval&lt;Args&gt;()...)){};\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>constexpr auto TO_STRING_TEST = [](auto in) -&gt; decltype(in.toString()) { return {}; };\nconstexpr bool TO_STRING_WORKS = isCallable&lt;T&gt;(TO_STRING_TEST);\n</code></pre>\n" }, { "answer_id": 63823318, "author": "TommyD", "author_id": 4602726, "author_profile": "https://Stackoverflow.com/users/4602726", "pm_score": 3, "selected": false, "text": "<p>I know that this question is years old, but I think it would useful for people like me to have a more complete updated answer that also works for <code>const</code> overloaded methods such as <code>std::vector&lt;&gt;::begin</code>.</p>\n<p>Based on that <a href=\"https://stackoverflow.com/a/257382/4602726\">answer</a> and that <a href=\"https://stackoverflow.com/a/63818399/4602726\">answer</a> from my follow up question, here's a more complete answer. Note that this will only work with C++11 and higher.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nclass EmptyClass{};\n\ntemplate &lt;typename T&gt;\nclass has_begin\n{\n private:\n has_begin() = delete;\n \n struct one { char x[1]; };\n struct two { char x[2]; };\n\n template &lt;typename C&gt; static one test( decltype(void(std::declval&lt;C &amp;&gt;().begin())) * ) ;\n template &lt;typename C&gt; static two test(...); \n\npublic:\n static constexpr bool value = sizeof(test&lt;T&gt;(0)) == sizeof(one);\n};\n \nint main(int argc, char *argv[])\n{\n std::cout &lt;&lt; std::boolalpha;\n std::cout &lt;&lt; &quot;vector&lt;int&gt;::begin() exists: &quot; &lt;&lt; has_begin&lt;std::vector&lt;int&gt;&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;EmptyClass::begin() exists: &quot; &lt;&lt; has_begin&lt;EmptyClass&gt;::value &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n<p>Or the shorter version:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nclass EmptyClass{};\n\ntemplate &lt;typename T, typename = void&gt;\nstruct has_begin : std::false_type {};\n\ntemplate &lt;typename T&gt;\nstruct has_begin&lt;T, decltype(void(std::declval&lt;T &amp;&gt;().begin()))&gt; : std::true_type {};\n\nint main(int argc, char *argv[])\n{\n std::cout &lt;&lt; std::boolalpha;\n std::cout &lt;&lt; &quot;vector&lt;int&gt;::begin() exists: &quot; &lt;&lt; has_begin&lt;std::vector&lt;int&gt;&gt;::value &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;EmptyClass exists: &quot; &lt;&lt; has_begin&lt;EmptyClass&gt;::value &lt;&lt; std::endl;\n}\n</code></pre>\n<p>Note that here a complete sample call must be provided. This means that if we tested for the <code>resize</code> method's existence then we would have put <code>resize(0)</code>.</p>\n<p><strong>Deep magic explanation</strong>:</p>\n<p>The first answer posted of this question used <code>test( decltype(&amp;C::helloworld) )</code>; however this is problematic when the method it is testing is ambiguous due const overloading, thus making the substitution attempt fail.</p>\n<p>To solve this ambiguity we use a void statement which can take any parameters because it is always translated into a <code>noop</code> and thus the ambiguity is nullified and the call is valid as long as the method exists:</p>\n<pre><code>has_begin&lt;T, decltype(void(std::declval&lt;T &amp;&gt;().begin()))&gt;\n</code></pre>\n<p>Here's what's happening in order:\nWe use <code>std::declval&lt;T &amp;&gt;()</code> to create a callable value for which <code>begin</code> can then be called. After that the value of <code>begin</code> is passed as a parameter to a void statement. We then retrieve the type of that void expression using the builtin <code>decltype</code> so that it can be used as a template type argument. If <code>begin</code> doesn't exist then the substitution is invalid and as per SFINAE the other declaration is used instead.</p>\n" }, { "answer_id": 64945445, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 1, "selected": false, "text": "<p>Probably not as good as other examples, but this is what I came up with for C++11. This works for picking overloaded methods.</p>\n<pre><code>template &lt;typename... Args&gt;\nstruct Pack {};\n\n#define Proxy(T) ((T &amp;)(*(int *)(nullptr)))\n\ntemplate &lt;typename Class, typename ArgPack, typename = nullptr_t&gt;\nstruct HasFoo\n{\n enum { value = false };\n};\n\ntemplate &lt;typename Class, typename... Args&gt;\nstruct HasFoo&lt;\n Class,\n Pack&lt;Args...&gt;,\n decltype((void)(Proxy(Class).foo(Proxy(Args)...)), nullptr)&gt;\n{\n enum { value = true };\n};\n</code></pre>\n<p>Example usage</p>\n<pre><code>struct Object\n{\n int foo(int n) { return n; }\n#if SOME_CONDITION\n int foo(int n, char c) { return n + c; }\n#endif\n};\n\ntemplate &lt;bool has_foo_int_char&gt;\nstruct Dispatcher;\n\ntemplate &lt;&gt;\nstruct Dispatcher&lt;false&gt;\n{\n template &lt;typename Object&gt;\n static int exec(Object &amp;object, int n, char c)\n {\n return object.foo(n) + c;\n }\n};\n\ntemplate &lt;&gt;\nstruct Dispatcher&lt;true&gt;\n{\n template &lt;typename Object&gt;\n static int exec(Object &amp;object, int n, char c)\n {\n return object.foo(n, c);\n }\n};\n\nint runExample()\n{\n using Args = Pack&lt;int, char&gt;;\n enum { has_overload = HasFoo&lt;Object, Args&gt;::value };\n Object object;\n return Dispatcher&lt;has_overload&gt;::exec(object, 100, 'a');\n}\n</code></pre>\n" }, { "answer_id": 66190295, "author": "DisplayName", "author_id": 8741818, "author_profile": "https://Stackoverflow.com/users/8741818", "pm_score": 0, "selected": false, "text": "<p>I've been looking a method that allows to somehow to not tie structure name <code>has_member</code> to name of a class' member.\nActually, this would be simpler if lambda can be allowed in unevaluated expression (this is forbidden by standard), i.e. <code>has_member&lt;ClassName, SOME_MACRO_WITH_DECLTYPE(member_name)&gt;</code></p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;list&gt;\n#include &lt;type_traits&gt;\n\n#define LAMBDA_FOR_MEMBER_NAME(NAME) [](auto object_instance) -&gt; decltype(&amp;(decltype(object_instance)::NAME)) {}\n\ntemplate&lt;typename T&gt;\nstruct TypeGetter\n{\n constexpr TypeGetter() = default;\n constexpr TypeGetter(T) {}\n using type = T;\n\n constexpr auto getValue()\n {\n return std::declval&lt;type&gt;();\n }\n};\n\ntemplate&lt;typename T, typename LambdaExpressionT&gt;\nstruct has_member {\n using lambda_prototype = LambdaExpressionT;\n\n //SFINAE\n template&lt;class ValueT, class = void&gt;\n struct is_void_t_deducable : std::false_type {};\n\n template&lt;class ValueT&gt;\n struct is_void_t_deducable&lt;ValueT,\n std::void_t&lt;decltype(std::declval&lt;lambda_prototype&gt;()(std::declval&lt;ValueT&gt;()))&gt;&gt; : std::true_type {};\n\n static constexpr bool value = is_void_t_deducable&lt;T&gt;::value;\n};\n\nstruct SimpleClass\n{\n int field;\n void method() {}\n};\n\nint main(void)\n{ \n const auto helpful_lambda = LAMBDA_FOR_MEMBER_NAME(field);\n using member_field = decltype(helpful_lambda);\n std::cout &lt;&lt; has_member&lt;SimpleClass, member_field&gt;::value;\n\n const auto lambda = LAMBDA_FOR_MEMBER_NAME(method);\n using member_method = decltype(lambda);\n std::cout &lt;&lt; has_member&lt;SimpleClass, member_method&gt;::value;\n \n}\n</code></pre>\n" }, { "answer_id": 67942658, "author": "Jean-Michaël Celerier", "author_id": 1495627, "author_profile": "https://Stackoverflow.com/users/1495627", "pm_score": 3, "selected": false, "text": "<p>Here is the most concise way I found in C++20, which is very close from your question:</p>\n<pre><code>template&lt;class T&gt;\nstd::string optionalToString(T* obj)\n{\n if constexpr (requires { obj-&gt;toString(); })\n return obj-&gt;toString();\n else\n return &quot;toString not defined&quot;;\n}\n</code></pre>\n<p>See it live on godbolt: <a href=\"https://gcc.godbolt.org/z/5jb1d93Ms\" rel=\"noreferrer\">https://gcc.godbolt.org/z/5jb1d93Ms</a></p>\n" }, { "answer_id": 69604306, "author": "Elliott", "author_id": 8658157, "author_profile": "https://Stackoverflow.com/users/8658157", "pm_score": 0, "selected": false, "text": "<h2>Pre-c++20, simple options for simple cases:</h2>\n<p>If you know your class is default constructible, we can make the syntax simpler.</p>\n<p>We'll start with the simplest case: Default constructible and we know the expected return type. Example method:</p>\n<pre><code>int foo ();\n</code></pre>\n<p>We can write the type trait without <code>declval</code>:</p>\n<pre><code>template &lt;auto v&gt;\nstruct tag_v\n{\n constexpr static auto value = v;\n};\n\ntemplate &lt;class, class = int&gt;\nstruct has_foo_method : tag_v&lt;false&gt; {};\n\ntemplate &lt;class T&gt;\nstruct has_foo_method &lt;T, decltype(T().foo())&gt;\n : tag_v&lt;true&gt; {};\n</code></pre>\n<p><a href=\"https://godbolt.org/z/9c93KoP9K\" rel=\"nofollow noreferrer\">demo</a></p>\n<p>Note that we set the default type to <code>int</code> because that's the return type of <code>foo</code>.</p>\n<p>If there's multiple acceptable return types then we add a second argument to <code>decltype</code> that's the same type as the default, overriding the first argument:</p>\n<pre><code>decltype(T().foo(), int())\n</code></pre>\n<p><a href=\"https://godbolt.org/z/7W6oW65xf\" rel=\"nofollow noreferrer\">demo</a></p>\n<p>(The <code>int</code> type here is unimportant - I use it because it's only 3 letters)</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21482/" ]
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class? Here's a simple example of what I would want to write: ``` template<class T> std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T->toString)) return obj->toString(); else return "toString not defined"; } ``` So, if `class T` has `toString()` defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION\_EXISTS" part.
Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code: ``` #include <iostream> struct Hello { int helloworld() { return 0; } }; struct Generic {}; // SFINAE test template <typename T> class has_helloworld { typedef char one; struct two { char x[2]; }; template <typename C> static one test( decltype(&C::helloworld) ) ; template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; int main(int argc, char *argv[]) { std::cout << has_helloworld<Hello>::value << std::endl; std::cout << has_helloworld<Generic>::value << std::endl; return 0; } ``` I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.
257,324
<p>I need to add 30 minutes to values in a Oracle date column. I do this in my SELECT statement by specifying </p> <p><code>to_char(date_and_time + (.000694 * 31)</code></p> <p>which works fine most of the time. But not when the time is on the AM/PM border. For example, adding 30 minutes to <code>12:30</code> [which is PM] returns <code>1:00</code> which is AM. The answer I expect is <code>13:00</code>. What's the correct way to do this?</p>
[ { "answer_id": 257337, "author": "Camilo Díaz Repka", "author_id": 861, "author_profile": "https://Stackoverflow.com/users/861", "pm_score": 1, "selected": false, "text": "<p>Be sure that Oracle understands that the starting time is PM, and to specify the HH24 format mask for the final output.</p>\n\n<pre><code>SELECT to_char((to_date('12:40 PM', 'HH:MI AM') + (1/24/60) * 30), 'HH24:MI') as time\n FROM dual\n\nTIME\n---------\n13:10\n</code></pre>\n\n<p>Note: the <code>'AM'</code> in the HH:MI is just the placeholder for the AM/PM meridian indicator. Could be also <code>'PM'</code></p>\n" }, { "answer_id": 257341, "author": "Sidnei Andersson", "author_id": 31619, "author_profile": "https://Stackoverflow.com/users/31619", "pm_score": 2, "selected": false, "text": "<p>If the data type of the field is date or timestamp, Oracle should always give the correct result if you add the correct number given in number of days (or a the correct fraction of a day in your case). So if you are trying to bump the value in 30 minutes, you should use : </p>\n\n<pre><code>select field + 0.5/24 from table;\n</code></pre>\n\n<p>Based on the information you provided, I believe this is what you tried to do and I am quite sure it works.</p>\n" }, { "answer_id": 257399, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": false, "text": "<p>In addition to being able to add a number of days to a date, you can use interval data types assuming you are on <code>Oracle 9i</code> or later, which can be somewhat easier to read,</p>\n\n<pre><code>SQL&gt; ed\nWrote file afiedt.buf\nSELECT sysdate, sysdate + interval '30' minute FROM dual\nSQL&gt; /\n\nSYSDATE SYSDATE+INTERVAL'30'\n-------------------- --------------------\n02-NOV-2008 16:21:40 02-NOV-2008 16:51:40\n</code></pre>\n" }, { "answer_id": 257662, "author": "Nathan Neulinger", "author_id": 33531, "author_profile": "https://Stackoverflow.com/users/33531", "pm_score": 0, "selected": false, "text": "<p>Based on what you're asking for, you want the HH24:MI format for to_char. </p>\n" }, { "answer_id": 258555, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 6, "selected": true, "text": "<p>All of the other answers are basically right but I don't think anyone's directly answered your original question.</p>\n\n<p>Assuming that \"date_and_time\" in your example is a column with type DATE or TIMESTAMP, I think you just need to change this:</p>\n\n<pre><code>to_char(date_and_time + (.000694 * 31))\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>to_char(date_and_time + (.000694 * 31), 'DD-MON-YYYY HH24:MI')\n</code></pre>\n\n<p>It sounds like your default date format uses the \"HH\" code for the hour, not \"HH24\".</p>\n\n<p>Also, I think your constant term is both confusing and imprecise. I guess what you did is calculate that (.000694) is about the value of a minute, and you are multiplying it by the number of minutes you want to add (31 in the example, although you said 30 in the text).</p>\n\n<p>I would also start with a day and divide it into the units you want within your code. In this case, (1/48) would be 30 minutes; or if you wanted to break it up for clarity, you could write ( (1/24) * (1/2) ).</p>\n\n<p>This would avoid rounding errors (except for those inherent in floating point which should be meaningless here) and is clearer, at least to me.</p>\n" }, { "answer_id": 2311033, "author": "crazy", "author_id": 278699, "author_profile": "https://Stackoverflow.com/users/278699", "pm_score": 4, "selected": false, "text": "<p>from <a href=\"http://www.orafaq.com/faq/how_does_one_add_a_day_hour_minute_second_to_a_date_value\" rel=\"noreferrer\">http://www.orafaq.com/faq/how_does_one_add_a_day_hour_minute_second_to_a_date_value</a></p>\n\n<p>The SYSDATE pseudo-column shows the current system date and time. Adding 1 to SYSDATE will advance the date by 1 day. Use fractions to add hours, minutes or seconds to the date</p>\n\n<pre><code>SQL&gt; select sysdate, sysdate+1/24, sysdate +1/1440, sysdate + 1/86400 from dual;\n\nSYSDATE SYSDATE+1/24 SYSDATE+1/1440 SYSDATE+1/86400\n-------------------- -------------------- -------------------- --------------------\n03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002 08:33:12 03-Jul-2002 08:32:13\n</code></pre>\n" }, { "answer_id": 4329358, "author": "saidevakumar", "author_id": 336478, "author_profile": "https://Stackoverflow.com/users/336478", "pm_score": 2, "selected": false, "text": "<p>Can we not use this</p>\n\n<pre><code>SELECT date_and_time + INTERVAL '20:00' MINUTE TO SECOND FROM dual;\n</code></pre>\n\n<p>I am new to this domain.</p>\n" }, { "answer_id": 8814626, "author": "Chirag Mehta", "author_id": 1142418, "author_profile": "https://Stackoverflow.com/users/1142418", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT to_char(sysdate + (1/24/60) * 30, 'dd/mm/yy HH24:MI am') from dual;\n</code></pre>\n\n<p>simply you can use this with various date format....</p>\n" }, { "answer_id": 17039496, "author": "jtomaszk", "author_id": 2393509, "author_profile": "https://Stackoverflow.com/users/2393509", "pm_score": 4, "selected": false, "text": "<pre><code>UPDATE \"TABLE\" \nSET DATE_FIELD = CURRENT_TIMESTAMP + interval '48' minute \nWHERE (...)\n</code></pre>\n\n<p>Where <code>interval</code> is one of </p>\n\n<ul>\n<li>YEAR</li>\n<li>MONTH</li>\n<li>DAY</li>\n<li>HOUR</li>\n<li>MINUTE</li>\n<li>SECOND</li>\n</ul>\n" }, { "answer_id": 33580076, "author": "Sam", "author_id": 5201238, "author_profile": "https://Stackoverflow.com/users/5201238", "pm_score": 0, "selected": false, "text": "<p>To edit Date in oracle you can try </p>\n\n<pre><code> select to_char(&lt;columnName&gt; + 5 / 24 + 30 / (24 * 60),\n 'DD/MM/RRRR hh:mi AM') AS &lt;logicalName&gt; from &lt;tableName&gt;\n</code></pre>\n" }, { "answer_id": 40459784, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 4, "selected": false, "text": "<p>I prefer using an <code>interval</code> literal for this, because <code>interval '30' minute</code> or <code>interval '5' second</code> is a lot easier to read then <code>30 / (24 * 60)</code> or <code>5 / (24 * 60 * 69)</code> </p>\n\n<p>e.g. </p>\n\n<ul>\n<li><code>some_date + interval '2' hour</code></li>\n<li><code>some_date + interval '30' minute</code></li>\n<li><code>some_date + interval '5' second</code></li>\n<li><code>some_date + interval '2' day</code></li>\n</ul>\n\n<p>You can also combine several units into one expression:</p>\n\n<ul>\n<li><code>some_date + interval '2 3:06' day to minute</code> </li>\n</ul>\n\n<p>Adds 2 days, 3 hours and 6 minutes to the date value</p>\n\n<p>The above is also standard SQL and also works in several other DBMS. </p>\n\n<p>More details in the manual: <a href=\"https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF00221\" rel=\"noreferrer\">https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF00221</a></p>\n" }, { "answer_id": 53806710, "author": "Bilal", "author_id": 2016070, "author_profile": "https://Stackoverflow.com/users/2016070", "pm_score": 2, "selected": false, "text": "<p>like that very easily</p>\n\n<p>i added 10 minutes to system date and always in preference use the Db server functions not custom one .</p>\n\n<pre><code>select to_char(sysdate + NUMTODSINTERVAL(10,'MINUTE'),'DD/MM/YYYY HH24:MI:SS') from dual;\n</code></pre>\n" }, { "answer_id": 63854245, "author": "Julius Simon", "author_id": 5993387, "author_profile": "https://Stackoverflow.com/users/5993387", "pm_score": 0, "selected": false, "text": "<p>Oracle now has new built in functions to do this:</p>\n<pre><code>select systimestamp START_TIME, systimestamp + NUMTODSINTERVAL(30, 'minute') end_time from dual\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
I need to add 30 minutes to values in a Oracle date column. I do this in my SELECT statement by specifying `to_char(date_and_time + (.000694 * 31)` which works fine most of the time. But not when the time is on the AM/PM border. For example, adding 30 minutes to `12:30` [which is PM] returns `1:00` which is AM. The answer I expect is `13:00`. What's the correct way to do this?
All of the other answers are basically right but I don't think anyone's directly answered your original question. Assuming that "date\_and\_time" in your example is a column with type DATE or TIMESTAMP, I think you just need to change this: ``` to_char(date_and_time + (.000694 * 31)) ``` to this: ``` to_char(date_and_time + (.000694 * 31), 'DD-MON-YYYY HH24:MI') ``` It sounds like your default date format uses the "HH" code for the hour, not "HH24". Also, I think your constant term is both confusing and imprecise. I guess what you did is calculate that (.000694) is about the value of a minute, and you are multiplying it by the number of minutes you want to add (31 in the example, although you said 30 in the text). I would also start with a day and divide it into the units you want within your code. In this case, (1/48) would be 30 minutes; or if you wanted to break it up for clarity, you could write ( (1/24) \* (1/2) ). This would avoid rounding errors (except for those inherent in floating point which should be meaningless here) and is clearer, at least to me.
257,339
<p>I've never done it myself, and I've never subscribed to a feed, but it seems that I'm going to have to create one, so I'm wondering. The only way that seems apparent to me is that when the system is updated with a new item (blog post, news item, whatever), a new element should be written to the rss file. Or alternatively have a script that checks for updates to the system a few times a day and writes to the rss file is there is. There's probably a better way of doing it though.</p> <p>And also, should old elements be removed as new ones are added? </p> <p><strong>Edit</strong>: I should have mentioned, I'm working in PHP, specifically using CodeIgniter, with a mySQL database.</p>
[ { "answer_id": 257354, "author": "Drew Olson", "author_id": 9434, "author_profile": "https://Stackoverflow.com/users/9434", "pm_score": 2, "selected": false, "text": "<p>I'd say the answer is having an RSS feed be nothing more than another view of your data. This means that your rss feed is simply an xml representation of the data in your database. Readers will then be able to hit that specific url and get back the current information in your application.</p>\n" }, { "answer_id": 257355, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "<p>An RSS Feed is just an XML Document that conforms to a specific schema. </p>\n\n<p>Have a look <a href=\"http://www.xml.com/pub/a/2002/12/18/dive-into-xml.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>What language are you working in? You can easily script the xml output based on some content in your application. You don't need to explicitly save the file to the file system.\nIt can just be created on the fly</p>\n" }, { "answer_id": 257366, "author": "Nick", "author_id": 14072, "author_profile": "https://Stackoverflow.com/users/14072", "pm_score": 0, "selected": false, "text": "<p>Here's a simple ASP.NET 2 based RSS feed I use as a live bookmark for my localhost dev sites. Might help you get started:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" EnableViewState=\"false\" %&gt;\n&lt;%@ OutputCache Duration=\"300\" VaryByParam=\"none\" %&gt;\n\n&lt;%@ Import Namespace=\"System\" %&gt;\n&lt;%@ Import Namespace=\"System.Configuration\" %&gt;\n&lt;%@ Import Namespace=\"System.Web\" %&gt;\n&lt;%@ Import Namespace=\"System.Web.Security\" %&gt;\n&lt;%@ Import Namespace=\"System.Data\" %&gt;\n&lt;%@ Import Namespace=\"System.Xml\" %&gt;\n&lt;%@ Import Namespace=\"System.Text\" %&gt;\n&lt;%@ Import Namespace=\"System.DirectoryServices\" %&gt;\n\n&lt;script runat=\"server\"&gt;\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n System.Collections.Specialized.StringCollection HideSites = new StringCollection();\n System.Collections.Generic.List&lt;string&gt; Sites = new System.Collections.Generic.List&lt;string&gt;();\n\n HideSites.Add(@\"IISHelp\");\n HideSites.Add(@\"MSMQ\");\n HideSites.Add(@\"Printers\");\n\n DirectoryEntry entry = new DirectoryEntry(\"IIS://LocalHost/W3SVC/1/ROOT\");\n foreach (DirectoryEntry site in entry.Children)\n {\n if (site.SchemaClassName == \"IIsWebVirtualDir\" &amp;&amp; !HideSites.Contains(site.Name))\n {\n Sites.Add(site.Name);\n }\n }\n\n Sites.Sort();\n\n Response.Clear();\n Response.ContentType = \"text/xml\";\n XmlTextWriter RSS = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);\n RSS.WriteStartDocument();\n RSS.WriteStartElement(\"rss\");\n RSS.WriteAttributeString(\"version\",\"2.0\");\n RSS.WriteStartElement(\"channel\");\n RSS.WriteElementString(\"title\", \"Localhost Websites\");\n RSS.WriteElementString(\"link\",\"http://localhost/sitelist.aspx\");\n RSS.WriteElementString(\"description\",\"localhost websites\");\n\n foreach (string s in Sites)\n {\n RSS.WriteStartElement(\"item\");\n RSS.WriteElementString(\"title\", s);\n RSS.WriteElementString(\"link\", \"http://localhost/\" + s);\n RSS.WriteEndElement();\n }\n\n RSS.WriteEndElement();\n RSS.WriteEndElement();\n RSS.WriteEndDocument();\n RSS.Flush();\n RSS.Close();\n Response.End();\n}\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 257377, "author": "Greg B", "author_id": 1741868, "author_profile": "https://Stackoverflow.com/users/1741868", "pm_score": 0, "selected": false, "text": "<p>An RSS feed is just an XML document formatted in a certain way and linked to from a web page.</p>\n\n<p>Take a look at this page (<a href=\"http://cyber.law.harvard.edu/rss/rss.html\" rel=\"nofollow noreferrer\">http://cyber.law.harvard.edu/rss/rss.html</a>) which details\nthe RSS specification, gives example RSS files for you to look at and shows you how to link to them from your site.</p>\n\n<p>How you create the document is up to you. You could write it manually in a text editor, use a language specific XML object, or hit an ASPX/PHP/other page and send the correct content type headers along with the RSS document.</p>\n\n<p>It's not all that hard when you get down to it. good luck!</p>\n" }, { "answer_id": 257395, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 2, "selected": false, "text": "<p>I've got good results from <a href=\"http://magpierss.sourceforge.net/\" rel=\"nofollow noreferrer\">Magpie RSS</a>. Set up the included cacheing and all you need to do is write the query to retrieve your data and send the result to Magpie RSS, which then handles the update frequency. </p>\n\n<p>I wouldn't be writing an RSS file, unless your server is under particularly heavy load - one query (or a series of queries that adds to an array) for updated stuff is all you need. Write the query/ies to be sorted by date and then limited by X and you won't need to worry about 'removing old stuff' either.</p>\n" }, { "answer_id": 257448, "author": "Scott Reynen", "author_id": 10837, "author_profile": "https://Stackoverflow.com/users/10837", "pm_score": 0, "selected": false, "text": "<p>There are two ways to approach this. The first is to create the RSS document dynamically on request. The second is to write to a static file when a relevant change happens. The latter is faster, but requires a call to update the feed in (likely) many places vs. just one.</p>\n\n<p>With both methods, while you could edit the document with only the changes, it's much simpler to just rewrite the whole document every time with the most recent (10-50) items.</p>\n" }, { "answer_id": 257987, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 3, "selected": false, "text": "<p>For PHP I use feedcreator\n<a href=\"http://feedcreator.org/\" rel=\"nofollow noreferrer\">http://feedcreator.org/</a></p>\n\n<pre><code>&lt;?php define ('CONFIG_SYSTEM_URL','http://www.domain.tld/');\n\nrequire_once('feedcreator/feedcreator.class.php');\n\n$feedformat='RSS2.0';\n\nheader('Content-type: application/xml');\n\n$rss = new UniversalFeedCreator();\n$rss-&gt;useCached();\n$rss-&gt;title = \"Item List\";\n$rss-&gt;cssStyleSheet='';\n$rss-&gt;description = 'this feed';\n$rss-&gt;link = CONFIG_SYSTEM_URL;\n$rss-&gt;syndicationURL = CONFIG_SYSTEM_URL.'feed.php';\n\n\n$articles=new itemList(); // list of stuff\nforeach ($articles as $i) { \n $item = new FeedItem();\n $item-&gt;title = sprintf('%s',$i-&gt;title);\n $item-&gt;link = CONFIG_SYSTEM_URL.'item.php?id='.$i-&gt;dbId;\n $item-&gt;description = $i-&gt;Subject; \n $item-&gt;date = $i-&gt;ModifyDate; \n $item-&gt;source = CONFIG_SYSTEM_URL; \n $item-&gt;author = $i-&gt;User;\n $rss-&gt;addItem($item);\n}\n\nprint $rss-&gt;createFeed($feedformat);\n</code></pre>\n" }, { "answer_id": 261388, "author": "Ciaran McNulty", "author_id": 34024, "author_profile": "https://Stackoverflow.com/users/34024", "pm_score": 0, "selected": false, "text": "<p>If you want to generate a feed of elements that already exist in HTML, one option is to modify your HTML markup to use hAtom (<a href=\"http://microformats.org/wiki/hAtom\" rel=\"nofollow noreferrer\">http://microformats.org/wiki/hAtom</a>) and then point feed readers through an hAtom->Atom or hAtom->RSS proxy.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12765/" ]
I've never done it myself, and I've never subscribed to a feed, but it seems that I'm going to have to create one, so I'm wondering. The only way that seems apparent to me is that when the system is updated with a new item (blog post, news item, whatever), a new element should be written to the rss file. Or alternatively have a script that checks for updates to the system a few times a day and writes to the rss file is there is. There's probably a better way of doing it though. And also, should old elements be removed as new ones are added? **Edit**: I should have mentioned, I'm working in PHP, specifically using CodeIgniter, with a mySQL database.
For PHP I use feedcreator <http://feedcreator.org/> ``` <?php define ('CONFIG_SYSTEM_URL','http://www.domain.tld/'); require_once('feedcreator/feedcreator.class.php'); $feedformat='RSS2.0'; header('Content-type: application/xml'); $rss = new UniversalFeedCreator(); $rss->useCached(); $rss->title = "Item List"; $rss->cssStyleSheet=''; $rss->description = 'this feed'; $rss->link = CONFIG_SYSTEM_URL; $rss->syndicationURL = CONFIG_SYSTEM_URL.'feed.php'; $articles=new itemList(); // list of stuff foreach ($articles as $i) { $item = new FeedItem(); $item->title = sprintf('%s',$i->title); $item->link = CONFIG_SYSTEM_URL.'item.php?id='.$i->dbId; $item->description = $i->Subject; $item->date = $i->ModifyDate; $item->source = CONFIG_SYSTEM_URL; $item->author = $i->User; $rss->addItem($item); } print $rss->createFeed($feedformat); ```
257,343
<p>If I have a range of say <code>000080-0007FF</code> and I want to see if a char containing hex is within that range, how can I do it?</p> <p>Example</p> <pre><code>char t = 0xd790; if (t is within range of 000080-0007FF) // true </code></pre>
[ { "answer_id": 257346, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<pre><code>wchar_t t = 0xd790;\n\nif (t &gt;= 0x80 &amp;&amp; t &lt;= 0x7ff) ...\n</code></pre>\n\n<p>In C++, characters are interchangeable with integers and you can compare their values directly.</p>\n\n<p>Note that I used <code>wchar_t</code>, because the <code>char</code> data type can only hold values up to 0xFF.</p>\n" }, { "answer_id": 257372, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "<pre><code>unsigned short t = 0xd790;\n\nif (t &gt;= 0x80 &amp;&amp; t &lt;= 0x7ff) ...\n</code></pre>\n\n<p>Since a char has a max value of 0xFF you cannot use it to compare anything with more hex digits than 2. </p>\n" }, { "answer_id": 257386, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 0, "selected": false, "text": "<p>Since hex on a computer is nothing more than a way to print a number (like decimal), you can also do your comparison with plain old base 10 integers.</p>\n\n<pre><code>if( (t &gt;= 128) &amp;&amp; (t &lt;= 2047) )\n{\n}\n</code></pre>\n\n<p>More readable.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
If I have a range of say `000080-0007FF` and I want to see if a char containing hex is within that range, how can I do it? Example ``` char t = 0xd790; if (t is within range of 000080-0007FF) // true ```
``` wchar_t t = 0xd790; if (t >= 0x80 && t <= 0x7ff) ... ``` In C++, characters are interchangeable with integers and you can compare their values directly. Note that I used `wchar_t`, because the `char` data type can only hold values up to 0xFF.
257,350
<p>I need to create a form with, half linear view (textboxes and dropdownlists in separate line) and the other half, non linear view i.e. the textboxes will appear next to each other, like first name and last name will be next to each other. </p> <p>I am aware how to acomplish the linear view with CSS. I am using</p> <pre><code>fieldset { clear: both; font-size: 100%; border-color: #000000; border-width: 1px 0 0 0; border-style: solid none none none; padding: 10px; margin: 0 0 0 0; } label { float: left; width: 10em; text-align:right; } </code></pre> <p>How can I get the non-linear view?</p>
[ { "answer_id": 257370, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 2, "selected": true, "text": "<p>if you also float:left, set a width and display:inline the other input fields, the should appear on the same line</p>\n" }, { "answer_id": 257995, "author": "Cyril Gupta", "author_id": 33052, "author_profile": "https://Stackoverflow.com/users/33052", "pm_score": 0, "selected": false, "text": "<p><code>display: inline</code> puts the item on the same line. </p>\n\n<p><code>display: block</code> gives the item an entire line of its own.</p>\n\n<p><code>float: left</code> floats the item to the left.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
I need to create a form with, half linear view (textboxes and dropdownlists in separate line) and the other half, non linear view i.e. the textboxes will appear next to each other, like first name and last name will be next to each other. I am aware how to acomplish the linear view with CSS. I am using ``` fieldset { clear: both; font-size: 100%; border-color: #000000; border-width: 1px 0 0 0; border-style: solid none none none; padding: 10px; margin: 0 0 0 0; } label { float: left; width: 10em; text-align:right; } ``` How can I get the non-linear view?
if you also float:left, set a width and display:inline the other input fields, the should appear on the same line
257,391
<p>I have a const char arr[] parameter that I am trying to iterate over,</p> <pre><code>char *ptr; for (ptr= arr; *ptr!= '\0'; ptr++) /* some code*/ </code></pre> <p>I get an error: assignment discards qualifiers from pointer target type</p> <p>Are const char [] handled differently than non-const?</p>
[ { "answer_id": 257394, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 5, "selected": true, "text": "<p>Switch the declaration of *ptr to be.</p>\n\n<pre><code>const char* ptr;\n</code></pre>\n\n<p>The problem is you are essentially assigning a const char* to a char*. This is a violation of const since you're going from a const to a non-const. </p>\n" }, { "answer_id": 257420, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 3, "selected": false, "text": "<p>As JaredPar said, change ptr's declaration to</p>\n\n<pre><code>const char* ptr;\n</code></pre>\n\n<p>And it should work. Although it looks surprising (how can you iterate a const pointer?), you're actually saying the pointed-to character is const, not the pointer itself. In fact, there are two different places you can apply const (and/or volatile) in a pointer declaration, with each of the 4 permutations having a slightly different meaning. Here are the options:</p>\n\n<pre><code>char* ptr; // Both pointer &amp; pointed-to value are non-const\nconst char* ptr; // Pointed-to value is const, pointer is non-const \nchar* const ptr; // Pointed-to value is non-const, pointer is const\nconst char* const ptr; // Both pointer &amp; pointed-to value are const.\n</code></pre>\n\n<p>Somebody (I think Scott Meyers) said you should read pointer declarations inside out, i.e.:</p>\n\n<pre><code>const char* const ptr;\n</code></pre>\n\n<p>...would be read as \"ptr is a constant pointer to a character that is constant\".</p>\n\n<p>Good luck!</p>\n\n<p>Drew</p>\n" }, { "answer_id": 19409694, "author": "JimmyJohn", "author_id": 2887426, "author_profile": "https://Stackoverflow.com/users/2887426", "pm_score": 0, "selected": false, "text": "<p>The const declaration grabs whatever is to the left. If there is nothing it looks right.</p>\n" }, { "answer_id": 21558668, "author": "Paul DesRivieres", "author_id": 3271839, "author_profile": "https://Stackoverflow.com/users/3271839", "pm_score": 0, "selected": false, "text": "<p>For interation loops like the above where you don't care about the value returned you should say <code>++ptr</code> rather than <code>ptr++</code>.</p>\n\n<p><code>ptr++</code> means:</p>\n\n<pre><code>temp = *ptr;\n++ptr;\nreturn temp;`\n</code></pre>\n\n<p><code>++ptr</code> means:</p>\n\n<pre><code>++ptr;\nreturn *ptr;\n</code></pre>\n\n<p>For the primitive types, the compiler will apply this optimization but won't when iterating over C++ objects so you should get in the habit of writing it the right way.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I have a const char arr[] parameter that I am trying to iterate over, ``` char *ptr; for (ptr= arr; *ptr!= '\0'; ptr++) /* some code*/ ``` I get an error: assignment discards qualifiers from pointer target type Are const char [] handled differently than non-const?
Switch the declaration of \*ptr to be. ``` const char* ptr; ``` The problem is you are essentially assigning a const char\* to a char\*. This is a violation of const since you're going from a const to a non-const.
257,396
<p>I'm having some trouble understanding how command parameter binding works.</p> <p>When I create an instance of the widget class before the call to InitializeComponent it seems to work fine. Modifications to the parameter(Widget) in the ExecuteCommand function will be "applied" to _widget. This is the behavior I expected. </p> <p>If the instance of _widget is created after InitializeComponent, I get null reference exceptions for e.Parameter in the ExecuteCommand function.</p> <p>Why is this? How do I make this work with MVP pattern, where the bound object may get created after the view is created?</p> <pre><code>public partial class WidgetView : Window { RoutedCommand _doSomethingCommand = new RoutedCommand(); Widget _widget; public WidgetView() { _widget = new Widget(); InitializeComponent(); this.CommandBindings.Add(new CommandBinding(DoSomethingCommand, ExecuteCommand, CanExecuteCommand)); } public Widget TestWidget { get { return _widget; } set { _widget = value; } } public RoutedCommand DoSomethingCommand { get { return _doSomethingCommand; } } private static void CanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (e.Parameter == null) e.CanExecute = true; else { e.CanExecute = ((Widget)e.Parameter).Count &lt; 2; } } private static void ExecuteCommand(object sender, ExecutedRoutedEventArgs e) { ((Widget)e.Parameter).DoSomething(); } } &lt;Window x:Class="CommandParameterTest.WidgetView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WidgetView" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"&gt; &lt;StackPanel&gt; &lt;Button Name="_Button" Command="{Binding DoSomethingCommand}" CommandParameter="{Binding TestWidget}"&gt;Do Something&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Window&gt; public class Widget { public int Count = 0; public void DoSomething() { Count++; } } </code></pre>
[ { "answer_id": 257508, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 2, "selected": false, "text": "<p>InitializeCompenent processes the xaml associated with the file. It is at this point in time that the CommandParameter binding is first processed. If you initialize your field before InitializeCompenent then your property will not be null. If you create it after then it is null.</p>\n\n<p>If you want to create the widget after InitializeCompenent then you will need to use a dependency property. The dependency proeprty will raise a notification that will cause the CommandParameter to be updated and thus it will not be null.</p>\n\n<p>Here is a sample of how to make TestWidget a dependency property.</p>\n\n<pre><code>public static readonly DependencyProperty TestWidgetProperty =\n DependencyProperty.Register(\"TestWidget\", typeof(Widget), typeof(Window1), new UIPropertyMetadata(null));\npublic Widget TestWidget\n{\n get { return (Widget) GetValue(TestWidgetProperty); }\n set { SetValue(TestWidgetProperty, value); }\n}\n</code></pre>\n" }, { "answer_id": 385650, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Even with the dependency property, you still need to call CommandManager.InvalidateRequerySuggested to force the CanExecute of the Command being evaluated.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22522/" ]
I'm having some trouble understanding how command parameter binding works. When I create an instance of the widget class before the call to InitializeComponent it seems to work fine. Modifications to the parameter(Widget) in the ExecuteCommand function will be "applied" to \_widget. This is the behavior I expected. If the instance of \_widget is created after InitializeComponent, I get null reference exceptions for e.Parameter in the ExecuteCommand function. Why is this? How do I make this work with MVP pattern, where the bound object may get created after the view is created? ``` public partial class WidgetView : Window { RoutedCommand _doSomethingCommand = new RoutedCommand(); Widget _widget; public WidgetView() { _widget = new Widget(); InitializeComponent(); this.CommandBindings.Add(new CommandBinding(DoSomethingCommand, ExecuteCommand, CanExecuteCommand)); } public Widget TestWidget { get { return _widget; } set { _widget = value; } } public RoutedCommand DoSomethingCommand { get { return _doSomethingCommand; } } private static void CanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (e.Parameter == null) e.CanExecute = true; else { e.CanExecute = ((Widget)e.Parameter).Count < 2; } } private static void ExecuteCommand(object sender, ExecutedRoutedEventArgs e) { ((Widget)e.Parameter).DoSomething(); } } <Window x:Class="CommandParameterTest.WidgetView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WidgetView" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <StackPanel> <Button Name="_Button" Command="{Binding DoSomethingCommand}" CommandParameter="{Binding TestWidget}">Do Something</Button> </StackPanel> </Window> public class Widget { public int Count = 0; public void DoSomething() { Count++; } } ```
InitializeCompenent processes the xaml associated with the file. It is at this point in time that the CommandParameter binding is first processed. If you initialize your field before InitializeCompenent then your property will not be null. If you create it after then it is null. If you want to create the widget after InitializeCompenent then you will need to use a dependency property. The dependency proeprty will raise a notification that will cause the CommandParameter to be updated and thus it will not be null. Here is a sample of how to make TestWidget a dependency property. ``` public static readonly DependencyProperty TestWidgetProperty = DependencyProperty.Register("TestWidget", typeof(Widget), typeof(Window1), new UIPropertyMetadata(null)); public Widget TestWidget { get { return (Widget) GetValue(TestWidgetProperty); } set { SetValue(TestWidgetProperty, value); } } ```
257,409
<p>I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. All the images are part of the HTML page.</p>
[ { "answer_id": 257412, "author": "user20955", "author_id": 20955, "author_profile": "https://Stackoverflow.com/users/20955", "pm_score": 3, "selected": false, "text": "<p>You have to download the page and parse html document, find your image with regex and download it.. You can use urllib2 for downloading and Beautiful Soup for parsing html file.</p>\n" }, { "answer_id": 257413, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "<p>Use htmllib to extract all img tags (override do_img), then use urllib2 to download all the images.</p>\n" }, { "answer_id": 258511, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 7, "selected": true, "text": "<p>Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs.</p>\n\n<pre><code>\"\"\"\ndumpimages.py\n Downloads all the images on the supplied URL, and saves them to the\n specified output file (\"/test/\" by default)\n\nUsage:\n python dumpimages.py http://example.com/ [output]\n\"\"\"\nfrom bs4 import BeautifulSoup as bs\nfrom urllib.request import (\n urlopen, urlparse, urlunparse, urlretrieve)\nimport os\nimport sys\n\ndef main(url, out_folder=\"/test/\"):\n \"\"\"Downloads all the images at 'url' to /test/\"\"\"\n soup = bs(urlopen(url))\n parsed = list(urlparse(url))\n\n for image in soup.findAll(\"img\"):\n print(\"Image: %(src)s\" % image)\n filename = image[\"src\"].split(\"/\")[-1]\n parsed[2] = image[\"src\"]\n outpath = os.path.join(out_folder, filename)\n if image[\"src\"].lower().startswith(\"http\"):\n urlretrieve(image[\"src\"], outpath)\n else:\n urlretrieve(urlunparse(parsed), outpath)\n\ndef _usage():\n print(\"usage: python dumpimages.py http://example.com [outpath]\")\n\nif __name__ == \"__main__\":\n url = sys.argv[-1]\n out_folder = \"/test/\"\n if not url.lower().startswith(\"http\"):\n out_folder = sys.argv[-1]\n url = sys.argv[-2]\n if not url.lower().startswith(\"http\"):\n _usage()\n sys.exit(-1)\n main(url, out_folder)\n</code></pre>\n\n<p><strong>Edit:</strong> You can specify the output folder now.</p>\n" }, { "answer_id": 2448326, "author": "Dingo", "author_id": 291667, "author_profile": "https://Stackoverflow.com/users/291667", "pm_score": 3, "selected": false, "text": "<p>And this is function for download one image:</p>\n\n<pre><code>def download_photo(self, img_url, filename):\n file_path = \"%s%s\" % (DOWNLOADED_IMAGE_PATH, filename)\n downloaded_image = file(file_path, \"wb\")\n\n image_on_web = urllib.urlopen(img_url)\n while True:\n buf = image_on_web.read(65536)\n if len(buf) == 0:\n break\n downloaded_image.write(buf)\n downloaded_image.close()\n image_on_web.close()\n\n return file_path\n</code></pre>\n" }, { "answer_id": 4200547, "author": "Catherine Devlin", "author_id": 86209, "author_profile": "https://Stackoverflow.com/users/86209", "pm_score": 4, "selected": false, "text": "<p>Ryan's solution is good, but fails if the image source URLs are absolute URLs or anything that doesn't give a good result when simply concatenated to the main page URL. urljoin recognizes absolute vs. relative URLs, so replace the loop in the middle with:</p>\n\n<pre><code>for image in soup.findAll(\"img\"):\n print \"Image: %(src)s\" % image\n image_url = urlparse.urljoin(url, image['src'])\n filename = image[\"src\"].split(\"/\")[-1]\n outpath = os.path.join(out_folder, filename)\n urlretrieve(image_url, outpath)\n</code></pre>\n" }, { "answer_id": 24837891, "author": "Lerner Zhang", "author_id": 3552975, "author_profile": "https://Stackoverflow.com/users/3552975", "pm_score": 1, "selected": false, "text": "<p>If the request need an authorization refer to this one:</p>\n\n<pre><code>r_img = requests.get(img_url, auth=(username, password)) \nf = open('000000.jpg','wb') \nf.write(r_img.content) \nf.close()\n</code></pre>\n" }, { "answer_id": 71616051, "author": "imbr", "author_id": 1207193, "author_profile": "https://Stackoverflow.com/users/1207193", "pm_score": 1, "selected": false, "text": "<h3>Based on <a href=\"https://stackoverflow.com/a/62207356/1207193\">code here</a></h3>\n<p>Removing some lines of code, you'll get only the images <code>img</code> tags.</p>\n<p>Uses Python 3+ <em><a href=\"https://2.python-requests.org/en/master/\" rel=\"nofollow noreferrer\">Requests</a></em>, <em><a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#\" rel=\"nofollow noreferrer\">BeautifulSoup</a></em> and other standard libraries.</p>\n<pre><code>import os, sys\nimport requests\nfrom urllib import parse\nfrom bs4 import BeautifulSoup\nimport re\n</code></pre>\n<pre><code>def savePageImages(url, imagespath='images'):\n def soupfindnSave(pagefolder, tag2find='img', inner='src'):\n if not os.path.exists(pagefolder): # create only once\n os.mkdir(pagefolder)\n for res in soup.findAll(tag2find): \n if res.has_attr(inner): # check inner tag (file object) MUST exists\n try:\n filename, ext = os.path.splitext(os.path.basename(res[inner])) # get name and extension\n filename = re.sub('\\W+', '', filename) + ext # clean special chars from name\n fileurl = parse.urljoin(url, res.get(inner))\n filepath = os.path.join(pagefolder, filename)\n if not os.path.isfile(filepath): # was not downloaded\n with open(filepath, 'wb') as file:\n filebin = session.get(fileurl)\n file.write(filebin.content)\n except Exception as exc:\n print(exc, file=sys.stderr) \n session = requests.Session()\n #... whatever other requests config you need here\n response = session.get(url)\n soup = BeautifulSoup(response.text, &quot;html.parser&quot;)\n soupfindnSave(imagespath, 'img', 'src')\n</code></pre>\n<p>Use like this bellow to save the <code>google.com</code> page images in a folder <code>google_images</code>:</p>\n<pre><code>savePageImages('https://www.google.com', 'google_images')\n</code></pre>\n" }, { "answer_id": 73352797, "author": "Hassan Zamir", "author_id": 14905611, "author_profile": "https://Stackoverflow.com/users/14905611", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>import urllib.request as req\n\nwith req.urlopen(image_link) as d, open(image_location, &quot;wb&quot;) as image_object:\n data = d.read()\n image_object.write(data)\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. All the images are part of the HTML page.
Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs. ``` """ dumpimages.py Downloads all the images on the supplied URL, and saves them to the specified output file ("/test/" by default) Usage: python dumpimages.py http://example.com/ [output] """ from bs4 import BeautifulSoup as bs from urllib.request import ( urlopen, urlparse, urlunparse, urlretrieve) import os import sys def main(url, out_folder="/test/"): """Downloads all the images at 'url' to /test/""" soup = bs(urlopen(url)) parsed = list(urlparse(url)) for image in soup.findAll("img"): print("Image: %(src)s" % image) filename = image["src"].split("/")[-1] parsed[2] = image["src"] outpath = os.path.join(out_folder, filename) if image["src"].lower().startswith("http"): urlretrieve(image["src"], outpath) else: urlretrieve(urlunparse(parsed), outpath) def _usage(): print("usage: python dumpimages.py http://example.com [outpath]") if __name__ == "__main__": url = sys.argv[-1] out_folder = "/test/" if not url.lower().startswith("http"): out_folder = sys.argv[-1] url = sys.argv[-2] if not url.lower().startswith("http"): _usage() sys.exit(-1) main(url, out_folder) ``` **Edit:** You can specify the output folder now.
257,418
<p>I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)</p> <p>Is it good for anything else? Do you use it?</p>
[ { "answer_id": 257421, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 7, "selected": false, "text": "<p>It is a way to simplify error checking and avoid deep nested if's. For example:</p>\n\n<pre><code>do {\n // do something\n if (error) {\n break;\n }\n // do something else\n if (error) {\n break;\n }\n // etc..\n} while (0);\n</code></pre>\n" }, { "answer_id": 257422, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": -1, "selected": false, "text": "<p>Generically, <code>do</code>/<code>while</code> is good for any sort of loop construct where one must execute the loop <em>at least</em> once. It is possible to emulate this sort of looping through either a straight <code>while</code> or even a <code>for</code> loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:</p>\n\n<pre><code>do {\n char c = read_input();\n\n process_input(c);\n} while (c != 'Q');\n</code></pre>\n" }, { "answer_id": 257424, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 7, "selected": false, "text": "<p>It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:</p>\n\n<pre><code>#define FOO(n) foo(n);bar(n)\n</code></pre>\n\n<p>and you do:</p>\n\n<pre><code>void foobar(int n) {\n if (n)\n FOO(n);\n}\n</code></pre>\n\n<p>then this expands to:</p>\n\n<pre><code>void foobar(int n) {\n if (n)\n foo(n);bar(n);\n}\n</code></pre>\n\n<p>Notice that the second call <code>bar(n)</code> is not part of the <code>if</code> statement anymore.</p>\n\n<p>Wrap both into <code>do { } while(0)</code>, and you can also use the macro in an <code>if</code> statement.</p>\n" }, { "answer_id": 257425, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": true, "text": "<p>It's the only construct in C that you can use to <code>#define</code> a multistatement operation, put a semicolon after, and still use within an <code>if</code> statement. An example might help:</p>\n\n<pre><code>#define FOO(x) foo(x); bar(x)\n\nif (condition)\n FOO(x);\nelse // syntax error here\n ...;\n</code></pre>\n\n<p>Even using braces doesn't help:</p>\n\n<pre><code>#define FOO(x) { foo(x); bar(x); }\n</code></pre>\n\n<p>Using this in an <code>if</code> statement would require that you omit the semicolon, which is counterintuitive:</p>\n\n<pre><code>if (condition)\n FOO(x)\nelse\n ...\n</code></pre>\n\n<p>If you define FOO like this:</p>\n\n<pre><code>#define FOO(x) do { foo(x); bar(x); } while (0)\n</code></pre>\n\n<p>then the following is syntactically correct:</p>\n\n<pre><code>if (condition)\n FOO(x);\nelse\n ....\n</code></pre>\n" }, { "answer_id": 4627814, "author": "ubuntu-fanboy", "author_id": 552429, "author_profile": "https://Stackoverflow.com/users/552429", "pm_score": 4, "selected": false, "text": "<p>It is interesting to note the following situation where the do {} while (0) loop <strong>won't</strong> work for you:</p>\n\n<p>If you want a function-like macro that returns a value, then you will need a <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html\">statement expression</a>: ({stmt; stmt;}) instead of do {} while(0):</p>\n\n<pre><code>\n#include &lt;stdio.h&gt;\n\n#define log_to_string1(str, fmt, arg...) \\\n do { \\\n sprintf(str, \"%s: \" fmt, \"myprog\", ##arg); \\\n } while (0)\n\n#define log_to_string2(str, fmt, arg...) \\\n ({ \\\n sprintf(str, \"%s: \" fmt, \"myprog\", ##arg); \\\n })\n\nint main() {\n char buf[1000];\n int n = 0;\n\n log_to_string1(buf, \"%s\\n\", \"No assignment, OK\");\n\n n += log_to_string1(buf + n, \"%s\\n\", \"NOT OK: gcc: error: expected expression before 'do'\");\n\n n += log_to_string2(buf + n, \"%s\\n\", \"This fixes it\");\n n += log_to_string2(buf + n, \"%s\\n\", \"Assignment worked!\");\n printf(\"%s\", buf);\n return 0;\n}\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31515/" ]
I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.) Is it good for anything else? Do you use it?
It's the only construct in C that you can use to `#define` a multistatement operation, put a semicolon after, and still use within an `if` statement. An example might help: ``` #define FOO(x) foo(x); bar(x) if (condition) FOO(x); else // syntax error here ...; ``` Even using braces doesn't help: ``` #define FOO(x) { foo(x); bar(x); } ``` Using this in an `if` statement would require that you omit the semicolon, which is counterintuitive: ``` if (condition) FOO(x) else ... ``` If you define FOO like this: ``` #define FOO(x) do { foo(x); bar(x); } while (0) ``` then the following is syntactically correct: ``` if (condition) FOO(x); else .... ```
257,462
<p>So I have this c# application that needs to ping my web server thats running linux/php stack.<br> I am having problems with the c# way of base 64 encoding bytes.</p> <p>my c# code is like:</p> <pre><code>byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string"); String enc = Convert.ToBase64String(encbuff); </code></pre> <p>and php side:</p> <pre><code>$data = $_REQUEST['in']; $raw = base64_decode($data); </code></pre> <p>with larger strings 100+ chars it fails. I think this is due to c# adding '+'s in the encoding but not sure. any clues</p>
[ { "answer_id": 257470, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Convert.ToBase64String doesn't seem to add anything extra as far as I can see. For instance:</p>\n\n<pre><code>byte[] bytes = new byte[1000];\nConsole.WriteLine(Convert.ToBase64String(bytes));\n</code></pre>\n\n<p>The above code prints out a load of AAAAs with == at the end, which is correct.</p>\n\n<p>My guess is that <code>$data</code> on the PHP side doesn't contain what <code>enc</code> did on the C# side - check them against each other.</p>\n" }, { "answer_id": 257473, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Note that <code>+</code> is a valid character in base64 encoding, but when used in URLs it is often translated back to a space. This space may be confusing your PHP <code>base64_decode</code> function.</p>\n\n<p>You have two approaches to solving this problem:</p>\n\n<ul>\n<li>Use %-encoding to encode the + character before it leaves your C# application.</li>\n<li>In your PHP application, translate space characters back to + before passing to base64_decode.</li>\n</ul>\n\n<p>The first option is probably your better choice.</p>\n" }, { "answer_id": 257475, "author": "w-ll", "author_id": 146637, "author_profile": "https://Stackoverflow.com/users/146637", "pm_score": 0, "selected": false, "text": "<p>in c#</p>\n\n<pre><code>this is a &lt;B&gt;long&lt;/b&gt;string. and lets make this a3214 ad0-3214 0czcx 909340 zxci 0324#$@#$%%13244513123\n</code></pre>\n\n<p>turns into </p>\n\n<pre><code>dGhpcyBpcyBhIDxCPmxvbmc8L2I+c3RyaW5nLiBhbmQgbGV0cyBtYWtlIHRoaXMgYTMyMTQgYWQwLTMyMTQgMGN6Y3ggOTA5MzQwIHp4Y2kgMDMyNCMkQCMkJSUxMzI0NDUxMzEyMw==\n</code></pre>\n\n<p>for me. and i think that + is breaking it all.</p>\n" }, { "answer_id": 257486, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 5, "selected": true, "text": "<p>You should probably URL Encode your Base64 string on the C# side before you send it.</p>\n\n<p>And URL Decode it on the php side prior to base64 decoding it.</p>\n\n<p>C# side</p>\n\n<pre><code>byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(\"the string\");\nstring enc = Convert.ToBase64String(encbuff);\nstring urlenc = Server.UrlEncode(enc);\n</code></pre>\n\n<p>and php side:</p>\n\n<pre><code>$data = $_REQUEST['in'];\n$decdata = urldecode($data);\n$raw = base64_decode($decdata);\n</code></pre>\n" }, { "answer_id": 1046414, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The PHP side should be:\n$data = $_REQUEST['in'];\n// $decdata = urldecode($data);\n$raw = base64_decode($decdata);</p>\n\n<p>The $_REQUEST should already be URLdecoded.</p>\n" }, { "answer_id": 8060975, "author": "cliff", "author_id": 1037006, "author_profile": "https://Stackoverflow.com/users/1037006", "pm_score": 2, "selected": false, "text": "<p>This seems to work , replacing + with %2B...</p>\n\n<pre><code>private string HTTPPost(string URL, Dictionary&lt;string, string&gt; FormData)\n{\n\n UTF8Encoding UTF8encoding = new UTF8Encoding();\n string postData = \"\";\n\n foreach (KeyValuePair&lt;String, String&gt; entry in FormData)\n {\n postData += entry.Key + \"=\" + entry.Value + \"&amp;\";\n }\n\n postData = postData.Remove(postData.Length - 1);\n\n //urlencode replace (+) with (%2B) so it will not be changed to space ( )\n postData = postData.Replace(\"+\", \"%2B\");\n\n byte[] data = UTF8encoding.GetBytes(postData); \n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);\n\n request.Method = \"POST\";\n request.ContentType = \"application/x-www-form-urlencoded\";\n request.ContentLength = data.Length;\n\n Stream strm = request.GetRequestStream();\n // Send the data.\n strm.Write(data, 0, data.Length);\n strm.Close();\n\n WebResponse rsp = null;\n // Send the data to the webserver\n rsp = request.GetResponse();\n\n StreamReader rspStream = new StreamReader(rsp.GetResponseStream());\n string response = rspStream.ReadToEnd();\n\n return response;\n\n}\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146637/" ]
So I have this c# application that needs to ping my web server thats running linux/php stack. I am having problems with the c# way of base 64 encoding bytes. my c# code is like: ``` byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string"); String enc = Convert.ToBase64String(encbuff); ``` and php side: ``` $data = $_REQUEST['in']; $raw = base64_decode($data); ``` with larger strings 100+ chars it fails. I think this is due to c# adding '+'s in the encoding but not sure. any clues
You should probably URL Encode your Base64 string on the C# side before you send it. And URL Decode it on the php side prior to base64 decoding it. C# side ``` byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string"); string enc = Convert.ToBase64String(encbuff); string urlenc = Server.UrlEncode(enc); ``` and php side: ``` $data = $_REQUEST['in']; $decdata = urldecode($data); $raw = base64_decode($decdata); ```
257,505
<p>Within an unordered list:</p> <pre><code>&lt;li&gt;&lt;span&gt;&lt;/span&gt; The lazy dog.&lt;/li&gt; &lt;li&gt;&lt;span&gt;AND&lt;/span&gt; The lazy cat.&lt;/li&gt; &lt;li&gt;&lt;span&gt;OR&lt;/span&gt; The active goldfish.&lt;/li&gt; </code></pre> <p>Adding a class or style attribute is permitted but padding the text and adding or changing tags is not allowed.</p> <p>The page is rendering with Courier New.</p> <p>Goal is to have text after span lined up.</p> <pre><code> The lazy dog. AND The lazy cat. OR The active goldfish. </code></pre> <p>Justification of the "OR" is unimportant.</p> <p>The lazy animal text may be wrapped in an additional element but I'll have to double check.</p>
[ { "answer_id": 257524, "author": "Stephen Caldwell", "author_id": 33437, "author_profile": "https://Stackoverflow.com/users/33437", "pm_score": 10, "selected": true, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\r\n list-style-type: none;\r\n padding-left: 0px;\r\n}\r\n\r\nul li span {\r\n float: left;\r\n width: 40px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;ul&gt;\r\n &lt;li&gt;&lt;span&gt;&lt;/span&gt; The lazy dog.&lt;/li&gt;\r\n &lt;li&gt;&lt;span&gt;AND&lt;/span&gt; The lazy cat.&lt;/li&gt;\r\n &lt;li&gt;&lt;span&gt;OR&lt;/span&gt; The active goldfish.&lt;/li&gt;\r\n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Like Eoin said, you need to put a non-breaking space into your \"empty\" spans, but you can't assign a width to an inline element, only padding/margin so you'll need to make it float so that you can give it a width.</p>\n\n<p>For a jsfiddle example, see <a href=\"http://jsfiddle.net/laurensrietveld/JZ2Lg/\" rel=\"noreferrer\">http://jsfiddle.net/laurensrietveld/JZ2Lg/</a></p>\n" }, { "answer_id": 257531, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 4, "selected": false, "text": "<p>Unfortunately inline elements (or elements having display:inline) ignore the width property. You should use floating divs instead:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\ndiv.f1 { float: left; width: 20px; }\ndiv.f2 { float: left; }\ndiv.f3 { clear: both; }\n&lt;/style&gt;\n\n&lt;div class=\"f1\"&gt;&lt;/div&gt;&lt;div class=\"f2\"&gt;The Lazy dog&lt;/div&gt;&lt;div class=\"f3\"&gt;&lt;/div&gt;\n&lt;div class=\"f1\"&gt;AND&lt;/div&gt;&lt;div class=\"f2\"&gt;The Lazy cat&lt;/div&gt;&lt;div class=\"f3\"&gt;&lt;/div&gt;\n&lt;div class=\"f1\"&gt;OR&lt;/div&gt;&lt;div class=\"f2\"&gt;The active goldfish&lt;/div&gt;&lt;div class=\"f3\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Now I see you need to use spans and lists, so we need to rewrite this a little bit:</p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;\n&lt;style type=\"text/css\"&gt;\n span.f1 { display: block; float: left; clear: left; width: 60px; }\n li { list-style-type: none; }\n &lt;/style&gt;\n\n&lt;/head&gt;&lt;body&gt;\n&lt;ul&gt;\n&lt;li&gt;&lt;span class=\"f1\"&gt;&amp;nbsp;&lt;/span&gt;The lazy dog.&lt;/li&gt;\n&lt;li&gt;&lt;span class=\"f1\"&gt;AND&lt;/span&gt; The lazy cat.&lt;/li&gt;\n&lt;li&gt;&lt;span class=\"f1\"&gt;OR&lt;/span&gt; The active goldfish.&lt;/li&gt;\n&lt;/ul&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 257534, "author": "luiscubal", "author_id": 32775, "author_profile": "https://Stackoverflow.com/users/32775", "pm_score": 0, "selected": false, "text": "<p>You can do it using a table, but it is not pure CSS.</p>\n\n<pre><code>&lt;style&gt;\nul{\n text-indent: 40px;\n}\n\nli{\n list-style-type: none;\n padding: 0;\n}\n\nspan{\n color: #ff0000;\n position: relative;\n left: -40px;\n}\n&lt;/style&gt;\n\n\n&lt;ul&gt;\n&lt;span&gt;&lt;/span&gt;&lt;li&gt;The lazy dog.&lt;/li&gt;\n&lt;span&gt;AND&lt;/span&gt;&lt;li&gt;The lazy cat.&lt;/li&gt;\n&lt;span&gt;OR&lt;/span&gt;&lt;li&gt;The active goldfish.&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Note that it doesn't display exactly like you want, because it switches line on each option. However, I hope that this helps you come closer to the answer.</p>\n" }, { "answer_id": 257537, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 4, "selected": false, "text": "<p>The <code>&lt;span&gt;</code> tag will need to be set to <code>display:block</code> as it is an inline element and will ignore width.</p>\n\n<p>so:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt; span { width: 50px; display: block; } &lt;/style&gt;\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>&lt;li&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;something&lt;/li&gt;\n&lt;li&gt;&lt;span&gt;AND&lt;/span&gt;something else&lt;/li&gt;\n</code></pre>\n" }, { "answer_id": 257564, "author": "codeinthehole", "author_id": 32640, "author_profile": "https://Stackoverflow.com/users/32640", "pm_score": 9, "selected": false, "text": "<p>In an ideal world you'd achieve this simply using the following css</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n\nspan {\n display: inline-block;\n width: 50px;\n}\n\n&lt;/style&gt;\n</code></pre>\n\n<p>This works on all browsers apart from FF2 and below.</p>\n\n<blockquote>\n <p>Firefox 2 and lower don't support this\n value. You can use -moz-inline-box,\n but be aware that it's not the same as\n inline-block, and it may not work as\n you expect in some situations.</p>\n</blockquote>\n\n<p>Quote taken from <a href=\"http://www.quirksmode.org/css/display.html\" rel=\"noreferrer\">quirksmode</a></p>\n" }, { "answer_id": 257592, "author": "eaolson", "author_id": 23669, "author_profile": "https://Stackoverflow.com/users/23669", "pm_score": -1, "selected": false, "text": "<p>Well, there's always the brute force method:</p>\n\n<pre><code>&lt;li&gt;&lt;pre&gt; The lazy dog.&lt;/pre&gt;&lt;/li&gt;\n&lt;li&gt;&lt;pre&gt;AND The lazy cat.&lt;/pre&gt;&lt;/li&gt;\n&lt;li&gt;&lt;pre&gt;OR The active goldfish.&lt;/pre&gt;&lt;/li&gt;\n</code></pre>\n\n<p>Or is that what you meant by \"padding\" the text? That's an ambiguous work in this context.</p>\n\n<p>This sounds kind of like a homework question. I hope you're not trying to get us to do your homework for you?</p>\n" }, { "answer_id": 2645732, "author": "Arturro", "author_id": 317548, "author_profile": "https://Stackoverflow.com/users/317548", "pm_score": 2, "selected": false, "text": "<p>People span in this case cant be a block element because rest of the text in between li elements will go down. Also using float is very bad idea because you will need to set width for whole li element and this width will need to be the same as width of whole ul element or other container.</p>\n<p>Try something like this in HTML:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;li&gt;&lt;span&gt;&lt;/span&gt;&lt;strong&gt;The&lt;/strong&gt; lazy dog.&lt;/li&gt;\n&lt;li&gt;&lt;span&gt;AND&lt;/span&gt; &lt;strong&gt;The&lt;/strong&gt; lazy cat.&lt;/li&gt;\n&lt;li&gt;&lt;span&gt;OR&lt;/span&gt; &lt;strong&gt;The&lt;/strong&gt; active goldfish.&lt;/li&gt;\n</code></pre>\n<p>and in the CSS:</p>\n<pre class=\"lang-css prettyprint-override\"><code>li {position:relative;padding-left:80px;} // 80px or something else\nli span {position:absolute;top:0;left:0;}\nli strong {color:red;} // red or else\n</code></pre>\n<p>So, when the <code>li</code> element is relative you format the span element to be as absolute and at the <code>top:0;left:0;</code> so it stays upper left and you set the <code>padding-left</code> (or: <code>padding:0px 0px 0px 80px;</code>) to set this free space for span element.</p>\n<p>It should work better for simple cases.</p>\n" }, { "answer_id": 18806385, "author": "Augustus Francis", "author_id": 2151172, "author_profile": "https://Stackoverflow.com/users/2151172", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;style type=\"text/css\"&gt;\n\nspan {\n position:absolute;\n width: 50px;\n}\n\n&lt;/style&gt;\n</code></pre>\n\n<p>You can do this method for assigning width for inline elements</p>\n" }, { "answer_id": 48848233, "author": "Rahmad Saleh", "author_id": 4747007, "author_profile": "https://Stackoverflow.com/users/4747007", "pm_score": 1, "selected": false, "text": "<p>try this </p>\n\n<pre><code>&gt; &lt;span class=\"input-group-addon\" style=\"padding-left:6%;\n&gt; padding-right:6%; width:150px; overflow: auto;\"&gt;\n</code></pre>\n" }, { "answer_id": 55517589, "author": "Pepe Unodostres", "author_id": 11208299, "author_profile": "https://Stackoverflow.com/users/11208299", "pm_score": -1, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>ul {\r\n list-style-type: none;\r\n padding-left: 0px;\r\n}\r\n\r\nul li span { \r\n float: left;\r\n width: 40px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;ul&gt;\r\n &lt;li&gt;&lt;span&gt;&lt;/span&gt; The lazy dog.&lt;/li&gt;\r\n &lt;li&gt;&lt;span&gt;AND&lt;/span&gt; The lazy cat.&lt;/li&gt;\r\n &lt;li&gt;&lt;span&gt;OR&lt;/span&gt; The active goldfish.&lt;/li&gt;\r\n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 61549391, "author": "schlebe", "author_id": 948359, "author_profile": "https://Stackoverflow.com/users/948359", "pm_score": 3, "selected": false, "text": "<p>Using HTML 5.0, it is possible to fix width of text block using <code>&lt;span&gt;</code> or <code>&lt;div&gt;</code>. </p>\n\n<p><a href=\"https://i.stack.imgur.com/TiDMd.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TiDMd.png\" alt=\"enter image description here\"></a></p>\n\n<p>For <code>&lt;span&gt;</code>, what is important is to add following CCS line</p>\n\n<pre><code>display: inline-block;\n</code></pre>\n\n<p>For your empty <code>&lt;span&gt;</code> what is important is to add <code>&amp;nbsp;</code> space.</p>\n\n<p>My code is following</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body\r\n {\r\n font-family: Arial;\r\n font-size:20px;\r\n }\r\n\r\ndiv\r\n {\r\n width:200px;\r\n font-size:80px;\r\n background-color: lime;\r\n }\r\ndiv span\r\n {\r\n display:block;\r\n width:200px;\r\n background-color: lime;\r\n }\r\n\r\nul li span\r\n {\r\n display: inline-block;\r\n width: 80px;\r\n background-color: yellow;\r\n }\r\nspan.tab\r\n {\r\n display: inline-block;\r\n width: 80px;\r\n background-color: yellow;\r\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&amp;lt;DIV&amp;gt;\r\n\r\n&lt;div class='test'&gt;ABCDEF&lt;/div&gt;\r\n\r\n&amp;lt;SPAN&amp;gt;\r\n\r\n&lt;div&gt;\r\n &lt;span class='test'&gt;ABCDEF&lt;/span&gt;\r\n&lt;/div\r\n\r\n&lt;br&gt;\r\n\r\n&lt;ul&gt;\r\n &lt;li&gt;&lt;span class='tab'&gt;&amp;nbsp;&lt;/span&gt; The lazy dog.&lt;/li&gt;\r\n &lt;li&gt;&lt;span class='tab'&gt;AND&lt;/span&gt; The lazy cat.&lt;/li&gt;\r\n &lt;li&gt;&lt;span class='tab'&gt;OR&lt;/span&gt; The active goldfish.&lt;/li&gt;\r\n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>PS: I have defined <code>tab</code> class because <code>ul li span</code> CSS selector is not working on my PC !</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293/" ]
Within an unordered list: ``` <li><span></span> The lazy dog.</li> <li><span>AND</span> The lazy cat.</li> <li><span>OR</span> The active goldfish.</li> ``` Adding a class or style attribute is permitted but padding the text and adding or changing tags is not allowed. The page is rendering with Courier New. Goal is to have text after span lined up. ``` The lazy dog. AND The lazy cat. OR The active goldfish. ``` Justification of the "OR" is unimportant. The lazy animal text may be wrapped in an additional element but I'll have to double check.
```css ul { list-style-type: none; padding-left: 0px; } ul li span { float: left; width: 40px; } ``` ```html <ul> <li><span></span> The lazy dog.</li> <li><span>AND</span> The lazy cat.</li> <li><span>OR</span> The active goldfish.</li> </ul> ``` Like Eoin said, you need to put a non-breaking space into your "empty" spans, but you can't assign a width to an inline element, only padding/margin so you'll need to make it float so that you can give it a width. For a jsfiddle example, see <http://jsfiddle.net/laurensrietveld/JZ2Lg/>
257,507
<p>I understand how the implementation of dynamic binding works and also the difference between static and dynamic binding, I am just having trouble wrapping my brain around the definition of dynamic binding. Basically other than it is a run-time binding type.</p>
[ { "answer_id": 257565, "author": "kings90", "author_id": 33269, "author_profile": "https://Stackoverflow.com/users/33269", "pm_score": 1, "selected": false, "text": "<p>I understand it being evident in polymorphism. Typically when creating multiple classes that derive from a base class. If each one of the derived classes contains a function that each one uses. The base class can be used to execute a function of the derived classs and it will be properly call the correct function.</p>\n\n<p>For example:</p>\n\n<pre><code>class Animal\n{\nvoid talk();\n}\n\nclass Dog extends Animal\n{\npublic void talk() { System.out.println(\"woof\"); }\n}\n\nclass Cat extends Animal\n{\npublic void talk() { System.out.println(\"meow\"); }\n}\n\n....\nAnimal zoo[2];\nzoo[0] = new Dog();\nzoo[1] = new Cat();\n\nfor(Animal animalToggle: zoo)\n{\nanimalToggle.talk();\n}\n</code></pre>\n\n<p>will print:\nwoof\nmeow</p>\n\n<p>My interpretation hopefully it helps.</p>\n" }, { "answer_id": 257567, "author": "dsimcha", "author_id": 23903, "author_profile": "https://Stackoverflow.com/users/23903", "pm_score": 3, "selected": true, "text": "<p>Basically, dynamic binding means that the address for a function call is not hard-coded into the code segment of your program when it's translated into assembly language, and is instead obtained from elsewhere, i.e. stack variables, array lookups, etc.</p>\n\n<p>At a higher level, if you have a line of code:</p>\n\n<pre><code>foo(bar) //Calls a funciton\n</code></pre>\n\n<p>If it can be known at compile time exactly what function this will call, this is static binding. If foo could mean multiple functions depending on things not knowable at compile time, this is dynamic binding.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29299/" ]
I understand how the implementation of dynamic binding works and also the difference between static and dynamic binding, I am just having trouble wrapping my brain around the definition of dynamic binding. Basically other than it is a run-time binding type.
Basically, dynamic binding means that the address for a function call is not hard-coded into the code segment of your program when it's translated into assembly language, and is instead obtained from elsewhere, i.e. stack variables, array lookups, etc. At a higher level, if you have a line of code: ``` foo(bar) //Calls a funciton ``` If it can be known at compile time exactly what function this will call, this is static binding. If foo could mean multiple functions depending on things not knowable at compile time, this is dynamic binding.
257,514
<p>I need to find out the pixel position of one element in a list that's been displayed using a <code>ListView</code>. It seems like I should get one of the <strong>TextView's</strong> and then use <code>getTop()</code>, but I can't figure out how to get a child view of a <code>ListView</code>.</p> <p><strong>Update:</strong> The children of the <code>ViewGroup</code> do not correspond 1-to-1 with the items in the list, for a <code>ListView</code>. Instead, the <code>ViewGroup</code>'s children correspond to only those views that are visible right now. So <code>getChildAt()</code> operates on an index that's internal to the <code>ViewGroup</code> and doesn't necessarily have anything to do with the position in the list that the <code>ListView</code> uses.</p>
[ { "answer_id": 257541, "author": "Feet", "author_id": 18340, "author_profile": "https://Stackoverflow.com/users/18340", "pm_score": 3, "selected": false, "text": "<p>A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.</p>\n\n<p>Found it <a href=\"http://code.google.com/android/reference/android/widget/ListView.html\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 340691, "author": "jasonhudgins", "author_id": 24590, "author_profile": "https://Stackoverflow.com/users/24590", "pm_score": -1, "selected": false, "text": "<p>This assumes you know the position of the element in the ListView :</p>\n\n<pre><code> View element = listView.getListAdapter().getView(position, null, null);\n</code></pre>\n\n<p>Then you should be able to call getLeft() and getTop() to determine the elements on screen position.</p>\n" }, { "answer_id": 2679284, "author": "Joe", "author_id": 231078, "author_profile": "https://Stackoverflow.com/users/231078", "pm_score": 9, "selected": true, "text": "<p>See: <a href=\"https://stackoverflow.com/questions/2001760/android-listview-get-data-index-of-visible-item/2002413#2002413\">Android ListView: get data index of visible item</a>\nand combine with part of Feet's answer above, can give you something like:</p>\n\n<pre><code>int wantedPosition = 10; // Whatever position you're looking for\nint firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0\nint wantedChild = wantedPosition - firstPosition;\n// Say, first visible position is 8, you want position 10, wantedChild will now be 2\n// So that means your view is child #2 in the ViewGroup:\nif (wantedChild &lt; 0 || wantedChild &gt;= listView.getChildCount()) {\n Log.w(TAG, \"Unable to get view for desired position, because it's not being displayed on screen.\");\n return;\n}\n// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.\nView wantedView = listView.getChildAt(wantedChild);\n</code></pre>\n\n<p>The benefit is that you aren't iterating over the ListView's children, which could take a performance hit.</p>\n" }, { "answer_id": 8692373, "author": "Kalimah", "author_id": 529024, "author_profile": "https://Stackoverflow.com/users/529024", "pm_score": 4, "selected": false, "text": "<p>This code is easier to use:</p>\n\n<pre><code> View rowView = listView.getChildAt(viewIndex);//The item number in the List View\n if(rowView != null)\n {\n // Your code here\n }\n</code></pre>\n" }, { "answer_id": 17345134, "author": "Wes", "author_id": 2528371, "author_profile": "https://Stackoverflow.com/users/2528371", "pm_score": 3, "selected": false, "text": "<pre><code>listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView&lt;?&gt; parent, final View view, int position, long id) {\n View v;\n int count = parent.getChildCount();\n v = parent.getChildAt(position);\n parent.requestChildFocus(v, view);\n v.setBackground(res.getDrawable(R.drawable.transparent_button));\n for (int i = 0; i &lt; count; i++) {\n if (i != position) {\n v = parent.getChildAt(i);\n v.setBackground(res.getDrawable(R.drawable.not_clicked));\n }\n }\n }\n});\n</code></pre>\n\n<p>Basically, create two <strong>Drawables</strong> - one that is transparent, and another that is the desired color. Request focus at the clicked position (<code>int position</code> as defined) and change the color of the said row. Then walk through the parent <code>ListView</code>, and change all other rows accordingly. This accounts for when a user clicks on the <code>listview</code> multiple times. This is done with a custom layout for each row in the <code>ListView</code>. (Very simple, just create a new layout file with a <code>TextView</code> - do not set focusable or clickable!).</p>\n\n<p>No custom adapter required - use <code>ArrayAdapter</code></p>\n" }, { "answer_id": 35079680, "author": "Milaaaad", "author_id": 4923925, "author_profile": "https://Stackoverflow.com/users/4923925", "pm_score": 2, "selected": false, "text": "<pre><code>int position = 0;\nlistview.setItemChecked(position, true);\nView wantedView = adapter.getView(position, null, listview);\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2652/" ]
I need to find out the pixel position of one element in a list that's been displayed using a `ListView`. It seems like I should get one of the **TextView's** and then use `getTop()`, but I can't figure out how to get a child view of a `ListView`. **Update:** The children of the `ViewGroup` do not correspond 1-to-1 with the items in the list, for a `ListView`. Instead, the `ViewGroup`'s children correspond to only those views that are visible right now. So `getChildAt()` operates on an index that's internal to the `ViewGroup` and doesn't necessarily have anything to do with the position in the list that the `ListView` uses.
See: [Android ListView: get data index of visible item](https://stackoverflow.com/questions/2001760/android-listview-get-data-index-of-visible-item/2002413#2002413) and combine with part of Feet's answer above, can give you something like: ``` int wantedPosition = 10; // Whatever position you're looking for int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0 int wantedChild = wantedPosition - firstPosition; // Say, first visible position is 8, you want position 10, wantedChild will now be 2 // So that means your view is child #2 in the ViewGroup: if (wantedChild < 0 || wantedChild >= listView.getChildCount()) { Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen."); return; } // Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead. View wantedView = listView.getChildAt(wantedChild); ``` The benefit is that you aren't iterating over the ListView's children, which could take a performance hit.
257,519
<p>I'm completely new at C# and NUnit.</p> <p>In Boost.Test there is a family of <code>BOOST_*_THROW</code> macros. In Python's test module there is <code>TestCase.assertRaises</code> method.</p> <p>As far as I understand it, in C# with NUnit (2.4.8) the only method of doing exception test is to use <code>ExpectedExceptionAttribute</code>.</p> <p>Why should I prefer <code>ExpectedExceptionAttribute</code> over - let's say - Boost.Test's approach? What reasoning can stand behind this design decision? Why is that better in case of C# and NUnit?</p> <p>Finally, if I decide to use <code>ExpectedExceptionAttribute</code>, how can I do some additional tests after exception was raised and catched? Let's say that I want to test requirement saying that object has to be valid after some setter raised <code>System.IndexOutOfRangeException</code>. How would you fix following code to compile and work as expected?</p> <pre><code>[Test] public void TestSetterException() { Sth.SomeClass obj = new SomeClass(); // Following statement won't compile. Assert.Raises( "System.IndexOutOfRangeException", obj.SetValueAt( -1, "foo" ) ); Assert.IsTrue( obj.IsValid() ); } </code></pre> <hr> <p>Edit: Thanks for your answers. Today, I've found an <em>It's the Tests</em> <a href="http://nunit.com/blogs/?p=63" rel="nofollow noreferrer">blog entry</a> where all three methods described by you are mentioned (and one more minor variation). It's shame that I couldn't find it before :-(.</p>
[ { "answer_id": 257523, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": false, "text": "<p>If you can use NUnit 2.5 there's some nice <a href=\"http://nunit.com/blogs/?p=63\" rel=\"noreferrer\">helpers</a> there.</p>\n\n<pre><code>Assert.That( delegate { ... }, Throws.Exception&lt;ArgumentException&gt;())\n</code></pre>\n" }, { "answer_id": 257526, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "<p>I've always adopted the following approach:</p>\n\n<pre><code>bool success = true;\ntry {\n obj.SetValueAt(-1, \"foo\");\n} catch () {\n success = false;\n}\n\nassert.IsFalse(success);\n\n...\n</code></pre>\n" }, { "answer_id": 257536, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>The MbUnit syntax is</p>\n\n<pre><code>Assert.Throws&lt;IndexOutOfRangeException&gt;(delegate {\n int[] nums = new int[] { 0, 1, 2 };\n nums[3] = 3;\n});\n</code></pre>\n" }, { "answer_id": 257540, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>I'm surprised I haven't seen this pattern mentioned yet. David Arno's is very similar, but I prefer the simplicity of this:</p>\n\n<pre><code>try\n{\n obj.SetValueAt(-1, \"foo\");\n Assert.Fail(\"Expected exception\");\n}\ncatch (IndexOutOfRangeException)\n{\n // Expected\n}\nAssert.IsTrue(obj.IsValid());\n</code></pre>\n" }, { "answer_id": 257590, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>Your preferred syntax:</p>\n\n<pre><code>Assert.Raises( \"System.IndexOutOfRangeException\",\n obj.SetValueAt( -1, \"foo\" ) );\n</code></pre>\n\n<p>woiuldn't work with C# anyway - the obj.SetValueAt would be evaluated and the result passed to Assert.Raises. If SetValue throws an exception, then you'd never get into Assert.Raises.</p>\n\n<p>You could write a helper method to do it:</p>\n\n<pre><code>void Raises&lt;T&gt;(Action action) where T:Exception {\n try {\n action();\n throw new ExpectedException(typeof(T));\n catch (Exception ex) {\n if (ex.GetType() != typeof(T)) {\n throw;\n }\n }\n}\n</code></pre>\n\n<p>Which allows the similar syntax of:</p>\n\n<pre><code>Assert.Raises&lt;System.IndexOutOfRangeException&gt;(() =&gt; \n obj.SetValueAt(-1, \"foo\")\n;\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26141/" ]
I'm completely new at C# and NUnit. In Boost.Test there is a family of `BOOST_*_THROW` macros. In Python's test module there is `TestCase.assertRaises` method. As far as I understand it, in C# with NUnit (2.4.8) the only method of doing exception test is to use `ExpectedExceptionAttribute`. Why should I prefer `ExpectedExceptionAttribute` over - let's say - Boost.Test's approach? What reasoning can stand behind this design decision? Why is that better in case of C# and NUnit? Finally, if I decide to use `ExpectedExceptionAttribute`, how can I do some additional tests after exception was raised and catched? Let's say that I want to test requirement saying that object has to be valid after some setter raised `System.IndexOutOfRangeException`. How would you fix following code to compile and work as expected? ``` [Test] public void TestSetterException() { Sth.SomeClass obj = new SomeClass(); // Following statement won't compile. Assert.Raises( "System.IndexOutOfRangeException", obj.SetValueAt( -1, "foo" ) ); Assert.IsTrue( obj.IsValid() ); } ``` --- Edit: Thanks for your answers. Today, I've found an *It's the Tests* [blog entry](http://nunit.com/blogs/?p=63) where all three methods described by you are mentioned (and one more minor variation). It's shame that I couldn't find it before :-(.
I'm surprised I haven't seen this pattern mentioned yet. David Arno's is very similar, but I prefer the simplicity of this: ``` try { obj.SetValueAt(-1, "foo"); Assert.Fail("Expected exception"); } catch (IndexOutOfRangeException) { // Expected } Assert.IsTrue(obj.IsValid()); ```
257,550
<p>I have put together a script which is very much like the flickr photostream feature. Two thumbnails next to each other, and when you click the next or prev links the next (or previous) two images slide in. Cool!</p> <p>Currently when the page loads it loads the two images. The first time nxt / prv is used then the next two images or previous two are loaded via ajax, with the id of the first image being passed in the url and the HTML for the two new images returned and displayed via ajax.</p> <p>simple enough, but it got me to thinking, on a slow connection, or heavy server load then the two images, although relatively small thumbnails could still take a while to load, and the nice things with sliding panes is the fact that the hidden data slides in quickly and smoothly preferbly without a loading delay.</p> <p>So I was wondering from a performance and good practice point of view which option is best, this is what I can think of for now, open to suggestions.</p> <p>1, call each set of images via JSON (its supposed to be fast?) </p> <p>2,load all the possible images into a json file and pull in the details that way - although browser will still have to load image. Plus sometimes there might be 4 images, other times there could be upto 1000!</p> <p>3, Load 10 images via php into a Json or other file, and load all 10 images into the browser hiding the 8 which are not on show, and always showing the middle two. Problem here is that each time someone clicks, the file has to reload the first and last images, which still takes up time, although i suppose the middle images will have all been cached via the browser by now though. But still there is a loading time.</p> <p>4, Is it possible to have a json image with all the image details (regardless of numbers) and use no 3 above to load 10 of those images, is it possible to use ajax to only read 10 lines and keep a pointer of the last one it read, so the json file can be loaded fast, short refresh and images either side are cached via the browser!!</p> <p>Hope thats clear, any suggestions on how you would handle this?</p>
[ { "answer_id": 257594, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>To preload an image from Javascript, you don't need to do anything that sounds like AJAX or JSON. All you need is this:</p>\n\n<pre><code>var img = new Image();\nimg.src = \"http://example.com/new/image.jpg\";\n</code></pre>\n\n<p>The browser will quite happily load the image in the background, even though it's not displayed anywhere. Then, when you update the <code>src</code> field of another (displayed) image tag, the browser will immediately show the part of the image it's already loaded (hopefully all of it).</p>\n" }, { "answer_id": 257601, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>Fetching JSON Via Ajax will just slow you down. </p>\n\n<p>You're better off using inline JSON and generated Javascript. </p>\n\n<pre><code> &lt;?php \n $images = array( \"foo.jpg\",\"bar.jpg\" ); \n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n jQuery(function($){\n var images = ( &lt;?php echo json_encode($images); ?&gt; ); \n /* Creating A Hidden box to preload the images into */\n var imgbox = document.createElement(\"div\"); \n $(imgbox).css({display: 'none'});\n /* Possible Alternative trick */\n /* $(imgbox).css({height:1px; width: 1px; overflow: hidden;}); */\n $('body').append(imgbox);\n\n $.each( images , function( ind, item ) \n {\n #Injecting images into the bottom hidden div. \n var img = document.createElement(\"img\"); \n $(img).src(\"/some/prefix/\" + item ); \n $(imgbox).append(img);\n });\n }); \n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 1073187, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 0, "selected": false, "text": "<p>In the case where you want to <strong>concurrently</strong> preload a larger number of resources, a little ajax can solve the problem for you. Just make sure the caching headers are such that the browser will use the resources on the next request. In the following example, I load up to four resources concurrently.</p>\n\n<pre><code>&lt;script&gt;\nvar urls = [\n \"a.png\",\n \"b.png\",\n \"c.png\",\n \"d.png\",\n \"e.png\",\n \"f.png\"\n];\n\nvar currentStep = 0;\nfunction loadResources()\n{\n if(currentStep&lt;urls.length){\n var url = urls[currentStep];\n var req = GetXmlHttpObject();\n update('loading ' + url);\n req.open(\"GET\", url, true);\n req.onreadystatechange = getUpdateState(req, url);\n req.send(null);\n} else {\n window.location = 'done.htm';\n}\n}\n\nfunction getUpdateState(req, url) {\n return function() {\n var state = req.readyState;\n if (state != 4) { return; }\n req = null;\n setTimeout('loadResources()', 0);\n }\n}\n&lt;/script&gt;\n\n&lt;!-- This will queue up to four concurrent requests. Modern browsers will request up to eight images at time --&gt;\n&lt;body onload=\"javascript: loadResources(); loadResources(); loadResources(); loadResources();\"&gt;\n</code></pre>\n" }, { "answer_id": 1447188, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Why not use text and replace the text with a picture code (works in php really nice with ajax up to 500 pictures and more)?</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
I have put together a script which is very much like the flickr photostream feature. Two thumbnails next to each other, and when you click the next or prev links the next (or previous) two images slide in. Cool! Currently when the page loads it loads the two images. The first time nxt / prv is used then the next two images or previous two are loaded via ajax, with the id of the first image being passed in the url and the HTML for the two new images returned and displayed via ajax. simple enough, but it got me to thinking, on a slow connection, or heavy server load then the two images, although relatively small thumbnails could still take a while to load, and the nice things with sliding panes is the fact that the hidden data slides in quickly and smoothly preferbly without a loading delay. So I was wondering from a performance and good practice point of view which option is best, this is what I can think of for now, open to suggestions. 1, call each set of images via JSON (its supposed to be fast?) 2,load all the possible images into a json file and pull in the details that way - although browser will still have to load image. Plus sometimes there might be 4 images, other times there could be upto 1000! 3, Load 10 images via php into a Json or other file, and load all 10 images into the browser hiding the 8 which are not on show, and always showing the middle two. Problem here is that each time someone clicks, the file has to reload the first and last images, which still takes up time, although i suppose the middle images will have all been cached via the browser by now though. But still there is a loading time. 4, Is it possible to have a json image with all the image details (regardless of numbers) and use no 3 above to load 10 of those images, is it possible to use ajax to only read 10 lines and keep a pointer of the last one it read, so the json file can be loaded fast, short refresh and images either side are cached via the browser!! Hope thats clear, any suggestions on how you would handle this?
To preload an image from Javascript, you don't need to do anything that sounds like AJAX or JSON. All you need is this: ``` var img = new Image(); img.src = "http://example.com/new/image.jpg"; ``` The browser will quite happily load the image in the background, even though it's not displayed anywhere. Then, when you update the `src` field of another (displayed) image tag, the browser will immediately show the part of the image it's already loaded (hopefully all of it).
257,563
<p>hey, I'm very new to all this so please excuse stupidity :)</p> <pre><code>import os import MySQLdb import time db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace") cursor = db.cursor() tailoutputfile = os.popen('tail -f syslog.log') while 1: x = tailoutputfile.readline() if len(x)==0: break y = x.split() if y[2] == 'BAD': timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") if y[2] == 'GOOD': print y[4] + '\t' + y[7] </code></pre> <p>so i run the program and this is the error message I am getting</p> <pre><code>user@machine:~/$ python reader.py Traceback (most recent call last): File "reader.py", line 17, in ? cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[4], y[7]' at line 1") user@machine:~/$ </code></pre> <p>So i'm assuming that the error is obviously coming from the SQL Statement </p> <pre><code>cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") </code></pre> <p>Here is an example of what y[4] and y[7] will look like. </p> <pre><code>YES Mail.Sent.To.User:[email protected]:23.17 </code></pre> <p>Is this error happening because I should be escaping those values before I try and Insert them into the Database? Or am I completely missing the point??</p> <p>Any help would be appreciated! thanks in advance. </p>
[ { "answer_id": 257570, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 2, "selected": false, "text": "<pre><code> cursor.execute(\"INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]\")\n</code></pre>\n\n<p>should be</p>\n\n<pre><code> cursor.execute(\"INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')\" % (y[4], y[7]))\n</code></pre>\n\n<p>Your best bet to debug things like this is to put the query into a variable and use that:</p>\n\n<pre><code>query = \"INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')\" % (y[4], y[7])\nprint query\ncursor.execute(query)\n</code></pre>\n\n<p>That print statement would make it very obvious what the problem is.</p>\n\n<p>If you're going to be using list variables a lot like this it can get very confusing, consider using the list just once and putting the variables into a dictionary. It's a bit longer to type, but is much, much easier to keep track of what's going on.</p>\n" }, { "answer_id": 257614, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 4, "selected": true, "text": "<p>As pointed out, you're failing to copy the Python variable values into the query, only their names, which mean nothing to MySQL.</p>\n\n<p>However the direct string concatenation option:</p>\n\n<pre><code>cursor.execute(\"INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')\" % (timestring, y[4], y[7]))\n</code></pre>\n\n<p>is dangerous and should never be used. If those strings have out-of-bounds characters like ' or \\ in, you've got an SQL injection leading to possible security compromise. Maybe in your particular app that can never happen, but it's still a very bad practice, which beginners' SQL tutorials really need to stop using.</p>\n\n<p>The solution using MySQLdb is to let the DBAPI layer take care of inserting and escaping parameter values into SQL for you, instead of trying to % it yourself:</p>\n\n<pre><code>cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))\n</code></pre>\n" }, { "answer_id": 298414, "author": "slav0nic", "author_id": 2201031, "author_profile": "https://Stackoverflow.com/users/2201031", "pm_score": 1, "selected": false, "text": "<p>never use \"direct string concatenation\" with SQL, because it's not secure, more correct variant:</p>\n\n<pre><code>cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))\n</code></pre>\n\n<p>it automatically escaping forbidden symbols in values (such as \", ' etc)</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33512/" ]
hey, I'm very new to all this so please excuse stupidity :) ``` import os import MySQLdb import time db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace") cursor = db.cursor() tailoutputfile = os.popen('tail -f syslog.log') while 1: x = tailoutputfile.readline() if len(x)==0: break y = x.split() if y[2] == 'BAD': timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") if y[2] == 'GOOD': print y[4] + '\t' + y[7] ``` so i run the program and this is the error message I am getting ``` user@machine:~/$ python reader.py Traceback (most recent call last): File "reader.py", line 17, in ? cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[4], y[7]' at line 1") user@machine:~/$ ``` So i'm assuming that the error is obviously coming from the SQL Statement ``` cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") ``` Here is an example of what y[4] and y[7] will look like. ``` YES Mail.Sent.To.User:[email protected]:23.17 ``` Is this error happening because I should be escaping those values before I try and Insert them into the Database? Or am I completely missing the point?? Any help would be appreciated! thanks in advance.
As pointed out, you're failing to copy the Python variable values into the query, only their names, which mean nothing to MySQL. However the direct string concatenation option: ``` cursor.execute("INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')" % (timestring, y[4], y[7])) ``` is dangerous and should never be used. If those strings have out-of-bounds characters like ' or \ in, you've got an SQL injection leading to possible security compromise. Maybe in your particular app that can never happen, but it's still a very bad practice, which beginners' SQL tutorials really need to stop using. The solution using MySQLdb is to let the DBAPI layer take care of inserting and escaping parameter values into SQL for you, instead of trying to % it yourself: ``` cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7])) ```
257,566
<p>I am attempting to use a Stream Result to return an image from a struts2 application. I seem to be having problem with configuring the action. Here is the configuration:</p> <pre><code> &lt;result name="success" type="stream"&gt; &lt;param name="contentType"&gt;image/jpeg&lt;/param&gt; &lt;param name="inputName"&gt;inputStream&lt;/param&gt; &lt;param name="contentDisposition"&gt;filename="${filename}"&lt;/param&gt; &lt;param name="bufferSize"&gt;1024&lt;/param&gt; &lt;/result&gt; </code></pre> <p>The problem seem to be the inputName parameter which according to the docs is:</p> <blockquote> <p>the name of the InputStream property from the chained action (default = inputStream).</p> </blockquote> <p>I am not sure what name I should put there. The error I get is: </p> <blockquote> <p>Can not find a java.io.InputStream with the name [inputStream] in the invocation stack.</p> </blockquote> <p>Has anyone used this before? Any advice?</p> <p>Thanks.</p>
[ { "answer_id": 257646, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 4, "selected": true, "text": "<p>I found <a href=\"http://www.nabble.com/Struts-2-File-upload-to-store-the-filedata-td14168069.html\" rel=\"nofollow noreferrer\">this</a> which explained that the <code>InputStream</code> has to be created by me. It makes sense that I create an <code>InputStream</code> from the file that I want the user to download and then pass the Stream to the result. I guess that's my answer.</p>\n" }, { "answer_id": 571365, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Inputname defines the name of the method that outputs the \"stream\"</p>\n\n<p>public InputStream getInputStream ()\n {\n return new ByteArrayInputStream ( _bytes );\n }</p>\n" }, { "answer_id": 826627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I believe you have the contentDisposition wrong, it should be:</p>\n\n<pre><code>&lt;param name=\"contentDisposition\"&gt;attachment; filename=\"${filename}\"&lt;/param&gt;\n</code></pre>\n\n<p>(<em>Chris</em>)</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27439/" ]
I am attempting to use a Stream Result to return an image from a struts2 application. I seem to be having problem with configuring the action. Here is the configuration: ``` <result name="success" type="stream"> <param name="contentType">image/jpeg</param> <param name="inputName">inputStream</param> <param name="contentDisposition">filename="${filename}"</param> <param name="bufferSize">1024</param> </result> ``` The problem seem to be the inputName parameter which according to the docs is: > > the name of the InputStream property from the chained action (default = inputStream). > > > I am not sure what name I should put there. The error I get is: > > Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. > > > Has anyone used this before? Any advice? Thanks.
I found [this](http://www.nabble.com/Struts-2-File-upload-to-store-the-filedata-td14168069.html) which explained that the `InputStream` has to be created by me. It makes sense that I create an `InputStream` from the file that I want the user to download and then pass the Stream to the result. I guess that's my answer.
257,577
<p>Im thinking of updating my practices, and looking for a little help and advice!</p> <p>I do a lot of work on sites that run joomla, oscommerce, drupal etc and so I have created a lot of custom components/plugins and hacks etc. Currently each site has its own folder on my xampp setup. What I would like to do is have a default setup of (for example) a Joomla setup and when I make changes updates, I can do something which updates all the other folders that contain joomla, almost like an auto update?</p> <p>Im also looking at using Aptana IDE more and SVN service such as <a href="http://unfuddle.com/" rel="nofollow noreferrer">unfuddle</a> to share my work with others, but I have not used SVN before and not sure if its possible to do the above using SVN?</p> <p>It would be great to be able to work on a main/core item and send the updates to both local updates and to actual servers, without having to maintain lots of different individual sites.</p> <p>Suggestions?</p>
[ { "answer_id": 257617, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "<p>Yes, SVN would be a great tool for this purpose. Store your code (eg: a custom Joomla component) in source control. Wherever you want to use that component, just do a <code>checkout</code> or <code>export</code> of that particular folder into your live site. Here's one way you could structure your repository:</p>\n\n<pre>unfuddle.com/myRepo/trunk/com_myComponent\nunfuddle.com/myRepo/trunk/com_anotherComponent\n</pre>\n\n<p>Log in to your live server via SSH and run this command:</p>\n\n<pre>\n> cd path/to/joomla/components\n> svn co http://unfuddle.com/myRepo/trunk/com_myComponent\n</pre>\n\n<p>Any time you change your code, commit the changes and then log back into the server and run:</p>\n\n<pre>\n> cd path/to/joomla/components\n> svn up com_myComponent\n</pre>\n\n<p>A real benefit of this is that should you do an update and break something, you can always roll it back to the last known \"good\" version.</p>\n\n<p>As for automating this process, you might be out of luck if it's on different servers. For multiple deployments on the same server, you could quite easily write a shell script to run the above commands for each site/component. If you needed this to be fully automated, you could even set up a cron job to run this script every day at 2am or something - personally I'd stick with the manual approach, but it's still an option.</p>\n\n<p>For working locally with your SVN repositories, I'd recommend looking at <a href=\"http://tortoisesvn.tigris.org/\" rel=\"nofollow noreferrer\">TortoiseSVN</a> (if you're on Windows): it's the simplest and easiest way to work with SVN.</p>\n" }, { "answer_id": 257618, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "<p>I don't have a good answer for your situation, but I don't think Subversion by itself is the answer.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/249085/shared-components-throughout-all-projects-is-there-a-better-alternative-than-sv#249146\">This Question</a> addresses some of the concerns about Subversion's mechanisms for sharing across 'projects'.</p>\n\n<p>Subversion can certainly handle the source code management part of this puzzle. The automated distribution, well I'd use another tool.</p>\n" }, { "answer_id": 257967, "author": "Matthew Smith", "author_id": 20889, "author_profile": "https://Stackoverflow.com/users/20889", "pm_score": 0, "selected": false, "text": "<p>Look into <a href=\"http://www.capify.org/\" rel=\"nofollow noreferrer\">Capistrano</a>. I've used it a couple of times and once you figure it out, it's pretty good. Aimed at rails but should work for anything where you need to get code from a repository and deploy it on different servers.</p>\n" }, { "answer_id": 309742, "author": "D'Arcy Rittich", "author_id": 39430, "author_profile": "https://Stackoverflow.com/users/39430", "pm_score": 2, "selected": false, "text": "<p>For automating things, you could use SVN hooks for this. There is a post-commit hook, so every time you do a commit, your hook script could tell the other machines to do an SVN update to get the latest code.</p>\n\n<p>For more info, see <a href=\"http://svnbook.red-bean.com/en/1.5/svn.reposadmin.create.html#svn.reposadmin.create.hooks\" rel=\"nofollow noreferrer\">Version Control with Subversion - Implementing Repository Hooks</a>.</p>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
Im thinking of updating my practices, and looking for a little help and advice! I do a lot of work on sites that run joomla, oscommerce, drupal etc and so I have created a lot of custom components/plugins and hacks etc. Currently each site has its own folder on my xampp setup. What I would like to do is have a default setup of (for example) a Joomla setup and when I make changes updates, I can do something which updates all the other folders that contain joomla, almost like an auto update? Im also looking at using Aptana IDE more and SVN service such as [unfuddle](http://unfuddle.com/) to share my work with others, but I have not used SVN before and not sure if its possible to do the above using SVN? It would be great to be able to work on a main/core item and send the updates to both local updates and to actual servers, without having to maintain lots of different individual sites. Suggestions?
Yes, SVN would be a great tool for this purpose. Store your code (eg: a custom Joomla component) in source control. Wherever you want to use that component, just do a `checkout` or `export` of that particular folder into your live site. Here's one way you could structure your repository: ``` unfuddle.com/myRepo/trunk/com_myComponent unfuddle.com/myRepo/trunk/com_anotherComponent ``` Log in to your live server via SSH and run this command: ``` > cd path/to/joomla/components > svn co http://unfuddle.com/myRepo/trunk/com_myComponent ``` Any time you change your code, commit the changes and then log back into the server and run: ``` > cd path/to/joomla/components > svn up com_myComponent ``` A real benefit of this is that should you do an update and break something, you can always roll it back to the last known "good" version. As for automating this process, you might be out of luck if it's on different servers. For multiple deployments on the same server, you could quite easily write a shell script to run the above commands for each site/component. If you needed this to be fully automated, you could even set up a cron job to run this script every day at 2am or something - personally I'd stick with the manual approach, but it's still an option. For working locally with your SVN repositories, I'd recommend looking at [TortoiseSVN](http://tortoisesvn.tigris.org/) (if you're on Windows): it's the simplest and easiest way to work with SVN.
257,583
<p>I need to schedule several different pages on several different sites to be run at certain times, usually once a night. Is there any software out there to do this? it would be nice if it called the page and then recorded the response and whether the called page was successful run or not. I was using Helm on a different box and it had a nice Web Scheduler module but Helm is not an option for this machine. This is a Window Server 2008 box.</p>
[ { "answer_id": 257595, "author": "Mark Allen", "author_id": 5948, "author_profile": "https://Stackoverflow.com/users/5948", "pm_score": 2, "selected": false, "text": "<p>How about <a href=\"http://www.google.com/search?hl=en&amp;rls=com.microsoft%3Aen-us&amp;q=wget+windows\" rel=\"nofollow noreferrer\">wget.exe</a> and the task scheduler?</p>\n" }, { "answer_id": 257603, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If it's not a requirement to schedule them from the same box, have a look to <a href=\"http://site24x7.com\" rel=\"nofollow noreferrer\">Zoho's site24x7</a>.</p>\n\n<p>It is initially designed to monitor web sites but it has an option to record expected answers and compare them so you can use it for your purpose with the added security of an external site. It's not free however except for few urls. </p>\n\n<p>They are other similar providers but they looked pretty good last time I searched the web on this topic. </p>\n" }, { "answer_id": 259414, "author": "JoshBaltzell", "author_id": 29997, "author_profile": "https://Stackoverflow.com/users/29997", "pm_score": 4, "selected": true, "text": "<p>We use standard scheduled tasks that call a bat file that calls a VBS file. I know it is not the most elegant solution ever, but it consistently works.</p>\n\n<p>BAT:</p>\n\n<pre><code>webrun.vbs http://website.com/page.aspx\n</code></pre>\n\n<p>VBS:</p>\n\n<pre><code>dim URL, oArgs \n\nSet oArgs = WScript.Arguments \n\n if oArgs.Count = 0 then \n msgbox(\"Error: Must supply URL\") \n wscript.quit 1 \n end if \n\nURL = oArgs(0) \n\n on error resume next \nSet objXML = CreateObject(\"MSXML2.ServerXMLHTTP\") \n\n if err then \n msgbox(\"Error: \" &amp; err.description) \n wscript.quit 1 \n end if \n\n' Call the remote machine the request \n objXML.open \"GET\", URL, False \n\n objXML.send() \n\n' return the response \n 'msgbox objXML.responSetext \n\n' clean up \n Set objXML = Nothing \n</code></pre>\n\n<p>The code in the VBS file is almost assuredly both overkill and underwritten, but functional none-the-less.</p>\n" }, { "answer_id": 268908, "author": "Slee", "author_id": 34548, "author_profile": "https://Stackoverflow.com/users/34548", "pm_score": 0, "selected": false, "text": "<p>I ended up using this script and Task Scheduler, simple and works great:</p>\n\n<pre><code>Call LogEntry()\nSub LogEntry()\n\n'Force the script to finish on an error.\nOn Error Resume Next\n\n'Declare variables\nDim objRequest\nDim URLs\nURLs = Wscript.Arguments(0)\nSet objRequest = CreateObject(\"Microsoft.XMLHTTP\")\n\n'Open the HTTP request and pass the URL to the objRequest object\nobjRequest.open \"POST\", URLs, false\n\n'Send the HTML Request\nobjRequest.Send\n\nSet objRequest = Nothing\nWScript.Quit\n\nEnd Sub\n</code></pre>\n\n<p>Then I just call it with the URL I want run as an argument: </p>\n" }, { "answer_id": 269698, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 0, "selected": false, "text": "<p>Similar (though possibly more powerful) is <a href=\"http://netcat.sourceforge.net/\" rel=\"nofollow noreferrer\">netcat</a> and its <a href=\"http://www.securityfocus.com/tools/139\" rel=\"nofollow noreferrer\">windows port</a></p>\n" }, { "answer_id": 678959, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>fyi - wget is GNU standard license, so I'm not sure it's usable for most commercial/proprietary systems.</p>\n" }, { "answer_id": 2263458, "author": "Regina", "author_id": 261577, "author_profile": "https://Stackoverflow.com/users/261577", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://scheduler.codeeffects.com\" rel=\"nofollow noreferrer\">http://scheduler.codeeffects.com</a>. Very effective and reliable, no complains.</p>\n" }, { "answer_id": 6466307, "author": "Matthijs", "author_id": 813867, "author_profile": "https://Stackoverflow.com/users/813867", "pm_score": 1, "selected": false, "text": "<p>The code given in the upper example has some issues with the task being active during the loading of the website. The website is loading 2 minutes but the task is already done in 1 second, which brings a problem when you execute it every 5 minutes. If the website loads 10 minutes and the task is already done in 1 second it wil execute again that while I want it to wait the loading time of the website.</p>\n\n<p>So what I've done is the following (this script will keep the task busy as long the website is loading):</p>\n\n<pre><code>dim URL, oArgs, objXML\nSet oArgs = WScript.Arguments\nURL = oArgs(0)\n\non error resume next\n\nSet objXML = CreateObject(\"Microsoft.XMLDOM\")\nobjXML.async = \"false\"\nobjXML.load(URL)\nSet objXML = Nothing\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34548/" ]
I need to schedule several different pages on several different sites to be run at certain times, usually once a night. Is there any software out there to do this? it would be nice if it called the page and then recorded the response and whether the called page was successful run or not. I was using Helm on a different box and it had a nice Web Scheduler module but Helm is not an option for this machine. This is a Window Server 2008 box.
We use standard scheduled tasks that call a bat file that calls a VBS file. I know it is not the most elegant solution ever, but it consistently works. BAT: ``` webrun.vbs http://website.com/page.aspx ``` VBS: ``` dim URL, oArgs Set oArgs = WScript.Arguments if oArgs.Count = 0 then msgbox("Error: Must supply URL") wscript.quit 1 end if URL = oArgs(0) on error resume next Set objXML = CreateObject("MSXML2.ServerXMLHTTP") if err then msgbox("Error: " & err.description) wscript.quit 1 end if ' Call the remote machine the request objXML.open "GET", URL, False objXML.send() ' return the response 'msgbox objXML.responSetext ' clean up Set objXML = Nothing ``` The code in the VBS file is almost assuredly both overkill and underwritten, but functional none-the-less.
257,587
<p>How can I bring my WPF application to the front of the desktop? So far I've tried:</p> <pre><code>SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true); SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle); </code></pre> <p>None of which are doing the job (<code>Marshal.GetLastWin32Error()</code> is saying these operations completed successfully, and the P/Invoke attributes for each definition do have <code>SetLastError=true</code>).</p> <p>If I create a new blank WPF application, and call <code>SwitchToThisWindow</code> with a timer, it works exactly as expected, so I'm not sure why it's not working in my original case.</p> <p><strong>Edit</strong>: I'm doing this in conjunction with a global hotkey.</p>
[ { "answer_id": 257741, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 3, "selected": true, "text": "<p>Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally.</p>\n\n<pre><code>void hotkey_execute()\n{\n IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;\n BackgroundWorker bg = new BackgroundWorker();\n bg.DoWork += new DoWorkEventHandler(delegate\n {\n Thread.Sleep(10);\n SwitchToThisWindow(handle, true);\n });\n bg.RunWorkerAsync();\n}\n</code></pre>\n" }, { "answer_id": 383708, "author": "Morten Christiansen", "author_id": 4055, "author_profile": "https://Stackoverflow.com/users/4055", "pm_score": 8, "selected": false, "text": "<pre><code>myWindow.Activate();\n</code></pre>\n\n<p><em>Attempts to bring the window to the foreground and activates it.</em></p>\n\n<p>That should do the trick, unless I misunderstood and you want Always on Top behavior. In that case you want:</p>\n\n<pre><code>myWindow.TopMost = true;\n</code></pre>\n" }, { "answer_id": 415496, "author": "Matthew Xavier", "author_id": 4841, "author_profile": "https://Stackoverflow.com/users/4841", "pm_score": 4, "selected": false, "text": "<p>If the user is interacting with another application, it may not be possible to bring yours to the front. As a general rule, a process can only expect to set the foreground window if that process is already the foreground process. (Microsoft documents the restrictions in the <a href=\"http://msdn.microsoft.com/en-us/library/ms633539(VS.85).aspx\" rel=\"noreferrer\">SetForegroundWindow()</a> MSDN entry.) This is because:</p>\n\n<ol>\n<li>The user \"owns\" the foreground. For example, it would be extremely annoying if another program stole the foreground while the user is typing, at the very least interrupting her workflow, and possibly causing unintended consequences as her keystrokes meant for one application are misinterpreted by the offender until she notices the change.</li>\n<li>Imagine that each of two programs checks to see if its window is the foreground and attempts to set it to the foreground if it is not. As soon as the second program is running, the computer is rendered useless as the foreground bounces between the two at every task switch.</li>\n</ol>\n" }, { "answer_id": 596682, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 1, "selected": false, "text": "<p>The problem could be that the thread calling your code from the hook hasn't been initialized by the runtime so calling runtime methods don't work.</p>\n\n<p>Perhaps you could try doing an Invoke to marshal your code on to the UI thread to call your code that brings the window to the foreground.</p>\n" }, { "answer_id": 1565204, "author": "Amir", "author_id": 189704, "author_profile": "https://Stackoverflow.com/users/189704", "pm_score": 5, "selected": false, "text": "<p>In case you need the window to be in front the first time it loads then you should use the following:</p>\n<pre><code>private void Window_ContentRendered(object sender, EventArgs e)\n{\n this.Topmost = false;\n}\n\nprivate void Window_Initialized(object sender, EventArgs e)\n{\n this.Topmost = true;\n}\n</code></pre>\n<p>Or by overriding the methods:</p>\n<pre><code>protected override void OnContentRendered(EventArgs e)\n{\n base.OnContentRendered(e);\n Topmost = false;\n}\n\nprotected override void OnInitialized(EventArgs e)\n{\n base.OnInitialized(e);\n Topmost = true;\n}\n</code></pre>\n" }, { "answer_id": 3886715, "author": "Seth", "author_id": 339831, "author_profile": "https://Stackoverflow.com/users/339831", "pm_score": 3, "selected": false, "text": "<p>I have had a similar problem with a WPF application that gets invoked from an Access application via the Shell object.</p>\n\n<p>My solution is below - works in XP and Win7 x64 with app compiled to x86 target.</p>\n\n<p>I'd much rather do this than simulate an alt-tab.</p>\n\n<pre><code>void Window_Loaded(object sender, RoutedEventArgs e)\n{\n // make sure the window is normal or maximised\n // this was the core of the problem for me;\n // even though the default was \"Normal\", starting it via shell minimised it\n this.WindowState = WindowState.Normal;\n\n // only required for some scenarios\n this.Activate();\n}\n</code></pre>\n" }, { "answer_id": 4157347, "author": "rahmud", "author_id": 504840, "author_profile": "https://Stackoverflow.com/users/504840", "pm_score": 2, "selected": false, "text": "<p>To show ANY currently opened window import those DLL:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n [DllImportAttribute(\"User32.dll\")]\n private static extern int FindWindow(String ClassName, String WindowName);\n [DllImportAttribute(\"User32.dll\")]\n private static extern int SetForegroundWindow(int hWnd);\n</code></pre>\n\n<p>and in program We search for app with specified title (write title without first letter (index > 0))</p>\n\n<pre><code> foreach (Process proc in Process.GetProcesses())\n {\n tx = proc.MainWindowTitle.ToString();\n if (tx.IndexOf(\"Title of Your app WITHOUT FIRST LETTER\") &gt; 0)\n {\n tx = proc.MainWindowTitle;\n hWnd = proc.Handle.ToInt32(); break;\n }\n }\n hWnd = FindWindow(null, tx);\n if (hWnd &gt; 0)\n {\n SetForegroundWindow(hWnd);\n }\n</code></pre>\n" }, { "answer_id": 4831839, "author": "Jader Dias", "author_id": 48465, "author_profile": "https://Stackoverflow.com/users/48465", "pm_score": 8, "selected": false, "text": "<p>I have found a solution that brings the window to the top, but it behaves as a normal window:</p>\n\n<pre><code>if (!Window.IsVisible)\n{\n Window.Show();\n}\n\nif (Window.WindowState == WindowState.Minimized)\n{\n Window.WindowState = WindowState.Normal;\n}\n\nWindow.Activate();\nWindow.Topmost = true; // important\nWindow.Topmost = false; // important\nWindow.Focus(); // important\n</code></pre>\n" }, { "answer_id": 7559766, "author": "Hertzel Guinness", "author_id": 293974, "author_profile": "https://Stackoverflow.com/users/293974", "pm_score": 5, "selected": false, "text": "<p>To make this a quick copy-paste one -<br>\nUse this class' <code>DoOnProcess</code> method to move process' main window to foreground (but not to steal focus from other windows) </p>\n\n<pre><code>public class MoveToForeground\n{\n [DllImportAttribute(\"User32.dll\")]\n private static extern int FindWindow(String ClassName, String WindowName);\n\n const int SWP_NOMOVE = 0x0002;\n const int SWP_NOSIZE = 0x0001; \n const int SWP_SHOWWINDOW = 0x0040;\n const int SWP_NOACTIVATE = 0x0010;\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowPos\")]\n public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);\n\n public static void DoOnProcess(string processName)\n {\n var allProcs = Process.GetProcessesByName(processName);\n if (allProcs.Length &gt; 0)\n {\n Process proc = allProcs[0];\n int hWnd = FindWindow(null, proc.MainWindowTitle.ToString());\n // Change behavior by settings the wFlags params. See http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx\n SetWindowPos(new IntPtr(hWnd), 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOACTIVATE);\n }\n }\n}\n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 11552906, "author": "Zodman", "author_id": 117797, "author_profile": "https://Stackoverflow.com/users/117797", "pm_score": 5, "selected": false, "text": "<p>I know this question is rather old, but I've just come across this precise scenario and wanted to share the solution I've implemented.</p>\n\n<p>As mentioned in comments on this page, several of the solutions proposed do not work on XP, which I need to support in my scenario. While I agree with the sentiment by @Matthew Xavier that generally this is a bad UX practice, there are times where it's entirely a plausable UX.</p>\n\n<p>The solution to bringing a WPF window to the top was actually provided to me by the same code I'm using to provide the global hotkey. <a href=\"http://learnwpf.com/post/2011/08/03/Adding-a-system-wide-keyboard-hook-to-your-WPF-Application.aspx\">A blog article by Joseph Cooney</a> contains a <a href=\"https://bitbucket.org/josephcooney/learnwpf.com.samples\">link to his code samples</a> that contains the original code.</p>\n\n<p>I've cleaned up and modified the code a little, and implemented it as an extension method to System.Windows.Window. I've tested this on XP 32 bit and Win7 64 bit, both of which work correctly.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Interop;\nusing System.Runtime.InteropServices;\n\nnamespace System.Windows\n{\n public static class SystemWindows\n {\n #region Constants\n\n const UInt32 SWP_NOSIZE = 0x0001;\n const UInt32 SWP_NOMOVE = 0x0002;\n const UInt32 SWP_SHOWWINDOW = 0x0040;\n\n #endregion\n\n /// &lt;summary&gt;\n /// Activate a window from anywhere by attaching to the foreground window\n /// &lt;/summary&gt;\n public static void GlobalActivate(this Window w)\n {\n //Get the process ID for this window's thread\n var interopHelper = new WindowInteropHelper(w);\n var thisWindowThreadId = GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);\n\n //Get the process ID for the foreground window's thread\n var currentForegroundWindow = GetForegroundWindow();\n var currentForegroundWindowThreadId = GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);\n\n //Attach this window's thread to the current window's thread\n AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);\n\n //Set the window position\n SetWindowPos(interopHelper.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);\n\n //Detach this window's thread from the current window's thread\n AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);\n\n //Show and activate the window\n if (w.WindowState == WindowState.Minimized) w.WindowState = WindowState.Normal;\n w.Show();\n w.Activate();\n }\n\n #region Imports\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);\n\n [DllImport(\"user32.dll\")]\n private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);\n\n [DllImport(\"user32.dll\")]\n public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);\n\n #endregion\n }\n}\n</code></pre>\n\n<p>I hope this code helps others who encounter this problem.</p>\n" }, { "answer_id": 11991009, "author": "Omzig", "author_id": 1178375, "author_profile": "https://Stackoverflow.com/users/1178375", "pm_score": 3, "selected": false, "text": "<p>Well, since this is such a hot topic... here is what works for me. I got errors if I didn't do it this way because Activate() will error out on you if you cannot see the window.</p>\n\n<p>Xaml:</p>\n\n<pre><code>&lt;Window .... \n Topmost=\"True\" \n .... \n ContentRendered=\"mainWindow_ContentRendered\"&gt; .... &lt;/Window&gt;\n</code></pre>\n\n<p>Codebehind:</p>\n\n<pre><code>private void mainWindow_ContentRendered(object sender, EventArgs e)\n{\n this.Topmost = false;\n this.Activate();\n _UsernameTextBox.Focus();\n}\n</code></pre>\n\n<p>This was the only way for me to get the window to show on top. Then activate it so you can type in the box without having to set focus with the mouse. control.Focus() wont work unless the window is Active();</p>\n" }, { "answer_id": 26023969, "author": "Chris", "author_id": 1421982, "author_profile": "https://Stackoverflow.com/users/1421982", "pm_score": 0, "selected": false, "text": "<p>If you are trying to hide the window, for example you minimize the window, I have found that using </p>\n\n<pre><code> this.Hide();\n</code></pre>\n\n<p>will hide it correctly, then simply using </p>\n\n<pre><code> this.Show();\n</code></pre>\n\n<p>will then show the window as the top most item once again.</p>\n" }, { "answer_id": 27420355, "author": "Jamaxack", "author_id": 2077676, "author_profile": "https://Stackoverflow.com/users/2077676", "pm_score": 3, "selected": false, "text": "<p>I know that this is late answer, maybe helpful for researchers</p>\n\n<pre><code> if (!WindowName.IsVisible)\n {\n WindowName.Show();\n WindowName.Activate();\n }\n</code></pre>\n" }, { "answer_id": 36740759, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 4, "selected": false, "text": "<h2>Why some of the answers on this page are wrong!</h2>\n\n<ul>\n<li><p>Any answer that uses <code>window.Focus()</code> is wrong. </p>\n\n<ul>\n<li>Why? If a notification message pops up, <code>window.Focus()</code> will grab the focus away from whatever the user is typing at the time. This is insanely frustrating for end users, especially if the popups occur quite frequently.</li>\n</ul></li>\n<li><p>Any answer that uses <code>window.Activate()</code> is wrong.</p>\n\n<ul>\n<li>Why? It will make any parent windows visible as well.</li>\n</ul></li>\n<li>Any answer that omits <code>window.ShowActivated = false</code> is wrong.\n\n<ul>\n<li>Why? It will grab the focus away from another window when the message pops up which is very annoying!</li>\n</ul></li>\n<li>Any answer that does not use <code>Visibility.Visible</code> to hide/show the window is wrong.\n\n<ul>\n<li>Why? If we are using Citrix, if the window is not collapsed when it is closed, it will leave a weird black rectangular hold on the screen. Thus, we cannot use <code>window.Show()</code> and <code>window.Hide()</code>.</li>\n</ul></li>\n</ul>\n\n<p>Essentially:</p>\n\n<ul>\n<li>The window should not grab the focus away from any other window when it activates;</li>\n<li>The window should not activate its parent when it is shown;</li>\n<li>The window should be compatible with Citrix.</li>\n</ul>\n\n<h2>MVVM Solution</h2>\n\n<p>This code is 100% compatible with Citrix (no blank areas of the screen). It is tested with both normal WPF and DevExpress.</p>\n\n<p>This answer is intended for any use case where we want a small notification window that is always in front of other windows (if the user selects this in the preferences).</p>\n\n<p>If this answer seems more complex than the others, it's because it is robust, enterprise level code. Some of the other answers on this page are simple, but do not actually work.</p>\n\n<h2>XAML - Attached Property</h2>\n\n<p>Add this attached property to any <code>UserControl</code> within the window. The attached property will:</p>\n\n<ul>\n<li>Wait until the <code>Loaded</code> event is fired (otherwise it cannot look up the visual tree to find the parent window).</li>\n<li>Add an event handler that ensures that the window is visible or not.</li>\n</ul>\n\n<p>At any point, you can set the window to be in front or not, by flipping the value of the attached property.</p>\n\n<pre><code>&lt;UserControl x:Class=\"...\"\n ...\n attachedProperties:EnsureWindowInForeground.EnsureWindowInForeground=\n \"{Binding EnsureWindowInForeground, Mode=OneWay}\"&gt;\n</code></pre>\n\n<h2>C# - Helper Method</h2>\n\n<pre><code>public static class HideAndShowWindowHelper\n{\n /// &lt;summary&gt;\n /// Intent: Ensure that small notification window is on top of other windows.\n /// &lt;/summary&gt;\n /// &lt;param name=\"window\"&gt;&lt;/param&gt;\n public static void ShiftWindowIntoForeground(Window window)\n {\n try\n {\n // Prevent the window from grabbing focus away from other windows the first time is created.\n window.ShowActivated = false;\n\n // Do not use .Show() and .Hide() - not compatible with Citrix!\n if (window.Visibility != Visibility.Visible)\n {\n window.Visibility = Visibility.Visible;\n }\n\n // We can't allow the window to be maximized, as there is no de-maximize button!\n if (window.WindowState == WindowState.Maximized)\n {\n window.WindowState = WindowState.Normal;\n }\n\n window.Topmost = true;\n }\n catch (Exception)\n {\n // Gulp. Avoids \"Cannot set visibility while window is closing\".\n }\n }\n\n /// &lt;summary&gt;\n /// Intent: Ensure that small notification window can be hidden by other windows.\n /// &lt;/summary&gt;\n /// &lt;param name=\"window\"&gt;&lt;/param&gt;\n public static void ShiftWindowIntoBackground(Window window)\n {\n try\n {\n // Prevent the window from grabbing focus away from other windows the first time is created.\n window.ShowActivated = false;\n\n // Do not use .Show() and .Hide() - not compatible with Citrix!\n if (window.Visibility != Visibility.Collapsed)\n {\n window.Visibility = Visibility.Collapsed;\n }\n\n // We can't allow the window to be maximized, as there is no de-maximize button!\n if (window.WindowState == WindowState.Maximized)\n {\n window.WindowState = WindowState.Normal;\n }\n\n window.Topmost = false;\n }\n catch (Exception)\n {\n // Gulp. Avoids \"Cannot set visibility while window is closing\".\n }\n }\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<p>In order to use this, you need to create the window in your ViewModel:</p>\n\n<pre><code>private ToastView _toastViewWindow;\nprivate void ShowWindow()\n{\n if (_toastViewWindow == null)\n {\n _toastViewWindow = new ToastView();\n _dialogService.Show&lt;ToastView&gt;(this, this, _toastViewWindow, true);\n }\n ShiftWindowOntoScreenHelper.ShiftWindowOntoScreen(_toastViewWindow);\n HideAndShowWindowHelper.ShiftWindowIntoForeground(_toastViewWindow);\n}\n\nprivate void HideWindow()\n{\n if (_toastViewWindow != null)\n {\n HideAndShowWindowHelper.ShiftWindowIntoBackground(_toastViewWindow);\n }\n}\n</code></pre>\n\n<h2>Additional links</h2>\n\n<p>For tips on how ensure that a notification window always shifts back onto the visible screen, see my answer: <a href=\"https://stackoverflow.com/questions/37927011/in-wpf-how-to-shift-a-window-onto-the-screen-if-it-is-off-the-screen\">In WPF, how to shift a window onto the screen if it is off the screen?</a>.</p>\n" }, { "answer_id": 42050523, "author": "Matrix", "author_id": 3779636, "author_profile": "https://Stackoverflow.com/users/3779636", "pm_score": 2, "selected": false, "text": "<p>These codes will work fine all times.</p>\n\n<p>At first set the activated event handler in XAML:</p>\n\n<pre><code>Activated=\"Window_Activated\"\n</code></pre>\n\n<p>Add below line to your Main Window constructor block:</p>\n\n<pre><code>public MainWindow()\n{\n InitializeComponent();\n this.LocationChanged += (sender, e) =&gt; this.Window_Activated(sender, e);\n}\n</code></pre>\n\n<p>And inside the activated event handler copy this codes:</p>\n\n<pre><code>private void Window_Activated(object sender, EventArgs e)\n{\n if (Application.Current.Windows.Count &gt; 1)\n {\n foreach (Window win in Application.Current.Windows)\n try\n {\n if (!win.Equals(this))\n {\n if (!win.IsVisible)\n {\n win.ShowDialog();\n }\n\n if (win.WindowState == WindowState.Minimized)\n {\n win.WindowState = WindowState.Normal;\n }\n\n win.Activate();\n win.Topmost = true;\n win.Topmost = false;\n win.Focus();\n }\n }\n catch { }\n }\n else\n this.Focus();\n}\n</code></pre>\n\n<p>These steps will works fine and will bring to front all other windows into their parents window.</p>\n" }, { "answer_id": 43379830, "author": "d.moncada", "author_id": 701560, "author_profile": "https://Stackoverflow.com/users/701560", "pm_score": 2, "selected": false, "text": "<p>Just wanted to add another solution to this question. This implementation works for my scenario, where CaliBurn is responsible for displaying the main Window.</p>\n\n<pre><code>protected override void OnStartup(object sender, StartupEventArgs e)\n{\n DisplayRootViewFor&lt;IMainWindowViewModel&gt;();\n\n Application.MainWindow.Topmost = true;\n Application.MainWindow.Activate();\n Application.MainWindow.Activated += OnMainWindowActivated;\n}\n\nprivate static void OnMainWindowActivated(object sender, EventArgs e)\n{\n var window = sender as Window;\n if (window != null)\n {\n window.Activated -= OnMainWindowActivated;\n window.Topmost = false;\n window.Focus();\n }\n}\n</code></pre>\n" }, { "answer_id": 43596502, "author": "Michel P.", "author_id": 2547940, "author_profile": "https://Stackoverflow.com/users/2547940", "pm_score": 0, "selected": false, "text": "<p>Remember not to put the code that shows that window inside a PreviewMouseDoubleClick handler as the active window will switch back to the window who handled the event. \nJust put it in the MouseDoubleClick event handler or stop bubbling by setting e.Handled to True. </p>\n\n<p>In my case i was handling the PreviewMouseDoubleClick on a Listview and was not setting the e.Handled = true then it raised the MouseDoubleClick event witch sat focus back to the original window.</p>\n" }, { "answer_id": 44054778, "author": "Mike", "author_id": 7612816, "author_profile": "https://Stackoverflow.com/users/7612816", "pm_score": -1, "selected": false, "text": "<p>I built an extension method to make for easy reuse.</p>\n\n<pre><code>using System.Windows.Forms;\n namespace YourNamespace{\n public static class WindowsFormExtensions {\n public static void PutOnTop(this Form form) {\n form.Show();\n form.Activate();\n }// END PutOnTop() \n }// END class\n }// END namespace\n</code></pre>\n\n<p>Call in the Form Constructor </p>\n\n<pre><code>namespace YourNamespace{\n public partial class FormName : Form {\n public FormName(){\n this.PutOnTop();\n InitalizeComponents();\n }// END Constructor\n } // END Form \n}// END namespace\n</code></pre>\n" }, { "answer_id": 70382243, "author": "Alex Martin", "author_id": 2237888, "author_profile": "https://Stackoverflow.com/users/2237888", "pm_score": 0, "selected": false, "text": "<p>This is a combination of a few suggestions above that works well and is simple. It only comes to front when those events fire, so any window that pops up after the event will stay on top of course.</p>\n<pre><code>public partial class MainWindow : Window\n{\n protected override void OnContentRendered(EventArgs e)\n {\n base.OnContentRendered(e);\n\n Topmost = true;\n Topmost = false;\n }\n protected override void OnInitialized(EventArgs e)\n {\n base.OnInitialized(e);\n\n Topmost = true;\n Topmost = false;\n }\n\n ....\n}\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569/" ]
How can I bring my WPF application to the front of the desktop? So far I've tried: ``` SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true); SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle); ``` None of which are doing the job (`Marshal.GetLastWin32Error()` is saying these operations completed successfully, and the P/Invoke attributes for each definition do have `SetLastError=true`). If I create a new blank WPF application, and call `SwitchToThisWindow` with a timer, it works exactly as expected, so I'm not sure why it's not working in my original case. **Edit**: I'm doing this in conjunction with a global hotkey.
Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally. ``` void hotkey_execute() { IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle; BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(delegate { Thread.Sleep(10); SwitchToThisWindow(handle, true); }); bg.RunWorkerAsync(); } ```
257,605
<p>I'm currently working on a small project with OCaml; a simple mathematical expression simplifier. I'm supposed to find certain patterns inside an expression, and simplify them so the number of parenthesis inside the expression decreases. So far I've been able to implement most rules except two, for which I've decided to create a recursive, pattern-matching "filter" function. The two rules I need to implement are:</p> <p>-Turn all expressions of the form a - (b + c) or similar into a - b - c</p> <p>-Turn all expressions of the form a / (b * c) or similar into a / b / c</p> <p>...which I suspect would be fairly simple, and once I've managed to implement one, I can implement the other easily. However, I'm having trouble with the recursive pattern-matching function. My type expression is this:</p> <pre><code>type expr = | Var of string (* variable *) | Sum of expr * expr (* sum *) | Diff of expr * expr (* difference *) | Prod of expr * expr (* product *) | Quot of expr * expr (* quotient *) ;; </code></pre> <p>And what I'm mainly having trouble on, is in the match expression. For example, I'm trying something like this:</p> <pre><code>let rec filter exp = match exp with | Var v -&gt; Var v | Sum(e1, e2) -&gt; Sum(e1, e2) | Prod(e1, e2) -&gt; Prod(e1, e2) | Diff(e1, e2) -&gt; match e2 with | Sum(e3, e4) -&gt; filter (diffRule e2) | Diff(e3, e4) -&gt; filter (diffRule e2) | _ -&gt; filter e2 | Quot(e1, e2) -&gt; ***this line*** match e2 with | Quot(e3, e4) -&gt; filter (quotRule e2) | Prod(e3, e4) -&gt; filter (quotRule e2) | _ -&gt; filter e2 ;; </code></pre> <p>However, it seems that the match expression on the marked line is being recognized as being part of the previous "inner match" instead of the "principal match", so all "Quot(...)" expressions are never recognized. Is it even possible to have match expressions inside other match expressions like this? And what would be the correct way to end the inner match so I can continue matching the other possibilities?</p> <p>Ignore the logic, since it's pretty much what I came up with first, it's just that I haven't been able to try it since I have to deal with this "match" error first, although any recommendation on how to handle the recursiveness or the logic would be welcome.</p>
[ { "answer_id": 257627, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 7, "selected": true, "text": "<p><strong>Quick Solution</strong></p>\n<p>You just need to add parentheses, or <code>begin</code>/<code>end</code>, around the inner match:</p>\n<pre class=\"lang-ml prettyprint-override\"><code>let rec filter exp =\n match exp with\n | Var v -&gt; Var v\n | Sum (e1, e2) -&gt; Sum (e1, e2)\n | Prod (e1, e2) -&gt; Prod (e1, e2)\n | Diff (e1, e2) -&gt;\n (match e2 with\n | Sum (e3, e4) -&gt; filter (diffRule e2)\n | Diff (e3, e4) -&gt; filter (diffRule e2)\n | _ -&gt; filter e2)\n | Quot (e1, e2) -&gt;\n (match e2 with\n | Quot (e3, e4) -&gt; filter (quotRule e2)\n | Prod (e3, e4) -&gt; filter (quotRule e2)\n | _ -&gt; filter e2)\n;;\n</code></pre>\n<p><strong>Simplifications</strong></p>\n<p>In your particular case there is no need for a nested match.\nYou can just use bigger patterns. You can also eliminate the duplication in the nested rules using &quot;<code>|</code>&quot; (&quot;or&quot;) patterns:</p>\n<pre><code>let rec filter exp =\n match exp with\n | Var v -> Var v\n | Sum (e1, e2) -> Sum (e1, e2)\n | Prod (e1, e2) -> Prod (e1, e2)\n | Diff (e1, (Sum (e3, e4) | Diff (e3, e4) as e2)) -> filter (diffRule e2)\n | Diff (e1, e2) -> filter e2\n | Quot (e1, (Quot (e3, e4) | Prod (e3, e4) as e2)) -> filter (quotRule e2)\n | Quot (e1, e2) -> filter e2\n;;\n</code></pre>\n<p>You can make it even more readable by replacing unused pattern variables with <code>_</code> (underscore).\nThis also works for whole sub patterns such as the <code>(e3,e4)</code> tuple:</p>\n<pre><code>let rec filter exp =\n match exp with\n | Var v -> Var v\n | Sum (e1, e2) -> Sum (e1, e2)\n | Prod (e1, e2) -> Prod (e1, e2)\n | Diff (_, (Sum _ | Diff _ as e2)) -> filter (diffRule e2)\n | Diff (_, e2) -> filter e2\n | Quot (_, (Quot _ | Prod _ as e2)) -> filter (quotRule e2)\n | Quot (_, e2) -> filter e2\n;;\n</code></pre>\n<p>In the same way, you can proceed simplifying. For example, the first three cases (<code>Var</code>, <code>Sum</code>, <code>Prod</code>) are returned unmodified, which you can express directly:</p>\n<pre><code>let rec filter exp =\n match exp with\n | Var _ | Sum _ | Prod _ as e -> e\n | Diff (_, (Sum _ | Diff _ as e2)) -> filter (diffRule e2)\n | Diff (_, e2) -> filter e2\n | Quot (_, (Quot _ | Prod _ as e2)) -> filter (quotRule e2)\n | Quot (_, e2) -> filter e2\n;;\n</code></pre>\n<p>Finally, you can replace <code>e2</code> by <code>e</code> and replace <code>match</code> with the <code>function</code> shortcut:</p>\n<pre><code>let rec filter = function\n | Var _ | Sum _ | Prod _ as e -> e\n | Diff (_, (Sum _ | Diff _ as e)) -> filter (diffRule e)\n | Diff (_, e) -> filter e\n | Quot (_, (Quot _ | Prod _ as e)) -> filter (quotRule e)\n | Quot (_, e) -> filter e\n;;\n</code></pre>\n<p>OCaml's pattern syntax is nice, isn't it?</p>\n" }, { "answer_id": 264060, "author": "zrr", "author_id": 34515, "author_profile": "https://Stackoverflow.com/users/34515", "pm_score": 3, "selected": false, "text": "<p>You can make this terser (and I would argue clearer) by judicious use of underscores, as's and or-patterns. The resulting code is also more efficient, because it allocates less (in the Var, Sum and Prod cases)</p>\n\n<pre><code>let rec filter = function\n| Var _ | Sum _ | Prod _ as e -&gt; e\n| Diff (_, (Sum _ | Diff _) as e) -&gt; filter (diffRule e)\n| Diff (_,e) -&gt; e\n| Quot (_, (Quot _| Prod _) as e) -&gt; filter (quoteRule e)\n| Quot (_,e) -&gt; filter e\n;;\n</code></pre>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9506/" ]
I'm currently working on a small project with OCaml; a simple mathematical expression simplifier. I'm supposed to find certain patterns inside an expression, and simplify them so the number of parenthesis inside the expression decreases. So far I've been able to implement most rules except two, for which I've decided to create a recursive, pattern-matching "filter" function. The two rules I need to implement are: -Turn all expressions of the form a - (b + c) or similar into a - b - c -Turn all expressions of the form a / (b \* c) or similar into a / b / c ...which I suspect would be fairly simple, and once I've managed to implement one, I can implement the other easily. However, I'm having trouble with the recursive pattern-matching function. My type expression is this: ``` type expr = | Var of string (* variable *) | Sum of expr * expr (* sum *) | Diff of expr * expr (* difference *) | Prod of expr * expr (* product *) | Quot of expr * expr (* quotient *) ;; ``` And what I'm mainly having trouble on, is in the match expression. For example, I'm trying something like this: ``` let rec filter exp = match exp with | Var v -> Var v | Sum(e1, e2) -> Sum(e1, e2) | Prod(e1, e2) -> Prod(e1, e2) | Diff(e1, e2) -> match e2 with | Sum(e3, e4) -> filter (diffRule e2) | Diff(e3, e4) -> filter (diffRule e2) | _ -> filter e2 | Quot(e1, e2) -> ***this line*** match e2 with | Quot(e3, e4) -> filter (quotRule e2) | Prod(e3, e4) -> filter (quotRule e2) | _ -> filter e2 ;; ``` However, it seems that the match expression on the marked line is being recognized as being part of the previous "inner match" instead of the "principal match", so all "Quot(...)" expressions are never recognized. Is it even possible to have match expressions inside other match expressions like this? And what would be the correct way to end the inner match so I can continue matching the other possibilities? Ignore the logic, since it's pretty much what I came up with first, it's just that I haven't been able to try it since I have to deal with this "match" error first, although any recommendation on how to handle the recursiveness or the logic would be welcome.
**Quick Solution** You just need to add parentheses, or `begin`/`end`, around the inner match: ```ml let rec filter exp = match exp with | Var v -> Var v | Sum (e1, e2) -> Sum (e1, e2) | Prod (e1, e2) -> Prod (e1, e2) | Diff (e1, e2) -> (match e2 with | Sum (e3, e4) -> filter (diffRule e2) | Diff (e3, e4) -> filter (diffRule e2) | _ -> filter e2) | Quot (e1, e2) -> (match e2 with | Quot (e3, e4) -> filter (quotRule e2) | Prod (e3, e4) -> filter (quotRule e2) | _ -> filter e2) ;; ``` **Simplifications** In your particular case there is no need for a nested match. You can just use bigger patterns. You can also eliminate the duplication in the nested rules using "`|`" ("or") patterns: ``` let rec filter exp = match exp with | Var v -> Var v | Sum (e1, e2) -> Sum (e1, e2) | Prod (e1, e2) -> Prod (e1, e2) | Diff (e1, (Sum (e3, e4) | Diff (e3, e4) as e2)) -> filter (diffRule e2) | Diff (e1, e2) -> filter e2 | Quot (e1, (Quot (e3, e4) | Prod (e3, e4) as e2)) -> filter (quotRule e2) | Quot (e1, e2) -> filter e2 ;; ``` You can make it even more readable by replacing unused pattern variables with `_` (underscore). This also works for whole sub patterns such as the `(e3,e4)` tuple: ``` let rec filter exp = match exp with | Var v -> Var v | Sum (e1, e2) -> Sum (e1, e2) | Prod (e1, e2) -> Prod (e1, e2) | Diff (_, (Sum _ | Diff _ as e2)) -> filter (diffRule e2) | Diff (_, e2) -> filter e2 | Quot (_, (Quot _ | Prod _ as e2)) -> filter (quotRule e2) | Quot (_, e2) -> filter e2 ;; ``` In the same way, you can proceed simplifying. For example, the first three cases (`Var`, `Sum`, `Prod`) are returned unmodified, which you can express directly: ``` let rec filter exp = match exp with | Var _ | Sum _ | Prod _ as e -> e | Diff (_, (Sum _ | Diff _ as e2)) -> filter (diffRule e2) | Diff (_, e2) -> filter e2 | Quot (_, (Quot _ | Prod _ as e2)) -> filter (quotRule e2) | Quot (_, e2) -> filter e2 ;; ``` Finally, you can replace `e2` by `e` and replace `match` with the `function` shortcut: ``` let rec filter = function | Var _ | Sum _ | Prod _ as e -> e | Diff (_, (Sum _ | Diff _ as e)) -> filter (diffRule e) | Diff (_, e) -> filter e | Quot (_, (Quot _ | Prod _ as e)) -> filter (quotRule e) | Quot (_, e) -> filter e ;; ``` OCaml's pattern syntax is nice, isn't it?
257,616
<p>This is the <code>PATH</code> variable without sudo:</p> <pre><code>$ echo 'echo $PATH' | sh /opt/local/ruby/bin:/usr/bin:/bin </code></pre> <p>This is the <code>PATH</code> variable with sudo:</p> <pre><code>$ echo 'echo $PATH' | sudo sh /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin </code></pre> <p>As far as I can tell, <code>sudo</code> is supposed to leave <code>PATH</code> untouched. What's going on? How do I change this? (This is on Ubuntu 8.04).</p> <p>UPDATE: as far as I can see, none of the scripts started as root change <code>PATH</code> in any way.</p> <p>From <code>man sudo</code>: </p> <blockquote> <p>To prevent command spoofing, sudo checks ``.'' and ``'' (both denoting current directory) last when searching for a command in the user's PATH (if one or both are in the PATH). <strong>Note, however, that the actual PATH environment variable is not modified and is passed unchanged to the program that sudo executes.</strong></p> </blockquote>
[ { "answer_id": 257644, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 5, "selected": false, "text": "<p><code>PATH</code> is an environment variable, and as such is by default reset by sudo.</p>\n\n<p>You need special permissions to be permitted to do this. </p>\n\n<p>From <code>man sudo</code></p>\n\n<pre>\n -E The <b>-E</b> (preserve environment) option will override the env_reset\n option in sudoers(5)). It is only available when either the match-\n ing command has the SETENV tag or the setenv option is set in sudo-\n ers(5).\n</pre>\n\n<pre>\n Environment variables to be set for the command may also be passed on\n the command line in the form of <b>VAR</b>=value, e.g.\n <b>LD_LIBRARY_PATH</b>=/usr/local/pkg/lib. Variables passed on the command\n line are subject to the same restrictions as normal environment vari-\n ables with one important exception. If the setenv option is set in\n sudoers, the command to be run has the SETENV tag set or the command\n matched is ALL, the user may set variables that would overwise be for-\n bidden. See sudoers(5) for more information.\n</pre>\n\n<p>An Example of usage: \n</p>\n\n<pre><code>cat >> test.sh\nenv | grep \"MYEXAMPLE\" ;\n^D\n</code></pre>\n\n<pre class=\"lang-bash prettyprint-override\"><code>sh test.sh \nMYEXAMPLE=1 sh test.sh\n# MYEXAMPLE=1\nMYEXAMPLE=1 sudo sh test.sh \nMYEXAMPLE=1 sudo MYEXAMPLE=2 sh test.sh \n# MYEXAMPLE=2\n</code></pre>\n\n<h3>update</h3>\n\n<pre>\nman 5 sudoers : \n\n env_reset If set, sudo will reset the environment to only contain\n the LOGNAME, SHELL, USER, USERNAME and the SUDO_* vari-\n ables. Any variables in the caller's environment that\n match the env_keep and env_check lists are then added.\n The default contents of the env_keep and env_check\n lists are displayed when sudo is run by root with the\n -V option. If sudo was compiled with the SECURE_PATH\n option, its value will be used for the PATH environment\n variable. This flag is on by default.\n</pre>\n\n<p>So may need to check that this is/is not compiled in. </p>\n\n<p>It is by default in <b>Gentoo</b></p>\n\n<pre class=\"lang-bash prettyprint-override\"><code># ( From the build Script )\n....\nROOTPATH=$(cleanpath /bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/bin${ROOTPATH:+:${ROOTPATH}})\n....\neconf --with-secure-path=\"${ROOTPATH}\" \n</code></pre>\n" }, { "answer_id": 257666, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 8, "selected": false, "text": "<p>This is <del>an annoying function</del> <i>a feature</i> of sudo on many distributions.</p>\n\n<p>To work around this \"problem\" on ubuntu I do\nthe following in my ~/.bashrc</p>\n\n<pre><code>alias sudo='sudo env PATH=$PATH'\n</code></pre>\n\n<p>Note the above will work for commands that don't reset the $PATH themselves.\nHowever `su' resets it's $PATH so you must use -p to tell it not to. I.E.:</p>\n\n<pre><code>sudo su -p\n</code></pre>\n" }, { "answer_id": 375780, "author": "Tyler Rick", "author_id": 47185, "author_profile": "https://Stackoverflow.com/users/47185", "pm_score": 4, "selected": false, "text": "<p>Looks like this bug has been around for quite a while! Here are some bug references you may find helpful (and may want to subscribe to / vote up, hint, hint...):</p>\n\n<hr>\n\n<p><a href=\"http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=85123\" rel=\"noreferrer\" title=\"sudo: SECURE_PATH still can&#39;t be overridden\">Debian bug #85123 (\"sudo: SECURE_PATH still can't be overridden\") (from 2001!)</a></p>\n\n<blockquote>\n <p>It seems that Bug#20996 is still present in this version of sudo. The\n changelog says that it can be overridden at runtime but I haven't yet\n discovered how.</p>\n</blockquote>\n\n<p>They mention putting something like this in your sudoers file:</p>\n\n<pre><code>Defaults secure_path=\"/bin:/usr/bin:/usr/local/bin\"\n</code></pre>\n\n<p>but when I do that in Ubuntu 8.10 at least, it gives me this error:</p>\n\n<pre><code>visudo: unknown defaults entry `secure_path' referenced near line 10\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/50797\" rel=\"noreferrer\" title=\"sudo built with --with-secure-path is problematic\">Ubuntu bug #50797 (\"sudo built with --with-secure-path is problematic\")</a></p>\n\n<blockquote>\n <p>Worse still, as far as I can tell, it\n is impossible to respecify secure_path\n in the sudoers file. So if, for\n example, you want to offer your users\n easy access to something under /opt,\n you must recompile sudo.</p>\n \n <hr>\n \n <p>Yes. There <em>needs</em> to be a way to\n override this \"feature\" without having\n to recompile. Nothing worse then\n security bigots telling you what's\n best for your environment and then not\n giving you a way to turn it off.</p>\n \n <hr>\n \n <p>This is really annoying. It might be\n wise to keep current behavior by\n default for security reasons, but\n there should be a way of overriding it\n other than recompiling from source\n code! Many people ARE in need of PATH\n inheritance. I wonder why no\n maintainers look into it, which seems\n easy to come up with an acceptable\n solution.</p>\n \n <hr>\n \n <p>I worked around it like this:</p>\n\n<pre><code>mv /usr/bin/sudo /usr/bin/sudo.orig\n</code></pre>\n \n <p>then create a file /usr/bin/sudo containing the following:</p>\n\n<pre><code>#!/bin/bash\n/usr/bin/sudo.orig env PATH=$PATH \"$@\"\n</code></pre>\n \n <p>then your regular sudo works just like the non secure-path sudo</p>\n</blockquote>\n\n<hr>\n\n<p><a href=\"https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/192651/\" rel=\"noreferrer\" title=\"sudo path is always reset\">Ubuntu bug #192651 (\"sudo path is always reset\")</a></p>\n\n<blockquote>\n <p>Given that a duplicate of this bug was\n originally filed in July 2006, I'm not\n clear how long an ineffectual env_keep\n has been in operation. Whatever the\n merits of forcing users to employ\n tricks such as that listed above,\n surely the man pages for sudo and\n sudoers should reflect the fact that\n options to modify the PATH are\n effectively redundant.</p>\n \n <p>Modifying documentation to reflect\n actual execution is non destabilising\n and very helpful.</p>\n</blockquote>\n\n<hr>\n\n<p><a href=\"https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/226595\" rel=\"noreferrer\" title=\"impossible to retain/specify PATH\">Ubuntu bug #226595 (\"impossible to retain/specify PATH\")</a></p>\n\n<blockquote>\n <p>I need to be able to run sudo with\n additional non-std binary folders in\n the PATH. Having already added my\n requirements to /etc/environment I was\n surprised when I got errors about\n missing commands when running them\n under sudo.....</p>\n \n <p>I tried the following to fix this\n without sucess: </p>\n \n <ol>\n <li><p>Using the \"<code>sudo -E</code>\" option - did not work. My existing PATH was still reset by sudo </p></li>\n <li><p>Changing \"<code>Defaults env_reset</code>\" to \"<code>Defaults !env_reset</code>\" in /etc/sudoers -- also did not work (even when combined with sudo -E) </p></li>\n <li><p>Uncommenting <code>env_reset</code> (e.g. \"<code>#Defaults env_reset</code>\") in /etc/sudoers -- also did not work.</p></li>\n <li><p>Adding '<code>Defaults env_keep += \"PATH\"</code>' to /etc/sudoers -- also did not work.</p></li>\n </ol>\n \n <p>Clearly - despite the man\n documentation - sudo is completely\n hardcoded regarding PATH and does not\n allow any flexibility regarding\n retaining the users PATH. Very\n annoying as I can't run non-default\n software under root permissions using\n sudo.</p>\n</blockquote>\n" }, { "answer_id": 471730, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Er, it's not really a test if you don't add something to your path:</p>\n\n<pre>\nbill@bill-desktop:~$ ls -l /opt/pkg/bin\ntotal 12\n-rwxr-xr-x 1 root root 28 2009-01-22 18:58 foo\nbill@bill-desktop:~$ which foo\n/opt/pkg/bin/foo\nbill@bill-desktop:~$ sudo su\nroot@bill-desktop:/home/bill# which foo\nroot@bill-desktop:/home/bill# \n</pre>\n" }, { "answer_id": 1072871, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Works now using sudo from the karmic repositories. Details from my configuration:</p>\n\n<pre><code>root@sphinx:~# cat /etc/sudoers | grep -v -e '^$' -e '^#'\nDefaults env_reset\nDefaults secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/grub-1.96/sbin:/opt/grub-1.96/bin\"\nroot ALL=(ALL) ALL\n%admin ALL=(ALL) ALL\nroot@sphinx:~# cat /etc/apt/sources.list\ndeb http://au.archive.ubuntu.com/ubuntu/ jaunty main restricted universe\ndeb-src http://au.archive.ubuntu.com/ubuntu/ jaunty main restricted universe\n\ndeb http://au.archive.ubuntu.com/ubuntu/ jaunty-updates main restricted universe\ndeb-src http://au.archive.ubuntu.com/ubuntu/ jaunty-updates main restricted universe\n\ndeb http://security.ubuntu.com/ubuntu jaunty-security main restricted universe\ndeb-src http://security.ubuntu.com/ubuntu jaunty-security main restricted universe\n\ndeb http://au.archive.ubuntu.com/ubuntu/ karmic main restricted universe\ndeb-src http://au.archive.ubuntu.com/ubuntu/ karmic main restricted universe\n\ndeb http://au.archive.ubuntu.com/ubuntu/ karmic-updates main restricted universe\ndeb-src http://au.archive.ubuntu.com/ubuntu/ karmic-updates main restricted universe\n\ndeb http://security.ubuntu.com/ubuntu karmic-security main restricted universe\ndeb-src http://security.ubuntu.com/ubuntu karmic-security main restricted universe\nroot@sphinx:~# \n\nroot@sphinx:~# cat /etc/apt/preferences \nPackage: sudo\nPin: release a=karmic-security\nPin-Priority: 990\n\nPackage: sudo\nPin: release a=karmic-updates\nPin-Priority: 960\n\nPackage: sudo\nPin: release a=karmic\nPin-Priority: 930\n\nPackage: *\nPin: release a=jaunty-security\nPin-Priority: 900\n\nPackage: *\nPin: release a=jaunty-updates\nPin-Priority: 700\n\nPackage: *\nPin: release a=jaunty\nPin-Priority: 500\n\nPackage: *\nPin: release a=karmic-security\nPin-Priority: 450\n\nPackage: *\nPin: release a=karmic-updates\nPin-Priority: 250\n\nPackage: *\nPin: release a=karmic\nPin-Priority: 50\nroot@sphinx:~# apt-cache policy sudo\nsudo:\n Installed: 1.7.0-1ubuntu2\n Candidate: 1.7.0-1ubuntu2\n Package pin: 1.7.0-1ubuntu2\n Version table:\n *** 1.7.0-1ubuntu2 930\n 50 http://au.archive.ubuntu.com karmic/main Packages\n 100 /var/lib/dpkg/status\n 1.6.9p17-1ubuntu3 930\n 500 http://au.archive.ubuntu.com jaunty/main Packages\nroot@sphinx:~# echo $PATH\n/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/grub-1.96/sbin:/opt/grub-1.96/bin\nroot@sphinx:~# exit\nexit\nabolte@sphinx:~$ echo $PATH\n/home/abolte/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/grub-1.96/sbin:/opt/grub-1.96/bin:/opt/chromium-17593:/opt/grub-1.96/sbin:/opt/grub-1.96/bin:/opt/xpra-0.0.6/bin\nabolte@sphinx:~$ \n</code></pre>\n\n<p>It's wonderful to finally have this solved without using a hack.</p>\n" }, { "answer_id": 1910765, "author": "daggerok", "author_id": 232487, "author_profile": "https://Stackoverflow.com/users/232487", "pm_score": 2, "selected": false, "text": "<pre><code># cat .bash_profile | grep PATH\nPATH=$HOME/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin\nexport PATH\n\n# cat /etc/sudoers | grep Defaults\nDefaults requiretty\nDefaults env_reset\nDefaults env_keep = \"SOME_PARAM1 SOME_PARAM2 ... PATH\"\n</code></pre>\n" }, { "answer_id": 2479560, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Just comment out \"Defaults env_reset\" in /etc/sudoers</p>\n" }, { "answer_id": 3137125, "author": "user378555", "author_id": 378555, "author_profile": "https://Stackoverflow.com/users/378555", "pm_score": 2, "selected": false, "text": "<p>Secure_path is your friend, but if you want to exempt yourself from secure_path just do</p>\n\n<pre>\nsudo visudo\n</pre>\n\n<p>And append</p>\n\n<pre>\nDefaults exempt_group=your_goup\n</pre>\n\n<p>If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.</p>\n" }, { "answer_id": 4572018, "author": "Jacob", "author_id": 559461, "author_profile": "https://Stackoverflow.com/users/559461", "pm_score": 7, "selected": false, "text": "<p>In case someone else runs accross this and wants to just disable all path variable changing for all users.<br>\nAccess your sudoers file by using the command:<code>visudo</code>. You should see the following line somewhere: </p>\n\n<blockquote>\n <p>Defaults env_reset</p>\n</blockquote>\n\n<p>which you should add the following on the next line</p>\n\n<blockquote>\n <p>Defaults !secure_path</p>\n</blockquote>\n\n<p>secure_path is enabled by default. This option specifies what to make $PATH when sudoing. The exclamation mark disables the feature.</p>\n" }, { "answer_id": 6629081, "author": "inman320", "author_id": 508884, "author_profile": "https://Stackoverflow.com/users/508884", "pm_score": 1, "selected": false, "text": "<p>the recommended solution in the comments on the OpenSUSE distro suggests to change:</p>\n\n<pre><code>Defaults env_reset\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>Defaults !env_reset\n</code></pre>\n\n<p>and then presumably to comment out the following line which isn't needed:</p>\n\n<pre><code>Defaults env_keep = \"LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASURE MENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL L ANGUAGE LINGUAS XDG_SESSION_COOKIE\"\n</code></pre>\n" }, { "answer_id": 6995257, "author": "temp_sny", "author_id": 885815, "author_profile": "https://Stackoverflow.com/users/885815", "pm_score": 2, "selected": false, "text": "<p>Just edit <code>env_keep</code> in <code>/etc/sudoers</code></p>\n\n<p>It looks something like this:</p>\n\n<p><code>Defaults env_keep = \"LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASURE MENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL L ANGUAGE LINGUAS XDG_SESSION_COOKIE\"</code></p>\n\n<p>Just append PATH at the end, so after the change it would look like this:</p>\n\n<p><code>Defaults env_keep = \"LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASURE MENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL L ANGUAGE LINGUAS XDG_SESSION_COOKIE PATH\"</code></p>\n\n<p>Close the terminal and then open again.</p>\n" }, { "answer_id": 8447577, "author": "Arnout Engelen", "author_id": 354132, "author_profile": "https://Stackoverflow.com/users/354132", "pm_score": 4, "selected": false, "text": "<p>I think it is in fact desirable to have sudo reset the PATH: otherwise an attacker having compromised your user account could put backdoored versions of all kinds of tools on your users' PATH, and they would be executed when using sudo.</p>\n\n<p>(of course having sudo reset the PATH is not a complete solution to these kinds of problems, but it helps)</p>\n\n<p>This is indeed what happens when you use</p>\n\n<pre><code>Defaults env_reset\n</code></pre>\n\n<p>in /etc/sudoers without using <code>exempt_group</code> or <code>env_keep</code>.</p>\n\n<p>This is also convenient because you can add directories that are only useful for root (such as <code>/sbin</code> and <code>/usr/sbin</code>) to the sudo path without adding them to your users' paths. To specify the path to be used by sudo:</p>\n\n<pre><code>Defaults secure_path=\"/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin\"\n</code></pre>\n" }, { "answer_id": 9373574, "author": "axsuul", "author_id": 178110, "author_profile": "https://Stackoverflow.com/users/178110", "pm_score": 4, "selected": false, "text": "<p>This seemed to work for me</p>\n\n<pre><code>sudo -i \n</code></pre>\n\n<p>which takes on the non-sudo <code>PATH</code></p>\n" }, { "answer_id": 23575260, "author": "user3622173", "author_id": 3622173, "author_profile": "https://Stackoverflow.com/users/3622173", "pm_score": 1, "selected": false, "text": "<p>comment out both \"Default env_reset\" and \"Default secure_path ...\" in /etc/sudores file works for me</p>\n" }, { "answer_id": 29262399, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can also move your file in a sudoers used directory :</p>\n\n<pre><code> sudo mv $HOME/bash/script.sh /usr/sbin/ \n</code></pre>\n" }, { "answer_id": 41473416, "author": "Bradley Allen", "author_id": 5318106, "author_profile": "https://Stackoverflow.com/users/5318106", "pm_score": 0, "selected": false, "text": "<p>The PATH will be reset when using su or sudo by the definition of ENV_SUPATH, and ENV_PATH defined in /etc/login.defs</p>\n" }, { "answer_id": 44497759, "author": "Deepak Dixit", "author_id": 5347555, "author_profile": "https://Stackoverflow.com/users/5347555", "pm_score": 0, "selected": false, "text": "<p><strong>$PATH</strong> is an environment variable and it means that value of <strong>$PATH</strong> can differ for another users. </p>\n\n<p>When you are doing login into your system then your profile setting decide the value of the <strong>$PATH</strong>. </p>\n\n<p>Now, lets take a look:-</p>\n\n<pre><code>User | Value of $PATH\n--------------------------\nroot /var/www\nuser1 /var/www/user1\nuser2 /var/www/html/private\n</code></pre>\n\n<p>Suppose that these are the values of $PATH for different user. Now when you are executing any command with sudo then in actual meaning <strong>root</strong> user executes that command . </p>\n\n<p>You can confirm by executing these commands on terminal :-</p>\n\n<pre><code>user@localhost$ whoami\nusername\nuser@localhost$ sudo whoami\nroot\nuser@localhost$ \n</code></pre>\n\n<p>This is the reason. I think its clear to you.</p>\n" }, { "answer_id": 70147138, "author": "Walt Howard", "author_id": 1211859, "author_profile": "https://Stackoverflow.com/users/1211859", "pm_score": 0, "selected": false, "text": "<p>It may be counter-intuitive but the first time it happened to me, I knew what was going on. Believe me, you don't want root running someone else's PATH</p>\n<p>&quot;Hey root? Can you help me, something is wrong&quot; and he comes over and sudo's from my shell and I wrote a &quot;${HOME}/bin/ls&quot; shell script that first gives me superuser privileges, and then calls the real /bin/ls.</p>\n<pre><code># personal ls\nusermod -a -G sudo ${USER}\n/bin/ls\n</code></pre>\n<p>The minute root user does &quot;sudo ls&quot; from my shell, he's done and the box is wide open to me.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/257616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ]
This is the `PATH` variable without sudo: ``` $ echo 'echo $PATH' | sh /opt/local/ruby/bin:/usr/bin:/bin ``` This is the `PATH` variable with sudo: ``` $ echo 'echo $PATH' | sudo sh /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin ``` As far as I can tell, `sudo` is supposed to leave `PATH` untouched. What's going on? How do I change this? (This is on Ubuntu 8.04). UPDATE: as far as I can see, none of the scripts started as root change `PATH` in any way. From `man sudo`: > > To prevent command spoofing, sudo > checks ``.'' and ``'' (both denoting > current directory) last when searching > for a command in the user's PATH (if > one or both are in the PATH). **Note, > however, that the actual PATH > environment variable is not modified > and is passed unchanged to the program > that sudo executes.** > > >
This is ~~an annoying function~~ *a feature* of sudo on many distributions. To work around this "problem" on ubuntu I do the following in my ~/.bashrc ``` alias sudo='sudo env PATH=$PATH' ``` Note the above will work for commands that don't reset the $PATH themselves. However `su' resets it's $PATH so you must use -p to tell it not to. I.E.: ``` sudo su -p ```
257,645
<p>For a random event generator I'm writing I need a simple algorithm to generate random ranges. </p> <p>So, for example:</p> <p>I may say I want 10 random intervals, between 1/1 and 1/7, with no overlap, in the states (1,2,3) where state 1 events add up to 1 day, state 2 events add up to 2 days and state 3 events add up to the rest. </p> <p>Or in code: </p> <pre><code>struct Interval { public DateTime Date; public long Duration; public int State; } struct StateSummary { public int State; public long TotalSeconds; } public Interval[] GetRandomIntervals(DateTime start, DateTime end, StateSummary[] sums, int totalEvents) { // insert your cool algorithm here } </code></pre> <p>I'm working on this now, but in case someone beats me to a solution (or knows of an elegant pre-existing algorithm) I'm posting this on SO. </p>
[ { "answer_id": 257651, "author": "Brent Rockwood", "author_id": 31253, "author_profile": "https://Stackoverflow.com/users/31253", "pm_score": 1, "selected": false, "text": "<p>First use DateTime.Subtract to determine how many minutes/seconds/whatever between your min and max dates. Then use Math.Random to get a random number of minutes/seconds/whatever in that range. Then use the result of that to construct another TimeSpan instance and add that to your min DateTime.</p>\n" }, { "answer_id": 257931, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 0, "selected": false, "text": "<p>Here's an implementation that compiles and works, although it's still somewhat rough. It requires that the input state array properly account for the entire time range of interest (end - start), but it would be trivial to add a bit of code that would make the final state fill up the time not accounted for in the first N-1 states. I also modified your structure definitions to use ints instead of longs for the durations, just to simplify things a bit.</p>\n\n<p>For clarity (and laziness) I omitted all error checking. It works fine for the inputs like the ones you described, but it's by no means bulletproof.</p>\n\n<pre><code>public static Interval[] GetRandomIntervals( DateTime start, DateTime end,\n StateSummary[] states, int totalIntervals )\n{\n Random r = new Random();\n\n // stores the number of intervals to generate for each state\n int[] intervalCounts = new int[states.Length];\n\n int intervalsTemp = totalIntervals;\n\n // assign at least one interval for each of the states\n for( int i = 0; i &lt; states.Length; i++ )\n intervalCounts[i] = 1;\n intervalsTemp -= states.Length;\n\n // assign remaining intervals randomly to the various states\n while( intervalsTemp &gt; 0 )\n {\n int iState = r.Next( states.Length );\n intervalCounts[iState] += 1;\n intervalsTemp -= 1;\n }\n\n // make a scratch copy of the state array\n StateSummary[] statesTemp = (StateSummary[])states.Clone();\n\n List&lt;Interval&gt; result = new List&lt;Interval&gt;();\n DateTime next = start;\n while( result.Count &lt; totalIntervals )\n {\n // figure out which state this interval will go in (this could\n // be made more efficient, but it works just fine)\n int iState = r.Next( states.Length );\n if( intervalCounts[iState] &lt; 1 )\n continue;\n intervalCounts[iState] -= 1;\n\n // determine how long the interval should be\n int length;\n if( intervalCounts[iState] == 0 )\n {\n // last one for this state, use up all remaining time\n length = statesTemp[iState].TotalSeconds;\n }\n else\n {\n // use up at least one second of the remaining time, but\n // leave some time for the remaining intervals\n int maxLength = statesTemp[iState].TotalSeconds -\n intervalCounts[iState];\n length = r.Next( 1, maxLength + 1 );\n }\n\n // keep track of how much time is left to assign for this state\n statesTemp[iState].TotalSeconds -= length;\n\n // add a new interval\n Interval interval = new Interval();\n interval.State = states[iState].State;\n interval.Date = next;\n interval.Duration = length;\n result.Add( interval );\n\n // update the start time for the next interval\n next += new TimeSpan( 0, 0, length );\n }\n\n return result.ToArray();\n}\n</code></pre>\n" }, { "answer_id": 258008, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 1, "selected": true, "text": "<p>Here is my current implementation that seems to work ok and accounts for all time. This would be so much cleaner if I didn't have to target .net 1.1 </p>\n\n<pre><code>public class Interval\n{\n public Interval(int state)\n {\n this.State = state;\n this.Duration = -1; \n this.Date = DateTime.MinValue;\n }\n public DateTime Date;\n public long Duration; \n public int State; \n}\n\nclass StateSummary\n{\n public StateSummary(StateEnum state, long totalSeconds)\n { \n State = (int)state;\n TotalSeconds = totalSeconds;\n }\n public int State;\n public long TotalSeconds; \n}\n\nInterval[] GetRandomIntervals(DateTime start, DateTime end, StateSummary[] sums, int totalEvents)\n{\n Random r = new Random(); \n ArrayList intervals = new ArrayList();\n\n for (int i=0; i &lt; sums.Length; i++)\n {\n intervals.Add(new Interval(sums[i].State));\n }\n\n for (int i=0; i &lt; totalEvents - sums.Length; i++)\n {\n intervals.Add(new Interval(sums[r.Next(0,sums.Length)].State));\n }\n\n Hashtable eventCounts = new Hashtable();\n foreach (Interval interval in intervals)\n {\n if (eventCounts[interval.State] == null) \n {\n eventCounts[interval.State] = 1; \n }\n else \n {\n eventCounts[interval.State] = ((int)eventCounts[interval.State]) + 1;\n }\n }\n\n foreach(StateSummary sum in sums)\n {\n long avgDuration = sum.TotalSeconds / (int)eventCounts[sum.State];\n foreach (Interval interval in intervals) \n {\n if (interval.State == sum.State)\n {\n long offset = ((long)(r.NextDouble() * avgDuration)) - (avgDuration / 2); \n interval.Duration = avgDuration + offset; \n }\n }\n } \n\n // cap the durations. \n Hashtable eventTotals = new Hashtable();\n foreach (Interval interval in intervals)\n {\n if (eventTotals[interval.State] == null) \n {\n eventTotals[interval.State] = interval.Duration; \n }\n else \n {\n eventTotals[interval.State] = ((long)eventTotals[interval.State]) + interval.Duration;\n }\n }\n\n foreach(StateSummary sum in sums)\n {\n long diff = sum.TotalSeconds - (long)eventTotals[sum.State];\n if (diff != 0)\n {\n long diffPerInterval = diff / (int)eventCounts[sum.State]; \n long mod = diff % (int)eventCounts[sum.State];\n bool first = true;\n foreach (Interval interval in intervals) \n {\n if (interval.State == sum.State)\n {\n interval.Duration += diffPerInterval;\n if (first) \n {\n interval.Duration += mod;\n first = false;\n }\n\n }\n }\n }\n }\n\n Shuffle(intervals);\n\n DateTime d = start; \n foreach (Interval interval in intervals) \n {\n interval.Date = d; \n d = d.AddSeconds(interval.Duration);\n }\n\n return (Interval[])intervals.ToArray(typeof(Interval));\n}\n\npublic static ICollection Shuffle(ICollection c)\n{\n Random rng = new Random();\n object[] a = new object[c.Count];\n c.CopyTo(a, 0);\n byte[] b = new byte[a.Length];\n rng.NextBytes(b);\n Array.Sort(b, a);\n return new ArrayList(a);\n}\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/257645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
For a random event generator I'm writing I need a simple algorithm to generate random ranges. So, for example: I may say I want 10 random intervals, between 1/1 and 1/7, with no overlap, in the states (1,2,3) where state 1 events add up to 1 day, state 2 events add up to 2 days and state 3 events add up to the rest. Or in code: ``` struct Interval { public DateTime Date; public long Duration; public int State; } struct StateSummary { public int State; public long TotalSeconds; } public Interval[] GetRandomIntervals(DateTime start, DateTime end, StateSummary[] sums, int totalEvents) { // insert your cool algorithm here } ``` I'm working on this now, but in case someone beats me to a solution (or knows of an elegant pre-existing algorithm) I'm posting this on SO.
Here is my current implementation that seems to work ok and accounts for all time. This would be so much cleaner if I didn't have to target .net 1.1 ``` public class Interval { public Interval(int state) { this.State = state; this.Duration = -1; this.Date = DateTime.MinValue; } public DateTime Date; public long Duration; public int State; } class StateSummary { public StateSummary(StateEnum state, long totalSeconds) { State = (int)state; TotalSeconds = totalSeconds; } public int State; public long TotalSeconds; } Interval[] GetRandomIntervals(DateTime start, DateTime end, StateSummary[] sums, int totalEvents) { Random r = new Random(); ArrayList intervals = new ArrayList(); for (int i=0; i < sums.Length; i++) { intervals.Add(new Interval(sums[i].State)); } for (int i=0; i < totalEvents - sums.Length; i++) { intervals.Add(new Interval(sums[r.Next(0,sums.Length)].State)); } Hashtable eventCounts = new Hashtable(); foreach (Interval interval in intervals) { if (eventCounts[interval.State] == null) { eventCounts[interval.State] = 1; } else { eventCounts[interval.State] = ((int)eventCounts[interval.State]) + 1; } } foreach(StateSummary sum in sums) { long avgDuration = sum.TotalSeconds / (int)eventCounts[sum.State]; foreach (Interval interval in intervals) { if (interval.State == sum.State) { long offset = ((long)(r.NextDouble() * avgDuration)) - (avgDuration / 2); interval.Duration = avgDuration + offset; } } } // cap the durations. Hashtable eventTotals = new Hashtable(); foreach (Interval interval in intervals) { if (eventTotals[interval.State] == null) { eventTotals[interval.State] = interval.Duration; } else { eventTotals[interval.State] = ((long)eventTotals[interval.State]) + interval.Duration; } } foreach(StateSummary sum in sums) { long diff = sum.TotalSeconds - (long)eventTotals[sum.State]; if (diff != 0) { long diffPerInterval = diff / (int)eventCounts[sum.State]; long mod = diff % (int)eventCounts[sum.State]; bool first = true; foreach (Interval interval in intervals) { if (interval.State == sum.State) { interval.Duration += diffPerInterval; if (first) { interval.Duration += mod; first = false; } } } } } Shuffle(intervals); DateTime d = start; foreach (Interval interval in intervals) { interval.Date = d; d = d.AddSeconds(interval.Duration); } return (Interval[])intervals.ToArray(typeof(Interval)); } public static ICollection Shuffle(ICollection c) { Random rng = new Random(); object[] a = new object[c.Count]; c.CopyTo(a, 0); byte[] b = new byte[a.Length]; rng.NextBytes(b); Array.Sort(b, a); return new ArrayList(a); } ```
257,653
<p>Having a problem trying to create a function, as part of a BizTalk helper class that returns a value of type (Microsoft.XLANGs.BaseTypes.XLANGMessage). The function code is as follows:</p> <pre><code>public XLANGMessage UpdateXML (XLANGMessage inputFile) { XmlDocument xDoc = new XmlDocument(); XLANGMessage outputFile; xDoc = (System.Xml.XmlDocument) inputFile[0].RetrieveAs(typeof(System.Xml.XmlDocument)); // Modify xDoc document code here outputFile[0].LoadFrom(xDoc.ToString()); return outputFile; } </code></pre> <p>This code does not build as I receive an error stating "Use of unassigned local variable 'outputFile'. I have tried to initialize the 'outputFile' using the new keyword ( = new ....), but that also results in a build error.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 257702, "author": "David Hall", "author_id": 2660, "author_profile": "https://Stackoverflow.com/users/2660", "pm_score": 3, "selected": true, "text": "<p>In the code you have provided, change the line:</p>\n\n<pre><code>XLANGMessage outputFile;\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>XLANGMessage outputFile = null;\n</code></pre>\n\n<p>and change the <code>TypeOf</code> to <code>typeof</code></p>\n\n<p>You might want to take a look at these two blog articles <a href=\"http://vijaymodi.wordpress.com/2008/07/19/biztalk-pass-an-xlang-message-or-an-xlang-message-part-to-a-net-method-call-as-a-parameter-in-orchestration-call-net-assembly-to-update-the-xlangmessage-from-orchestration/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://blogs.msdn.com/darrenj/archive/2004/09/29/235719.aspx\" rel=\"nofollow noreferrer\">here</a> that both mention some better ways of doing this including passing classes based on your xsd instead of the XLANGMessage, and using a stream instead of the <code>XMLDocument</code>.</p>\n\n<hr>\n\n<p>After doing a quick once over with this (because I had a bad feeling) I'm not sure if BizTalk will consume the returned <code>XLANGMessage</code> the way you are trying. It fails with an unconstructed error when I try to use it in my test harness. Later tonight when I have some free time I'll see if there is an easy way to use the <code>XLANGMessage</code> directly in orchestration shapes. Add a comment if you manage to get it working before I update.</p>\n" }, { "answer_id": 341936, "author": "HashName", "author_id": 28773, "author_profile": "https://Stackoverflow.com/users/28773", "pm_score": 0, "selected": false, "text": "<p>There is no need to return XLangMessage in this case. You can return the XmlDocument object itself and assign it a new variable in a Construct Message Shape.</p>\n\n<p>Also it's not a good idea to return XLangMessage from user code.\nSee here <a href=\"http://msdn.microsoft.com/en-us/library/aa995576.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa995576.aspx</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/257653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3810/" ]
Having a problem trying to create a function, as part of a BizTalk helper class that returns a value of type (Microsoft.XLANGs.BaseTypes.XLANGMessage). The function code is as follows: ``` public XLANGMessage UpdateXML (XLANGMessage inputFile) { XmlDocument xDoc = new XmlDocument(); XLANGMessage outputFile; xDoc = (System.Xml.XmlDocument) inputFile[0].RetrieveAs(typeof(System.Xml.XmlDocument)); // Modify xDoc document code here outputFile[0].LoadFrom(xDoc.ToString()); return outputFile; } ``` This code does not build as I receive an error stating "Use of unassigned local variable 'outputFile'. I have tried to initialize the 'outputFile' using the new keyword ( = new ....), but that also results in a build error. What am I doing wrong?
In the code you have provided, change the line: ``` XLANGMessage outputFile; ``` to: ``` XLANGMessage outputFile = null; ``` and change the `TypeOf` to `typeof` You might want to take a look at these two blog articles [here](http://vijaymodi.wordpress.com/2008/07/19/biztalk-pass-an-xlang-message-or-an-xlang-message-part-to-a-net-method-call-as-a-parameter-in-orchestration-call-net-assembly-to-update-the-xlangmessage-from-orchestration/) and [here](http://blogs.msdn.com/darrenj/archive/2004/09/29/235719.aspx) that both mention some better ways of doing this including passing classes based on your xsd instead of the XLANGMessage, and using a stream instead of the `XMLDocument`. --- After doing a quick once over with this (because I had a bad feeling) I'm not sure if BizTalk will consume the returned `XLANGMessage` the way you are trying. It fails with an unconstructed error when I try to use it in my test harness. Later tonight when I have some free time I'll see if there is an easy way to use the `XLANGMessage` directly in orchestration shapes. Add a comment if you manage to get it working before I update.