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
|
---|---|---|---|---|---|---|
112,102 | <p>Is there a secure way of logging into a Gmail account on a web browser, from an external Java program? I know the following works, but is there a safer alternative?</p>
<pre><code>Desktop.getDesktop().browse(new URI(
"https://www.google.com/accounts/ServiceLoginAuth?continue=http://mail.google.com/gmail" +
"&service=mail&Email=LOGIN&Passwd=PASSWORD&null=Sign+in"));
</code></pre>
<p><strong>Clarification</strong>: The external Java program is <a href="http://gmailassistant.sourceforge.net/" rel="nofollow noreferrer">GmailAssistant</a>, a Gmail notifier that already uses the IMAP capabilities of JavaMail. I just need a way of allowing the user to access the account directly in a web browser.</p>
| [
{
"answer_id": 112108,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 1,
"selected": false,
"text": "<p>If you are afraid that the link is visible in the Page, create a javascript document that sends a POST request to the server.</p>\n"
},
{
"answer_id": 112130,
"author": "VP.",
"author_id": 18642,
"author_profile": "https://Stackoverflow.com/users/18642",
"pm_score": 2,
"selected": false,
"text": "<p>Depending of how much you want to integrate, you can check Google single sign-on (SSO) api. I'm studing how to use it and the best way to integrate it</p>\n\n<p><a href=\"http://code.google.com/apis/apps/sso/saml_reference_implementation.html\" rel=\"nofollow noreferrer\">http://code.google.com/apis/apps/sso/saml_reference_implementation.html</a></p>\n\n<p>Victor</p>\n\n<p>UPDATED:</p>\n\n<p>As a better option, you should check this link as well <a href=\"http://esoeproject.org/\" rel=\"nofollow noreferrer\">http://esoeproject.org/</a></p>\n"
},
{
"answer_id": 112134,
"author": "Joannes Vermorel",
"author_id": 18858,
"author_profile": "https://Stackoverflow.com/users/18858",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to programmatically access the content of a GMail account, I would strongly suggest to use the <a href=\"http://mail.google.com/support/bin/answer.py?hl=en&answer=75725\" rel=\"nofollow noreferrer\">IMAP access provided by Google</a>.</p>\n\n<p>Looking at the question the other way around, you can setup an <a href=\"http://openid-provider.appspot.com/\" rel=\"nofollow noreferrer\">OpenID</a> authentication scheme based on your Google account.</p>\n"
},
{
"answer_id": 112247,
"author": "Roshan",
"author_id": 15806,
"author_profile": "https://Stackoverflow.com/users/15806",
"pm_score": 2,
"selected": false,
"text": "<p>If you're really wanting to control a browser from Java, you'll have to use a web-connector such as <a href=\"http://selenium-rc.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a> or <a href=\"http://code.google.com/p/webdriver/\" rel=\"nofollow noreferrer\">WebDriver</a>. Both of these let you control a browser directly from within Java and simulate a user typing text, clicking on links and submitting forms. One thing to keep in mind when doing this with Selenium is that it interacts with a complete new profile which is usually independent of your standard Firefox probile. </p>\n"
},
{
"answer_id": 115112,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 0,
"selected": false,
"text": "<p>I used google's IMAP access with the JavaMail API, and it was very simple.</p>\n"
},
{
"answer_id": 306784,
"author": "Stephen",
"author_id": 37193,
"author_profile": "https://Stackoverflow.com/users/37193",
"pm_score": 0,
"selected": false,
"text": "<p>If you're worried about the URL being sent for the login, understand that:</p>\n\n<ol>\n<li>https:// starts with www.google.com and will encrypt the session <em>before</em></li>\n<li>sending the login details (or even the page it's going to</li>\n</ol>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20029/"
]
| Is there a secure way of logging into a Gmail account on a web browser, from an external Java program? I know the following works, but is there a safer alternative?
```
Desktop.getDesktop().browse(new URI(
"https://www.google.com/accounts/ServiceLoginAuth?continue=http://mail.google.com/gmail" +
"&service=mail&Email=LOGIN&Passwd=PASSWORD&null=Sign+in"));
```
**Clarification**: The external Java program is [GmailAssistant](http://gmailassistant.sourceforge.net/), a Gmail notifier that already uses the IMAP capabilities of JavaMail. I just need a way of allowing the user to access the account directly in a web browser. | Depending of how much you want to integrate, you can check Google single sign-on (SSO) api. I'm studing how to use it and the best way to integrate it
<http://code.google.com/apis/apps/sso/saml_reference_implementation.html>
Victor
UPDATED:
As a better option, you should check this link as well <http://esoeproject.org/> |
112,158 | <p>On my team, we usually do string concatentation like this:</p>
<pre><code>var url = // some dynamically generated URL
var sb = new StringBuffer();
sb.append("<a href='").append(url).append("'>click here</a>");
</code></pre>
<p>Obviously the following is much more readable:</p>
<pre><code>var url = // some dynamically generated URL
var sb = "<a href='" + url + "'>click here</a>";
</code></pre>
<p>But the JS experts claim that the <code>+</code> operator is less performant than <code>StringBuffer.append()</code>. Is this really true?</p>
| [
{
"answer_id": 112164,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 5,
"selected": false,
"text": "<p>Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then focus on the bottlenecks. </p>\n\n<p>I would guess that string concatenation isn't going to be your bottleneck.</p>\n"
},
{
"answer_id": 112171,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 4,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>var s = [\"<a href='\", url, \"'>click here</a>\"].join(\"\");\n</code></pre>\n"
},
{
"answer_id": 112174,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": false,
"text": "<p>JavaScript doesn't have a native StringBuffer object, so I'm assuming this is from a library you are using, or a feature of an unusual host environment (i.e. not a browser).</p>\n\n<p>I doubt a library (written in JS) would produce anything faster, although a native StringBuffer object might. The definitive answer can be found with a profiler (if you are running in a browser then Firebug will provide you with a profiler for the JS engine found in Firefox).</p>\n"
},
{
"answer_id": 112176,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 3,
"selected": false,
"text": "<p>In the words of Knuth, \"premature optimization is the root of all evil!\" The small defference either way will most likely not have much of an effect in the end; I'd choose the more readable one.</p>\n"
},
{
"answer_id": 112181,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, according to the usual benchmarks. E.G : <a href=\"http://mckoss.com/jscript/SpeedTrial.htm\" rel=\"nofollow noreferrer\">http://mckoss.com/jscript/SpeedTrial.htm</a>.</p>\n\n<p>But for the small strings, this is irrelevant. You will only care about performances on very large strings. What's more, in most JS script, the bottle neck is rarely on the string manipulations since there is not enough of it.</p>\n\n<p>You'd better watch the DOM manipulation.</p>\n"
},
{
"answer_id": 112184,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 7,
"selected": false,
"text": "<p>Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.</p>\n\n<p>Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; <a href=\"http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/\" rel=\"noreferrer\">String Performance an Analysis</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/FcI38.jpg\" alt=\"join() once, concat() once, join() for, += for, concat() for\"></p>\n\n<p>More:<br>\n<a href=\"http://ajaxian.com/archives/string-performance-in-ie-arrayjoin-vs-continued\" rel=\"noreferrer\">Ajaxian >> String Performance in IE: Array.join vs += continued</a></p>\n"
},
{
"answer_id": 112185,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": false,
"text": "<p>Agreed with <a href=\"https://stackoverflow.com/questions/112158/javascript-string-concatenation#112164\">Michael Haren</a>.</p>\n\n<p>Also consider the use of arrays and join if performance is indeed an issue.</p>\n\n<pre><code>var buffer = [\"<a href='\", url, \"'>click here</a>\"];\nbuffer.push(\"More stuff\");\nalert(buffer.join(\"\"));\n</code></pre>\n"
},
{
"answer_id": 112196,
"author": "David Ameller",
"author_id": 19689,
"author_profile": "https://Stackoverflow.com/users/19689",
"pm_score": 1,
"selected": false,
"text": "<p>As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.</p>\n"
},
{
"answer_id": 112223,
"author": "amix",
"author_id": 20081,
"author_profile": "https://Stackoverflow.com/users/20081",
"pm_score": 3,
"selected": false,
"text": "<p>Like already some users have noted: This is irrelevant for small strings.</p>\n\n<p>And new JavaScript engines in Firefox, Safari or Google Chrome optimize so</p>\n\n<pre><code>\"<a href='\" + url + \"'>click here</a>\";\n</code></pre>\n\n<p>is as fast as</p>\n\n<pre><code>[\"<a href='\", url, \"'>click here</a>\"].join(\"\");\n</code></pre>\n"
},
{
"answer_id": 112355,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": 7,
"selected": true,
"text": "<p>Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is.</p>\n\n<p>If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother.</p>\n"
},
{
"answer_id": 6970699,
"author": "jasonc65",
"author_id": 729005,
"author_profile": "https://Stackoverflow.com/users/729005",
"pm_score": 2,
"selected": false,
"text": "<p>I like to use functional style, such as:</p>\n\n<pre><code>function href(url,txt) {\n return \"<a href='\" +url+ \"'>\" +txt+ \"</a>\"\n}\n\nfunction li(txt) {\n return \"<li>\" +txt+ \"</li>\"\n}\n\nfunction ul(arr) {\n return \"<ul>\" + arr.map(li).join(\"\") + \"</ul>\"\n}\n\ndocument.write(\n ul(\n [\n href(\"http://url1\",\"link1\"),\n href(\"http://url2\",\"link2\"),\n href(\"http://url3\",\"link3\")\n ]\n )\n)\n</code></pre>\n\n<p>This style looks readable and transparent. It leads to the creation of utilities which reduces repetition in code.</p>\n\n<p>This also tends to use intermediate strings automatically.</p>\n"
},
{
"answer_id": 12537903,
"author": "James McMahon",
"author_id": 20774,
"author_profile": "https://Stackoverflow.com/users/20774",
"pm_score": 2,
"selected": false,
"text": "<p>It is pretty easy to set up a quick benchmark and check out Javascript performance variations using <a href=\"http://jsperf.com/\" rel=\"nofollow\">jspref.com</a>. Which probably wasn't around when this question was asked. But for people stumbling on this question they should take alook at the site.</p>\n\n<p>I did a quick test of various methods of concatenation at <a href=\"http://jsperf.com/string-concat-methods-test\" rel=\"nofollow\">http://jsperf.com/string-concat-methods-test</a>. </p>\n"
},
{
"answer_id": 13679887,
"author": "Ed Kern",
"author_id": 1872043,
"author_profile": "https://Stackoverflow.com/users/1872043",
"pm_score": 2,
"selected": false,
"text": "<p>The easier to read method saves humans perceptible amounts of time when looking at the code, whereas the \"faster\" method only wastes imperceptible and likely negligible amounts of time when people are browsing the page.</p>\n\n<p>I know this post is lame, but I accidentally posted something entirely different thinking this was a different thread and I don't know how to delete posts. My bad...</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
| On my team, we usually do string concatentation like this:
```
var url = // some dynamically generated URL
var sb = new StringBuffer();
sb.append("<a href='").append(url).append("'>click here</a>");
```
Obviously the following is much more readable:
```
var url = // some dynamically generated URL
var sb = "<a href='" + url + "'>click here</a>";
```
But the JS experts claim that the `+` operator is less performant than `StringBuffer.append()`. Is this really true? | Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is.
If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother. |
112,169 | <p>For years I've been using ShellExecute() API to launch the default web browser from within my applications. Like this:</p>
<pre><code>ShellExecute( hwnd, _T("open"),
_T("http://www.winability.com/home/"),
NULL, NULL, SW_NORMAL );
</code></pre>
<p>It's been working fine until a couple of weeks ago, when Google released its Chrome browser. Now, if Chrome is installed on the computer, the ShellExecute API no longer opens a web page.</p>
<p>Has anyone figured out yet how to solve this problem? (Short of detecting Chrome and displaying a message telling the user it's Chrome's fault?)</p>
<p>EDIT: the code provided by Sergey seems to work, so I've accepted it as "the" answer. Except that I don't like the call to WinExec: MSDN reads that WinExec is provided only for compatibility with 16-bit applications. IOW, it may stop working with any Service Pack. I did not try it, but I would not be surprised if it has already stopped working with Windows x64, since it does not support 16-bit applications at all. So, instead of WinExec, I'm going to use ShellExecute, with the path taken from the registry like Sergey's code does, and the URL as the argument. Thanks! </p>
| [
{
"answer_id": 112213,
"author": "Sergey Kornilov",
"author_id": 10969,
"author_profile": "https://Stackoverflow.com/users/10969",
"pm_score": 3,
"selected": true,
"text": "<p>Here is the code that works across all browsers. The trick is to call WinExec if ShellExecute fails.</p>\n\n<pre><code>HINSTANCE GotoURL(LPCTSTR url, int showcmd)\n{\n TCHAR key[MAX_PATH + MAX_PATH];\n\n // First try ShellExecute()\n HINSTANCE result = 0;\n\n CString strURL = url;\n\n if ( strURL.Find(\".htm\") <0 && strURL.Find(\"http\") <0 )\n result = ShellExecute(NULL, _T(\"open\"), url, NULL, NULL, showcmd);\n\n // If it failed, get the .htm regkey and lookup the program\n if ((UINT)result <= HINSTANCE_ERROR) {\n\n if (GetRegKey(HKEY_CLASSES_ROOT, _T(\".htm\"), key) == ERROR_SUCCESS) {\n lstrcat(key, _T(\"\\\\shell\\\\open\\\\command\"));\n\n if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) {\n TCHAR *pos;\n pos = _tcsstr(key, _T(\"\\\"%1\\\"\"));\n if (pos == NULL) { // No quotes found\n pos = strstr(key, _T(\"%1\")); // Check for %1, without quotes\n if (pos == NULL) // No parameter at all...\n pos = key+lstrlen(key)-1;\n else\n *pos = '\\0'; // Remove the parameter\n }\n else\n *pos = '\\0'; // Remove the parameter\n\n lstrcat(pos, _T(\" \\\"\"));\n lstrcat(pos, url);\n lstrcat(pos, _T(\"\\\"\"));\n result = (HINSTANCE) WinExec(key,showcmd);\n }\n }\n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 11482357,
"author": "dyasta",
"author_id": 191514,
"author_profile": "https://Stackoverflow.com/users/191514",
"pm_score": 0,
"selected": false,
"text": "<p>After hearing reports of ShellExecute failing on a minority of systems, I implemented a function similar to the example given by Sergey Kornilov. This was about a year ago. Same premise - Do a direct HKCR lookup of the .HTM file handler.</p>\n\n<p>However, it turns out that some users have editors (e.g. UltraEdit) that register themselves to 'open' .htm files (instead of 'edit' them). Thus, <em>if</em> ShellExecute fails, this secondary method will also fail in those cases. It opens the editor, as the shell association errantly instructs.</p>\n\n<p><strong>Thus, the user should use the HTTP handler instead, or at least in preference of the HTML handler.</strong></p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17037/"
]
| For years I've been using ShellExecute() API to launch the default web browser from within my applications. Like this:
```
ShellExecute( hwnd, _T("open"),
_T("http://www.winability.com/home/"),
NULL, NULL, SW_NORMAL );
```
It's been working fine until a couple of weeks ago, when Google released its Chrome browser. Now, if Chrome is installed on the computer, the ShellExecute API no longer opens a web page.
Has anyone figured out yet how to solve this problem? (Short of detecting Chrome and displaying a message telling the user it's Chrome's fault?)
EDIT: the code provided by Sergey seems to work, so I've accepted it as "the" answer. Except that I don't like the call to WinExec: MSDN reads that WinExec is provided only for compatibility with 16-bit applications. IOW, it may stop working with any Service Pack. I did not try it, but I would not be surprised if it has already stopped working with Windows x64, since it does not support 16-bit applications at all. So, instead of WinExec, I'm going to use ShellExecute, with the path taken from the registry like Sergey's code does, and the URL as the argument. Thanks! | Here is the code that works across all browsers. The trick is to call WinExec if ShellExecute fails.
```
HINSTANCE GotoURL(LPCTSTR url, int showcmd)
{
TCHAR key[MAX_PATH + MAX_PATH];
// First try ShellExecute()
HINSTANCE result = 0;
CString strURL = url;
if ( strURL.Find(".htm") <0 && strURL.Find("http") <0 )
result = ShellExecute(NULL, _T("open"), url, NULL, NULL, showcmd);
// If it failed, get the .htm regkey and lookup the program
if ((UINT)result <= HINSTANCE_ERROR) {
if (GetRegKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS) {
lstrcat(key, _T("\\shell\\open\\command"));
if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) {
TCHAR *pos;
pos = _tcsstr(key, _T("\"%1\""));
if (pos == NULL) { // No quotes found
pos = strstr(key, _T("%1")); // Check for %1, without quotes
if (pos == NULL) // No parameter at all...
pos = key+lstrlen(key)-1;
else
*pos = '\0'; // Remove the parameter
}
else
*pos = '\0'; // Remove the parameter
lstrcat(pos, _T(" \""));
lstrcat(pos, url);
lstrcat(pos, _T("\""));
result = (HINSTANCE) WinExec(key,showcmd);
}
}
}
return result;
}
``` |
112,197 | <p>I want to create a hidden field and create a link in one helper and then output both to my erb.</p>
<pre><code><%= my_cool_helper "something", form %>
</code></pre>
<p>Should out put the results of</p>
<pre><code>link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"
</code></pre>
<p>What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.</p>
| [
{
"answer_id": 112210,
"author": "Sixty4Bit",
"author_id": 1681,
"author_profile": "https://Stackoverflow.com/users/1681",
"pm_score": 4,
"selected": false,
"text": "<p>So far the best I have come up with is:</p>\n\n<pre><code>def my_cool_helper(name, form)\n out = capture { link_to name, a_path }\n out << capture { form.hidden_field name.tableize, value => 'something' }\nend\n</code></pre>\n\n<p>Is there a better way?</p>\n"
},
{
"answer_id": 112211,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": true,
"text": "<p>There are several ways to do this.</p>\n\n<p>Remember that the existing rails helpers like <code>link_to</code>, etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple).</p>\n\n<p>EG:</p>\n\n<pre><code>link_to( \"something\", something_path ) + #NOTE THE PLUS FOR STRING CONCAT\n form.hidden_field('something'.tableize, :value=>'something')\n</code></pre>\n\n<p>If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call <code>render :partial</code>.</p>\n\n<p>If you're doing more complicated stuff than even that, then you may want to look at errtheblog's <a href=\"http://errtheblog.com/posts/11-block-to-partial\" rel=\"nofollow noreferrer\">block_to_partial</a> helper, which is pretty cool</p>\n"
},
{
"answer_id": 35012017,
"author": "Jay_Pandya",
"author_id": 5101365,
"author_profile": "https://Stackoverflow.com/users/5101365",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to buffer other output which apart from string then you can use <code>concat</code> instead of <code>+</code>.\nsee this - <a href=\"http://thepugautomatic.com/2013/06/helpers/\" rel=\"nofollow\">http://thepugautomatic.com/2013/06/helpers/</a></p>\n"
},
{
"answer_id": 59817311,
"author": "Joshua Pinter",
"author_id": 293280,
"author_profile": "https://Stackoverflow.com/users/293280",
"pm_score": 2,
"selected": false,
"text": "<h2>Using <code>safe_join</code>.</h2>\n\n<p>I typically prefer just concatenating with <code>+</code>, as shown in <a href=\"https://stackoverflow.com/a/112211/293280\">Orion Edwards's Answer</a>, but here's another option I recently discovered.</p>\n\n<pre><code>safe_join( [\n link_to( \"something\", something_path ),\n form.hidden_field( \"something\".tableize, value: \"something\" )\n] )\n</code></pre>\n\n<p>It has the advantage of explicitly listing all of the elements and the joining of those elements. </p>\n\n<p>I find that with long elements, the <code>+</code> symbol can get lost at the end of the line. Additionally, if you're concatenating more than a few elements, I find listing them in an Array like this to be more obvious to the next reader.</p>\n"
},
{
"answer_id": 64621458,
"author": "estani",
"author_id": 1182464,
"author_profile": "https://Stackoverflow.com/users/1182464",
"pm_score": 1,
"selected": false,
"text": "<pre class=\"lang-rb prettyprint-override\"><code>def output_siblings\n div1 = tag.div 'some content'\n div2 = tag.div 'other content'\n\n div1 + div2\nend\n</code></pre>\n<p>just simplifying some other answers in here.</p>\n"
},
{
"answer_id": 68521973,
"author": "Clay Shentrup",
"author_id": 8925319,
"author_profile": "https://Stackoverflow.com/users/8925319",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me.</p>\n<pre><code>def format_paragraphs(text)\n text.split(/\\r?\\n/).sum do |paragraph|\n tag.p(paragraph)\n end\nend\n</code></pre>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
]
| I want to create a hidden field and create a link in one helper and then output both to my erb.
```
<%= my_cool_helper "something", form %>
```
Should out put the results of
```
link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"
```
What would the definition of the helper look like? The details of what link\_to and the form.hidden\_field don't really matter. What matters is, how do I return the output from two different calls. | There are several ways to do this.
Remember that the existing rails helpers like `link_to`, etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple).
EG:
```
link_to( "something", something_path ) + #NOTE THE PLUS FOR STRING CONCAT
form.hidden_field('something'.tableize, :value=>'something')
```
If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call `render :partial`.
If you're doing more complicated stuff than even that, then you may want to look at errtheblog's [block\_to\_partial](http://errtheblog.com/posts/11-block-to-partial) helper, which is pretty cool |
112,224 | <p>I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency.</p>
<blockquote>
<blockquote>
<p>RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"?</p>
</blockquote>
</blockquote>
<p>I mean like the desktop or firefox, not something within my project.</p>
| [
{
"answer_id": 112593,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 6,
"selected": true,
"text": "<p>Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define it to have a TransparenyKey color and BackColor of the same value. </p>\n\n<p>Getting it to ignore the mouse is simple enough, you just need to override the WndProc and tell the WM_HITTEST that all mouse positions are to be treated as transparent. Thus causing the mouse to interact with whatever happens to be underneath the window. Something like this...</p>\n\n<pre><code> protected override void WndProc(ref Message m)\n {\n if (m.Msg == (int)WM_NCHITTEST)\n m.Result = (IntPtr)HTTRANSPARENT;\n else\n base.WndProc(ref m);\n }\n</code></pre>\n"
},
{
"answer_id": 74103981,
"author": "Andres Gutierrez",
"author_id": 20267566,
"author_profile": "https://Stackoverflow.com/users/20267566",
"pm_score": 0,
"selected": false,
"text": "<p>A much simpler method that might work.</p>\n<p>step 1.) click on the panel in (design)</p>\n<p>step 2.) look in properties</p>\n<p>step 3.) set Enabled to False</p>\n<p>this allowed me to click past my panel to the one behind it.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18309/"
]
| I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency.
>
>
> >
> > RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"?
> >
> >
> >
>
>
>
I mean like the desktop or firefox, not something within my project. | Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define it to have a TransparenyKey color and BackColor of the same value.
Getting it to ignore the mouse is simple enough, you just need to override the WndProc and tell the WM\_HITTEST that all mouse positions are to be treated as transparent. Thus causing the mouse to interact with whatever happens to be underneath the window. Something like this...
```
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)WM_NCHITTEST)
m.Result = (IntPtr)HTTRANSPARENT;
else
base.WndProc(ref m);
}
``` |
112,234 | <p>Let's say that I have two arrays (in Java),</p>
<p>int[] numbers; and int[] colors;</p>
<p>Each ith element of numbers corresponds to its ith element in colors.
Ex, numbers = {4,2,1}
colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc.</p>
<p>I want to sort the numbers array, but then still have it so each element matches up with its pair in colors.</p>
<p>Ex. numbers = {1,2,4};
colors = {0x01,0x24,0x11};</p>
<p>What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable.</p>
<p><strong>Note: I know the "best" solution is to make a class for the two elements and use a custom comparator. This question is meant to ask people for the quickest way to code this. Imagine being at a programming competition, you wouldn't want to be making all these extra classes, anonymous classes for the comparator, etc. Better yet, forget Java; how would you code it in C?</strong></p>
| [
{
"answer_id": 112240,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>You need to sort the colors array by its relative item in the numbers array. Specify a comparator that compares numbers and use that as the comparison for the colors array.</p>\n"
},
{
"answer_id": 112243,
"author": "JeffFoster",
"author_id": 9853,
"author_profile": "https://Stackoverflow.com/users/9853",
"pm_score": 2,
"selected": false,
"text": "<p>Why not introduce an object to represent a number and a color and implement a comparator function for that?</p>\n\n<p>Also, do you really need an array, why not use something derived from Collection?</p>\n"
},
{
"answer_id": 112254,
"author": "Frank Pape",
"author_id": 10367,
"author_profile": "https://Stackoverflow.com/users/10367",
"pm_score": 3,
"selected": false,
"text": "<p>It seems like the cleanest thing to do would be to create a custom property class that implements Comparable. For example:</p>\n\n<pre><code>class Color implements Comparable {\n private int number;\n private int color;\n\n // (snip ctor, setters, etc.)\n\n public int getNumber() {\n return number;\n }\n public int getColor() {\n return color;\n }\n\n public int compareTo(Color other) {\n if (this.getNumber() == other.getNumber) {\n return 0;\n } else if (this.getNumber() > other.getNumber) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n</code></pre>\n\n<p>Then you can separate your sorting algorithm from the ordering logic (you could use Collections.sort if you use a List instead of an array), and most importantly, you won't have to worry about somehow getting two arrays out of sync.</p>\n"
},
{
"answer_id": 112258,
"author": "finrod",
"author_id": 8295,
"author_profile": "https://Stackoverflow.com/users/8295",
"pm_score": 2,
"selected": false,
"text": "<p>If you'd be willing to allocate some extra space, you could generate another array, call it extra, with elements like this:</p>\n\n<pre><code>extra = [0,1,...,numbers.length-1]\n</code></pre>\n\n<p>Then you could sort this extra array using Arrays.sort() with custom comparator (that, while comparing elements i and j really compares numbers[extra[i]] and numbers[extra[j]]). This way after sorting the extra array, extra[0] would contain the index of the smallest number and, as numbers and colours didn't move, the corresponding colour.<br>\nThis isn't very nice, but it gets the job done, and I can't really think of an easier way to do it.</p>\n\n<p>As a side note, in the competition I usually find the C++ templated pairs and nice maps indispensable ;)</p>\n"
},
{
"answer_id": 112259,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 4,
"selected": false,
"text": "<p>You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.</p>\n\n<p>Java code example:</p>\n\n<pre><code>Integer[] idx = new Integer[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i; \nArrays.sort(idx, new Comparator<Integer>() {\n public int compare(Integer i1, Integer i2) { \n return Double.compare(numbers[i1], numbers[i2]);\n } \n});\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n</code></pre>\n\n<p>Note that you have to use <code>Integer</code> instead of <code>int</code> or you can't use a custom comparator. </p>\n"
},
{
"answer_id": 112299,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>I like @tovare's solution. Make a pointer array:</p>\n\n<pre><code>int ptr[] = { 1, 2, 3 };\n</code></pre>\n\n<p>and then when you sort on numbers, swap the values in ptr instead of in numbers. Then access through the ptr array, like</p>\n\n<pre><code>for (int i = 0; i < ptr.length; i++)\n{\n printf(\"%d %d\\n\", numbers[ptr[i]], colors[ptr[i]]);\n}\n</code></pre>\n\n<p>Update: ok, it appears others have beaten me to this. No XP for me.</p>\n"
},
{
"answer_id": 112310,
"author": "Zach Scrivena",
"author_id": 20029,
"author_profile": "https://Stackoverflow.com/users/20029",
"pm_score": 1,
"selected": false,
"text": "<p>Would it suffice to code your own sort method? A simple bubblesort would probably be quick to code (and get right). No need for extra classes or comparators.</p>\n"
},
{
"answer_id": 112352,
"author": "theycallhimtom",
"author_id": 20087,
"author_profile": "https://Stackoverflow.com/users/20087",
"pm_score": 2,
"selected": false,
"text": "<p>One quick hack would be to combine the two arrays with bit shifts. Make an array of longs such that the most significant 32 bits is the number and the least significant 32 is the color. Use a sorting method and then unpack.</p>\n"
},
{
"answer_id": 112677,
"author": "shiva",
"author_id": 11018,
"author_profile": "https://Stackoverflow.com/users/11018",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way to do this in C, would be bubblesort + dual pointers. Ofcourse the fastest would be quicksort + two pointers. Ofcourse the 2nd pointer maintains the correlation between the two arrays.</p>\n\n<p>I would rather define values that are stored in two arrays as a struct, and use the struct in a single array. Then use quicksort on it. you can write a generic version of sort, by calling a compare function, which can then be written for each struct, but then you already know that :)</p>\n"
},
{
"answer_id": 118259,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 2,
"selected": false,
"text": "<p>An example illustrating using a third index array. Not sure if this is the best implementation.</p>\n\n<p><code><pre><br>\n import java.util.*;</p>\n\n<pre><code>public class Sort {\n\n private static void printTable(String caption, Integer[] numbers, \n Integer[] colors, Integer[] sortOrder){\n\n System.out.println(caption+\n \"\\nNo Num Color\"+\n \"\\n----------------\");\n\n for(int i=0;i<sortOrder.length;i++){\n System.out.printf(\"%x %d %d\\n\", \n i,numbers[sortOrder[i]],colors[sortOrder[i]]);\n\n }\n }\n\n\n public static void main(String[] args) {\n\n final Integer[] numbers = {1,4,3,4,2,6};\n final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};\n Integer[] sortOrder = new Integer[numbers.length];\n\n // Create index array.\n for(int i=0; i<sortOrder.length; i++){\n sortOrder[i] = i;\n }\n printTable(\"\\nNot sorted\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return numbers[b]-numbers[a];\n }});\n printTable(\"\\nSorted by numbers\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return colors[b]-colors[a];\n }});\n printTable(\"\\nSorted by colors\",numbers, colors, sortOrder);\n }\n}\n</code></pre>\n\n<p></pre></code></p>\n\n<p>The output should look like this:</p>\n\n<pre>\n\nNot sorted\nNo Num Color\n----------------\n0 1 80\n1 4 52\n2 3 0\n3 4 254\n4 2 255\n5 6 255\n\nSorted by numbers\nNo Num Color\n----------------\n0 6 255\n1 4 52\n2 4 254\n3 3 0\n4 2 255\n5 1 80\n\nSorted by colors\nNo Num Color\n----------------\n0 6 255\n1 2 255\n2 4 254\n3 1 80\n4 4 52\n5 3 0\n</pre>\n"
},
{
"answer_id": 3699287,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 0,
"selected": false,
"text": "<p>Use a <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeMap.html\" rel=\"nofollow noreferrer\">TreeMap</a></p>\n"
},
{
"answer_id": 36692597,
"author": "kevinarpe",
"author_id": 257299,
"author_profile": "https://Stackoverflow.com/users/257299",
"pm_score": 1,
"selected": false,
"text": "<p>Credit to <code>@tovare</code> for the original best answer.</p>\n\n<p>My answer below removes the (now) unnecessary autoboxing via Maven dependency <a href=\"http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22net.mintern%22%20AND%20a%3A%22primitive%22\" rel=\"nofollow noreferrer\">{net.mintern : primitive : 1.2.2}</a> from this answer: <a href=\"https://stackoverflow.com/a/27095994/257299\">https://stackoverflow.com/a/27095994/257299</a></p>\n\n<pre><code>int[] idx = new int[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i;\nfinal boolean isStableSort = false;\nPrimitive.sort(idx,\n (i1, i2) -> Double.compare(numbers[i1], numbers[i2]),\n isStableSort);\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n</code></pre>\n"
},
{
"answer_id": 45503395,
"author": "Tung Ha",
"author_id": 8416517,
"author_profile": "https://Stackoverflow.com/users/8416517",
"pm_score": 1,
"selected": false,
"text": "<p>I guess you want performance optimization while trying to avoid using array of objects (which can cause a painful GC event).\nUnfortunately there's no general solution, thought.\nBut, for your specific case, in which numbers are different from each others, there might be two arrays to be created only.</p>\n\n<pre><code>/**\n * work only for array of different numbers\n */\nprivate void sortPairArray(int[] numbers, int[] colors) {\n int[] tmpNumbers = Arrays.copyOf(numbers, numbers.length);\n int[] tmpColors = Arrays.copyOf(colors, colors.length);\n Arrays.sort(numbers);\n for (int i = 0; i < tmpNumbers.length; i++) {\n int number = tmpNumbers[i];\n int index = Arrays.binarySearch(numbers, number); // surely this will be found\n colors[index] = tmpColors[i];\n }\n}\n</code></pre>\n\n<p>Two sorted arrays can be replace by <a href=\"http://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/ints/Int2IntOpenHashMap.html\" rel=\"nofollow noreferrer\">Int2IntOpenHashMap</a>, which performs faster run, but memory usage could be double.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16773/"
]
| Let's say that I have two arrays (in Java),
int[] numbers; and int[] colors;
Each ith element of numbers corresponds to its ith element in colors.
Ex, numbers = {4,2,1}
colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc.
I want to sort the numbers array, but then still have it so each element matches up with its pair in colors.
Ex. numbers = {1,2,4};
colors = {0x01,0x24,0x11};
What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable.
**Note: I know the "best" solution is to make a class for the two elements and use a custom comparator. This question is meant to ask people for the quickest way to code this. Imagine being at a programming competition, you wouldn't want to be making all these extra classes, anonymous classes for the comparator, etc. Better yet, forget Java; how would you code it in C?** | You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.
Java code example:
```
Integer[] idx = new Integer[numbers.length];
for( int i = 0 ; i < idx.length; i++ ) idx[i] = i;
Arrays.sort(idx, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return Double.compare(numbers[i1], numbers[i2]);
}
});
// numbers[idx[i]] is the sorted number at index i
// colors[idx[i]] is the sorted color at index i
```
Note that you have to use `Integer` instead of `int` or you can't use a custom comparator. |
112,235 | <p>There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts?</p>
<p>I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in.</p>
<p>I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question.</p>
| [
{
"answer_id": 112240,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>You need to sort the colors array by its relative item in the numbers array. Specify a comparator that compares numbers and use that as the comparison for the colors array.</p>\n"
},
{
"answer_id": 112243,
"author": "JeffFoster",
"author_id": 9853,
"author_profile": "https://Stackoverflow.com/users/9853",
"pm_score": 2,
"selected": false,
"text": "<p>Why not introduce an object to represent a number and a color and implement a comparator function for that?</p>\n\n<p>Also, do you really need an array, why not use something derived from Collection?</p>\n"
},
{
"answer_id": 112254,
"author": "Frank Pape",
"author_id": 10367,
"author_profile": "https://Stackoverflow.com/users/10367",
"pm_score": 3,
"selected": false,
"text": "<p>It seems like the cleanest thing to do would be to create a custom property class that implements Comparable. For example:</p>\n\n<pre><code>class Color implements Comparable {\n private int number;\n private int color;\n\n // (snip ctor, setters, etc.)\n\n public int getNumber() {\n return number;\n }\n public int getColor() {\n return color;\n }\n\n public int compareTo(Color other) {\n if (this.getNumber() == other.getNumber) {\n return 0;\n } else if (this.getNumber() > other.getNumber) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n</code></pre>\n\n<p>Then you can separate your sorting algorithm from the ordering logic (you could use Collections.sort if you use a List instead of an array), and most importantly, you won't have to worry about somehow getting two arrays out of sync.</p>\n"
},
{
"answer_id": 112258,
"author": "finrod",
"author_id": 8295,
"author_profile": "https://Stackoverflow.com/users/8295",
"pm_score": 2,
"selected": false,
"text": "<p>If you'd be willing to allocate some extra space, you could generate another array, call it extra, with elements like this:</p>\n\n<pre><code>extra = [0,1,...,numbers.length-1]\n</code></pre>\n\n<p>Then you could sort this extra array using Arrays.sort() with custom comparator (that, while comparing elements i and j really compares numbers[extra[i]] and numbers[extra[j]]). This way after sorting the extra array, extra[0] would contain the index of the smallest number and, as numbers and colours didn't move, the corresponding colour.<br>\nThis isn't very nice, but it gets the job done, and I can't really think of an easier way to do it.</p>\n\n<p>As a side note, in the competition I usually find the C++ templated pairs and nice maps indispensable ;)</p>\n"
},
{
"answer_id": 112259,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 4,
"selected": false,
"text": "<p>You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.</p>\n\n<p>Java code example:</p>\n\n<pre><code>Integer[] idx = new Integer[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i; \nArrays.sort(idx, new Comparator<Integer>() {\n public int compare(Integer i1, Integer i2) { \n return Double.compare(numbers[i1], numbers[i2]);\n } \n});\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n</code></pre>\n\n<p>Note that you have to use <code>Integer</code> instead of <code>int</code> or you can't use a custom comparator. </p>\n"
},
{
"answer_id": 112299,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>I like @tovare's solution. Make a pointer array:</p>\n\n<pre><code>int ptr[] = { 1, 2, 3 };\n</code></pre>\n\n<p>and then when you sort on numbers, swap the values in ptr instead of in numbers. Then access through the ptr array, like</p>\n\n<pre><code>for (int i = 0; i < ptr.length; i++)\n{\n printf(\"%d %d\\n\", numbers[ptr[i]], colors[ptr[i]]);\n}\n</code></pre>\n\n<p>Update: ok, it appears others have beaten me to this. No XP for me.</p>\n"
},
{
"answer_id": 112310,
"author": "Zach Scrivena",
"author_id": 20029,
"author_profile": "https://Stackoverflow.com/users/20029",
"pm_score": 1,
"selected": false,
"text": "<p>Would it suffice to code your own sort method? A simple bubblesort would probably be quick to code (and get right). No need for extra classes or comparators.</p>\n"
},
{
"answer_id": 112352,
"author": "theycallhimtom",
"author_id": 20087,
"author_profile": "https://Stackoverflow.com/users/20087",
"pm_score": 2,
"selected": false,
"text": "<p>One quick hack would be to combine the two arrays with bit shifts. Make an array of longs such that the most significant 32 bits is the number and the least significant 32 is the color. Use a sorting method and then unpack.</p>\n"
},
{
"answer_id": 112677,
"author": "shiva",
"author_id": 11018,
"author_profile": "https://Stackoverflow.com/users/11018",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way to do this in C, would be bubblesort + dual pointers. Ofcourse the fastest would be quicksort + two pointers. Ofcourse the 2nd pointer maintains the correlation between the two arrays.</p>\n\n<p>I would rather define values that are stored in two arrays as a struct, and use the struct in a single array. Then use quicksort on it. you can write a generic version of sort, by calling a compare function, which can then be written for each struct, but then you already know that :)</p>\n"
},
{
"answer_id": 118259,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 2,
"selected": false,
"text": "<p>An example illustrating using a third index array. Not sure if this is the best implementation.</p>\n\n<p><code><pre><br>\n import java.util.*;</p>\n\n<pre><code>public class Sort {\n\n private static void printTable(String caption, Integer[] numbers, \n Integer[] colors, Integer[] sortOrder){\n\n System.out.println(caption+\n \"\\nNo Num Color\"+\n \"\\n----------------\");\n\n for(int i=0;i<sortOrder.length;i++){\n System.out.printf(\"%x %d %d\\n\", \n i,numbers[sortOrder[i]],colors[sortOrder[i]]);\n\n }\n }\n\n\n public static void main(String[] args) {\n\n final Integer[] numbers = {1,4,3,4,2,6};\n final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};\n Integer[] sortOrder = new Integer[numbers.length];\n\n // Create index array.\n for(int i=0; i<sortOrder.length; i++){\n sortOrder[i] = i;\n }\n printTable(\"\\nNot sorted\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return numbers[b]-numbers[a];\n }});\n printTable(\"\\nSorted by numbers\",numbers, colors, sortOrder);\n\n Arrays.sort(sortOrder,new Comparator<Integer>() { \n public int compare(Integer a, Integer b){\n return colors[b]-colors[a];\n }});\n printTable(\"\\nSorted by colors\",numbers, colors, sortOrder);\n }\n}\n</code></pre>\n\n<p></pre></code></p>\n\n<p>The output should look like this:</p>\n\n<pre>\n\nNot sorted\nNo Num Color\n----------------\n0 1 80\n1 4 52\n2 3 0\n3 4 254\n4 2 255\n5 6 255\n\nSorted by numbers\nNo Num Color\n----------------\n0 6 255\n1 4 52\n2 4 254\n3 3 0\n4 2 255\n5 1 80\n\nSorted by colors\nNo Num Color\n----------------\n0 6 255\n1 2 255\n2 4 254\n3 1 80\n4 4 52\n5 3 0\n</pre>\n"
},
{
"answer_id": 3699287,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 0,
"selected": false,
"text": "<p>Use a <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeMap.html\" rel=\"nofollow noreferrer\">TreeMap</a></p>\n"
},
{
"answer_id": 36692597,
"author": "kevinarpe",
"author_id": 257299,
"author_profile": "https://Stackoverflow.com/users/257299",
"pm_score": 1,
"selected": false,
"text": "<p>Credit to <code>@tovare</code> for the original best answer.</p>\n\n<p>My answer below removes the (now) unnecessary autoboxing via Maven dependency <a href=\"http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22net.mintern%22%20AND%20a%3A%22primitive%22\" rel=\"nofollow noreferrer\">{net.mintern : primitive : 1.2.2}</a> from this answer: <a href=\"https://stackoverflow.com/a/27095994/257299\">https://stackoverflow.com/a/27095994/257299</a></p>\n\n<pre><code>int[] idx = new int[numbers.length];\nfor( int i = 0 ; i < idx.length; i++ ) idx[i] = i;\nfinal boolean isStableSort = false;\nPrimitive.sort(idx,\n (i1, i2) -> Double.compare(numbers[i1], numbers[i2]),\n isStableSort);\n\n// numbers[idx[i]] is the sorted number at index i\n// colors[idx[i]] is the sorted color at index i\n</code></pre>\n"
},
{
"answer_id": 45503395,
"author": "Tung Ha",
"author_id": 8416517,
"author_profile": "https://Stackoverflow.com/users/8416517",
"pm_score": 1,
"selected": false,
"text": "<p>I guess you want performance optimization while trying to avoid using array of objects (which can cause a painful GC event).\nUnfortunately there's no general solution, thought.\nBut, for your specific case, in which numbers are different from each others, there might be two arrays to be created only.</p>\n\n<pre><code>/**\n * work only for array of different numbers\n */\nprivate void sortPairArray(int[] numbers, int[] colors) {\n int[] tmpNumbers = Arrays.copyOf(numbers, numbers.length);\n int[] tmpColors = Arrays.copyOf(colors, colors.length);\n Arrays.sort(numbers);\n for (int i = 0; i < tmpNumbers.length; i++) {\n int number = tmpNumbers[i];\n int index = Arrays.binarySearch(numbers, number); // surely this will be found\n colors[index] = tmpColors[i];\n }\n}\n</code></pre>\n\n<p>Two sorted arrays can be replace by <a href=\"http://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/ints/Int2IntOpenHashMap.html\" rel=\"nofollow noreferrer\">Int2IntOpenHashMap</a>, which performs faster run, but memory usage could be double.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20068/"
]
| There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts?
I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in.
I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question. | You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.
Java code example:
```
Integer[] idx = new Integer[numbers.length];
for( int i = 0 ; i < idx.length; i++ ) idx[i] = i;
Arrays.sort(idx, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return Double.compare(numbers[i1], numbers[i2]);
}
});
// numbers[idx[i]] is the sorted number at index i
// colors[idx[i]] is the sorted color at index i
```
Note that you have to use `Integer` instead of `int` or you can't use a custom comparator. |
112,249 | <p>I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands.</p>
<p>Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again.</p>
<p>An update table set replicated=0;</p>
<p>is not possible:</p>
<ul>
<li>It takes very much time</li>
<li>It duplicates the size of the tabel because of MVCC</li>
<li>It is done in one transaction: It either fails or goes through.</li>
</ul>
<p>I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it.</p>
<p>Several other problems:
Doing an </p>
<pre><code>update set replicated=0 where id >10000 and id<20000
</code></pre>
<p>is also bad: It does a sequential scan all over the whole table which is too slow.
If it weren't doing that, it would still be slow because it would be too many seeks.</p>
<p>What I really need is a way of going through all rows, changing them and not being bound to a giant transaction.</p>
<p>Strangely, an</p>
<pre><code>UPDATE table
SET replicated=0
WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000)
</code></pre>
<p>is also slow, although it should be a good thing: Go through the table in DISK-order...</p>
<p>(Note that in that case there was also an index that covered this)</p>
<p>(An update LIMIT like Mysql is unavailable for PostgresQL)</p>
<p>BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible
It's PostgresQL 7.4 unfortunately.</p>
<p>The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes.</p>
<p>The database itself only contains 5 tables, one is a very large one.
But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that!</p>
<p>Any ideas?</p>
| [
{
"answer_id": 112260,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 3,
"selected": false,
"text": "<p>How about adding a new table to store this replicated value (and a primary key to link each record to the main table). Then you simply add a record for every replicated item, and delete records to remove the replicated flag. (Or maybe the other way around - a record for every non-replicated record, depending on which is the common case).</p>\n\n<p>That would also simplify the case when you want to set them all back to 0, as you can just truncate the table (which zeroes the table size on disk, you don't even have to vacuum to free up the space)</p>\n"
},
{
"answer_id": 112315,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 2,
"selected": false,
"text": "<p>If you are trying to reset the whole table, not just a few rows, it is usually faster (on extremely large datasets -- not on regular tables) to simply <code>CREATE TABLE bar AS SELECT everything, but, copied, 0 FROM foo</code>, and then swap the tables and drop the old one. Obviously you would need to ensure nothing gets inserted into the original table while you are doing that. You'll need to recreate that index, too.</p>\n\n<p><strong>Edit</strong>: A simple improvement in order to avoid locking the table while you copy 14 Gigabytes:</p>\n\n<pre><code>lock ;\ncreate a new table, bar;\nswap tables so that all writes go to bar;\nunlock;\ncreate table baz as select from foo;\ndrop foo;\ncreate the index on baz;\nlock;\ninsert into baz from bar;\nswap tables;\nunlock;\ndrop bar;\n</code></pre>\n\n<p>(let writes happen while you are doing the copy, and insert them post-factum).</p>\n"
},
{
"answer_id": 113993,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 1,
"selected": false,
"text": "<p>This is pseudocode. You'll need 400MB (for ints) or 800MB (for bigints) temporary file (you can compress it with zlib if it is a problem). It will need about 100 scans of a table for vacuums. But it will not bloat a table more than 1% (at most 1000000 dead rows at any time). You can also trade less scans for more table bloat.</p>\n\n<pre><code>// write all ids to temporary file in disk order \n// no where clause will ensure disk order\n$file = tmpfile();\nfor $id, $replicated in query(\"select id, replicated from table\") {\n if ( $replicated<>0 ) {\n write($file,&$id,sizeof($id));\n }\n}\n\n// prepare an update query\nquery(\"prepare set_replicated_0(bigint) as\n update table set replicated=0 where id=?\");\n\n// reread this file, launch prepared query and every 1000000 updates commit\n// and vacuum a table\nrewind($file);\n$counter = 0;\nquery(\"start transaction\");\nwhile read($file,&$id,sizeof($id)) {\n query(\"execute set_replicated_0($id)\");\n $counter++;\n if ( $counter % 1000000 == 0 ) {\n query(\"commit\");\n query(\"vacuum table\");\n query(\"start transaction\");\n }\n}\nquery(\"commit\");\nquery(\"vacuum table\");\nclose($file);\n</code></pre>\n"
},
{
"answer_id": 116712,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 2,
"selected": false,
"text": "<p>While you cannot likely fix the problem of space usage (it is temporary, just until a vacuum) you can probably really speed up the process in terms of clock time. The fact that PostgreSQL uses MVCC means that you should be able to do this without any issues related to newly inserted rows. The create table as select will get around some of the performance issues, but will not allow for continued use of the table, and takes just as much space. Just ditch the index, and rebuild it, then do a vacuum.</p>\n\n<pre><code>drop index replication_flag;\nupdate big_table set replicated=0;\ncreate index replication_flag on big_table btree(ID) WHERE replicated=0;\nvacuum full analyze big_table;\n</code></pre>\n"
},
{
"answer_id": 2369953,
"author": "norlan V",
"author_id": 285142,
"author_profile": "https://Stackoverflow.com/users/285142",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's better to change your postgres to version 8.X. probably the cause is the low version of Postgres. Also try this query below. I hope this can help. </p>\n\n<pre><code>UPDATE table1 SET name = table2.value\nFROM table2 \nWHERE table1.id = table2.id;\n</code></pre>\n"
},
{
"answer_id": 3481980,
"author": "Kapil",
"author_id": 394560,
"author_profile": "https://Stackoverflow.com/users/394560",
"pm_score": 0,
"selected": false,
"text": "<p>I guess what you need to do is\na. copy the 2000 records PK value into a temporary table with the same standard limit, etc.\nb. select the same 2000 records and perform the necessary operations in the cursor as it is.\nc. If successful, run a single update query against the records in the temp table. Clear the temp table and run step a again.\nd. If unsuccessful, clear the temp table without running the update query.\nSimple, efficient and reliable.\nRegards,\nKT</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20088/"
]
| I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands.
Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again.
An update table set replicated=0;
is not possible:
* It takes very much time
* It duplicates the size of the tabel because of MVCC
* It is done in one transaction: It either fails or goes through.
I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it.
Several other problems:
Doing an
```
update set replicated=0 where id >10000 and id<20000
```
is also bad: It does a sequential scan all over the whole table which is too slow.
If it weren't doing that, it would still be slow because it would be too many seeks.
What I really need is a way of going through all rows, changing them and not being bound to a giant transaction.
Strangely, an
```
UPDATE table
SET replicated=0
WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000)
```
is also slow, although it should be a good thing: Go through the table in DISK-order...
(Note that in that case there was also an index that covered this)
(An update LIMIT like Mysql is unavailable for PostgresQL)
BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible
It's PostgresQL 7.4 unfortunately.
The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes.
The database itself only contains 5 tables, one is a very large one.
But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that!
Any ideas? | How about adding a new table to store this replicated value (and a primary key to link each record to the main table). Then you simply add a record for every replicated item, and delete records to remove the replicated flag. (Or maybe the other way around - a record for every non-replicated record, depending on which is the common case).
That would also simplify the case when you want to set them all back to 0, as you can just truncate the table (which zeroes the table size on disk, you don't even have to vacuum to free up the space) |
112,277 | <p>Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:</p>
<pre><code>#include <iostream>
using namespace std;
template< int n >
struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };
template<>
struct factorial< 0 > { enum { ret = 1 }; };
int main() {
cout << "7! = " << factorial< 7 >::ret << endl; // 5040
return 0;
}
</code></pre>
<p>If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?</p>
| [
{
"answer_id": 112285,
"author": "Maxim Ananyev",
"author_id": 404206,
"author_profile": "https://Stackoverflow.com/users/404206",
"pm_score": 2,
"selected": false,
"text": "<p>google Alexandrescu, Modern C++ Design: Generic Programming and Design Patterns Applied</p>\n"
},
{
"answer_id": 112288,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201704315\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Modern C++</a> is one of the best introductions I've read. It covers actual useful examples of template metaprogramming. Also take a look at the companion library <a href=\"http://loki-lib.sourceforge.net/\" rel=\"noreferrer\">Loki</a>.</p>\n"
},
{
"answer_id": 112292,
"author": "Alaric",
"author_id": 19744,
"author_profile": "https://Stackoverflow.com/users/19744",
"pm_score": 5,
"selected": false,
"text": "<p>Andrei Alexandrescu's <a href=\"http://erdani.com/index.php/books/modern-c-design/\" rel=\"noreferrer\">Modern C++ Design</a> book covers a lot of this and other tricks for speedy and efficient modern C++ code and is the basis for the <a href=\"http://loki-lib.sourceforge.net/\" rel=\"noreferrer\">Loki</a> library.</p>\n\n<p>Also worth mentioning is the <a href=\"http://boost.org\" rel=\"noreferrer\">Boost</a> libraries, which heavily use these techniques and are usually of very high quality to learn from (although some are quite dense).</p>\n"
},
{
"answer_id": 112293,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 2,
"selected": false,
"text": "<p>Veldhuizen's original papers were good. If you up for a whole book, then there's Vandevoorde's book \"C++ Templates Complete Guide\". And when you're ready for the master's course, try Alexandrescu's Modern C++ Design.</p>\n"
},
{
"answer_id": 112294,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0201704315\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Modern C++ Design</a>, a brilliant book and design pattern framework by Alexandrescu. Word of warning, after reading this book I stopped doing C++ and thought \"What the heck, I can just pick a better language and get it for free\".</p>\n"
},
{
"answer_id": 112301,
"author": "Nik",
"author_id": 5354,
"author_profile": "https://Stackoverflow.com/users/5354",
"pm_score": 3,
"selected": false,
"text": "<p>Two good books that spring to mind are:</p>\n\n<ul>\n<li>Modern C++ Design / Andrei Alexandrescu (It's actually 7 years old despite the name!)</li>\n<li>C++ Templates: The Complete Guide / Vandevoorde & Josuttis</li>\n</ul>\n\n<p>It's quite an in-depth field, so a good book like one of these is definitely recommended over websites. Some of the more advanced techniques will have you studying the code for some time to figure out how they work!</p>\n"
},
{
"answer_id": 112302,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 8,
"selected": true,
"text": "<p><em>[Answering my own question]</em></p>\n\n<p>The best introductions I've found so far are chapter 10, \"Static Metaprogramming in C++\" from <em>Generative Programming, Methods, Tools, and Applications</em> by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, \"Metaprograms\" of <em>C++ Templates: The Complete Guide</em> by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843.</p>\n\n<p><img src=\"https://i.stack.imgur.com/q79o3.gif\" alt=\"alt text\"> <img src=\"https://i.stack.imgur.com/FreHD.gif\" alt=\"alt text\"> <img src=\"https://i.stack.imgur.com/89bSK.gif\" alt=\"alt text\"> <img src=\"https://i.stack.imgur.com/oDM2G.gif\" alt=\"alt text\"></p>\n\n<p>Todd Veldhuizen has an excellent tutorial <a href=\"http://www.cs.rpi.edu/~musser/design/blitz/meta-art.html\" rel=\"noreferrer\">here</a>.</p>\n\n<p>A good resource for C++ programming in general is <em>Modern C++ Design</em> by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 \"Compile-Time Assertions\", 2.4 \"Mapping Integral Constants to Types\", 2.6 \"Type Selection\", 2.7 \"Detecting Convertibility and Inheritance at Compile Time\", 2.9 \"<code>NullType</code> and <code>EmptyType</code>\" and 2.10 \"Type Traits\".</p>\n\n<p>The best intermediate/advanced resource I've found is <em>C++ Template Metaprogramming</em> by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256</p>\n\n<p>If you'd prefer just one book, get <em>C++ Templates: The Complete Guide</em> since it is also the definitive reference for templates in general.</p>\n"
},
{
"answer_id": 112403,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "<p>There won't be a large list of books, as the list of people with a lot of experience is limited. Template metaprogramming started for real around the first C++ Template Programming Workshop in 2000, and many of the authors named so far attended. (IIRC, Andrei didn't.) These pioneers greatly influenced the field, and basically what should be written is now written. Personally, I'd advice Vandevoorde & Josuttis. Alexandrescu's is a tough book if you're new to the field.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
]
| Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:
```
#include <iostream>
using namespace std;
template< int n >
struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };
template<>
struct factorial< 0 > { enum { ret = 1 }; };
int main() {
cout << "7! = " << factorial< 7 >::ret << endl; // 5040
return 0;
}
```
If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)? | *[Answering my own question]*
The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from *Generative Programming, Methods, Tools, and Applications* by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of *C++ Templates: The Complete Guide* by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843.
   
Todd Veldhuizen has an excellent tutorial [here](http://www.cs.rpi.edu/~musser/design/blitz/meta-art.html).
A good resource for C++ programming in general is *Modern C++ Design* by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 "Compile-Time Assertions", 2.4 "Mapping Integral Constants to Types", 2.6 "Type Selection", 2.7 "Detecting Convertibility and Inheritance at Compile Time", 2.9 "`NullType` and `EmptyType`" and 2.10 "Type Traits".
The best intermediate/advanced resource I've found is *C++ Template Metaprogramming* by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256
If you'd prefer just one book, get *C++ Templates: The Complete Guide* since it is also the definitive reference for templates in general. |
112,372 | <p>Is it possible to over interface? when designing an system now, I will start from interfaces and progressively write unit tests along with the interfaces until I have a pattern that works well.. I'll move onto writing some concrete classes and set the unit tests up against these..</p>
<p>Now I'm someone who loves interfaces, I will generally end up only ever passing/returning primatives or interfaces around when I control the code.. so far I've found this to be ideal, you can easily adapt and enhance a system generally without impacting the dependent systems.</p>
<p>I obviously don't need to sell the reasons for using interfaces, but im wondering if its overboard to interface everything, ps. I'm <strong>not</strong> talking about blank interfaces as in something crazy like:</p>
<pre><code>interface IStringCollection : ICollection<string>
{
}
</code></pre>
<p>I'm talking more something like:</p>
<pre><code>interface ISomethingProvider
{
ISomething Provide(ISomethingOptions options);
}
</code></pre>
<p>Is this really over the top? my reasoning is that any type could gain from interfacing at some point.. and the only real problem I've had is that I've had to learn what I think is a better way to design classes, as you don't have daft interactions and 'hacks' going on.</p>
<p>Would love your feedback about if this is a timebomb, and when you decide to interface vs not.. </p>
<p>ps- this isn't really so much about how to write interfaces.</p>
| [
{
"answer_id": 112385,
"author": "TonyOssa",
"author_id": 3276,
"author_profile": "https://Stackoverflow.com/users/3276",
"pm_score": 0,
"selected": false,
"text": "<p>ISwissArmyKnife!</p>\n\n<p>Consult this:</p>\n\n<p><a href=\"http://thedailywtf.com/Articles/Classic-WTF-Implements-ISwissArmyKnife.aspx\" rel=\"nofollow noreferrer\">http://thedailywtf.com/Articles/Classic-WTF-Implements-ISwissArmyKnife.aspx</a></p>\n"
},
{
"answer_id": 112389,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 1,
"selected": false,
"text": "<p>It can be a real pain to work out the eventual call stack before you step with the debugger if you have interfaces everywhere. I tend to prefer interfaces only when:</p>\n\n<ol>\n<li>you need team members to agree on who should do what before they start coding - an interface then documents the border exactly</li>\n<li>when you actually need an interface to solve the problem, so at least two implementations that don't extend each other</li>\n<li>You expect case 2</li>\n</ol>\n"
},
{
"answer_id": 112390,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 1,
"selected": false,
"text": "<p>I find that interfaces complicates the design, especially for other people to cowork on your stuff. Don't get me wrong, interfaces are great for a lot of stuff, but mostly if you want two or more classes to share a common interface.</p>\n\n<p>If you find yourself in the situation where you suddenly need an interface, refactoring with tools like Resharper is a breeze :)</p>\n"
},
{
"answer_id": 112401,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>As with anything else - use with moderation and where necessary. Ask yourself \"<strong>Are you gonna need it?</strong>\".</p>\n"
},
{
"answer_id": 112416,
"author": "Arthur Vanderbilt",
"author_id": 18354,
"author_profile": "https://Stackoverflow.com/users/18354",
"pm_score": 3,
"selected": false,
"text": "<p>Interfaces describe a contract for behavior. If you need to address some set of objects according to a behavioral pattern, interfaces are useful, not so much if you're simply describing the structure of objects. I think you need to have a good reason to use them, such as using a factory that creates behaviorally related objects or establishing a behavioral contract for part of a library. Using interfaces aimlessly can make a library difficult to read / understand / maintain.</p>\n"
},
{
"answer_id": 112436,
"author": "warren_s",
"author_id": 6255,
"author_profile": "https://Stackoverflow.com/users/6255",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't solely a .NET thing, the same problem occurs in Java quite often.</p>\n\n<p>Unless it's a completely obvious requirement, I vote for not using interfaces and simply refactoring when the need becomes clear.</p>\n\n<p>The pragmatic approach says to just do the <em>simplest thing that could possibly work</em>, and don't get caught in architecture astronautics.</p>\n"
},
{
"answer_id": 112465,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 3,
"selected": false,
"text": "<p>In short yes it is possible to over interface a project. Take into account when the situation really calls for an Abstract Base Class and an interface, while they both are similar there are distinct advantages to using both <a href=\"http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx\" rel=\"nofollow noreferrer\">See Here</a>. Typically I've noticed that people use Interfaces when they really should be using Abstract Base Classes. From a OO perspective interfaces should be used to list common behavior that may span vastly different classes. For example you may have an IMove interface with a method called Move(). Now imagine you have an Airplane, Car, Person, and Insect class. Airplane and Car may inherit from an abstract Vehicle class but still need to use IMove and so will Insect and Person but they will all implement move differently. I've noticed, my self included, people tend to use Interfaces to \"group\" classes together when really that should be handled by a base class.</p>\n"
},
{
"answer_id": 112476,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to not use too many interfaces for testing purposes. I would rather make a private value public and/or unsealing classes and/or temp methods while building and testing until I am at the point where I have built other objects and tests that will eventually exercise what it was that i needed. Sometmes its a pain in the butt to rack your changes that way but your tests will tell you when you forgot to change something.</p>\n"
},
{
"answer_id": 112534,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to over-interface. The rule where I work is that if you have an interface in your application, you need to have at least two classes that implement it (or have a reasonable expectation that you will be adding implementing classes in the near future).</p>\n\n<p>If you need to create mock objects for testing, then having the mock class and the real class implement a common interface is a valid reason to use an interface.</p>\n\n<p>I would not recommend automatically using interfaces for everything in your application, especially because a single class can usually be easily refactored into an interface if necessary.</p>\n"
},
{
"answer_id": 1277135,
"author": "Jim Cooper",
"author_id": 45659,
"author_profile": "https://Stackoverflow.com/users/45659",
"pm_score": 2,
"selected": false,
"text": "<p>Whenever I see or hear someone say this </p>\n\n<blockquote>\n <p>Interfaces describe a contract for behavior</p>\n</blockquote>\n\n<p>I know I've found someone who doesn't understand interfaces.</p>\n\n<p>Interfaces <strong><em>cannot</em></strong> do that. It is impossible. Interfaces <strong><em>do not prescribe, force, or in any way constrain behaviour</em></strong>.</p>\n\n<p>Interfaces describe a contract for an <strong><em>interface</em></strong>, hence the name. They do not have behaviour. </p>\n\n<p>You might hope that the names you give your interface's methods will imply a required behaviour to anyone implementing it, but there is no requirement that they do so. There is no behavioural contract, nor can there ever be one.</p>\n\n<p>If you require a certain type of behaviour then you must use classes to enforce it (eg with the Template pattern) - that's where all the behaviour is.</p>\n\n<p>Interfaces are regularly abused as a design construct, and one of the reasons is because of widespread belief in this fallacy.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is it possible to over interface? when designing an system now, I will start from interfaces and progressively write unit tests along with the interfaces until I have a pattern that works well.. I'll move onto writing some concrete classes and set the unit tests up against these..
Now I'm someone who loves interfaces, I will generally end up only ever passing/returning primatives or interfaces around when I control the code.. so far I've found this to be ideal, you can easily adapt and enhance a system generally without impacting the dependent systems.
I obviously don't need to sell the reasons for using interfaces, but im wondering if its overboard to interface everything, ps. I'm **not** talking about blank interfaces as in something crazy like:
```
interface IStringCollection : ICollection<string>
{
}
```
I'm talking more something like:
```
interface ISomethingProvider
{
ISomething Provide(ISomethingOptions options);
}
```
Is this really over the top? my reasoning is that any type could gain from interfacing at some point.. and the only real problem I've had is that I've had to learn what I think is a better way to design classes, as you don't have daft interactions and 'hacks' going on.
Would love your feedback about if this is a timebomb, and when you decide to interface vs not..
ps- this isn't really so much about how to write interfaces. | Interfaces describe a contract for behavior. If you need to address some set of objects according to a behavioral pattern, interfaces are useful, not so much if you're simply describing the structure of objects. I think you need to have a good reason to use them, such as using a factory that creates behaviorally related objects or establishing a behavioral contract for part of a library. Using interfaces aimlessly can make a library difficult to read / understand / maintain. |
112,396 | <p>I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (<a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> and <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a>) to a remote location over SSH many times in an hour.</p>
<p>One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?</p>
| [
{
"answer_id": 112409,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 12,
"selected": true,
"text": "<p>Short answer:</p>\n\n<pre><code>$ ssh-keygen -p\n</code></pre>\n\n<p>This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).</p>\n\n<hr>\n\n<p>If you would like to do it all on one line without prompts do:</p>\n\n<pre><code>$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]\n</code></pre>\n\n<p><strong>Important:</strong> Beware that when executing commands they will typically be logged in your <code>~/.bash_history</code> file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise. </p>\n\n<p>Notice though that you can still use <code>-f keyfile</code> without having to specify <code>-P</code> nor <code>-N</code>, and that the keyfile defaults to <code>~/.ssh/id_rsa</code>, so in many cases, it's not even needed.</p>\n\n<p>You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.</p>\n"
},
{
"answer_id": 112618,
"author": "mlambie",
"author_id": 17453,
"author_profile": "https://Stackoverflow.com/users/17453",
"pm_score": 6,
"selected": false,
"text": "<p>You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.</p>\n\n<pre><code>if [ -f ~/.agent.env ] ; then\n . ~/.agent.env > /dev/null\n if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then\n echo \"Stale agent file found. Spawning new agent… \"\n eval `ssh-agent | tee ~/.agent.env`\n ssh-add\n fi \nelse\n echo \"Starting ssh-agent\"\n eval `ssh-agent | tee ~/.agent.env`\n ssh-add\nfi\n</code></pre>\n\n<p>On some Linux distros (Ubuntu, Debian) you can use:</p>\n\n<pre><code>ssh-copy-id -i ~/.ssh/id_dsa.pub username@host\n</code></pre>\n\n<p>This will copy the generated id to a remote machine and add it to the remote keychain.</p>\n\n<p>You can read more <a href=\"http://lambie.org/2004/02/13/ssh-auto-authentication/\" rel=\"noreferrer\">here</a> and <a href=\"http://lambie.org/2005/08/12/ssh-agent/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 50703802,
"author": "Karan",
"author_id": 9898576,
"author_profile": "https://Stackoverflow.com/users/9898576",
"pm_score": 7,
"selected": false,
"text": "<p><code>$ ssh-keygen -p</code> worked for me </p>\n\n<p>Opened git bash. Pasted : <code>$ ssh-keygen -p</code></p>\n\n<p>Hit enter for default location.</p>\n\n<p>Enter old passphrase </p>\n\n<p>Enter new passphrase - BLANK</p>\n\n<p>Confirm new passphrase - BLANK</p>\n\n<p>BOOM the pain of entering passphrase for git push was gone.</p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 57749743,
"author": "bbaassssiiee",
"author_id": 571517,
"author_profile": "https://Stackoverflow.com/users/571517",
"pm_score": 3,
"selected": false,
"text": "<p>On the <strong>Mac</strong> you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.</p>\n\n<pre><code>ssh-keygen -K\n</code></pre>\n\n<p>Add this to <code>~/.ssh/config</code></p>\n\n<pre><code>UseKeychain yes\n</code></pre>\n"
},
{
"answer_id": 57762729,
"author": "Ajit Goel",
"author_id": 391918,
"author_profile": "https://Stackoverflow.com/users/391918",
"pm_score": 3,
"selected": false,
"text": "<p>On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file. </p>\n"
},
{
"answer_id": 58052425,
"author": "ccalvert",
"author_id": 253576,
"author_profile": "https://Stackoverflow.com/users/253576",
"pm_score": 5,
"selected": false,
"text": "<p>To change or remove the passphrase, I often find it simplest to pass in only the <code>p</code> and <code>f</code> flags, then let the system prompt me to supply the passphrases:</p>\n\n<p><code>ssh-keygen -p -f <name-of-private-key></code></p>\n\n<p>For instance:</p>\n\n<p><code>ssh-keygen -p -f id_rsa</code></p>\n\n<p>Enter an empty password if you want to remove the passphrase.</p>\n\n<p>A sample run to remove or change a password looks something like this:</p>\n\n<pre><code>ssh-keygen -p -f id_rsa\nEnter old passphrase: \nKey has comment 'bcuser@pl1909'\nEnter new passphrase (empty for no passphrase): \nEnter same passphrase again: \nYour identification has been saved with the new passphrase.\n</code></pre>\n\n<p>When adding a passphrase to a key that has no passphrase, the run looks something like this:</p>\n\n<pre><code>ssh-keygen -p -f id_rsa\nKey has comment 'charlie@elf-path'\nEnter new passphrase (empty for no passphrase): \nEnter same passphrase again: \nYour identification has been saved with the new passphrase.\n</code></pre>\n"
},
{
"answer_id": 65566332,
"author": "Kreshel",
"author_id": 13803364,
"author_profile": "https://Stackoverflow.com/users/13803364",
"pm_score": 3,
"selected": false,
"text": "<p>In windows for me it kept saying\n"id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\\id_ed25135" at the end.</p>\n<p>This is what I ended up typing and worked:<br />\nssh-keygen -p -f C:\\Users\\john\\.ssh\\id_ed25135</p>\n<p>This worked. Because for some reason, in Cmder the default path was something like this C:\\Users\\capit/.ssh/id_ed25135 (some were backslashes: "\\" and some were forward slashes: "/")</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14191/"
]
| I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit ([Git](http://en.wikipedia.org/wiki/Git_%28software%29) and [SVN](http://en.wikipedia.org/wiki/Apache_Subversion)) to a remote location over SSH many times in an hour.
One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys? | Short answer:
```
$ ssh-keygen -p
```
This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).
---
If you would like to do it all on one line without prompts do:
```
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
```
**Important:** Beware that when executing commands they will typically be logged in your `~/.bash_history` file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.
Notice though that you can still use `-f keyfile` without having to specify `-P` nor `-N`, and that the keyfile defaults to `~/.ssh/id_rsa`, so in many cases, it's not even needed.
You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent. |
112,412 | <p>I would like to use Visual Studio 2008 to the greatest extent possible while effectively compiling/linking/building/etc code as if all these build processes were being done by the tools provided with MASM 6.11. The exact version of MASM does not matter, so long as it's within the 6.x range, as that is what my college is using to teach 16-bit assembly.</p>
<p>I have done some research on the subject and have come to the conclusion that there are several options:</p>
<ol>
<li>Reconfigure VS to call the MASM 6.11 executables with the same flags, etc as MASM 6.11 would natively do.</li>
<li>Create intermediary batch file(s) to be called by VS to then invoke the proper commands for MASM's linker, etc.</li>
<li>Reconfigure VS's built-in build tools/rules (assembler, linker, etc) to provide an environment identical to the one used by MASM 6.11.</li>
</ol>
<p>Option (2) was brought up when I realized that the options available in VS's "External Tools" interface may be insufficient to correctly invoke MASM's build tools, thus a batch file to interpret VS's strict method of passing arguments might be helpful, as a lot of my learning about how to get this working involved my manually calling ML.exe, LINK.exe, etc from the command prompt.</p>
<p>Below are several links that may prove useful in answering my question. Please keep in mind that I have read them all and none are the actual solution. I can only hope my specifying MASM 6.11 doesn't prevent anyone from contributing a perhaps more generalized answer.</p>
<p>Similar method used to Option (2), but users on the thread are not contactable:<br>
<a href="http://www.codeguru.com/forum/archive/index.php/t-284051.html" rel="nofollow noreferrer">http://www.codeguru.com/forum/archive/index.php/t-284051.html</a><br>
(also, I have my doubts about the necessity of an intermediary batch file)</p>
<p>Out of date explanation to my question:<br>
<a href="http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html" rel="nofollow noreferrer">http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html</a></p>
<p>Probably the closest thing I've come to a definitive solution, but refers to a suite of tools from something besides MASM, also uses a batch file:<br>
<a href="http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit" rel="nofollow noreferrer">http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit</a></p>
<p>I apologize if my terminology for the tools used in each step of the code -> exe process is off, but since I'm trying to reproduce the entirety of steps in between completion of writing the code and generating an executable, I don't think it matters much.</p>
| [
{
"answer_id": 112600,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>instead of batch files, why not use the a custom build step defined on the file?</p>\n"
},
{
"answer_id": 192118,
"author": "R Caloca",
"author_id": 13004,
"author_profile": "https://Stackoverflow.com/users/13004",
"pm_score": 0,
"selected": false,
"text": "<p>If you are going to use Visual Studio, couldn't you give them a skeleton project in C/C++ with the entry point for a console app calling a function that has en empty inline assembly block, and let them fill their results in it?</p>\n"
},
{
"answer_id": 195269,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "<p>You can create a makefile project. In Visual Studio, under File / New / Project, choose Visual C++ / Makefile project.</p>\n\n<p>This allows you to run an arbitrary command to build your project. It doesn't have to be C/C++. It doesn't even have to be a traditional NMake makefile. I've used it to compile a driver using a batch file, and using a NAnt script.</p>\n\n<p>It should be fairly easy to get it to run the MASM 6.x toolchain.</p>\n"
},
{
"answer_id": 205948,
"author": "tabdamage",
"author_id": 28022,
"author_profile": "https://Stackoverflow.com/users/28022",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest to define Custom Build rules depending on file extension.\n(Visual Studio 2008, at least in Professinal Edition, can generate .rules files, which can be distributed). There you can define custom build tools for asm files. By using this approach, you should be able to leave the linker step as is.</p>\n\n<p>Way back, we used MASM32 <a href=\"http://www.masm32.com/\" rel=\"nofollow noreferrer\">link text</a> as IDE to help students learn assembly. You could check their batchfiles what they do to assemble and link.</p>\n"
},
{
"answer_id": 292121,
"author": "TCJ",
"author_id": 10344,
"author_profile": "https://Stackoverflow.com/users/10344",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use Irvine's guide? Irvine's library is nice and if you want, you can ignore it and work with Windows procs directly. I've searching for a guide like this, Irvine's was the best solution.</p>\n"
},
{
"answer_id": 2403173,
"author": "Sam Harwell",
"author_id": 138304,
"author_profile": "https://Stackoverflow.com/users/138304",
"pm_score": 3,
"selected": true,
"text": "<p>There is a MASM rules file located at (32-bit system remove <code>(x86)</code>):</p>\n\n<pre><code>C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\VCProjectDefaults\\masm.rules\n</code></pre>\n\n<p>Copy that file to your project directory, and add it to the Custom Build Rules for your project. Then \"Modify Rule File...\", select the MASM build rule and \"Modify Build Rule...\".</p>\n\n<p>Add a property:</p>\n\n<ul>\n<li>User property type: <strong>String</strong></li>\n<li>Default value: <strong>*.inc</strong></li>\n<li>Description: <strong>Add additional MASM file dependencies.</strong></li>\n<li>Display name: <strong>Additional Dependencies</strong></li>\n<li>Is read only: <strong>False</strong></li>\n<li>Name: <strong>AdditionalDependencies</strong></li>\n<li>Property page name: <strong>General</strong></li>\n<li>Switch: <strong>[value]</strong></li>\n</ul>\n\n<p>Set the Additional Dependencies value to <strong>[AdditionalDependencies]</strong>. The build should now automatically detect changes to <code>*.inc</code>, and you can edit the properties for an individual asm file to specify others.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20110/"
]
| I would like to use Visual Studio 2008 to the greatest extent possible while effectively compiling/linking/building/etc code as if all these build processes were being done by the tools provided with MASM 6.11. The exact version of MASM does not matter, so long as it's within the 6.x range, as that is what my college is using to teach 16-bit assembly.
I have done some research on the subject and have come to the conclusion that there are several options:
1. Reconfigure VS to call the MASM 6.11 executables with the same flags, etc as MASM 6.11 would natively do.
2. Create intermediary batch file(s) to be called by VS to then invoke the proper commands for MASM's linker, etc.
3. Reconfigure VS's built-in build tools/rules (assembler, linker, etc) to provide an environment identical to the one used by MASM 6.11.
Option (2) was brought up when I realized that the options available in VS's "External Tools" interface may be insufficient to correctly invoke MASM's build tools, thus a batch file to interpret VS's strict method of passing arguments might be helpful, as a lot of my learning about how to get this working involved my manually calling ML.exe, LINK.exe, etc from the command prompt.
Below are several links that may prove useful in answering my question. Please keep in mind that I have read them all and none are the actual solution. I can only hope my specifying MASM 6.11 doesn't prevent anyone from contributing a perhaps more generalized answer.
Similar method used to Option (2), but users on the thread are not contactable:
<http://www.codeguru.com/forum/archive/index.php/t-284051.html>
(also, I have my doubts about the necessity of an intermediary batch file)
Out of date explanation to my question:
<http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html>
Probably the closest thing I've come to a definitive solution, but refers to a suite of tools from something besides MASM, also uses a batch file:
<http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit>
I apologize if my terminology for the tools used in each step of the code -> exe process is off, but since I'm trying to reproduce the entirety of steps in between completion of writing the code and generating an executable, I don't think it matters much. | There is a MASM rules file located at (32-bit system remove `(x86)`):
```
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults\masm.rules
```
Copy that file to your project directory, and add it to the Custom Build Rules for your project. Then "Modify Rule File...", select the MASM build rule and "Modify Build Rule...".
Add a property:
* User property type: **String**
* Default value: **\*.inc**
* Description: **Add additional MASM file dependencies.**
* Display name: **Additional Dependencies**
* Is read only: **False**
* Name: **AdditionalDependencies**
* Property page name: **General**
* Switch: **[value]**
Set the Additional Dependencies value to **[AdditionalDependencies]**. The build should now automatically detect changes to `*.inc`, and you can edit the properties for an individual asm file to specify others. |
112,433 | <p>In a C++ project I'm working on, I have a <em>flag</em> kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:</p>
<ul>
<li>new record</li>
<li>deleted record</li>
<li>modified record</li>
<li>existing record</li>
</ul>
<p>Now, for each record I wish to keep this attribute, so I could use an enum:</p>
<pre><code>enum { xNew, xDeleted, xModified, xExisting }
</code></pre>
<p>However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: </p>
<pre><code>showRecords(xNew | xDeleted);
</code></pre>
<p>So, it seems I have three possible appoaches:</p>
<pre><code>#define X_NEW 0x01
#define X_DELETED 0x02
#define X_MODIFIED 0x04
#define X_EXISTING 0x08
</code></pre>
<p>or</p>
<pre><code>typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
</code></pre>
<p>or </p>
<pre><code>namespace RecordType {
static const uint8 xNew = 1;
static const uint8 xDeleted = 2;
static const uint8 xModified = 4;
static const uint8 xExisting = 8;
}
</code></pre>
<p>Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with <code>enum</code> I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With <code>const</code> I think I also lose type safety since a random <code>uint8</code> could get in by mistake.</p>
<p>Is there some other cleaner way?</p>
<p>If not, what would you use and why?</p>
<p>P.S. The rest of the code is rather clean modern C++ without <code>#define</code>s, and I have used namespaces and templates in few spaces, so those aren't out of question either.</p>
| [
{
"answer_id": 112445,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 2,
"selected": false,
"text": "<p>Even if you have to use 4 byte to store an enum (I'm not that familiar with C++ -- I know you can specify the underlying type in C#), it's still worth it -- use enums.</p>\n\n<p>In this day and age of servers with GBs of memory, things like 4 bytes vs. 1 byte of memory at the application level in general don't matter. Of course, if in your particular situation, memory usage is that important (and you can't get C++ to use a byte to back the enum), then you can consider the 'static const' route.</p>\n\n<p>At the end of the day, you have to ask yourself, is it worth the maintenance hit of using 'static const' for the 3 bytes of memory savings for your data structure?</p>\n\n<p>Something else to keep in mind -- IIRC, on x86, data structures are 4-byte aligned, so unless you have a number of byte-width elements in your 'record' structure, it might not actually matter. Test and make sure it does before you make a tradeoff in maintainability for performance/space.</p>\n"
},
{
"answer_id": 112460,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 2,
"selected": false,
"text": "<p>Enums would be more appropriate as they provide \"meaning to the identifiers\" as well as type safety. You can clearly tell \"xDeleted\" is of \"RecordType\" and that represent \"type of a record\" (wow!) even after years. Consts would require comments for that, also they would require going up and down in code.</p>\n"
},
{
"answer_id": 112470,
"author": "Abbas",
"author_id": 4714,
"author_profile": "https://Stackoverflow.com/users/4714",
"pm_score": 3,
"selected": false,
"text": "<p>Here are couple of articles on const vs. macros vs. enums:</p>\n\n<p><a href=\"http://www.embedded.com/electronics-blogs/programming-pointers/4023858/Symbolic-Constants\" rel=\"nofollow noreferrer\">Symbolic Constants</a>\n<br /><a href=\"http://www.embedded.com/electronics-blogs/programming-pointers/4023879/Enumeration-Constants-vs-Constant-Objects\" rel=\"nofollow noreferrer\">Enumeration Constants vs. Constant Objects</a></p>\n\n<p>I think you should avoid macros especially since you wrote most of your new code is in modern C++.</p>\n"
},
{
"answer_id": 112475,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 5,
"selected": false,
"text": "<p>Have you ruled out std::bitset? Sets of flags is what it's for. Do</p>\n\n<pre><code>typedef std::bitset<4> RecordType;\n</code></pre>\n\n<p>then</p>\n\n<pre><code>static const RecordType xNew(1);\nstatic const RecordType xDeleted(2);\nstatic const RecordType xModified(4);\nstatic const RecordType xExisting(8);\n</code></pre>\n\n<p>Because there are a bunch of operator overloads for bitset, you can now do</p>\n\n<pre><code>RecordType rt = whatever; // unsigned long or RecordType expression\nrt |= xNew; // set \nrt &= ~xDeleted; // clear \nif ((rt & xModified) != 0) ... // test\n</code></pre>\n\n<p>Or something very similar to that - I'd appreciate any corrections since I haven't tested this. You can also refer to the bits by index, but it's generally best to define only one set of constants, and RecordType constants are probably more useful.</p>\n\n<p>Assuming you have ruled out bitset, I vote for the <strong>enum</strong>.</p>\n\n<p>I don't buy that casting the enums is a serious disadvantage - OK so it's a bit noisy, and assigning an out-of-range value to an enum is undefined behaviour so it's theoretically possible to shoot yourself in the foot on some unusual C++ implementations. But if you only do it when necessary (which is when going from int to enum iirc), it's perfectly normal code that people have seen before.</p>\n\n<p>I'm dubious about any space cost of the enum, too. uint8 variables and parameters probably won't use any less stack than ints, so only storage in classes matters. There are some cases where packing multiple bytes in a struct will win (in which case you can cast enums in and out of uint8 storage), but normally padding will kill the benefit anyhow.</p>\n\n<p>So the enum has no disadvantages compared with the others, and as an advantage gives you a bit of type-safety (you can't assign some random integer value without explicitly casting) and clean ways of referring to everything.</p>\n\n<p>For preference I'd also put the \"= 2\" in the enum, by the way. It's not necessary, but a \"principle of least astonishment\" suggests that all 4 definitions should look the same.</p>\n"
},
{
"answer_id": 112500,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 2,
"selected": false,
"text": "<p>Do you actually need to pass around the flag values as a conceptual whole, or are you going to have a lot of per-flag code? Either way, I think having this as class or struct of 1-bit bitfields might actually be clearer:</p>\n\n<pre><code>struct RecordFlag {\n unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;\n};\n</code></pre>\n\n<p>Then your record class could have a struct RecordFlag member variable, functions can take arguments of type struct RecordFlag, etc. The compiler should pack the bitfields together, saving space.</p>\n"
},
{
"answer_id": 112529,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 0,
"selected": false,
"text": "<p>I would rather go with</p>\n\n<pre><code>typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;\n</code></pre>\n\n<p>Simply because: </p>\n\n<ol>\n<li>It is cleaner and it makes the code readable and maintainable. </li>\n<li>It logically groups the constants.</li>\n<li>Programmer's time is more important, unless your job <em>is</em> to save those 3 bytes. </li>\n</ol>\n"
},
{
"answer_id": 112591,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 6,
"selected": false,
"text": "<h2>Forget the defines</h2>\n\n<p>They will pollute your code.</p>\n\n<h2>bitfields?</h2>\n\n<pre><code>struct RecordFlag {\n unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;\n};\n</code></pre>\n\n<p><strong>Don't ever use that</strong>. You are more concerned with speed than with economizing 4 ints. Using bit fields is actually slower than access to any other type.</p>\n\n<blockquote>However, bit members in structs have practical drawbacks. First, the ordering of bits in memory varies from compiler to compiler. In addition, <b>many popular compilers generate inefficient code for reading and writing bit members</b>, and there are potentially severe <b>thread safety issues</b> relating to bit fields (especially on multiprocessor systems) due to the fact that most machines cannot manipulate arbitrary sets of bits in memory, but must instead load and store whole words. e.g the following would not be thread-safe, in spite of the use of a mutex</blockquote>\n\n<p>Source: <a href=\"http://en.wikipedia.org/wiki/Bit_field\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Bit_field</a>:</p>\n\n<p>And if you need more reasons to <strong>not</strong> use bitfields, perhaps <a href=\"http://en.wikipedia.org/wiki/Raymond_Chen\" rel=\"noreferrer\">Raymond Chen</a> will convince you in his <a href=\"http://blogs.msdn.com/oldnewthing\" rel=\"noreferrer\">The Old New Thing</a> Post: <strong>The cost-benefit analysis of bitfields for a collection of booleans</strong> at <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/11/26/9143050.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2008/11/26/9143050.aspx</a></p>\n\n<h2>const int?</h2>\n\n<pre><code>namespace RecordType {\n static const uint8 xNew = 1;\n static const uint8 xDeleted = 2;\n static const uint8 xModified = 4;\n static const uint8 xExisting = 8;\n}\n</code></pre>\n\n<p>Putting them in a namespace is cool. If they are declared in your CPP or header file, their values will be inlined. You'll be able to use switch on those values, but it will slightly increase coupling.</p>\n\n<p>Ah, yes: <strong>remove the static keyword</strong>. static is deprecated in C++ when used as you do, and if uint8 is a buildin type, you won't need this to declare this in an header included by multiple sources of the same module. In the end, the code should be:</p>\n\n<pre><code>namespace RecordType {\n const uint8 xNew = 1;\n const uint8 xDeleted = 2;\n const uint8 xModified = 4;\n const uint8 xExisting = 8;\n}\n</code></pre>\n\n<p>The problem of this approach is that your code knows the value of your constants, which increases slightly the coupling.</p>\n\n<h2>enum</h2>\n\n<p>The same as const int, with a somewhat stronger typing.</p>\n\n<pre><code>typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;\n</code></pre>\n\n<p>They are still polluting the global namespace, though.\nBy the way... <strong>Remove the typedef</strong>. You're working in C++. Those typedefs of enums and structs are polluting the code more than anything else.</p>\n\n<p>The result is kinda:</p>\n\n<pre><code>enum RecordType { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;\n\nvoid doSomething(RecordType p_eMyEnum)\n{\n if(p_eMyEnum == xNew)\n {\n // etc.\n }\n}\n</code></pre>\n\n<p>As you see, your enum is polluting the global namespace.\nIf you put this enum in an namespace, you'll have something like:</p>\n\n<pre><code>namespace RecordType {\n enum Value { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;\n}\n\nvoid doSomething(RecordType::Value p_eMyEnum)\n{\n if(p_eMyEnum == RecordType::xNew)\n {\n // etc.\n }\n}\n</code></pre>\n\n<h2>extern const int ?</h2>\n\n<p>If you want to decrease coupling (i.e. being able to hide the values of the constants, and so, modify them as desired without needing a full recompilation), you can declare the ints as extern in the header, and as constant in the CPP file, as in the following example:</p>\n\n<pre><code>// Header.hpp\nnamespace RecordType {\n extern const uint8 xNew ;\n extern const uint8 xDeleted ;\n extern const uint8 xModified ;\n extern const uint8 xExisting ;\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>// Source.hpp\nnamespace RecordType {\n const uint8 xNew = 1;\n const uint8 xDeleted = 2;\n const uint8 xModified = 4;\n const uint8 xExisting = 8;\n}\n</code></pre>\n\n<p>You won't be able to use switch on those constants, though. So in the end, pick your poison...\n:-p</p>\n"
},
{
"answer_id": 112838,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I probably wouldn't use an enum for this kind of a thing where the values can be combined together, more typically enums are mutually exclusive states.</p>\n\n<p>But whichever method you use, to make it more clear that these are values which are bits which can be combined together, use this syntax for the actual values instead:</p>\n\n<pre><code>#define X_NEW (1 << 0)\n#define X_DELETED (1 << 1)\n#define X_MODIFIED (1 << 2)\n#define X_EXISTING (1 << 3)\n</code></pre>\n\n<p>Using a left-shift there helps to indicate that each value is intended to be a single bit, it is less likely that later on someone would do something wrong like add a new value and assign it something a value of 9.</p>\n"
},
{
"answer_id": 112846,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 2,
"selected": false,
"text": "<p>If you want the type safety of classes, with the convenience of enumeration syntax and bit checking, consider <a href=\"http://www.artima.com/cppsource/safelabels.html\" rel=\"nofollow noreferrer\">Safe Labels in C++</a>. I've worked with the author, and he's pretty smart.</p>\n\n<p>Beware, though. In the end, this package uses templates <em>and</em> macros!</p>\n"
},
{
"answer_id": 113370,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 2,
"selected": false,
"text": "<p>Based on <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a>, <a href=\"http://en.wikipedia.org/wiki/Coupling_(computer_science)\" rel=\"nofollow noreferrer\">high cohesion and low coupling</a>, ask these questions -</p>\n\n<ul>\n<li>Who needs to know? my class, my library, other classes, other libraries, 3rd parties</li>\n<li>What level of abstraction do I need to provide? Does the consumer understand bit operations.</li>\n<li>Will I have have to interface from VB/C# etc?</li>\n</ul>\n\n<p>There is a great book \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633620\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Large-Scale C++ Software Design</a>\", this promotes base types externally, if you can avoid another header file/interface dependancy you should try to. </p>\n"
},
{
"answer_id": 113453,
"author": "Thomas Koschel",
"author_id": 2012356,
"author_profile": "https://Stackoverflow.com/users/2012356",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using Qt you should have a look for <a href=\"http://doc.trolltech.com/4.3/qflags.html#details\" rel=\"nofollow noreferrer\" title=\"QFlags\">QFlags</a>.\nThe QFlags class provides a type-safe way of storing OR-combinations of enum values.</p>\n"
},
{
"answer_id": 113469,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 3,
"selected": false,
"text": "<p>If possible do NOT use macros. They aren't too much admired when it comes to modern C++.</p>\n"
},
{
"answer_id": 113560,
"author": "mat_geek",
"author_id": 11032,
"author_profile": "https://Stackoverflow.com/users/11032",
"pm_score": 8,
"selected": true,
"text": "<p>Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage.</p>\n\n<p>Place the enum in a namespace to prevent the constants from polluting the global namespace.</p>\n\n<pre><code>namespace RecordType {\n</code></pre>\n\n<p>An enum declares and defines a compile time checked typed. Always use compile time type checking to make sure arguments and variables are given the correct type. There is no need for the typedef in C++.</p>\n\n<pre><code>enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8,\n</code></pre>\n\n<p>Create another member for an invalid state. This can be useful as error code; for example, when you want to return the state but the I/O operation fails. It is also useful for debugging; use it in initialisation lists and destructors to know if the variable's value should be used.</p>\n\n<pre><code>xInvalid = 16 };\n</code></pre>\n\n<p>Consider that you have two purposes for this type. To track the current state of a record and to create a mask to select records in certain states. Create an inline function to test if the value of the type is valid for your purpose; as a state marker vs a state mask. This will catch bugs as the <code>typedef</code> is just an <code>int</code> and a value such as <code>0xDEADBEEF</code> may be in your variable through uninitialised or mispointed variables.</p>\n\n<pre><code>inline bool IsValidState( TRecordType v) {\n switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; }\n return false;\n}\n\n inline bool IsValidMask( TRecordType v) {\n return v >= xNew && v < xInvalid ;\n}\n</code></pre>\n\n<p>Add a <code>using</code> directive if you want to use the type often.</p>\n\n<pre><code>using RecordType ::TRecordType ;\n</code></pre>\n\n<p>The value checking functions are useful in asserts to trap bad values as soon as they are used. The quicker you catch a bug when running, the less damage it can do.</p>\n\n<p>Here are some examples to put it all together.</p>\n\n<pre><code>void showRecords(TRecordType mask) {\n assert(RecordType::IsValidMask(mask));\n // do stuff;\n}\n\nvoid wombleRecord(TRecord rec, TRecordType state) {\n assert(RecordType::IsValidState(state));\n if (RecordType ::xNew) {\n // ...\n} in runtime\n\nTRecordType updateRecord(TRecord rec, TRecordType newstate) {\n assert(RecordType::IsValidState(newstate));\n //...\n if (! access_was_successful) return RecordType ::xInvalid;\n return newstate;\n}\n</code></pre>\n\n<p>The only way to ensure correct value safety is to use a dedicated class with operator overloads and that is left as an exercise for another reader.</p>\n"
},
{
"answer_id": 114620,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Not that I like to over-engineer everything but sometimes in these cases it may be worth creating a (small) class to encapsulate this information.\nIf you create a class RecordType then it might have functions like: </p>\n\n<p>void setDeleted();</p>\n\n<p>void clearDeleted();</p>\n\n<p>bool isDeleted();</p>\n\n<p>etc... (or whatever convention suits)</p>\n\n<p>It could validate combinations (in the case where not all combinations are legal, eg if 'new' and 'deleted' could not both be set at the same time). If you just used bit masks etc then the code that sets the state needs to validate, a class can encapsulate that logic too. </p>\n\n<p>The class may also give you the ability to attach meaningful logging info to each state, you could add a function to return a string representation of the current state etc (or use the streaming operators '<<'). </p>\n\n<p>For all that if you are worried about storage you could still have the class only have a 'char' data member, so only take a small amount of storage (assuming it is non virtual). Of course depending on the hardware etc you may have alignment issues. </p>\n\n<p>You could have the actual bit values not visible to the rest of the 'world' if they are in an anonymous namespace inside the cpp file rather than in the header file.</p>\n\n<p>If you find that the code using the enum/#define/ bitmask etc has a lot of 'support' code to deal with invalid combinations, logging etc then encapsulation in a class may be worth considering. Of course most times simple problems are better off with simple solutions...</p>\n"
},
{
"answer_id": 11847029,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>With defines I lose type safety</p>\n</blockquote>\n\n<p>Not necessarily...</p>\n\n<pre><code>// signed defines\n#define X_NEW 0x01u\n#define X_NEW (unsigned(0x01)) // if you find this more readable...\n</code></pre>\n\n<blockquote>\n <p>and with enum I lose some space (integers)</p>\n</blockquote>\n\n<p>Not necessarily - but you do have to be explicit at points of storage...</p>\n\n<pre><code>struct X\n{\n RecordType recordType : 4; // use exactly 4 bits...\n RecordType recordType2 : 4; // use another 4 bits, typically in the same byte\n // of course, the overall record size may still be padded...\n};\n</code></pre>\n\n<blockquote>\n <p>and probably have to cast when I want to do bitwise operation.</p>\n</blockquote>\n\n<p>You can create operators to take the pain out of that:</p>\n\n<pre><code>RecordType operator|(RecordType lhs, RecordType rhs)\n{\n return RecordType((unsigned)lhs | (unsigned)rhs);\n}\n</code></pre>\n\n<blockquote>\n <p>With const I think I also lose type safety since a random uint8 could get in by mistake.</p>\n</blockquote>\n\n<p>The same can happen with any of these mechanisms: range and value checks are normally orthogonal to type safety (though user-defined-types - i.e. your own classes - can enforce \"invariants\" about their data). With enums, the compiler's free to pick a larger type to host the values, and an uninitialised, corrupted or just miss-set enum variable could still end up interpretting its bit pattern as a number you wouldn't expect - comparing unequal to any of the enumeration identifiers, any combination of them, and 0.</p>\n\n<blockquote>\n <p>Is there some other cleaner way? / If not, what would you use and why?</p>\n</blockquote>\n\n<p>Well, in the end the tried-and-trusted C-style bitwise OR of enumerations works pretty well once you have bit fields and custom operators in the picture. You can further improve your robustness with some custom validation functions and assertions as in mat_geek's answer; techniques often equally applicable to handling string, int, double values etc..</p>\n\n<p>You could argue that this is \"cleaner\":</p>\n\n<pre><code>enum RecordType { New, Deleted, Modified, Existing };\n\nshowRecords([](RecordType r) { return r == New || r == Deleted; });\n</code></pre>\n\n<p>I'm indifferent: the data bits pack tighter but the code grows significantly... depends how many objects you've got, and the lamdbas - beautiful as they are - are still messier and harder to get right than bitwise ORs.</p>\n\n<p>BTW /- the argument about thread safety's pretty weak IMHO - best remembered as a background consideration rather than becoming a dominant decision-driving force; sharing a mutex across the bitfields is a more likely practice even if unaware of their packing (mutexes are relatively bulky data members - I have to be really concerned about performance to consider having multiple mutexes on members of one object, and I'd look carefully enough to notice they were bit fields). Any sub-word-size type could have the same problem (e.g. a <code>uint8_t</code>). Anyway, you could try atomic compare-and-swap style operations if you're desperate for higher concurrency.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
]
| In a C++ project I'm working on, I have a *flag* kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:
* new record
* deleted record
* modified record
* existing record
Now, for each record I wish to keep this attribute, so I could use an enum:
```
enum { xNew, xDeleted, xModified, xExisting }
```
However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like:
```
showRecords(xNew | xDeleted);
```
So, it seems I have three possible appoaches:
```
#define X_NEW 0x01
#define X_DELETED 0x02
#define X_MODIFIED 0x04
#define X_EXISTING 0x08
```
or
```
typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
```
or
```
namespace RecordType {
static const uint8 xNew = 1;
static const uint8 xDeleted = 2;
static const uint8 xModified = 4;
static const uint8 xExisting = 8;
}
```
Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with `enum` I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With `const` I think I also lose type safety since a random `uint8` could get in by mistake.
Is there some other cleaner way?
If not, what would you use and why?
P.S. The rest of the code is rather clean modern C++ without `#define`s, and I have used namespaces and templates in few spaces, so those aren't out of question either. | Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage.
Place the enum in a namespace to prevent the constants from polluting the global namespace.
```
namespace RecordType {
```
An enum declares and defines a compile time checked typed. Always use compile time type checking to make sure arguments and variables are given the correct type. There is no need for the typedef in C++.
```
enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8,
```
Create another member for an invalid state. This can be useful as error code; for example, when you want to return the state but the I/O operation fails. It is also useful for debugging; use it in initialisation lists and destructors to know if the variable's value should be used.
```
xInvalid = 16 };
```
Consider that you have two purposes for this type. To track the current state of a record and to create a mask to select records in certain states. Create an inline function to test if the value of the type is valid for your purpose; as a state marker vs a state mask. This will catch bugs as the `typedef` is just an `int` and a value such as `0xDEADBEEF` may be in your variable through uninitialised or mispointed variables.
```
inline bool IsValidState( TRecordType v) {
switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; }
return false;
}
inline bool IsValidMask( TRecordType v) {
return v >= xNew && v < xInvalid ;
}
```
Add a `using` directive if you want to use the type often.
```
using RecordType ::TRecordType ;
```
The value checking functions are useful in asserts to trap bad values as soon as they are used. The quicker you catch a bug when running, the less damage it can do.
Here are some examples to put it all together.
```
void showRecords(TRecordType mask) {
assert(RecordType::IsValidMask(mask));
// do stuff;
}
void wombleRecord(TRecord rec, TRecordType state) {
assert(RecordType::IsValidState(state));
if (RecordType ::xNew) {
// ...
} in runtime
TRecordType updateRecord(TRecord rec, TRecordType newstate) {
assert(RecordType::IsValidState(newstate));
//...
if (! access_was_successful) return RecordType ::xInvalid;
return newstate;
}
```
The only way to ensure correct value safety is to use a dedicated class with operator overloads and that is left as an exercise for another reader. |
112,439 | <p>If you had read my other <a href="https://stackoverflow.com/questions/111700/6502-cpu-emulation">question</a>, you'll know I've spent this weekend putting together a 6502 CPU emulator as a programming exercise.</p>
<p>The CPU emulator is mostly complete, and seems to be fairly accurate from my limited testing, however it is running incredibly fast, and I want to throttle it down to the actual clock speed of the machine.</p>
<p>My current test loop is this:</p>
<pre><code> // Just loop infinitely.
while (1 == 1)
{
CPU.ClockCyclesBeforeNext--;
if (CPU.ClockCyclesBeforeNext <= 0)
{
// Find out how many clock cycles this instruction will take
CPU.ClockCyclesBeforeNext = CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].CpuCycles;
// Run the instruction
CPU.ExecuteInstruction(CPU.Memory[CPU.PC]);
// Debugging Info
CPU.DumpDebug();
Console.WriteLine(CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength);
// Move to next instruction
CPU.PC += 1 + CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength;
}
}
</code></pre>
<p>As you can tell, each opcode takes a specific amount of time to complete, so I do not run the next instruction until I count down the CPU Cycle clock. This provides proper timing between opcodes, its just that the entire thing runs way to fast.</p>
<p>The targeted CPU speed is 1.79mhz, however I'd like whatever solution to the clock issue to keep the speed at 1.79mhz even as I add complexity, so I don't have to adjust it up.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 112467,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>I would use the clock cycles to calculate time and them sleep the difference in time. Of course, to do this, you need a high-resolution clock. They way you are doing it is going to spike the CPU in spinning loops.</p>\n"
},
{
"answer_id": 112469,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at the original quicktime documentation for inspiration.</p>\n\n<p>It was written a long time ago, when displaying video meant just swapping still frames at high enough speed, but the Apple guys decided they needed a full time-management framework. The design at first looks overengineered, but it let them deal with widely different speed requirements and keep them tightly synchronized.</p>\n\n<p>you're fortunate that 6502 has deterministic time behaviour, the exact time each instruction takes is well documented; but it's not constant. some instructions take 2 cycles, other 3. Just like frames in QuickTime, a video doesn't have a 'frames per second' parameter, each frame tells how long it wants to be in screen.</p>\n\n<p>Since modern CPU's are so non-deterministic, and multitasking OS's can even freeze for a few miliseconds (virtual memory!), you should keep a tab if you're behind schedule, or if you can take a few microseconds nap.</p>\n"
},
{
"answer_id": 827720,
"author": "Jason Fritcher",
"author_id": 56038,
"author_profile": "https://Stackoverflow.com/users/56038",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote a Z80 emulator many years ago, and to do cycle accurate execution, I divided the clock rate into a number of small blocks and had the core execute that many clock cycles. In my case, I tied it to the frame rate of the game system I was emulating. Each opcode knew how many cycles it took to execute and the core would keep running opcodes until the specified number of cycles had been executed. I had an outer run loop that would run the cpu core, and run other parts of the emulated system and then sleep until the start time of the next iteration.</p>\n\n<p>EDIT: Adding example of run loop.</p>\n\n<pre><code>int execute_run_loop( int cycles )\n{\n int n = 0;\n while( n < cycles )\n {\n /* Returns number of cycles executed */\n n += execute_next_opcode();\n }\n\n return n;\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 1393529,
"author": "David Gardner",
"author_id": 86080,
"author_profile": "https://Stackoverflow.com/users/86080",
"pm_score": 3,
"selected": false,
"text": "<p>As jfk says, the most common way to do this is <strong>tie the cpu speed to the vertical refresh of the (emulated) video output</strong>.</p>\n\n<p>Pick a number of cycles to run per video frame. This will often be machine-specific but you can calculate it by something like :</p>\n\n<pre><code>cycles = clock speed in Hz / required frames-per-second\n</code></pre>\n\n<p>Then you also get to do a sleep until the video update is hit, at which point you start the next n cycles of CPU emulation.</p>\n\n<p>If you're emulating something in particular then you just need to look up the fps rate and processor speed to get this approximately right.</p>\n\n<p>EDIT: If you don't have any external timing requirements then it is normal for an emulator to just run as fast as it possibly can. Sometimes this is a desired effect and sometimes not :)</p>\n"
},
{
"answer_id": 13263744,
"author": "Nick Westgate",
"author_id": 313445,
"author_profile": "https://Stackoverflow.com/users/313445",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is available if audio emulation is implemented, and if audio output is tied to the system/CPU clock. In particular I know that this is the case with the 8-bit Apple ][ computers.</p>\n\n<p>Usually sound is generated in buffers of a fixed size (which is a fixed time), so operation (generation of data etc) of these buffers can be tied to CPU throughput via synchronization primitives.</p>\n"
},
{
"answer_id": 21909710,
"author": "Gianluca Ghettini",
"author_id": 958464,
"author_profile": "https://Stackoverflow.com/users/958464",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, as said before most of the time you don't need a CPU emulator to emulate instructions at the same speed of the real thing. What user perceive is the <em>output</em> of the computation (i.e. audio and video outputs) so you only need to be in sync with such outputs which doesn't mean you must have necessarily an exact CPU emulation speed.</p>\n\n<p>In other words, if the frame rate of the video input is, let's say, 50Hz, then let the CPU emulator run as fast as it can to draw the screen but be sure to output the screen frames at the correct rate (50Hz). From an external point of view your emulator is emulating at the correct speed.</p>\n\n<p>Trying to be cycle exact even in the execution time is a non-sense on a multi-tasking OS like Windows or Linux because the emulator instruction time (tipically 1uS for vintage 80s CPUs) and the scheduling time slot of the modern OS are comparable.</p>\n\n<p>Trying to output something at a 50Hz rate is a much simpler task you can do very good on any modern machine </p>\n"
},
{
"answer_id": 31866088,
"author": "Jay",
"author_id": 390720,
"author_profile": "https://Stackoverflow.com/users/390720",
"pm_score": 0,
"selected": false,
"text": "<p>I am in the process of making something a little more general use case based, such as the ability to convert time to an estimated amount of instructions and vice versa.</p>\n\n<p>The project homepage is @ <a href=\"http://net7mma.codeplex.com\" rel=\"nofollow\">http://net7mma.codeplex.com</a></p>\n\n<p>The code starts like this: (I think)</p>\n\n<pre><code> #region Copyright\n/*\nThis file came from Managed Media Aggregation, You can always find the latest version @ https://net7mma.codeplex.com/\n\n [email protected] / (SR. Software Engineer ASTI Transportation Inc. http://www.asti-trans.com)\n\nPermission is hereby granted, free of charge, \n * to any person obtaining a copy of this software and associated documentation files (the \"Software\"), \n * to deal in the Software without restriction, \n * including without limitation the rights to :\n * use, \n * copy, \n * modify, \n * merge, \n * publish, \n * distribute, \n * sublicense, \n * and/or sell copies of the Software, \n * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * \n * [email protected] should be contacted for further details.\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n * \n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, \n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, \n * ARISING FROM, \n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n * \n * v//\n */\n#endregion\nnamespace Media.Concepts.Classes\n{\n //Windows.Media.Clock has a fairly complex but complete API\n\n /// <summary>\n /// Provides a clock with a given offset and calendar.\n /// </summary>\n public class Clock : Media.Common.BaseDisposable\n {\n static bool GC = false;\n\n #region Fields\n\n /// <summary>\n /// Indicates when the clock was created\n /// </summary>\n public readonly System.DateTimeOffset Created;\n\n /// <summary>\n /// The calendar system of the clock\n /// </summary>\n public readonly System.Globalization.Calendar Calendar;\n\n /// <summary>\n /// The amount of ticks which occur per update of the <see cref=\"System.Environment.TickCount\"/> member.\n /// </summary>\n public readonly long TicksPerUpdate;\n\n /// <summary>\n /// The amount of instructions which occured when synchronizing with the system clock.\n /// </summary>\n public readonly long InstructionsPerClockUpdate;\n\n #endregion\n\n #region Properties\n\n /// <summary>\n /// The TimeZone offset of the clock from UTC\n /// </summary>\n public System.TimeSpan Offset { get { return Created.Offset; } }\n\n /// <summary>\n /// The average amount of operations per tick.\n /// </summary>\n public long AverageOperationsPerTick { get { return InstructionsPerClockUpdate / TicksPerUpdate; } }\n\n /// <summary>\n /// The <see cref=\"System.TimeSpan\"/> which represents <see cref=\"TicksPerUpdate\"/> as an amount of time.\n /// </summary>\n public System.TimeSpan SystemClockResolution { get { return System.TimeSpan.FromTicks(TicksPerUpdate); } }\n\n /// <summary>\n /// Return the current system time in the TimeZone offset of this clock\n /// </summary>\n public System.DateTimeOffset Now { get { return System.DateTimeOffset.Now.ToOffset(Offset).Add(new System.TimeSpan((long)(AverageOperationsPerTick / System.TimeSpan.TicksPerMillisecond))); } }\n\n /// <summary>\n /// Return the current system time in the TimeZone offset of this clock converter to UniversalTime.\n /// </summary>\n public System.DateTimeOffset UtcNow { get { return Now.ToUniversalTime(); } }\n\n //public bool IsUtc { get { return Offset == System.TimeSpan.Zero; } }\n\n //public bool IsDaylightSavingTime { get { return Created.LocalDateTime.IsDaylightSavingTime(); } }\n\n #endregion\n\n #region Constructor\n\n /// <summary>\n /// Creates a clock using the system's current timezone and calendar.\n /// The system clock is profiled to determine it's accuracy\n /// <see cref=\"System.DateTimeOffset.Now.Offset\"/>\n /// <see cref=\"System.Globalization.CultureInfo.CurrentCulture.Calendar\"/>\n /// </summary>\n public Clock(bool shouldDispose = true)\n : this(System.DateTimeOffset.Now.Offset, System.Globalization.CultureInfo.CurrentCulture.Calendar, shouldDispose)\n {\n try { if (false == GC && System.Runtime.GCSettings.LatencyMode != System.Runtime.GCLatencyMode.NoGCRegion) GC = System.GC.TryStartNoGCRegion(0); }\n catch { }\n finally\n {\n\n System.Threading.Thread.BeginCriticalRegion();\n\n //Sample the TickCount\n long ticksStart = System.Environment.TickCount,\n ticksEnd;\n\n //Continually sample the TickCount. while the value has not changed increment InstructionsPerClockUpdate\n while ((ticksEnd = System.Environment.TickCount) == ticksStart) ++InstructionsPerClockUpdate; //+= 4; Read,Assign,Compare,Increment\n\n //How many ticks occur per update of TickCount\n TicksPerUpdate = ticksEnd - ticksStart;\n\n System.Threading.Thread.EndCriticalRegion();\n }\n }\n\n /// <summary>\n /// Constructs a new clock using the given TimeZone offset and Calendar system\n /// </summary>\n /// <param name=\"timeZoneOffset\"></param>\n /// <param name=\"calendar\"></param>\n /// <param name=\"shouldDispose\">Indicates if the instace should be diposed when Dispose is called.</param>\n public Clock(System.TimeSpan timeZoneOffset, System.Globalization.Calendar calendar, bool shouldDispose = true)\n {\n //Allow disposal\n ShouldDispose = shouldDispose;\n\n Calendar = System.Globalization.CultureInfo.CurrentCulture.Calendar;\n\n Created = new System.DateTimeOffset(System.DateTime.Now, timeZoneOffset);\n }\n\n #endregion\n\n #region Overrides\n\n public override void Dispose()\n {\n\n if (false == ShouldDispose) return;\n\n base.Dispose();\n\n try\n {\n if (System.Runtime.GCSettings.LatencyMode == System.Runtime.GCLatencyMode.NoGCRegion)\n {\n System.GC.EndNoGCRegion();\n\n GC = false;\n }\n }\n catch { }\n }\n\n #endregion\n\n //Methods or statics for OperationCountToTimeSpan? (Estimate)\n public void NanoSleep(int nanos)\n {\n Clock.NanoSleep((long)nanos);\n }\n\n public static void NanoSleep(long nanos)\n {\n System.Threading.Thread.BeginCriticalRegion(); \n\n NanoSleep(ref nanos); \n\n System.Threading.Thread.EndCriticalRegion();\n }\n\n static void NanoSleep(ref long nanos)\n {\n try\n {\n unchecked\n {\n while (Common.Binary.Clamp(--nanos, 0, 1) >= 2)\n { \n /* if(--nanos % 2 == 0) */\n NanoSleep(long.MinValue); //nanos -= 1 + (ops / (ulong)AverageOperationsPerTick);// *10;\n }\n }\n }\n catch\n {\n return;\n }\n }\n }\n}\n</code></pre>\n\n<p>Once you have some type of layman clock implementation you advance to something like a <code>Timer</code></p>\n\n<pre><code>/// <summary>\n/// Provides a Timer implementation which can be used across all platforms and does not rely on the existing Timer implementation.\n/// </summary>\npublic class Timer : Common.BaseDisposable\n{\n readonly System.Threading.Thread m_Counter; // m_Consumer, m_Producer\n\n internal System.TimeSpan m_Frequency;\n\n internal ulong m_Ops = 0, m_Ticks = 0;\n\n bool m_Enabled;\n\n internal System.DateTimeOffset m_Started;\n\n public delegate void TickEvent(ref long ticks);\n\n public event TickEvent Tick;\n\n public bool Enabled { get { return m_Enabled; } set { m_Enabled = value; } }\n\n public System.TimeSpan Frequency { get { return m_Frequency; } }\n\n internal ulong m_Bias;\n\n //\n\n //Could just use a single int, 32 bits is more than enough.\n\n //uint m_Flags;\n\n //\n\n readonly internal Clock m_Clock = new Clock();\n\n readonly internal System.Collections.Generic.Queue<long> Producer;\n\n void Count()\n {\n\n System.Threading.Thread Event = new System.Threading.Thread(new System.Threading.ThreadStart(() =>\n {\n System.Threading.Thread.BeginCriticalRegion();\n long sample;\n AfterSample:\n try\n {\n Top:\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;\n\n while (m_Enabled && Producer.Count >= 1)\n {\n sample = Producer.Dequeue();\n\n Tick(ref sample);\n }\n\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;\n\n if (false == m_Enabled) return;\n\n while (m_Enabled && Producer.Count == 0) if(m_Counter.IsAlive) m_Counter.Join(0); //++m_Ops;\n\n goto Top;\n }\n catch { if (false == m_Enabled) return; goto AfterSample; }\n finally { System.Threading.Thread.EndCriticalRegion(); }\n }))\n {\n IsBackground = false,\n Priority = System.Threading.ThreadPriority.AboveNormal\n };\n\n Event.TrySetApartmentState(System.Threading.ApartmentState.MTA);\n\n Event.Start();\n\n Approximate:\n\n ulong approximate = (ulong)Common.Binary.Clamp((m_Clock.AverageOperationsPerTick / (Frequency.Ticks + 1)), 1, ulong.MaxValue);\n\n try\n {\n m_Started = m_Clock.Now;\n\n System.Threading.Thread.BeginCriticalRegion();\n\n unchecked\n {\n Start:\n\n if (IsDisposed) return;\n\n switch (++m_Ops)\n {\n default:\n {\n if (m_Bias + ++m_Ops >= approximate)\n {\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;\n\n Producer.Enqueue((long)m_Ticks++);\n\n ulong x = ++m_Ops / approximate;\n\n while (1 > --x /*&& Producer.Count <= m_Frequency.Ticks*/) Producer.Enqueue((long)++m_Ticks);\n\n m_Ops = (++m_Ops * m_Ticks) - (m_Bias = ++m_Ops / approximate);\n\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;\n }\n\n if(Event != null) Event.Join(m_Frequency);\n\n goto Start;\n }\n }\n }\n }\n catch (System.Threading.ThreadAbortException) { if (m_Enabled) goto Approximate; System.Threading.Thread.ResetAbort(); }\n catch (System.OutOfMemoryException) { if ((ulong)Producer.Count > approximate) Producer.Clear(); if (m_Enabled) goto Approximate; }\n catch { if (m_Enabled) goto Approximate; }\n finally\n {\n Event = null;\n\n System.Threading.Thread.EndCriticalRegion();\n }\n }\n\n public Timer(System.TimeSpan frequency)\n {\n Producer = new System.Collections.Generic.Queue<long>((int)(m_Frequency = frequency).Ticks * 10);\n\n m_Counter = new System.Threading.Thread(new System.Threading.ThreadStart(Count))\n {\n IsBackground = false,\n Priority = System.Threading.ThreadPriority.AboveNormal\n };\n\n m_Counter.TrySetApartmentState(System.Threading.ApartmentState.MTA);\n\n Tick = delegate { m_Ops += 1 + m_Bias; };\n }\n\n public void Start()\n {\n if (m_Enabled) return;\n\n m_Enabled = true;\n\n m_Counter.Start();\n\n var p = System.Threading.Thread.CurrentThread.Priority;\n\n System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;\n\n while (m_Ops == 0) m_Counter.Join(0); //m_Clock.NanoSleep(0);\n\n System.Threading.Thread.CurrentThread.Priority = p;\n\n }\n\n public void Stop()\n {\n m_Enabled = false;\n }\n\n void Change(System.TimeSpan interval, System.TimeSpan dueTime)\n {\n m_Enabled = false;\n\n m_Frequency = interval;\n\n m_Enabled = true;\n }\n\n delegate void ElapsedEvent(object sender, object args);\n\n public override void Dispose()\n {\n if (IsDisposed) return; \n\n base.Dispose();\n\n Stop();\n\n try { m_Counter.Abort(m_Frequency); }\n catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); }\n catch { }\n\n Tick = null;\n\n //Producer.Clear();\n }\n\n}\n</code></pre>\n\n<p>Then you can really replicate some logic using something like</p>\n\n<pre><code> /// <summary>\n/// Provides a completely managed implementation of <see cref=\"System.Diagnostics.Stopwatch\"/> which expresses time in the same units as <see cref=\"System.TimeSpan\"/>.\n/// </summary>\npublic class Stopwatch : Common.BaseDisposable\n{\n internal Timer Timer;\n\n long Units;\n\n public bool Enabled { get { return Timer != null && Timer.Enabled; } }\n\n public double ElapsedMicroseconds { get { return Units * Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(Timer.Frequency); } }\n\n public double ElapsedMilliseconds { get { return Units * Timer.Frequency.TotalMilliseconds; } }\n\n public double ElapsedSeconds { get { return Units * Timer.Frequency.TotalSeconds; } }\n\n //public System.TimeSpan Elapsed { get { return System.TimeSpan.FromMilliseconds(ElapsedMilliseconds / System.TimeSpan.TicksPerMillisecond); } }\n\n public System.TimeSpan Elapsed\n {\n get\n {\n switch (Units)\n {\n case 0: return System.TimeSpan.Zero;\n default:\n {\n System.TimeSpan taken = System.DateTime.UtcNow - Timer.m_Started;\n\n return taken.Add(new System.TimeSpan(Units * Timer.Frequency.Ticks));\n\n //System.TimeSpan additional = new System.TimeSpan(Media.Common.Extensions.Math.MathExtensions.Clamp(Units, 0, Timer.Frequency.Ticks));\n\n //return taken.Add(additional);\n }\n }\n\n\n\n //////The maximum amount of times the timer can elapse in the given frequency\n ////double maxCount = (taken.TotalMilliseconds / Timer.Frequency.TotalMilliseconds) / ElapsedMilliseconds;\n\n ////if (Units > maxCount)\n ////{\n //// //How many more times the event was fired than needed\n //// double overage = (maxCount - Units);\n\n //// additional = new System.TimeSpan(System.Convert.ToInt64(Media.Common.Extensions.Math.MathExtensions.Clamp(Units, overage, maxCount)));\n\n //// //return taken.Add(new System.TimeSpan((long)Media.Common.Extensions.Math.MathExtensions.Clamp(Units, overage, maxCount)));\n ////}\n //////return taken.Add(new System.TimeSpan(Units));\n\n\n }\n }\n\n public void Start()\n {\n if (Enabled) return;\n\n Units = 0;\n\n //Create a Timer that will elapse every OneTick //`OneMicrosecond`\n Timer = new Timer(Media.Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick);\n\n //Handle the event by incrementing count\n Timer.Tick += Count;\n\n Timer.Start();\n }\n\n public void Stop()\n {\n if (false == Enabled) return;\n\n Timer.Stop();\n\n Timer.Dispose(); \n }\n\n void Count(ref long count) { ++Units; }\n}\n</code></pre>\n\n<p>Finally, create something semi useful e.g. a Bus and then perhaps a virtual screen to emit data to the bus...</p>\n\n<pre><code>public abstract class Bus : Common.CommonDisposable\n {\n public readonly Timer Clock = new Timer(Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick);\n\n public Bus() : base(false) { Clock.Start(); }\n }\n\n public class ClockedBus : Bus\n {\n long FrequencyHz, Maximum, End;\n\n readonly Queue<byte[]> Input = new Queue<byte[]>(), Output = new Queue<byte[]>();\n\n readonly double m_Bias;\n\n public ClockedBus(long frequencyHz, double bias = 1.5)\n {\n m_Bias = bias;\n\n cache = Clock.m_Clock.InstructionsPerClockUpdate / 1000;\n\n SetFrequency(frequencyHz);\n\n Clock.Tick += Clock_Tick;\n\n Clock.Start();\n }\n\n public void SetFrequency(long frequencyHz)\n {\n FrequencyHz = frequencyHz;\n\n //Clock.m_Frequency = new TimeSpan(Clock.m_Clock.InstructionsPerClockUpdate / 1000); \n\n //Maximum = System.TimeSpan.TicksPerSecond / Clock.m_Clock.InstructionsPerClockUpdate;\n\n //Maximum = Clock.m_Clock.InstructionsPerClockUpdate / System.TimeSpan.TicksPerSecond;\n\n Maximum = cache / (cache / FrequencyHz);\n\n Maximum *= System.TimeSpan.TicksPerSecond;\n\n Maximum = (cache / FrequencyHz);\n\n End = Maximum * 2;\n\n Clock.m_Frequency = new TimeSpan(Maximum);\n\n if (cache < frequencyHz * m_Bias) throw new Exception(\"Cannot obtain stable clock\");\n\n Clock.Producer.Clear();\n }\n\n public override void Dispose()\n {\n ShouldDispose = true;\n\n Clock.Tick -= Clock_Tick;\n\n Clock.Stop();\n\n Clock.Dispose();\n\n base.Dispose();\n }\n\n ~ClockedBus() { Dispose(); }\n\n long sample = 0, steps = 0, count = 0, avg = 0, cache = 1;\n\n void Clock_Tick(ref long ticks)\n {\n if (ShouldDispose == false && false == IsDisposed)\n {\n //Console.WriteLine(\"@ops=>\" + Clock.m_Ops + \" @ticks=>\" + Clock.m_Ticks + \" @Lticks=>\" + ticks + \"@=>\" + Clock.m_Clock.Now.TimeOfDay + \"@=>\" + (Clock.m_Clock.Now - Clock.m_Clock.Created));\n\n steps = sample;\n\n sample = ticks;\n\n ++count;\n\n System.ConsoleColor f = System.Console.ForegroundColor;\n\n if (count <= Maximum)\n {\n System.Console.BackgroundColor = ConsoleColor.Yellow;\n\n System.Console.ForegroundColor = ConsoleColor.Green;\n\n Console.WriteLine(\"count=> \" + count + \"@=>\" + Clock.m_Clock.Now.TimeOfDay + \"@=>\" + (Clock.m_Clock.Now - Clock.m_Clock.Created) + \" - \" + DateTime.UtcNow.ToString(\"MM/dd/yyyy hh:mm:ss.ffffff tt\"));\n\n avg = Maximum / count;\n\n if (Clock.m_Clock.InstructionsPerClockUpdate / count > Maximum)\n {\n System.Console.ForegroundColor = ConsoleColor.Red;\n\n Console.WriteLine(\"---- Over InstructionsPerClockUpdate ----\" + FrequencyHz);\n }\n }\n else if (count >= End)\n {\n System.Console.BackgroundColor = ConsoleColor.Black;\n\n System.Console.ForegroundColor = ConsoleColor.Blue;\n\n avg = Maximum / count;\n\n Console.WriteLine(\"avg=> \" + avg + \"@=>\" + FrequencyHz);\n\n count = 0;\n }\n }\n }\n\n //Read, Write at Frequency\n\n }\npublic class VirtualScreen\n {\n TimeSpan RefreshRate; \n bool VerticalSync; \n int Width, Height; \n Common.MemorySegment DisplayMemory, BackBuffer, DisplayBuffer;\n }\n</code></pre>\n\n<p>Here is how I tested the <code>StopWatch</code></p>\n\n<pre><code>internal class StopWatchTests\n {\n public void TestForOneMicrosecond()\n {\n System.Collections.Generic.List<System.Tuple<bool, System.TimeSpan, System.TimeSpan>> l = new System.Collections.Generic.List<System.Tuple<bool, System.TimeSpan, System.TimeSpan>>();\n\n //Create a Timer that will elapse every `OneMicrosecond`\n for (int i = 0; i <= 250; ++i) using (Media.Concepts.Classes.Stopwatch sw = new Media.Concepts.Classes.Stopwatch())\n {\n var started = System.DateTime.UtcNow;\n\n System.Console.WriteLine(\"Started: \" + started.ToString(\"MM/dd/yyyy hh:mm:ss.ffffff tt\"));\n\n //Define some amount of time\n System.TimeSpan sleepTime = Media.Common.Extensions.TimeSpan.TimeSpanExtensions.OneMicrosecond;\n\n System.Diagnostics.Stopwatch testSw = new System.Diagnostics.Stopwatch();\n\n //Start\n testSw.Start();\n\n //Start\n sw.Start();\n\n while (testSw.Elapsed.Ticks < sleepTime.Ticks - (Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick + Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick).Ticks)\n sw.Timer.m_Clock.NanoSleep(0); //System.Threading.Thread.SpinWait(0);\n\n //Sleep the desired amount\n //System.Threading.Thread.Sleep(sleepTime);\n\n //Stop\n testSw.Stop();\n\n //Stop\n sw.Stop();\n\n var finished = System.DateTime.UtcNow;\n\n var taken = finished - started;\n\n var cc = System.Console.ForegroundColor;\n\n System.Console.WriteLine(\"Finished: \" + finished.ToString(\"MM/dd/yyyy hh:mm:ss.ffffff tt\"));\n\n System.Console.WriteLine(\"Sleep Time: \" + sleepTime.ToString());\n\n System.Console.WriteLine(\"Real Taken Total: \" + taken.ToString());\n\n if (taken > sleepTime) \n {\n System.Console.ForegroundColor = System.ConsoleColor.Red;\n System.Console.WriteLine(\"Missed by: \" + (taken - sleepTime));\n }\n else\n {\n System.Console.ForegroundColor = System.ConsoleColor.Green;\n System.Console.WriteLine(\"Still have: \" + (sleepTime - taken));\n }\n\n System.Console.ForegroundColor = cc;\n\n System.Console.WriteLine(\"Real Taken msec Total: \" + taken.TotalMilliseconds.ToString());\n\n System.Console.WriteLine(\"Real Taken sec Total: \" + taken.TotalSeconds.ToString());\n\n System.Console.WriteLine(\"Real Taken μs Total: \" + Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(taken).ToString());\n\n System.Console.WriteLine(\"Managed Taken Total: \" + sw.Elapsed.ToString());\n\n System.Console.WriteLine(\"Diagnostic Taken Total: \" + testSw.Elapsed.ToString());\n\n System.Console.WriteLine(\"Diagnostic Elapsed Seconds Total: \" + ((testSw.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency)));\n\n //Write the rough amount of time taken in micro seconds\n System.Console.WriteLine(\"Managed Time Estimated Taken: \" + sw.ElapsedMicroseconds + \"μs\");\n\n //Write the rough amount of time taken in micro seconds\n System.Console.WriteLine(\"Diagnostic Time Estimated Taken: \" + Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(testSw.Elapsed) + \"μs\");\n\n System.Console.WriteLine(\"Managed Time Estimated Taken: \" + sw.ElapsedMilliseconds);\n\n System.Console.WriteLine(\"Diagnostic Time Estimated Taken: \" + testSw.ElapsedMilliseconds);\n\n System.Console.WriteLine(\"Managed Time Estimated Taken: \" + sw.ElapsedSeconds);\n\n System.Console.WriteLine(\"Diagnostic Time Estimated Taken: \" + testSw.Elapsed.TotalSeconds);\n\n if (sw.Elapsed < testSw.Elapsed)\n {\n System.Console.WriteLine(\"Faster than Diagnostic StopWatch\");\n l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(true, sw.Elapsed, testSw.Elapsed));\n }\n else if (sw.Elapsed > testSw.Elapsed)\n {\n System.Console.WriteLine(\"Slower than Diagnostic StopWatch\");\n l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(false, sw.Elapsed, testSw.Elapsed));\n }\n else\n {\n System.Console.WriteLine(\"Equal to Diagnostic StopWatch\");\n l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(true, sw.Elapsed, testSw.Elapsed));\n }\n }\n\n int w = 0, f = 0;\n\n var cc2 = System.Console.ForegroundColor;\n\n foreach (var t in l)\n {\n if (t.Item1)\n {\n System.Console.ForegroundColor = System.ConsoleColor.Green;\n ++w; System.Console.WriteLine(\"Faster than Diagnostic StopWatch by: \" + (t.Item3 - t.Item2));\n }\n else\n {\n System.Console.ForegroundColor = System.ConsoleColor.Red;\n ++f; System.Console.WriteLine(\"Slower than Diagnostic StopWatch by: \" + (t.Item2 - t.Item3));\n }\n }\n\n System.Console.ForegroundColor = System.ConsoleColor.Green;\n System.Console.WriteLine(\"Wins = \" + w);\n\n System.Console.ForegroundColor = System.ConsoleColor.Red;\n System.Console.WriteLine(\"Loss = \" + f);\n\n System.Console.ForegroundColor = cc2;\n }\n }\n</code></pre>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
| If you had read my other [question](https://stackoverflow.com/questions/111700/6502-cpu-emulation), you'll know I've spent this weekend putting together a 6502 CPU emulator as a programming exercise.
The CPU emulator is mostly complete, and seems to be fairly accurate from my limited testing, however it is running incredibly fast, and I want to throttle it down to the actual clock speed of the machine.
My current test loop is this:
```
// Just loop infinitely.
while (1 == 1)
{
CPU.ClockCyclesBeforeNext--;
if (CPU.ClockCyclesBeforeNext <= 0)
{
// Find out how many clock cycles this instruction will take
CPU.ClockCyclesBeforeNext = CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].CpuCycles;
// Run the instruction
CPU.ExecuteInstruction(CPU.Memory[CPU.PC]);
// Debugging Info
CPU.DumpDebug();
Console.WriteLine(CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength);
// Move to next instruction
CPU.PC += 1 + CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength;
}
}
```
As you can tell, each opcode takes a specific amount of time to complete, so I do not run the next instruction until I count down the CPU Cycle clock. This provides proper timing between opcodes, its just that the entire thing runs way to fast.
The targeted CPU speed is 1.79mhz, however I'd like whatever solution to the clock issue to keep the speed at 1.79mhz even as I add complexity, so I don't have to adjust it up.
Any ideas? | I wrote a Z80 emulator many years ago, and to do cycle accurate execution, I divided the clock rate into a number of small blocks and had the core execute that many clock cycles. In my case, I tied it to the frame rate of the game system I was emulating. Each opcode knew how many cycles it took to execute and the core would keep running opcodes until the specified number of cycles had been executed. I had an outer run loop that would run the cpu core, and run other parts of the emulated system and then sleep until the start time of the next iteration.
EDIT: Adding example of run loop.
```
int execute_run_loop( int cycles )
{
int n = 0;
while( n < cycles )
{
/* Returns number of cycles executed */
n += execute_next_opcode();
}
return n;
}
```
Hope this helps. |
112,440 | <p>I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!</p>
<pre><code> <SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
</code></pre>
<p>The error I am getting is when clicking on a drop down context menu on a page, for this line:</p>
<pre><code>newImage("\/_layouts\/images\/icon1.gif");
</code></pre>
<blockquote>
<p>The object doesn't accept this property or method
Code: 0</p>
</blockquote>
<p>I really don't see what could happen... Any tips on what may be happening here?</p>
| [
{
"answer_id": 112449,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 1,
"selected": false,
"text": "<p>Write proper xml with the \" around attributes.</p>\n\n<pre><code><script type=\"text/javascript\">\nfunction newImage(arg) {\n var rslt = new Image();\n rslt.src = arg;\n return rslt;\n}\nfunction changeImages(a, b) {\n a.src = b;\n}\nnewImage(\"/_layouts/images/icon1.gif\");\nnewImage(\"/_layouts/images/icon2.gif\");\n</script>\n</code></pre>\n"
},
{
"answer_id": 112452,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>should your script block not be:</p>\n\n<pre><code><script type=\"text/javascript\">\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 112453,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 0,
"selected": false,
"text": "<p>For starters, start your script block with</p>\n\n<pre><code><script type=\"text/javascript\">\n</code></pre>\n\n<p>Not</p>\n\n<pre><code><script language=JavaScript>\n</code></pre>\n\n<p>That's probably not the root of your problem, but since we can't see your script, that's about all we can offer.</p>\n"
},
{
"answer_id": 112456,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried loading your scripts into a JS debugger such as <a href=\"http://www.aptana.com/\" rel=\"nofollow noreferrer\">Aptana</a> or Firefox plugin like <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">Firebug</a>?</p>\n"
},
{
"answer_id": 112459,
"author": "Brendan Kidwell",
"author_id": 13958,
"author_profile": "https://Stackoverflow.com/users/13958",
"pm_score": 0,
"selected": false,
"text": "<p>You probably need to enlist the help of a Javascript debugger. I've never figured out how to make the various debuggers for IE work, so I can't help you if you're using IE.</p>\n\n<p>If you're using Firefox or you CAN use Firefox, make sure you have a Tools / Javascript Debugger command. (If you don't, reinstall it and be sure to enable that option.) Next, open up the debugger, rerun the problem page, and see what comes up.</p>\n"
},
{
"answer_id": 112461,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<p>Why are you escaping the forward slashes. That's not necessary. The two lines should be:</p>\n\n<pre><code>newImage(\"/_layouts/images/icon1.gif\");\nnewImage(\"/_layouts/images/icon2.gif\");\n</code></pre>\n"
},
{
"answer_id": 112783,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 0,
"selected": false,
"text": "<p>How are you calling changeImages? It looks as though you are not saving a reference to the images returned by newImage. You probably want to save the results of newImage and pass that to the changeImages routine. Then changeImages should look like this:</p>\n\n<pre><code>function changeImages(a, b) {\n a.src = b.src;\n}\n</code></pre>\n\n<p>You also may want to ensure that the images have finished loading before calling changeImages.</p>\n\n<p>You've posted the routine that throws the error, without posting the error or showing us how you are calling it. If none of the answers posted fix your problem then please post some detail about how you are calling the method, which specific line the error is on, and what the error message is.</p>\n"
},
{
"answer_id": 113145,
"author": "user10109",
"author_id": 10109,
"author_profile": "https://Stackoverflow.com/users/10109",
"pm_score": 2,
"selected": false,
"text": "<p>It is hard to answer your question with the limited information provided:</p>\n\n<ol>\n<li>You are not showing the complete script</li>\n<li>You never said what the exact error message is, or even what browser is giving the error.</li>\n<li>Which line number is the error supposedly coming from?</li>\n</ol>\n\n<p>I'd recommend using Firebug in firefox for debugging javascript if you aren't already. IE tends to give bogus line numbers.</p>\n\n<p>And as others have already said, the language attribute for script tags is deprecated.</p>\n"
},
{
"answer_id": 902837,
"author": "Ballsacian1",
"author_id": 100658,
"author_profile": "https://Stackoverflow.com/users/100658",
"pm_score": 0,
"selected": false,
"text": "<p>You firebug to debug.<br>\n<a href=\"http://www.mozilla.com/en-US/products/download.html?product=firefox-3.0.10&os=win&lang=en-US\" rel=\"nofollow noreferrer\">http://www.mozilla.com/en-US/products/download.html?product=firefox-3.0.10&os=win&lang=en-US</a><br>\n<a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/1843</a></p>\n\n<p>JSLint is also a nice resource.<br>\n<a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">http://www.jslint.com/</a></p>\n\n<p>Using CDATA instead of the <code><!-- // --></code><br>\n<a href=\"http://www.w3schools.com/XML/xml_cdata.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/XML/xml_cdata.asp</a></p>\n\n<pre><code><script type=\"text/javascript\">\n<![CDATA[\n]]>\n</script>\n</code></pre>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
]
| I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!
```
<SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
```
The error I am getting is when clicking on a drop down context menu on a page, for this line:
```
newImage("\/_layouts\/images\/icon1.gif");
```
>
> The object doesn't accept this property or method
> Code: 0
>
>
>
I really don't see what could happen... Any tips on what may be happening here? | Have you tried loading your scripts into a JS debugger such as [Aptana](http://www.aptana.com/) or Firefox plugin like [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843)? |
112,503 | <p>Given an array of <strong>n</strong> Objects, let's say it is an <strong>array of strings</strong>, and it has the following values:</p>
<pre><code>foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
</code></pre>
<p>What do I have to do to delete/remove all the strings/objects equal to <strong>"a"</strong> in the array?</p>
| [
{
"answer_id": 112507,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 4,
"selected": false,
"text": "<p>Make a <code>List</code> out of the array with <code>Arrays.asList()</code>, and call <code>remove()</code> on all the appropriate elements. Then call <code>toArray()</code> on the 'List' to make back into an array again.</p>\n\n<p>Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.</p>\n"
},
{
"answer_id": 112509,
"author": "alfinoba",
"author_id": 14921,
"author_profile": "https://Stackoverflow.com/users/14921",
"pm_score": -1,
"selected": false,
"text": "<p>Assign null to the array locations.</p>\n"
},
{
"answer_id": 112542,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 8,
"selected": true,
"text": "<p>[If you want some ready-to-use code, please scroll to my \"Edit3\" (after the cut). The rest is here for posterity.]</p>\n\n<p>To flesh out <a href=\"https://stackoverflow.com/a/112507/13\">Dustman's idea</a>:</p>\n\n<pre><code>List<String> list = new ArrayList<String>(Arrays.asList(array));\nlist.removeAll(Arrays.asList(\"a\"));\narray = list.toArray(array);\n</code></pre>\n\n<p>Edit: I'm now using <code>Arrays.asList</code> instead of <code>Collections.singleton</code>: singleton is limited to one entry, whereas the <code>asList</code> approach allows you to add other strings to filter out later: <code>Arrays.asList(\"a\", \"b\", \"c\")</code>.</p>\n\n<p>Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a <em>new</em> array sized exactly as required, use this instead:</p>\n\n<pre><code>array = list.toArray(new String[0]);\n</code></pre>\n\n<hr>\n\n<p>Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:</p>\n\n<pre><code>private static final String[] EMPTY_STRING_ARRAY = new String[0];\n</code></pre>\n\n<p>Then the function becomes:</p>\n\n<pre><code>List<String> list = new ArrayList<>();\nCollections.addAll(list, array);\nlist.removeAll(Arrays.asList(\"a\"));\narray = list.toArray(EMPTY_STRING_ARRAY);\n</code></pre>\n\n<p>This will then stop littering your heap with useless empty string arrays that would otherwise be <code>new</code>ed each time your function is called.</p>\n\n<p>cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:</p>\n\n<pre><code>array = list.toArray(new String[list.size()]);\n</code></pre>\n\n<p>I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling <code>size()</code> on the wrong list).</p>\n"
},
{
"answer_id": 114671,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 2,
"selected": false,
"text": "<p>Something about the make a list of it then remove then back to an array strikes me as wrong. Haven't tested, but I think the following will perform better. Yes I'm probably unduly pre-optimizing.</p>\n\n<pre><code>boolean [] deleteItem = new boolean[arr.length];\nint size=0;\nfor(int i=0;i<arr.length;i==){\n if(arr[i].equals(\"a\")){\n deleteItem[i]=true;\n }\n else{\n deleteItem[i]=false;\n size++;\n }\n}\nString[] newArr=new String[size];\nint index=0;\nfor(int i=0;i<arr.length;i++){\n if(!deleteItem[i]){\n newArr[index++]=arr[i];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 114720,
"author": "AngelOfCake",
"author_id": 1732,
"author_profile": "https://Stackoverflow.com/users/1732",
"pm_score": 0,
"selected": false,
"text": "<p>Arrgh, I can't get the code to show up correctly. Sorry, I got it working. Sorry again, I don't think I read the question properly.</p>\n\n<pre><code>String foo[] = {\"a\",\"cc\",\"a\",\"dd\"},\nremove = \"a\";\nboolean gaps[] = new boolean[foo.length];\nint newlength = 0;\n\nfor (int c = 0; c<foo.length; c++)\n{\n if (foo[c].equals(remove))\n {\n gaps[c] = true;\n newlength++;\n }\n else \n gaps[c] = false;\n\n System.out.println(foo[c]);\n}\n\nString newString[] = new String[newlength];\n\nSystem.out.println(\"\");\n\nfor (int c1=0, c2=0; c1<foo.length; c1++)\n{\n if (!gaps[c1])\n {\n newString[c2] = foo[c1];\n System.out.println(newString[c2]);\n c2++;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 117345,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": 1,
"selected": false,
"text": "<p>EDIT:</p>\n\n<p>The point with the nulls in the array has been cleared. Sorry for my comments. </p>\n\n<p>Original:</p>\n\n<p>Ehm... the line</p>\n\n<pre><code>array = list.toArray(array);\n</code></pre>\n\n<p>replaces all gaps in the array where the removed element has been with <strong>null</strong>. This might be <strong>dangerous</strong>, because the elements are removed, but the length of the array remains the same!</p>\n\n<p>If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:</p>\n\n<pre><code> String[] array = new String[] { \"a\", \"bc\" ,\"dc\" ,\"a\", \"ef\" };\n\n System.out.println(Arrays.toString(array));\n\n Set<String> asSet = new HashSet<String>(Arrays.asList(array));\n asSet.remove(\"a\");\n array = asSet.toArray(new String[] {});\n\n System.out.println(Arrays.toString(array));\n</code></pre>\n\n<p>Gives:</p>\n\n<pre><code>[a, bc, dc, a, ef]\n[dc, ef, bc]\n</code></pre>\n\n<p>Where as the current accepted answer from Chris Yester Young outputs:</p>\n\n<pre><code>[a, bc, dc, a, ef]\n[bc, dc, ef, null, ef]\n</code></pre>\n\n<p>with the code</p>\n\n<pre><code> String[] array = new String[] { \"a\", \"bc\" ,\"dc\" ,\"a\", \"ef\" };\n\n System.out.println(Arrays.toString(array));\n\n List<String> list = new ArrayList<String>(Arrays.asList(array));\n list.removeAll(Arrays.asList(\"a\"));\n array = list.toArray(array); \n\n System.out.println(Arrays.toString(array));\n</code></pre>\n\n<p>without any null values left behind.</p>\n"
},
{
"answer_id": 119463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can always do:</p>\n\n<pre><code>int i, j;\nfor (i = j = 0; j < foo.length; ++j)\n if (!\"a\".equals(foo[j])) foo[i++] = foo[j];\nfoo = Arrays.copyOf(foo, i);\n</code></pre>\n"
},
{
"answer_id": 130033,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on what you mean by \"remove\"? An array is a fixed size construct - you can't change the number of elements in it. So you can either a) create a new, shorter, array without the elements you don't want or b) assign the entries you don't want to something that indicates their 'empty' status; usually null if you are not working with primitives.</p>\n\n<p>In the first case create a List from the array, remove the elements, and create a new array from the list. If performance is important iterate over the array assigning any elements that shouldn't be removed to a list, and then create a new array from the list. In the second case simply go through and assign null to the array entries.</p>\n"
},
{
"answer_id": 4899240,
"author": "bugs_",
"author_id": 603314,
"author_profile": "https://Stackoverflow.com/users/603314",
"pm_score": 3,
"selected": false,
"text": "<p>You can use external library:</p>\n\n<pre><code>org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)\n</code></pre>\n\n<p>It is in project Apache Commons Lang <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow noreferrer\">http://commons.apache.org/lang/</a></p>\n"
},
{
"answer_id": 17488208,
"author": "DDSports",
"author_id": 1489005,
"author_profile": "https://Stackoverflow.com/users/1489005",
"pm_score": 2,
"selected": false,
"text": "<p>I realise this is a very old post, but some of the answers here helped me out, so here's my tuppence' ha'penny's worth!</p>\n\n<p>I struggled getting this to work for quite a while before before twigging that the array that I'm writing back into needed to be resized, unless the changes made to the <code>ArrayList</code> leave the list size unchanged.</p>\n\n<p>If the <code>ArrayList</code> that you're modifying ends up with greater or fewer elements than it started with, the line <code>List.toArray()</code> will cause an exception, so you need something like <code>List.toArray(new String[] {})</code> or <code>List.toArray(new String[0])</code> in order to create an array with the new (correct) size.</p>\n\n<p>Sounds obvious now that I know it. Not so obvious to an Android/Java newbie who's getting to grips with new and unfamiliar code constructs and not obvious from some of the earlier posts here, so just wanted to make this point really clear for anybody else scratching their heads for hours like I was!</p>\n"
},
{
"answer_id": 20301033,
"author": "Andre",
"author_id": 1755797,
"author_profile": "https://Stackoverflow.com/users/1755797",
"pm_score": 1,
"selected": false,
"text": "<p>My little contribution to this problem.</p>\n\n<pre><code>public class DeleteElementFromArray {\npublic static String foo[] = {\"a\",\"cc\",\"a\",\"dd\"};\npublic static String search = \"a\";\n\n\npublic static void main(String[] args) {\n long stop = 0;\n long time = 0;\n long start = 0;\n System.out.println(\"Searched value in Array is: \"+search);\n System.out.println(\"foo length before is: \"+foo.length);\n for(int i=0;i<foo.length;i++){ System.out.println(\"foo[\"+i+\"] = \"+foo[i]);}\n System.out.println(\"==============================================================\");\n start = System.nanoTime();\n foo = removeElementfromArray(search, foo);\n stop = System.nanoTime();\n time = stop - start;\n System.out.println(\"Equal search took in nano seconds = \"+time);\n System.out.println(\"==========================================================\");\n for(int i=0;i<foo.length;i++){ System.out.println(\"foo[\"+i+\"] = \"+foo[i]);}\n}\npublic static String[] removeElementfromArray( String toSearchfor, String arr[] ){\n int i = 0;\n int t = 0;\n String tmp1[] = new String[arr.length]; \n for(;i<arr.length;i++){\n if(arr[i] == toSearchfor){ \n i++;\n }\n tmp1[t] = arr[i];\n t++;\n } \n String tmp2[] = new String[arr.length-t]; \n System.arraycopy(tmp1, 0, tmp2, 0, tmp2.length);\n arr = tmp2; tmp1 = null; tmp2 = null;\n return arr;\n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 21368866,
"author": "Ali",
"author_id": 2671085,
"author_profile": "https://Stackoverflow.com/users/2671085",
"pm_score": 3,
"selected": false,
"text": "<p>See code below</p>\n\n<pre><code>ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));\na.remove(i);\nstrings = new String[a.size()];\na.toArray(strings);\n</code></pre>\n"
},
{
"answer_id": 23188826,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 5,
"selected": false,
"text": "<p>An alternative in Java 8: </p>\n\n<pre><code>String[] filteredArray = Arrays.stream(array)\n .filter(e -> !e.equals(foo)).toArray(String[]::new);\n</code></pre>\n"
},
{
"answer_id": 30151240,
"author": "Alex Salauyou",
"author_id": 3459206,
"author_profile": "https://Stackoverflow.com/users/3459206",
"pm_score": 3,
"selected": false,
"text": "<p>If you need to remove multiple elements from array without converting it to <code>List</code> nor creating additional array, you may do it in O(n) not dependent on count of items to remove.</p>\n\n<p>Here, <code>a</code> is initial array, <code>int... r</code> are distinct ordered indices (positions) of elements to remove:</p>\n\n<pre><code>public int removeItems(Object[] a, int... r) {\n int shift = 0; \n for (int i = 0; i < a.length; i++) { \n if (shift < r.length && i == r[shift]) // i-th item needs to be removed\n shift++; // increment `shift`\n else \n a[i - shift] = a[i]; // move i-th item `shift` positions left\n }\n for (int i = a.length - shift; i < a.length; i++)\n a[i] = null; // replace remaining items by nulls\n\n return a.length - shift; // return new \"length\"\n} \n</code></pre>\n\n<p>Small testing:</p>\n\n<pre><code>String[] a = {\"0\", \"1\", \"2\", \"3\", \"4\"};\nremoveItems(a, 0, 3, 4); // remove 0-th, 3-rd and 4-th items\nSystem.out.println(Arrays.asList(a)); // [1, 2, null, null, null]\n</code></pre>\n\n<p>In your task, you can first scan array to collect positions of \"a\", then call <code>removeItems()</code>. </p>\n"
},
{
"answer_id": 37767505,
"author": "PauLy",
"author_id": 1681312,
"author_profile": "https://Stackoverflow.com/users/1681312",
"pm_score": 0,
"selected": false,
"text": "<p>Will copy all elements except the one with index i:</p>\n\n<pre><code>if(i == 0){\n System.arraycopy(edges, 1, copyEdge, 0, edges.length -1 );\n }else{\n System.arraycopy(edges, 0, copyEdge, 0, i );\n System.arraycopy(edges, i+1, copyEdge, i, edges.length - (i+1) );\n }\n</code></pre>\n"
},
{
"answer_id": 44164752,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "<p>There are a lot of answers here--the problem as I see it is that you didn't say WHY you are using an array instead of a collection, so let me suggest a couple reasons and which solutions would apply (Most of the solutions have already been answered in other questions here, so I won't go into too much detail):</p>\n\n<p><strong>reason: You didn't know the collection package existed or didn't trust it</strong></p>\n\n<p>solution: Use a collection. </p>\n\n<p>If you plan on adding/deleting from the middle, use a LinkedList. If you are really worried about size or often index right into the middle of the collection use an ArrayList. Both of these should have delete operations.</p>\n\n<p><strong>reason: You are concerned about size or want control over memory allocation</strong></p>\n\n<p>solution: Use an ArrayList with a specific initial size.</p>\n\n<p>An ArrayList is simply an array that can expand itself, but it doesn't always need to do so. It will be very smart about adding/removing items, but again if you are inserting/removing a LOT from the middle, use a LinkedList.</p>\n\n<p><strong>reason: You have an array coming in and an array going out--so you want to operate on an array</strong></p>\n\n<p>solution: Convert it to an ArrayList, delete the item and convert it back</p>\n\n<p><strong>reason: You think you can write better code if you do it yourself</strong></p>\n\n<p>solution: you can't, use an Array or Linked list.</p>\n\n<p><strong>reason: this is a class assignment and you are not allowed or you do not have access to the collection apis for some reason</strong></p>\n\n<p>assumption: You need the new array to be the correct \"size\"</p>\n\n<p>solution:\nScan the array for matching items and count them. Create a new array of the correct size (original size - number of matches). use System.arraycopy repeatedly to copy each group of items you wish to retain into your new Array. If this is a class assignment and you can't use System.arraycopy, just copy them one at a time by hand in a loop but don't ever do this in production code because it's much slower. (These solutions are both detailed in other answers)</p>\n\n<p><strong>reason: you need to run bare metal</strong></p>\n\n<p>assumption: you MUST not allocate space unnecessarily or take too long</p>\n\n<p>assumption: You are tracking the size used in the array (length) separately because otherwise you'd have to reallocate your array for deletes/inserts.</p>\n\n<p>An example of why you might want to do this: a single array of primitives (Let's say int values) is taking a significant chunk of your ram--like 50%! An ArrayList would force these into a list of pointers to Integer objects which would use a few times that amount of memory.</p>\n\n<p>solution: Iterate over your array and whenever you find an element to remove (let's call it element n), use System.arraycopy to copy the tail of the array over the \"deleted\" element (Source and Destination are same array)--it is smart enough to do the copy in the correct direction so the memory doesn't overwrite itself:</p>\n\n<pre>\n System.arraycopy(ary, n+1, ary, n, length-n) \n length--;\n</pre>\n\n<p>You'll probably want to be smarter than this if you are deleting more than one element at a time. You would only move the area between one \"match\" and the next rather than the entire tail and as always, avoid moving any chunk twice.</p>\n\n<p>In this last case, you absolutely must do the work yourself, and using System.arraycopy is really the only way to do it since it's going to choose the best possibly way to move memory for your computer architecture--it should be many times faster than any code you could reasonably write yourself.</p>\n"
},
{
"answer_id": 53383108,
"author": "Ebin Joy",
"author_id": 5845024,
"author_profile": "https://Stackoverflow.com/users/5845024",
"pm_score": 2,
"selected": false,
"text": "<p>Initial array </p>\n\n<pre><code> int[] array = {5,6,51,4,3,2};\n</code></pre>\n\n<p>if you want remove 51 that is index 2, use following</p>\n\n<pre><code> for(int i = 2; i < array.length -1; i++){\n array[i] = array[i + 1];\n }\n</code></pre>\n"
},
{
"answer_id": 56652685,
"author": "Orlando Reyes",
"author_id": 6234849,
"author_profile": "https://Stackoverflow.com/users/6234849",
"pm_score": -1,
"selected": false,
"text": "<p>In an array of Strings like</p>\n\n<p>String name = 'a b c d e a f b d e' // could be like String name = 'aa bb c d e aa f bb d e'</p>\n\n<p>I build the following class</p>\n\n<pre><code>class clearname{\ndef parts\ndef tv\npublic def str = ''\nString name\nclearname(String name){\n this.name = name\n this.parts = this.name.split(\" \")\n this.tv = this.parts.size()\n}\npublic String cleared(){\n\n int i\n int k\n int j=0 \n for(i=0;i<tv;i++){\n for(k=0;k<tv;k++){\n if(this.parts[k] == this.parts[i] && k!=i){\n this.parts[k] = '';\n j++\n }\n }\n }\n def str = ''\n for(i=0;i<tv;i++){\n if(this.parts[i]!='')\n\n this.str += this.parts[i].trim()+' '\n } \n return this.str \n}}\n\n\n\nreturn new clearname(name).cleared()\n</code></pre>\n\n<p>getting this result</p>\n\n<p>a b c d e f</p>\n\n<p>hope this code help anyone \nRegards</p>\n"
},
{
"answer_id": 57382985,
"author": "milevyo",
"author_id": 4487286,
"author_profile": "https://Stackoverflow.com/users/4487286",
"pm_score": 0,
"selected": false,
"text": "<p>If it doesn't matter the order of the elements. you can swap between the elements foo[x] and foo[0], then call foo.drop(1). </p>\n\n<p><code>foo.drop(n)</code> removes (n) first elements from the array.</p>\n\n<p>I guess this is the simplest and resource efficient way to do.</p>\n\n<p><strong>PS</strong>: <code>indexOf</code> can be implemented in many ways, this is my version.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Integer indexOf(String[] arr, String value){\n for(Integer i = 0 ; i < arr.length; i++ )\n if(arr[i] == value)\n return i; // return the index of the element\n return -1 // otherwise -1\n}\n\nwhile (true) {\n Integer i;\n i = indexOf(foo,\"a\")\n if (i == -1) break;\n foo[i] = foo[0]; // preserve foo[0]\n foo.drop(1);\n}\n</code></pre>\n"
},
{
"answer_id": 66347083,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 0,
"selected": false,
"text": "<p><em>to remove</em> only the first <em>of several equal entries</em><br />\n<em>with a lambda</em></p>\n<pre><code>boolean[] done = {false};\nString[] arr = Arrays.stream( foo ).filter( e ->\n ! (! done[0] && Objects.equals( e, item ) && (done[0] = true) ))\n .toArray(String[]::new);\n</code></pre>\n<p>can remove <code>null</code> entries</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358/"
]
| Given an array of **n** Objects, let's say it is an **array of strings**, and it has the following values:
```
foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
```
What do I have to do to delete/remove all the strings/objects equal to **"a"** in the array? | [If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]
To flesh out [Dustman's idea](https://stackoverflow.com/a/112507/13):
```
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
```
Edit: I'm now using `Arrays.asList` instead of `Collections.singleton`: singleton is limited to one entry, whereas the `asList` approach allows you to add other strings to filter out later: `Arrays.asList("a", "b", "c")`.
Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a *new* array sized exactly as required, use this instead:
```
array = list.toArray(new String[0]);
```
---
Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:
```
private static final String[] EMPTY_STRING_ARRAY = new String[0];
```
Then the function becomes:
```
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);
```
This will then stop littering your heap with useless empty string arrays that would otherwise be `new`ed each time your function is called.
cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:
```
array = list.toArray(new String[list.size()]);
```
I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling `size()` on the wrong list). |
112,517 | <p>I have the following enum:</p>
<pre><code>public enum Status implements StringEnum{
ONLINE("on"),OFFLINE("off");
private String status = null;
private Status(String status) {
this.status = status;
}
public String toString() {
return this.status;
}
public static Status find(String value) {
for(Status status : Status.values()) {
if(status.toString().equals(value)) {
return status;
}
}
throw new IllegalArgumentException("Unknown value: " + value );
}
}
</code></pre>
<p>Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?</p>
<p>Thanks.</p>
| [
{
"answer_id": 112553,
"author": "Frank Pape",
"author_id": 10367,
"author_profile": "https://Stackoverflow.com/users/10367",
"pm_score": 4,
"selected": true,
"text": "<p>It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: <a href=\"http://zoom.z3950.org/bind/java/comment/static.html\" rel=\"nofollow noreferrer\">No static methods in interfaces</a></p>\n"
},
{
"answer_id": 112554,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>static methods cannot be defined in interfaces </li>\n<li>constructors cannot be defined in interfaces</li>\n<li><code>toString</code> is defined in <code>java.lang.Object</code>, requiring it in an interface will never result in a compile error if the method isn't defined.</li>\n</ol>\n\n<p>Why do you want to enforce the constructor anyway? You cannot create new instances of <code>enum</code>s at runtime anyway (unless maybe via some reflection mechanism).</p>\n"
},
{
"answer_id": 112877,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 2,
"selected": false,
"text": "<p>Enums already have a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)\" rel=\"nofollow noreferrer\">valueOf()</a> (your find method) method. And \"toString()\" is a java.lang.Object method, so, every class will have that, in other words, you can't force it! I can't see the value of enforcing a constructor since different enums could have different initializations.</p>\n\n<p>Kind Regards</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
]
| I have the following enum:
```
public enum Status implements StringEnum{
ONLINE("on"),OFFLINE("off");
private String status = null;
private Status(String status) {
this.status = status;
}
public String toString() {
return this.status;
}
public static Status find(String value) {
for(Status status : Status.values()) {
if(status.toString().equals(value)) {
return status;
}
}
throw new IllegalArgumentException("Unknown value: " + value );
}
}
```
Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?
Thanks. | It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: [No static methods in interfaces](http://zoom.z3950.org/bind/java/comment/static.html) |
112,532 | <p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p>
<p>Ex:<br />
User: "abd"<br />
Program:abdicate, abdomen, abduct...</p>
<p>Thanks!</p>
<hr>
<p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
| [
{
"answer_id": 112540,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var words = from word in dictionary\n where word.key.StartsWith(\"bla-bla-bla\");\n select word;\n</code></pre>\n"
},
{
"answer_id": 112541,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 1,
"selected": false,
"text": "<p>Try using regex to search through your list of words, e.g. /^word/ and report all matches.</p>\n"
},
{
"answer_id": 112556,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def main(script, name):\n for word in open(\"/usr/share/dict/words\"):\n if word.startswith(name):\n print word,\n\nif __name__ == \"__main__\":\n import sys\n main(*sys.argv)\n</code></pre>\n"
},
{
"answer_id": 112557,
"author": "Daniel",
"author_id": 6852,
"author_profile": "https://Stackoverflow.com/users/6852",
"pm_score": 3,
"selected": false,
"text": "<p>One of the best ways to do this is to use a directed graph to store your dictionary. It takes a little bit of setting up, but once done it is fairly easy to then do the type of searches you are talking about.</p>\n\n<p>The nodes in the graph correspond to a letter in your word, so each node will have one incoming link and up to 26 (in English) outgoing links.</p>\n\n<p>You could also use a hybrid approach where you maintain a sorted list containing your dictionary and use the directed graph as an index into your dictionary. Then you just look up your prefix in your directed graph and then go to that point in your dictionary and spit out all words matching your search criteria.</p>\n"
},
{
"answer_id": 112559,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": false,
"text": "<p>Use a <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"noreferrer\">trie</a>.</p>\n\n<p>Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix.</p>\n"
},
{
"answer_id": 112560,
"author": "Jakub Kotrla",
"author_id": 16943,
"author_profile": "https://Stackoverflow.com/users/16943",
"pm_score": 2,
"selected": false,
"text": "<p>If you really want to be efficient - use suffix trees or suffix arrays - <a href=\"http://en.wikipedia.org/wiki/Suffix_tree\" rel=\"nofollow noreferrer\">wikipedia article</a>.</p>\n\n<p>Your problem is what suffix trees were designed to handle.\nThere is even implementation for Python - <a href=\"http://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 112562,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "<p>If you need to be <em>really</em> fast, use a tree:</p>\n\n<p>build an array and split the words in 26 sets based on the first letter, then split each item in 26 based on the second letter, then again.</p>\n\n<p>So if your user types \"abd\" you would look for Array[0][1][3] and get a list of all the words starting like that. At that point your list should be small enough to pass over to the client and use javascript to filter.</p>\n"
},
{
"answer_id": 112563,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 4,
"selected": true,
"text": "<p>If you on a debian[-like] machine, </p>\n\n<pre><code>#!/bin/bash\necho -n \"Enter a word: \"\nread input\ngrep \"^$input\" /usr/share/dict/words\n</code></pre>\n\n<p>Takes all of 0.040s on my P200.</p>\n"
},
{
"answer_id": 112587,
"author": "user19745",
"author_id": 19745,
"author_profile": "https://Stackoverflow.com/users/19745",
"pm_score": 3,
"selected": false,
"text": "<pre><code>egrep `read input && echo ^$input` /usr/share/dict/words\n</code></pre>\n\n<p>oh I didn't see the Python edit, here is the same thing in python</p>\n\n<pre><code>my_input = raw_input(\"Enter beginning of word: \")\nmy_words = open(\"/usr/share/dict/words\").readlines()\nmy_found_words = [x for x in my_words if x[0:len(my_input)] == my_input]\n</code></pre>\n"
},
{
"answer_id": 112598,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<p>If you really want speed, use a trie/automaton. However, something that will be faster than simply scanning the whole list, given that the list of words is sorted:</p>\n\n<pre><code>from itertools import takewhile, islice\nimport bisect\n\ndef prefixes(words, pfx):\n return list(\n takewhile(lambda x: x.startswith(pfx), \n islice(words, \n bisect.bisect_right(words, pfx), \n len(words)))\n</code></pre>\n\n<p>Note that an automaton is O(1) with regard to the size of your dictionary, while this algorithm is O(log(m)) and then O(n) with regard to the number of strings that actually start with the prefix, while the full scan is O(m), with n << m.</p>\n"
},
{
"answer_id": 112843,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If your dictionary is really big, i'd suggest indexing with a python text index (PyLucene - note that i've never used the python extension for lucene) The search would be efficient and you could even return a search 'score'.</p>\n\n<p>Also, if your dictionary is relatively static you won't even have the overhead of re-indexing very often.</p>\n"
},
{
"answer_id": 114002,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use a bazooka to kill a fly. Use something simple just like SQLite. There are all the tools you need for every modern languages and you can just do :</p>\n\n<pre><code>\"SELECT word FROM dict WHERE word LIKE \"user_entry%\"\n</code></pre>\n\n<p>It's lightning fast and a baby could do it. What's more it's portable, persistent and so easy to maintain.</p>\n\n<p>Python tuto :</p>\n\n<p><a href=\"http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html\" rel=\"nofollow noreferrer\">http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html</a></p>\n"
},
{
"answer_id": 306465,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 0,
"selected": false,
"text": "<p>A linear scan is slow, but a prefix tree is probably overkill. Keeping the words sorted and using a binary search is a fast and simple compromise.</p>\n\n<pre><code>import bisect\nwords = sorted(map(str.strip, open('/usr/share/dict/words')))\ndef lookup(prefix):\n return words[bisect.bisect_left(words, prefix):bisect.bisect_right(words, prefix+'~')]\n\n>>> lookup('abdicat')\n['abdicate', 'abdication', 'abdicative', 'abdicator']\n</code></pre>\n"
},
{
"answer_id": 308443,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "<h2>Most Pythonic solution</h2>\n\n<pre><code># set your list of words, whatever the source\nwords_list = ('cat', 'dog', 'banana')\n# get the word from the user inpuit\nuser_word = raw_input(\"Enter a word:\\n\")\n# create an generator, so your output is flexible and store almost nothing in memory\nword_generator = (word for word in words_list if word.startswith(user_word))\n\n# now you in, you can make anything you want with it \n# here we just list it :\n\nfor word in word_generator :\n print word\n</code></pre>\n\n<p>Remember generators can be only used once, so turn it to a list (using list(word_generator)) or use the itertools.tee function if you expect using it more than once.</p>\n\n<h2>Best way to do it :</h2>\n\n<p>Store it into a database and use SQL to look for the word you need. If there is a lot of words in your dictionary, it will be much faster and efficient.</p>\n\n<p>Python got thousand of DB API to help you do the job ;-)</p>\n"
},
{
"answer_id": 53864726,
"author": "Mattias",
"author_id": 8265788,
"author_profile": "https://Stackoverflow.com/users/8265788",
"pm_score": 0,
"selected": false,
"text": "<p>If you store the words in a .csv file, you can use pandas to solve this rather neatly, and after you have read it once you can reuse the already loaded data frame if the user should be able to perform more than one search per session.</p>\n\n<pre><code>df = pd.read_csv('dictionary.csv')\nmatching_words = df[0].loc[df[0].str.startswith(user_entry)] \n</code></pre>\n"
},
{
"answer_id": 53868147,
"author": "Nitwit",
"author_id": 7958330,
"author_profile": "https://Stackoverflow.com/users/7958330",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>str.startswith()</code>. Reference from the official docs:</p>\n<blockquote>\n<h2><strong>str.startswith(prefix[, start[, end]])</strong></h2>\n<p>Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.</p>\n</blockquote>\n<p>try code below:</p>\n<pre><code>dictionary = ['apple', 'abdicate', 'orange', 'abdomen', 'abduct', 'banana']\nuser_input = input('Enter something: ')\nfor word in dictionary:\n if word.startswith(user_input):\n print(word)\n</code></pre>\n<p>Output:</p>\n<pre><code>Enter something: abd\nabdicate\nabdomen\nabduct\n</code></pre>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
| How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
---
Edit: I'm using python, but I assume that this is a fairly language-independent problem. | If you on a debian[-like] machine,
```
#!/bin/bash
echo -n "Enter a word: "
read input
grep "^$input" /usr/share/dict/words
```
Takes all of 0.040s on my P200. |
112,564 | <p>I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the <em>right</em> way?</p>
| [
{
"answer_id": 112659,
"author": "alif",
"author_id": 12650,
"author_profile": "https://Stackoverflow.com/users/12650",
"pm_score": 2,
"selected": false,
"text": "<p>Genshi.builder is for \"programmatically generating markup streams\"[1]. I believe the purpose of it is as a backend for the templating language. You're probably looking for the templating language for generating a whole page.</p>\n\n<p>You can, however do the following:</p>\n\n<pre><code>>>> import genshi.output\n>>> genshi.output.DocType('html')\n('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd')\n</code></pre>\n\n<p>See other Doctypes here: <a href=\"http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType\" rel=\"nofollow noreferrer\">http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType</a></p>\n\n<pre><code>[1] genshi.builder.__doc__\n</code></pre>\n"
},
{
"answer_id": 112860,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>It's not possible to build an entire page using just <code>genshi.builder.tag</code> -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want.</p>\n\n<p><code>genshi.builder.tag</code> is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output.</p>\n\n<p>See documentation for:</p>\n\n<ul>\n<li><a href=\"http://genshi.edgewall.org/wiki/Documentation/0.5.x/templates.html\" rel=\"noreferrer\">Creating and using templates</a></li>\n<li><a href=\"http://genshi.edgewall.org/wiki/Documentation/0.5.x/xml-templates.html\" rel=\"noreferrer\">The XML-based template language</a></li>\n<li><a href=\"http://genshi.edgewall.org/wiki/ApiDocs/0.5.x/genshi.builder\" rel=\"noreferrer\"><code>genshi.builder</code> API docs</a></li>\n</ul>\n\n<p>If you really want to generate a full document using only <code>builder.tag</code>, this (completely untested) code could be a good starting point:</p>\n\n<pre><code>from itertools import chain\nfrom genshi.core import DOCTYPE, Stream\nfrom genshi.output import DocType\nfrom genshi.builder import tag as t\n\n# Build the page using `genshi.builder.tag`\npage = t.html (t.head (t.title (\"Hello world!\")), t.body (t.div (\"Body text\")))\n\n# Convert the page element into a stream\nstream = page.generate ()\n\n# Chain the page stream with a stream containing only an HTML4 doctype declaration\nstream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream))\n\n# Convert the stream to text using the \"html\" renderer (could also be xml, xhtml, text, etc)\ntext = stream.render ('html')\n</code></pre>\n\n<p>The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader.</p>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
]
| I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the *right* way? | It's not possible to build an entire page using just `genshi.builder.tag` -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want.
`genshi.builder.tag` is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output.
See documentation for:
* [Creating and using templates](http://genshi.edgewall.org/wiki/Documentation/0.5.x/templates.html)
* [The XML-based template language](http://genshi.edgewall.org/wiki/Documentation/0.5.x/xml-templates.html)
* [`genshi.builder` API docs](http://genshi.edgewall.org/wiki/ApiDocs/0.5.x/genshi.builder)
If you really want to generate a full document using only `builder.tag`, this (completely untested) code could be a good starting point:
```
from itertools import chain
from genshi.core import DOCTYPE, Stream
from genshi.output import DocType
from genshi.builder import tag as t
# Build the page using `genshi.builder.tag`
page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text")))
# Convert the page element into a stream
stream = page.generate ()
# Chain the page stream with a stream containing only an HTML4 doctype declaration
stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream))
# Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc)
text = stream.render ('html')
```
The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader. |
112,582 | <p>I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached: </p>
<pre><code>#include<stdio.h>
#define MAX 255
int main(){
int arr[MAX]={0};
int idx=0;
/* Approach #1 */
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
while(arr[idx-1] != -1 && idx < MAX){
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}
/* Approach #2 */
do{
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}while(arr[idx-1] != -1 && idx < MAX);
// Main func continues here.
}
</code></pre>
<p>Any advice would be much appreciated!</p>
<p><strong>Update:</strong></p>
<p>Now it works! thanks MUCH <strong>all</strong> of you guys for such instant responses. This is definitely a great community, it's helping me a lot.</p>
| [
{
"answer_id": 112586,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<pre><code>arr[idx] <= MAX\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>idx <= MAX\n</code></pre>\n"
},
{
"answer_id": 112594,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 1,
"selected": false,
"text": "<p>C arrays begin counting from 0. </p>\n\n<p>If you allocate an array of size MAX, accessing the element at MAX would be an error.\nChange the loop to;</p>\n\n<pre><code>int arr[MAX];\nfor ( .... && idx < MAX )\n</code></pre>\n"
},
{
"answer_id": 112595,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 2,
"selected": true,
"text": "<pre><code>arr[idx] <= MAX\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>idx < MAX\n</code></pre>\n\n<p>unless you are checking the item instead of the index.</p>\n\n<p>You are also always checking the \"next\" element for -1 (arr[idx] != -1) because you are incrementing idx prior to checking your added value.</p>\n\n<p>so if you had</p>\n\n<pre><code>arr[idx-1] != -1\n</code></pre>\n\n<p>you would be fine.</p>\n"
},
{
"answer_id": 112599,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "<p>In your first while loop, the </p>\n\n<pre><code>arr[idx] <= MAX\n</code></pre>\n\n<p>line should read</p>\n\n<pre><code>idx <= MAX\n</code></pre>\n\n<p>In your second loop, you're incrementing idx before the test - it should end with</p>\n\n<pre><code>} while ((arr[idx-1] != -1) && (idx-1 <= MAX));\n</code></pre>\n\n<p>I also tend to parenthesize all internal conditions just to be absolutely certain that the precedence is correct (hence the extra brackets above).</p>\n"
},
{
"answer_id": 112615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>while(arr[idx] != -1 && idx <= MAX){ // Fixed by sklivvz\n printf(\"Enter elements, -1 to finish:\\n\");\n scanf(\"%d\", &arr[idx]);\n idx++; \n}\n</code></pre>\n\n<p>First of all, you should check if the index variabel idx is smaller than MAX (not smaller than or equal to). You would go out of bounds if your index equals MAX. An array with MAX = 10 has index values 0 to and including 9, but not 10.</p>\n\n<p>Secondly, you add the first element to arr[0], you increment your index from 0 to 1, then you jump back to the while-condition and check if arr[1] == -1, which it is not. So check instead that arr[idx-1] != -1. Note however that the first time you get to the while-loop, you will actually check arr[-1] != -1, which is also out of bounds. ;) So you need to figure out how to solve this one.</p>\n"
},
{
"answer_id": 112626,
"author": "RomanM",
"author_id": 14587,
"author_profile": "https://Stackoverflow.com/users/14587",
"pm_score": 1,
"selected": false,
"text": "<p>I'd go with somthing like this.</p>\n\n<p>You don't have to worry about array bounds and other confusing conditions.</p>\n\n<pre><code>int cnt = MAX; // how many elements in the array, in this case MAX\nint * p = &arr[0]; // p is a pointer to an integer and is initialize to the address of the first\n // element of the array. So now *p is the same as arr[0] and p is same as &arr[0]\n\n// iterate over all elements. stop when cnt == 0\nwhile (cnt) {\n\n // do somthing\n scanf(\"%d\", *p); // remember that *p is same as arr[some index]\n if (*p == -1) // inspect element to see what user entered\n break;\n\n cnt --; // loop counter\n p++; // incrementing p to point to next element in the array\n}\n</code></pre>\n"
},
{
"answer_id": 112638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>to Roman M:</p>\n\n<p>First of all, the guy asking the question has just started a programming course, and has probably not yet learned about pointers. Secondly, you now deal with both a counter and a pointer. I'm not sure I see the benefit of doing that versus using an index like this:</p>\n\n<p>for(idx=0; idx < MAX; ++idx) {</p>\n\n<pre><code>scanf(\"%d\", &arr[idx]);\nif(arr[idx] == -1)\n break;\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 113017,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 2,
"selected": false,
"text": "<p>Using a for loop you can eliminate the need for the messy <strong>idx-1</strong> checking code:</p>\n\n<pre><code>/* Approach #3*/\nint i;\nint value;\n\nfor (i = 0; i < MAX; ++i)\n{\n printf(\"Enter elements, -1 to finish:\\n\");\n scanf(\"%d\", &value);\n if (value == -1) break;\n arr[i] = value;\n}\n</code></pre>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
]
| I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached:
```
#include<stdio.h>
#define MAX 255
int main(){
int arr[MAX]={0};
int idx=0;
/* Approach #1 */
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
while(arr[idx-1] != -1 && idx < MAX){
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}
/* Approach #2 */
do{
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}while(arr[idx-1] != -1 && idx < MAX);
// Main func continues here.
}
```
Any advice would be much appreciated!
**Update:**
Now it works! thanks MUCH **all** of you guys for such instant responses. This is definitely a great community, it's helping me a lot. | ```
arr[idx] <= MAX
```
should be
```
idx < MAX
```
unless you are checking the item instead of the index.
You are also always checking the "next" element for -1 (arr[idx] != -1) because you are incrementing idx prior to checking your added value.
so if you had
```
arr[idx-1] != -1
```
you would be fine. |
112,601 | <p>I want to select the topmost element in a document that has a given namespace (prefix).</p>
<p>More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element. </p>
| [
{
"answer_id": 112602,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 2,
"selected": false,
"text": "<p>The XPath expression that I want is:</p>\n\n<pre><code>/html:html/html:body/node()|/foo:*\n</code></pre>\n\n<p>Where the \"html\" prefix is mapped to the XHTML namespace, and the \"foo\" prefix is mapped to my target namespace.</p>\n"
},
{
"answer_id": 113095,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 4,
"selected": true,
"text": "<p>In XPath 2.0 and XQuery 1.0 you can test against the namespace prefix using the <a href=\"http://www.w3.org/TR/xquery-operators/#func-in-scope-prefixes\" rel=\"noreferrer\">in-scope-prefixes()</a> function in a predicate. \ne.g.</p>\n\n<pre><code>//*[in-scope-prefixes(.)='html']\n</code></pre>\n\n<p>If you cant use v2, in XPath 1.0 you can use the <a href=\"http://www.w3.org/TR/xpath#function-namespace-uri\" rel=\"noreferrer\">namespace-uri()</a> function to test against the namespace itself.\ne.g.</p>\n\n<pre><code>//*[namespace-uri()='http://www.w3c.org/1999/xhtml']\n</code></pre>\n"
}
]
| 2008/09/21 | [
"https://Stackoverflow.com/questions/112601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
]
| I want to select the topmost element in a document that has a given namespace (prefix).
More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element. | In XPath 2.0 and XQuery 1.0 you can test against the namespace prefix using the [in-scope-prefixes()](http://www.w3.org/TR/xquery-operators/#func-in-scope-prefixes) function in a predicate.
e.g.
```
//*[in-scope-prefixes(.)='html']
```
If you cant use v2, in XPath 1.0 you can use the [namespace-uri()](http://www.w3.org/TR/xpath#function-namespace-uri) function to test against the namespace itself.
e.g.
```
//*[namespace-uri()='http://www.w3c.org/1999/xhtml']
``` |
112,612 | <p>I am hosting <a href="http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference" rel="nofollow noreferrer">SpiderMonkey</a> in a current project and would like to have template functions generate some of the simple property get/set methods, eg:</p>
<pre><code>template <typename TClassImpl, int32 TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToInt32(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
</code></pre>
<p>Used:</p>
<pre><code>::JSPropertySpec Vec2::s_JsProps[] = {
{"x", 1, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::x>, &JsWrap::WriteProp<Vec2, &Vec2::x>},
{"y", 2, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::y>, &JsWrap::WriteProp<Vec2, &Vec2::y>},
{0}
};
</code></pre>
<p>This works fine, however, if I add another member type:</p>
<pre><code>template <typename TClassImpl, JSObject* TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToObject(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
</code></pre>
<p>Then Visual C++ 9 attempts to use the JSObject* wrapper for int32 members!</p>
<pre><code>1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const '
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* '
1> d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp'
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp'
1> None of the functions with this name in scope match the target type
</code></pre>
<p>Surprisingly, parening JSObject* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject* PObject; ..., PObject TClassImpl::<em>mem>", void</em>, struct Undefined*, and double. Since the function usage is fully instantiated: "&ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.</p>
<p>Vec2 is just:</p>
<pre><code>class Vec2
{
public:
int32 x, y;
Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv);
static ::JSClass s_JsClass;
static ::JSPropertySpec s_JsProps[];
};
</code></pre>
<p>JSPropertySpec is described in JSAPI link in OP, taken from header:</p>
<pre><code>typedef JSBool
(* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id,
jsval *vp);
...
struct JSPropertySpec {
const char *name;
int8 tinyid;
uint8 flags;
JSPropertyOp getter;
JSPropertyOp setter;
};
</code></pre>
| [
{
"answer_id": 112679,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>Try changing the JSObject * to another pointer type to see if that reproduces the error. Is JSObject defined at the point of use? Also, maybe JSObject* needs to be in parens.</p>\n"
},
{
"answer_id": 112700,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>I am certainly no template guru, but does this boil down to a subtle case of trying to differentiate overloads based purely on the return type?</p>\n\n<p>Since C++ doesn't allow overloading of functions based on return type, perhaps the same thing applies to template parameters.</p>\n"
},
{
"answer_id": 112737,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 3,
"selected": true,
"text": "<p>Pretty sure VC++ has \"issues\" here. Comeau and g++ 4.2 are both happy with the following program:</p>\n\n<pre><code>struct X\n{\n int i;\n void* p;\n};\n\ntemplate<int X::*P>\nvoid foo(X* t)\n{\n t->*P = 0;\n}\n\ntemplate<void* X::*P>\nvoid foo(X* t)\n{\n t->*P = 0;\n}\n\nint main()\n{\n X x;\n foo<&X::i>(&x);\n foo<&X::p>(&x);\n}\n</code></pre>\n\n<p>VC++ 2008SP1, however, is having none of it.</p>\n\n<p>I haven't the time to read through my standard to find out exactly what's what... but I think VC++ is in the wrong here.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20135/"
]
| I am hosting [SpiderMonkey](http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference) in a current project and would like to have template functions generate some of the simple property get/set methods, eg:
```
template <typename TClassImpl, int32 TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToInt32(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
```
Used:
```
::JSPropertySpec Vec2::s_JsProps[] = {
{"x", 1, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::x>, &JsWrap::WriteProp<Vec2, &Vec2::x>},
{"y", 2, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::y>, &JsWrap::WriteProp<Vec2, &Vec2::y>},
{0}
};
```
This works fine, however, if I add another member type:
```
template <typename TClassImpl, JSObject* TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToObject(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
```
Then Visual C++ 9 attempts to use the JSObject\* wrapper for int32 members!
```
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const '
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* '
1> d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp'
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp'
1> None of the functions with this name in scope match the target type
```
Surprisingly, parening JSObject\* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject\* PObject; ..., PObject TClassImpl::*mem>", void*, struct Undefined\*, and double. Since the function usage is fully instantiated: "&ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.
Vec2 is just:
```
class Vec2
{
public:
int32 x, y;
Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv);
static ::JSClass s_JsClass;
static ::JSPropertySpec s_JsProps[];
};
```
JSPropertySpec is described in JSAPI link in OP, taken from header:
```
typedef JSBool
(* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id,
jsval *vp);
...
struct JSPropertySpec {
const char *name;
int8 tinyid;
uint8 flags;
JSPropertyOp getter;
JSPropertyOp setter;
};
``` | Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program:
```
struct X
{
int i;
void* p;
};
template<int X::*P>
void foo(X* t)
{
t->*P = 0;
}
template<void* X::*P>
void foo(X* t)
{
t->*P = 0;
}
int main()
{
X x;
foo<&X::i>(&x);
foo<&X::p>(&x);
}
```
VC++ 2008SP1, however, is having none of it.
I haven't the time to read through my standard to find out exactly what's what... but I think VC++ is in the wrong here. |
112,643 | <p>I know how to create a <code>SEL</code> at compile time using <code>@selector(MyMethodName:)</code> but what I want to do is create a selector dynamically from an <code>NSString</code>. Is this even possible?</p>
<p>What I can do:</p>
<pre><code>SEL selector = @selector(doWork:);
[myobj respondsToSelector:selector];
</code></pre>
<p>What I want to do: (pseudo code, this obviously doesn't work)</p>
<pre><code>SEL selector = selectorFromString(@"doWork");
[myobj respondsToSelector:selector];
</code></pre>
<p>I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time <code>@selector(myTarget:)</code> syntax.</p>
| [
{
"answer_id": 112668,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": true,
"text": "<p>I'm not an Objective-C programmer, merely a sympathizer, but maybe <a href=\"https://developer.apple.com/documentation/foundation/1395294-nsselectorfromstring?language=objc\" rel=\"noreferrer\">NSSelectorFromString</a> is what you need. It's mentioned explicity in the <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_9_section_3.html\" rel=\"noreferrer\">Runtime Reference</a> that you can use it to convert a string to a selector.</p>\n"
},
{
"answer_id": 112680,
"author": "Josh Gagnon",
"author_id": 7944,
"author_profile": "https://Stackoverflow.com/users/7944",
"pm_score": 5,
"selected": false,
"text": "<p>According to the XCode documentation, your psuedocode basically gets it right.</p>\n\n<blockquote>\n <p>It’s most efficient to assign values to SEL variables at compile time with the @selector() directive. However, in some cases, a program may need to convert a character string to a selector at runtime. This can be done with the NSSelectorFromString function:</p>\n</blockquote>\n\n<p><code>setWidthHeight = NSSelectorFromString(aBuffer);</code></p>\n\n<p>Edit: Bummer, too slow. :P</p>\n"
},
{
"answer_id": 21494661,
"author": "Alex Gray",
"author_id": 547214,
"author_profile": "https://Stackoverflow.com/users/547214",
"pm_score": 4,
"selected": false,
"text": "<p>I'd have to say that <em>it's a little more complicated</em> than the previous respondents' answers might suggest... if you indeed really want to <strong>create a selector</strong>... not just \"call one\" that you \"have laying around\"... </p>\n\n<p>You need to create a function pointer that will be called by your \"new\" method.. so for a method like <code>[self theMethod:(id)methodArg];</code>, you'd write...</p>\n\n<pre><code>void (^impBlock)(id,id) = ^(id _self, id methodArg) { \n [_self doSomethingWith:methodArg]; \n};\n</code></pre>\n\n<p>and then you need to generate the <code>IMP</code> block dynamically, this time, passing, \"self\", the <code>SEL</code>, and any arguments... </p>\n\n<pre><code>void(*impFunct)(id, SEL, id) = (void*) imp_implementationWithBlock(impBlock);\n</code></pre>\n\n<p>and add it to your class, along with an accurate method signature for the whole sucker (in this case <code>\"v@:@\"</code>, void return, object caller, object argument)</p>\n\n<pre><code> class_addMethod(self.class, @selector(theMethod:), (IMP)impFunct, \"v@:@\");\n</code></pre>\n\n<p>You can see some good examples of this kind of <a href=\"https://github.com/mralexgray/AtoZAutoBox\"><em>runtime shenanigans</em>, in one of my repos, here.</a></p>\n"
},
{
"answer_id": 22032339,
"author": "Krypton",
"author_id": 950983,
"author_profile": "https://Stackoverflow.com/users/950983",
"pm_score": 3,
"selected": false,
"text": "<p>I know this has been answered for long ago, but still I wanna share. This can be done using <code>sel_registerName</code> too.</p>\n\n<p>The example code in the question can be rewritten like this:</p>\n\n<pre><code>SEL selector = sel_registerName(\"doWork:\");\n[myobj respondsToSelector:selector];\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18590/"
]
| I know how to create a `SEL` at compile time using `@selector(MyMethodName:)` but what I want to do is create a selector dynamically from an `NSString`. Is this even possible?
What I can do:
```
SEL selector = @selector(doWork:);
[myobj respondsToSelector:selector];
```
What I want to do: (pseudo code, this obviously doesn't work)
```
SEL selector = selectorFromString(@"doWork");
[myobj respondsToSelector:selector];
```
I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time `@selector(myTarget:)` syntax. | I'm not an Objective-C programmer, merely a sympathizer, but maybe [NSSelectorFromString](https://developer.apple.com/documentation/foundation/1395294-nsselectorfromstring?language=objc) is what you need. It's mentioned explicity in the [Runtime Reference](http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_9_section_3.html) that you can use it to convert a string to a selector. |
112,664 | <p>I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS:</p>
<pre><code>F:\Cygnus>sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS
</code></pre>
<hr>
<p>a test</p>
<p>(1 rows affected)</p>
<pre><code>F:\Cygnus>
</code></pre>
<p>====================================================</p>
<p>From Cygwin:</p>
<pre><code>$ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS
</code></pre>
<blockquote>
<p>HResult 0x35, Level 16, State 1<br> Named Pipes Provider: Could not
open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL
Native Client : An error has occurred while establishing a connection
to the server. When connecting to SQL Server 2005, this failure may be
caused by the fact that under the default settings SQL Server does not
allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client
: Login timeout expired.</p>
</blockquote>
| [
{
"answer_id": 112688,
"author": "PostMan",
"author_id": 18405,
"author_profile": "https://Stackoverflow.com/users/18405",
"pm_score": 0,
"selected": false,
"text": "<p>You may have to allow remote connections for this, and give the full server name i.e SERVER\\SQLEXPRESS</p>\n"
},
{
"answer_id": 118071,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 4,
"selected": true,
"text": "<p>The backslash is being eaten by cygwin's bash shell. Try doubling it:</p>\n\n<pre><code>sqlcmd -Q \"select 'a test'\" -S .\\\\SQLEXPRESS\n</code></pre>\n"
},
{
"answer_id": 29771028,
"author": "Krzysztof Kuźnik",
"author_id": 4814638,
"author_profile": "https://Stackoverflow.com/users/4814638",
"pm_score": 0,
"selected": false,
"text": "<p>You can also pass query/instruction to db and receive output in shell if you use \"-Q\" switch:</p>\n\n<pre><code>sqlcmd -Q \"select * from nice.dbo.TableName ac ORDER BY 1 DESC\" -S server_name\\\\db_name\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8670/"
]
| I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS:
```
F:\Cygnus>sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS
```
---
a test
(1 rows affected)
```
F:\Cygnus>
```
====================================================
From Cygwin:
```
$ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS
```
>
> HResult 0x35, Level 16, State 1
> Named Pipes Provider: Could not
> open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL
> Native Client : An error has occurred while establishing a connection
> to the server. When connecting to SQL Server 2005, this failure may be
> caused by the fact that under the default settings SQL Server does not
> allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client
> : Login timeout expired.
>
>
> | The backslash is being eaten by cygwin's bash shell. Try doubling it:
```
sqlcmd -Q "select 'a test'" -S .\\SQLEXPRESS
``` |
112,707 | <p>Whenever I indent <code>HTML</code> in <code>PHP</code> mode, <code>emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)</code> pops up a frame and tells me to get <code>MUMODE</code> or <code>somesuch</code> extra add-on. I installed <code>PHP</code> Mode without a big hassle, but I don't know how to get this multi-mode rolling.<br>
<hr>
I'd like to know 2 things</p>
<pre><code>How to install and configure multi-mode
How to disable pop-ups in Emacs
</code></pre>
| [
{
"answer_id": 112906,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 3,
"selected": true,
"text": "<p>If you're running emacs 22, you should just be able to run:</p>\n\n<pre><code>M-x nxhtml-mumamo\n</code></pre>\n\n<p>when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info:</p>\n\n<p><a href=\"http://www.emacswiki.org/cgi-bin/wiki/MuMaMo\" rel=\"nofollow noreferrer\">http://www.emacswiki.org/cgi-bin/wiki/MuMaMo</a><br/>\n<a href=\"http://www.emacswiki.org/cgi-bin/wiki/PhpMode\" rel=\"nofollow noreferrer\">http://www.emacswiki.org/cgi-bin/wiki/PhpMode</a></p>\n"
},
{
"answer_id": 1661914,
"author": "RichieHH",
"author_id": 37370,
"author_profile": "https://Stackoverflow.com/users/37370",
"pm_score": 0,
"selected": false,
"text": "<p>multi-mode and html-php-mode can be found here : <a href=\"http://www.loveshack.ukfsn.org/emacs/\" rel=\"nofollow noreferrer\">http://www.loveshack.ukfsn.org/emacs/</a></p>\n\n<p>It can be initialized with:</p>\n\n<pre><code>(require 'html-php)\n(add-to-list 'auto-mode-alist '(\"\\\\.php\\\\'\" . html-php-mode))\n</code></pre>\n"
},
{
"answer_id": 12271624,
"author": "fxbois",
"author_id": 894017,
"author_profile": "https://Stackoverflow.com/users/894017",
"pm_score": 1,
"selected": false,
"text": "<p>web-mode.el is available on <a href=\"http://web-mode.org\" rel=\"nofollow\">http://web-mode.org</a>\nThis major mode is designed to edit html php templates (with JS and CSS)\nAdd those two lines in your <code>.emacs</code></p>\n\n<pre><code>(require 'web-mode)\n(add-to-list 'auto-mode-alist '(\"\\\\.phtml$\" . web-mode))\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
]
| Whenever I indent `HTML` in `PHP` mode, `emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)` pops up a frame and tells me to get `MUMODE` or `somesuch` extra add-on. I installed `PHP` Mode without a big hassle, but I don't know how to get this multi-mode rolling.
---
I'd like to know 2 things
```
How to install and configure multi-mode
How to disable pop-ups in Emacs
``` | If you're running emacs 22, you should just be able to run:
```
M-x nxhtml-mumamo
```
when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info:
<http://www.emacswiki.org/cgi-bin/wiki/MuMaMo>
<http://www.emacswiki.org/cgi-bin/wiki/PhpMode> |
112,721 | <p>I've got the following situation</p>
<ul>
<li>A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality</li>
<li>Lot of nice javascript written using jQuery (for a separate application)</li>
</ul>
<p>I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc). </p>
<p>What is my easiest option to bring the two together? Thanks!</p>
| [
{
"answer_id": 112731,
"author": "Jason Peacock",
"author_id": 18381,
"author_profile": "https://Stackoverflow.com/users/18381",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://ennerchi.com/projects/jrails\" rel=\"nofollow noreferrer\">jRails</a> is a drop-in replacement for scriptaculous/prototype in Rails using the jQuery library, it does exactly what you're looking for.</p>\n"
},
{
"answer_id": 112746,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 5,
"selected": true,
"text": "<pre><code>jQuery.noConflict();\n</code></pre>\n\n<p>Then use jQuery instead of $ to refer to jQuery. e.g.,</p>\n\n<pre><code>jQuery('div.foo').doSomething()\n</code></pre>\n\n<p>If you need to adapt jQuery code that uses $, you can surround it with this:</p>\n\n<pre><code>(function($) {\n...your code here...\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 112811,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 2,
"selected": false,
"text": "<p>I believe it's <code>jQuery.noConflict()</code>.</p>\n\n<p>You can call it standalone like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery.noConflict();\n\njQuery('div').hide();\n</code></pre>\n\n<p>Or you can assign it to another variable of your choosing:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var $j = jQuery.noConflict();\n\n$j('div').hide();\n</code></pre>\n\n<p>Or you can keep using jQuery's <code>$</code> function inside a block like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery.noConflict();\n\n // Put all your code in your document ready area\n jQuery(document).ready(function($){\n // Do jQuery stuff using $\n $(\"div\").hide();\n });\n// Use Prototype with $(...), etc.\n$('someid').hide();\n</code></pre>\n\n<p>For more information, see <a href=\"http://docs.jquery.com/Using_jQuery_with_Other_Libraries\" rel=\"nofollow noreferrer\">Using jQuery with Other Libraries</a> in the jQuery documentation.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16779/"
]
| I've got the following situation
* A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality
* Lot of nice javascript written using jQuery (for a separate application)
I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc).
What is my easiest option to bring the two together? Thanks! | ```
jQuery.noConflict();
```
Then use jQuery instead of $ to refer to jQuery. e.g.,
```
jQuery('div.foo').doSomething()
```
If you need to adapt jQuery code that uses $, you can surround it with this:
```
(function($) {
...your code here...
})(jQuery);
``` |
112,730 | <p>I have a <code>n...n</code> structure for two tables, <strong><code>makes</code></strong> and <strong><code>models</code></strong>. So far no problem.</p>
<p>In a third table (<strong><code>products</code></strong>) like:</p>
<pre><code>id
make_id
model_id
...
</code></pre>
<p>My problem is creating a view for products of one specifi <strong><code>make</code></strong> inside my <code>ProductsController</code> containing just that's make models:</p>
<p>I thought this could work:</p>
<pre><code>var $uses = array('Make', 'Model');
$this->Make->id = 5; // My Make
$this->Make->find(); // Returns only the make I want with it's Models (HABTM)
$this->Model->find('list'); // Returns ALL models
$this->Make->Model->find('list'); // Returns ALL models
</code></pre>
<p>So, If I want to use the <code>list</code> to pass to my view to create radio buttons I will have to do a <code>foreach()</code> in my <strong><code>make</code></strong> array to find all models titles and create a new array and send to the view via <code>$this->set()</code>.</p>
<pre><code>$makeArray = $this->Make->find();
foreach ($makeArray['Model'] as $model) {
$modelList[] = $model['title'];
}
$this->set('models', $models)
</code></pre>
<p>Is there any easier way to get that list without stressing the <strong><code>make</code></strong> Array. It will be a commom task to develops such scenarios in my application(s).</p>
<p>Thanks in advance for any hint!</p>
| [
{
"answer_id": 112868,
"author": "JayTee",
"author_id": 20153,
"author_profile": "https://Stackoverflow.com/users/20153",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my hint: Try getting your query written in regular SQL before trying to reconstruct using the Cake library. In essence you're doing a lot of extra work that the DB can do for you.\nYour approach (just for show - not good SQL):</p>\n\n<pre><code>SELECT * FROM makes, models, products WHERE make_id = 5\n</code></pre>\n\n<p>You're not taking into consideration the relationships (unless Cake auto-magically understands the relationships of the tables)</p>\n\n<p>You're probably looking for something that joins these things together:</p>\n\n<pre><code>SELECT models.title FROM models \nINNER JOIN products \n ON products.model_id = models.model_id \n AND products.make_id = 5\n</code></pre>\n\n<p>Hopefully this is a nudge in the right direction?</p>\n"
},
{
"answer_id": 113678,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 0,
"selected": false,
"text": "<p>All your different Make->find() and Model->find() calls are completely independent of each other. Even Make->Model->find() is the same as Model->find(), Cake does not in any way remember or take into account what you have already found in other models. What you're looking for is something like:</p>\n\n<pre><code>$this->Product->find('all', array('conditions' => array('make_id' => 5)));\n</code></pre>\n"
},
{
"answer_id": 123296,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 0,
"selected": false,
"text": "<p>Check out the Set::extract() method for getting a list of model titles from the results of $this->Make->find()</p>\n"
},
{
"answer_id": 160990,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 1,
"selected": false,
"text": "<p>Judging from your comment, what you're asking for is how to get results from a certain model, where the condition is in a HABTM related model. I.e. something you'd usually do with a JOIN statement in raw SQL.<br>\nCurrently that's one of the few weak points of Cake. There are different strategies to deal with that.</p>\n\n<ul>\n<li><p>Have the related model B return all ids of possible candidates for Model A, then do a second query on Model A. I.e.:</p>\n\n<pre><code>$this->ModelB->find('first', array('conditions' => array('field' => $condition)));\narray(\n ['ModelB'] => array( ... ),\n ['ModelA'] => array(\n [0] => array(\n 'id' => 1\n )\n)\n</code></pre>\n\n<p>Now you have an array of all ids of ModelA that belong to ModelB that matches your conditions, which you can easily extract using Set::extract(). Basically the equivalent of <code>SELECT model_a.id FROM model_b JOIN model_a WHERE model_b.field = xxx</code>. Next you look for ModelA:</p>\n\n<pre><code> $this->ModelA->find('all', array('conditions' => array('id' => $model_a_ids)));\n</code></pre>\n\n<p>That will produce <code>SELECT model_a.* FROM model_a WHERE id IN (1, 2, 3)</code>, which is a roundabout way of doing the JOIN statement. If you need conditions on more than one related model, repeat until you have all the ids for ModelA, SQL will use the intersection of all ids (<code>WHERE id IN (1, 2, 3) AND id IN (3, 4, 5)</code>).</p></li>\n<li><p>If you only need one condition on ModelB but want to retrieve ModelA, just search for ModelB. Cake will automatically retrieve related ModelAs for you (see above). You might need to Set::extract() them again, but that might already be sufficient.</p></li>\n<li><p>You can use the above method and combine it with the <a href=\"http://book.cakephp.org/view/474/Containable\" rel=\"nofollow noreferrer\">Containable behaviour</a> to get more control over the results.</p></li>\n<li><p>If all else fails or the above methods simply produce too much overhead, you can still write your own raw SQL with <code>$this->Model->query()</code>. If you stick to the Cake SQL standards (naming tables correctly with <code>FROM model_as AS ModelA</code>) Cake will still post-process your results correctly.</p></li>\n</ul>\n\n<p>Hope this sends you in the right direction.</p>\n"
},
{
"answer_id": 508683,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 1,
"selected": true,
"text": "<p>The solution can be achieved with the use of the <code>with</code> operation in habtm array on the model.</p>\n\n<p>Using <code>with</code> you can define the \"middle\" table like: </p>\n\n<pre><code>$habtm = \" ...\n 'with' => 'MakeModel',\n ... \";\n</code></pre>\n\n<p>And internally, in the Model or Controller, you can issue conditions to the <code>find</code> method.</p>\n\n<p>See: <a href=\"http://www.cricava.com/blogs/index.php?blog=6&title=modelizing_habtm_join_tables_in_cakephp_&more=1&c=1&tb=1&pb=1\" rel=\"nofollow noreferrer\">http://www.cricava.com/blogs/index.php?blog=6&title=modelizing_habtm_join_tables_in_cakephp_&more=1&c=1&tb=1&pb=1</a></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
]
| I have a `n...n` structure for two tables, **`makes`** and **`models`**. So far no problem.
In a third table (**`products`**) like:
```
id
make_id
model_id
...
```
My problem is creating a view for products of one specifi **`make`** inside my `ProductsController` containing just that's make models:
I thought this could work:
```
var $uses = array('Make', 'Model');
$this->Make->id = 5; // My Make
$this->Make->find(); // Returns only the make I want with it's Models (HABTM)
$this->Model->find('list'); // Returns ALL models
$this->Make->Model->find('list'); // Returns ALL models
```
So, If I want to use the `list` to pass to my view to create radio buttons I will have to do a `foreach()` in my **`make`** array to find all models titles and create a new array and send to the view via `$this->set()`.
```
$makeArray = $this->Make->find();
foreach ($makeArray['Model'] as $model) {
$modelList[] = $model['title'];
}
$this->set('models', $models)
```
Is there any easier way to get that list without stressing the **`make`** Array. It will be a commom task to develops such scenarios in my application(s).
Thanks in advance for any hint! | The solution can be achieved with the use of the `with` operation in habtm array on the model.
Using `with` you can define the "middle" table like:
```
$habtm = " ...
'with' => 'MakeModel',
... ";
```
And internally, in the Model or Controller, you can issue conditions to the `find` method.
See: <http://www.cricava.com/blogs/index.php?blog=6&title=modelizing_habtm_join_tables_in_cakephp_&more=1&c=1&tb=1&pb=1> |
112,738 | <p>Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? </p>
| [
{
"answer_id": 112756,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's a template class that declares a member variable for the arguments you want to bind and overloads () for the rest of the arguments.</p>\n"
},
{
"answer_id": 113134,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 6,
"selected": true,
"text": "<p>I like this piece of the <code>bind</code> source:</p>\n\n<pre><code>template<class R, class F, class L> class bind_t\n{\npublic:\n\n typedef bind_t this_type;\n\n bind_t(F f, L const & l): f_(f), l_(l) {}\n\n#define BOOST_BIND_RETURN return\n#include <boost/bind/bind_template.hpp>\n#undef BOOST_BIND_RETURN\n\n};\n</code></pre>\n\n<p>Tells you almost all you need to know, really.</p>\n\n<p>The <code>bind_template</code> header expands to a list of inline <code>operator()</code> definitions. For example, the simplest:</p>\n\n<pre><code>result_type operator()()\n{\n list0 a;\n BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);\n}\n</code></pre>\n\n<p>We can see the <code>BOOST_BIND_RETURN</code> macro expands to <code>return</code> at this point so the line is more like <code>return l_(type...)</code>.</p>\n\n<p>The one parameter version is here:</p>\n\n<pre><code>template<class A1> result_type operator()(A1 & a1)\n{\n list1<A1 &> a(a1);\n BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);\n}\n</code></pre>\n\n<p>It's pretty similar.</p>\n\n<p>The <code>listN</code> classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded <code>operator()</code> that calls the mysterious <code>unwrap</code> function. Ignoring some compiler specific overloads, it doesn't do a lot:</p>\n\n<pre><code>// unwrap\n\ntemplate<class F> inline F & unwrap(F * f, long)\n{\n return *f;\n}\n\ntemplate<class F> inline F & unwrap(reference_wrapper<F> * f, int)\n{\n return f->get();\n}\n\ntemplate<class F> inline F & unwrap(reference_wrapper<F> const * f, int)\n{\n return f->get();\n}\n</code></pre>\n\n<p>The naming convention seems to be: <code>F</code> is the type of the function parameter to <code>bind</code>. <code>R</code> is the return type. <code>L</code> tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much.</p>\n"
},
{
"answer_id": 1839773,
"author": "Decoder",
"author_id": 223820,
"author_profile": "https://Stackoverflow.com/users/223820",
"pm_score": 2,
"selected": false,
"text": "<p>By the way, if <code>bind_t</code> is collapsed and simplified by including <code>boost/bind/bind_template.hpp</code> , it becomes easier to understand like the following :</p>\n\n<pre><code>template<class R, class F, class L> \nclass bind_t\n{\n public:\n\n typedef bind_t this_type;\n\n bind_t(F f, L const & l): f_(f), l_(l) {}\n\n typedef typename result_traits<R, F>::type result_type;\n ...\n template<class A1> \n result_type operator()(A1 & a1)\n {\n list1<A1 &> a(a1);\n return l_(type<result_type>(), f_, a, 0);\n }\n private:\n F f_;\n L l_;\n\n};\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
| Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? | I like this piece of the `bind` source:
```
template<class R, class F, class L> class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
#define BOOST_BIND_RETURN return
#include <boost/bind/bind_template.hpp>
#undef BOOST_BIND_RETURN
};
```
Tells you almost all you need to know, really.
The `bind_template` header expands to a list of inline `operator()` definitions. For example, the simplest:
```
result_type operator()()
{
list0 a;
BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
```
We can see the `BOOST_BIND_RETURN` macro expands to `return` at this point so the line is more like `return l_(type...)`.
The one parameter version is here:
```
template<class A1> result_type operator()(A1 & a1)
{
list1<A1 &> a(a1);
BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
```
It's pretty similar.
The `listN` classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded `operator()` that calls the mysterious `unwrap` function. Ignoring some compiler specific overloads, it doesn't do a lot:
```
// unwrap
template<class F> inline F & unwrap(F * f, long)
{
return *f;
}
template<class F> inline F & unwrap(reference_wrapper<F> * f, int)
{
return f->get();
}
template<class F> inline F & unwrap(reference_wrapper<F> const * f, int)
{
return f->get();
}
```
The naming convention seems to be: `F` is the type of the function parameter to `bind`. `R` is the return type. `L` tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much. |
112,768 | <p>(ClientCookie is a module for (automatic) cookie-handling: <a href="http://wwwsearch.sourceforge.net/ClientCookie" rel="nofollow noreferrer">http://wwwsearch.sourceforge.net/ClientCookie</a>)</p>
<pre><code># I encode the data I'll be sending:
data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})
# And I send it and read the page:
page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data)
output = page.read()
</code></pre>
<p>The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?</p>
<p>Any help would be greatly appreciated! Thanks!</p>
| [
{
"answer_id": 112819,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 3,
"selected": true,
"text": "<p>Have you tried fetching the login page first?</p>\n\n<p>I would suggest using <a href=\"https://addons.mozilla.org/en-US/firefox/addon/966\" rel=\"nofollow noreferrer\">Tamper Data</a> to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly.</p>\n\n<p>That's the approach I used when writing the following, extracted from a script which needs to login to an Invision Power Board forum, using cookielib and urllib2 - you may find it useful as a reference.</p>\n\n<pre><code>import cookielib\nimport logging\nimport sys\nimport urllib\nimport urllib2\n\ncookies = cookielib.LWPCookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))\nurllib2.install_opener(opener)\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',\n 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',\n 'Accept-Language': 'en-gb,en;q=0.5',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',\n}\n\n# Fetch the login page to set initial cookies\nurllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))\n\n# Login so we can access the Off Topic forum\nlogin_headers = headers.copy()\nlogin_headers.update({\n 'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',\n 'Content-Type': 'application/x-www-form-urlencoded',\n})\nhtml = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',\n urllib.urlencode({\n 'referer': 'http://www.rllmukforum.com/index.php?',\n 'UserName': RLLMUK_USERNAME,\n 'PassWord': RLLMUK_PASSWORD,\n }),\n login_headers)).read()\nif 'The following errors were found' in html:\n logging.error('RLLMUK login failed')\n logging.info(html)\n sys.exit(1)\n</code></pre>\n"
},
{
"answer_id": 112895,
"author": "jacobian",
"author_id": 18184,
"author_profile": "https://Stackoverflow.com/users/18184",
"pm_score": 0,
"selected": false,
"text": "<p>I'd recommend taking a look at the <a href=\"http://wwwsearch.sourceforge.net/mechanize/\" rel=\"nofollow noreferrer\">mechanize</a> library; it's designed for precisely this type of task. It's also far easier than doing it by hand.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| (ClientCookie is a module for (automatic) cookie-handling: <http://wwwsearch.sourceforge.net/ClientCookie>)
```
# I encode the data I'll be sending:
data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})
# And I send it and read the page:
page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data)
output = page.read()
```
The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?
Any help would be greatly appreciated! Thanks! | Have you tried fetching the login page first?
I would suggest using [Tamper Data](https://addons.mozilla.org/en-US/firefox/addon/966) to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly.
That's the approach I used when writing the following, extracted from a script which needs to login to an Invision Power Board forum, using cookielib and urllib2 - you may find it useful as a reference.
```
import cookielib
import logging
import sys
import urllib
import urllib2
cookies = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language': 'en-gb,en;q=0.5',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}
# Fetch the login page to set initial cookies
urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))
# Login so we can access the Off Topic forum
login_headers = headers.copy()
login_headers.update({
'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',
'Content-Type': 'application/x-www-form-urlencoded',
})
html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',
urllib.urlencode({
'referer': 'http://www.rllmukforum.com/index.php?',
'UserName': RLLMUK_USERNAME,
'PassWord': RLLMUK_PASSWORD,
}),
login_headers)).read()
if 'The following errors were found' in html:
logging.error('RLLMUK login failed')
logging.info(html)
sys.exit(1)
``` |
112,770 | <p>Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?</p>
| [
{
"answer_id": 112773,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>Look up the <a href=\"http://svnbook.red-bean.com/en/1.0/re27.html\" rel=\"noreferrer\">svn switch</a> command. In particular, the <code>--relocate</code> option is what you want.</p>\n"
},
{
"answer_id": 112847,
"author": "Dara Kong",
"author_id": 11292,
"author_profile": "https://Stackoverflow.com/users/11292",
"pm_score": 1,
"selected": false,
"text": "<p>SVN command line - see <a href=\"http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.switch.html\" rel=\"nofollow noreferrer\">svn switch</a></p>\n\n<p>TortoiseSVN - see <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html\" rel=\"nofollow noreferrer\">relocate dialog</a></p>\n"
},
{
"answer_id": 113820,
"author": "Mauli",
"author_id": 917,
"author_profile": "https://Stackoverflow.com/users/917",
"pm_score": 5,
"selected": true,
"text": "<p>Example:</p>\n\n<pre><code>svn switch --relocate \\\n http://svn.example.com/path/to/repository/path/within/repository \\\n http://svnnew.example.com/new/repository/path/within/repository\n</code></pre>\n\n<p>One thing which is to remember, lets assume you checked out the project \"path/within/repository\" then you have to go to the <strong>root of your working copy</strong>, and execute the above command. it is <strong>NOT</strong> enough just to use the repository root (as in <em>svn switch --relocate <a href=\"http://svn.example.com/path/to/repository/\" rel=\"noreferrer\">http://svn.example.com/path/to/repository/</a> <a href=\"http://svnnew.example.com/new/repository/\" rel=\"noreferrer\">http://svnnew.example.com/new/repository/</a></em>), because that wouldn't work.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150/"
]
| Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository? | Example:
```
svn switch --relocate \
http://svn.example.com/path/to/repository/path/within/repository \
http://svnnew.example.com/new/repository/path/within/repository
```
One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the **root of your working copy**, and execute the above command. it is **NOT** enough just to use the repository root (as in *svn switch --relocate <http://svn.example.com/path/to/repository/> <http://svnnew.example.com/new/repository/>*), because that wouldn't work. |
112,775 | <p>Is it possible to have a <code>MySQLi prepared statement</code> within the <code>fetch()</code> call of a previous statement? If not, what's the best way around it?</p>
<p>Example code:</p>
<pre><code>if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item + $magic;
if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
$stmt2->bind_param("is", $itemID, $itemSummary);
$stmt2->execute();
$stmt2->close();
}
}
}
</code></pre>
| [
{
"answer_id": 112800,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": "<p>You should be able to do that, although you make have to start a second connection. </p>\n"
},
{
"answer_id": 1675327,
"author": "peterbriers",
"author_id": 202803,
"author_profile": "https://Stackoverflow.com/users/202803",
"pm_score": 2,
"selected": false,
"text": "<p>Or use <a href=\"http://php.net/manual/en/mysqli.store-result.php\" rel=\"nofollow noreferrer\"><code>store_result</code></a>.</p>\n"
},
{
"answer_id": 11923140,
"author": "Etherealone",
"author_id": 1576556,
"author_profile": "https://Stackoverflow.com/users/1576556",
"pm_score": 4,
"selected": false,
"text": "<p>This is the single connection way:</p>\n\n<pre><code>if($stmt = $link->prepare(\"SELECT item FROM data WHERE id = ?\")) {\n $stmt->bind_param(\"i\", $id);\n $stmt->execute();\n $stmt->store_result(); // <-- this\n $stmt->bind_result($item);\n while( $stmt->fetch() ) {\n /* Other code here */\n $itemSummary = $item + $magic;\n if($stmt2 = $link->prepare(\"INSERT INTO summaries (itemID, summary) VALUES (?, ?)\")) {\n $stmt2->bind_param(\"is\", $itemID, $itemSummary);\n $stmt2->execute();\n $stmt2->store_result(); // <-- this\n /*DO WHATEVER WITH STMT2*/\n $stmt2->close();\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6305/"
]
| Is it possible to have a `MySQLi prepared statement` within the `fetch()` call of a previous statement? If not, what's the best way around it?
Example code:
```
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item + $magic;
if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
$stmt2->bind_param("is", $itemID, $itemSummary);
$stmt2->execute();
$stmt2->close();
}
}
}
``` | You should be able to do that, although you make have to start a second connection. |
112,796 | <p>Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window:</p>
<pre><code>Variable Value Summary
jsonDict 0x45c540 4 key/value pairs
NSObject {...}
isa 0xa06e0720
</code></pre>
<p>I was expecting it to show me each element of the dictionary (similar to an array variable). </p>
| [
{
"answer_id": 112808,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 8,
"selected": true,
"text": "<p>In the gdb window you can use <code>po</code> to inspect the object.</p>\n\n<p>given:</p>\n\n<pre><code>NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];\n[dict setObject:@\"foo\" forKey:@\"bar\"];\n[dict setObject:@\"fiz\" forKey:@\"buz\"];\n</code></pre>\n\n<p>setting a breakpoint after the objects are added you can inspect what is in the dictionary</p>\n\n<pre><code>(gdb) po dict\n{\n bar = foo;\n buz = fiz;\n}\n</code></pre>\n\n<p>Of course these are <code>NSString</code> objects that print nicely. YMMV with other complex objects.</p>\n"
},
{
"answer_id": 114063,
"author": "Jens Ayton",
"author_id": 6443,
"author_profile": "https://Stackoverflow.com/users/6443",
"pm_score": 5,
"selected": false,
"text": "<p>You can right-click any object (ObjC or Core Foundation) variable and select “Print Description to Console” (also in Run->Variables View). This prints the result the obejct’s <code>-debugDescription</code> method, which by default calls <code>-description</code>. Unfortunately, <code>NSDictionary</code> overrides this to produce a bunch of internal data the you generally don’t care about, so in this specific case craigb’s solution is better. </p>\n\n<p>The displayed keys and values also use <code>-description</code>, so if you want useful information about your objects in collections and elsewhere, overriding <code>-description</code> is a must. I generally implement it along these lines, to match the format of the default <code>NSObject</code> implementation:</p>\n\n<pre>-(NSString *) description\n{\n return [NSString stringWithFormat:@\"<%@ %p>{foo: %@}\", [self class], self, [self foo]];\n}</pre>\n"
},
{
"answer_id": 11029942,
"author": "uranpro",
"author_id": 519358,
"author_profile": "https://Stackoverflow.com/users/519358",
"pm_score": 3,
"selected": false,
"text": "<p>You can use CFShow()</p>\n\n<pre><code>NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];\n[dict setObject:@\"foo\" forKey:@\"bar\"];\n[dict setObject:@\"fiz\" forKey:@\"buz\"];\nCFShow(dict);\n</code></pre>\n\n<p>In output you will see</p>\n\n<pre><code>{\n bar = foo;\n buz = fiz;\n}\n</code></pre>\n"
},
{
"answer_id": 13953946,
"author": "user1873574",
"author_id": 1873574,
"author_profile": "https://Stackoverflow.com/users/1873574",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use <a href=\"http://cocoadev.com/wiki/NSLog\" rel=\"nofollow noreferrer\">NSLog</a>.</p>\n<p>Also you can go in Debug area or xcode, then find out <code>All Variables, Registers, Globals and Statics</code> then select your variable. Right click on it. Then select <code>Print description of "...."</code></p>\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 16114195,
"author": "jkatzer",
"author_id": 193292,
"author_profile": "https://Stackoverflow.com/users/193292",
"pm_score": 2,
"selected": false,
"text": "<p>XCode 4.6 has added the following functionality which may be helpful to you</p>\n\n<pre><code>The elements of NSArray and NSDictionary objects can now be inspected in the Xcode debugger\n</code></pre>\n\n<p>Now you can inspect these object types without having to print the entire object in the console. Enjoy!</p>\n\n<p>Source: <a href=\"http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_4_6.html\" rel=\"nofollow\">http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_4_6.html</a></p>\n"
},
{
"answer_id": 20208725,
"author": "Taiko",
"author_id": 661720,
"author_profile": "https://Stackoverflow.com/users/661720",
"pm_score": 1,
"selected": false,
"text": "<p>Click on your dict, then click on the little \"i\" icon, it should do the job :-)\n<img src=\"https://i.stack.imgur.com/CnkOY.png\" alt=\"Xcode5, view the value of a dict\"></p>\n"
},
{
"answer_id": 55249909,
"author": "Pat",
"author_id": 173507,
"author_profile": "https://Stackoverflow.com/users/173507",
"pm_score": 1,
"selected": false,
"text": "<p>If you would like to print these in a breakpoint action in modern XCode (yes, I am 10 years after the original post!) use the following breakpoint expression in a \"Log Message\" action:</p>\n\n<p>@myDictionary.description@</p>\n\n<p>Below is a screenshot of my breakpoint action where the variable event is an NSString and the variable contextData is the NSDictionary that I am logging the contents of:\n<a href=\"https://i.stack.imgur.com/BXtPg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BXtPg.png\" alt=\"\"></a>:</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11292/"
]
| Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window:
```
Variable Value Summary
jsonDict 0x45c540 4 key/value pairs
NSObject {...}
isa 0xa06e0720
```
I was expecting it to show me each element of the dictionary (similar to an array variable). | In the gdb window you can use `po` to inspect the object.
given:
```
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"foo" forKey:@"bar"];
[dict setObject:@"fiz" forKey:@"buz"];
```
setting a breakpoint after the objects are added you can inspect what is in the dictionary
```
(gdb) po dict
{
bar = foo;
buz = fiz;
}
```
Of course these are `NSString` objects that print nicely. YMMV with other complex objects. |
112,812 | <p>How do I access parameters passed into an Oracle Form via a URL.
Eg given the url:</p>
<blockquote>
<p><a href="http://example.com/forms90/f90servlet?config=cust&form=" rel="nofollow noreferrer">http://example.com/forms90/f90servlet?config=cust&form=</a>'a_form'&p1=something&p2=else</p>
</blockquote>
<p>This will launch the 'a_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else')</p>
<p>Does anyone know how I can do this? (Or even if it is/isn't possible?</p>
<p>Thanks</p>
| [
{
"answer_id": 113990,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": true,
"text": "<p>Within Forms you can refer to the parameters p1 an p2 as follows:</p>\n\n<ul>\n<li>:PARAMETER.p1</li>\n<li>:PARAMETER.p2</li>\n</ul>\n\n<p>e.g.</p>\n\n<pre><code>if :PARAMETER.p1 = 'something' then\n do_something;\nend if;\n</code></pre>\n"
},
{
"answer_id": 118225,
"author": "Dave Smylie",
"author_id": 1505600,
"author_profile": "https://Stackoverflow.com/users/1505600",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Tony</p>\n\n<p>That was one part of the problem.</p>\n\n<p>The other needed part I eventually found on oracle.com was the url structure. After all the forms90 parameters (config etc), you need to supply an \"otherparams\" parameter supplying your parameters as a parameter to that. (parameters seperated by '+': eg</p>\n\n<blockquote>\n <p><a href=\"http://server.com/forms90/f90servlet?config=test&otherparams=param1=something+param2=else\" rel=\"nofollow noreferrer\">http://server.com/forms90/f90servlet?config=test&otherparams=param1=something+param2=else</a></p>\n</blockquote>\n\n<p>Thanks</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505600/"
]
| How do I access parameters passed into an Oracle Form via a URL.
Eg given the url:
>
> <http://example.com/forms90/f90servlet?config=cust&form=>'a\_form'&p1=something&p2=else
>
>
>
This will launch the 'a\_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else')
Does anyone know how I can do this? (Or even if it is/isn't possible?
Thanks | Within Forms you can refer to the parameters p1 an p2 as follows:
* :PARAMETER.p1
* :PARAMETER.p2
e.g.
```
if :PARAMETER.p1 = 'something' then
do_something;
end if;
``` |
112,818 | <p>I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed.</p>
<p>The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options. </p>
<p>What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code. </p>
<p>This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user. </p>
<p>Any suggestions on the best way to get this to work would be much appreciated.</p>
| [
{
"answer_id": 112828,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>When it works in debug, is that being used in SharePoint?</p>\n\n<p>Your page and the Sharepoint site might as well be on different servers as far as authentication is concerned -- in order to get the information over you might need to pass it via the QueryString from the webpart if you can -- or you might need to make your own webpart to do this (just put an IFRAME in the part with the src set to your page with the QueryString passing the username).</p>\n\n<p>It does seem that this would be a security issue if you use the name for anything though -- if you are just displaying it, then it's probably fine.</p>\n\n<p>If you actually need to be authenticated, you might need to add authentication into the web.config of the site hosting your standalone page.</p>\n\n<p>edit: I think you'd have better luck putting your page on the same port and server as SharePoint.</p>\n"
},
{
"answer_id": 113235,
"author": "Bryan Friedman",
"author_id": 16985,
"author_profile": "https://Stackoverflow.com/users/16985",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect you will have a hard time specifically querying SharePoint for the currently authenticated username. I can't think of a way to easily access the SharePoint context from a separate web application like you are describing.</p>\n\n<p>I don't know what kind of authentication scheme you are using, but you may want to consider using Kerberos, as I've found that it can make these kinds of scenarios a little easier by allowing for delegation and passing credentials from application to application or server to server. </p>\n"
},
{
"answer_id": 113838,
"author": "Alex Angas",
"author_id": 6651,
"author_profile": "https://Stackoverflow.com/users/6651",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to retrieve the currently authenticated user from the SharePoint context, you need to remain within the SharePoint context. This means hosting your custom web application within SharePoint (see <a href=\"http://msdn.microsoft.com/en-us/library/cc297200.aspx\" rel=\"nofollow noreferrer\" title=\"Deploying ASP.NET Web Applications in the Windows SharePoint Services 3.0 _layouts Folder\">http://msdn.microsoft.com/en-us/library/cc297200.aspx</a>). Then from your custom application reference Microsoft.SharePoint and use the SPContext object to retrieve the user name. For example:</p>\n\n<pre><code>SPContext.Current.Web.CurrentUser.LoginName\n</code></pre>\n\n<p>You can still use the Page Viewer Web Part to reference the URL of the site, now located within the SharePoint context.</p>\n"
},
{
"answer_id": 131561,
"author": "BenB",
"author_id": 11703,
"author_profile": "https://Stackoverflow.com/users/11703",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks heaps for the answers!</p>\n\n<p>Turns out that as long as the asp.net page is using the same URL and port as the Sharepoint site, authentication works across both sites.</p>\n\n<p>The solution is to use a Virtual Directory inside of the sharepoint site and install the asp.net page there.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11703/"
]
| I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed.
The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options.
What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code.
This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user.
Any suggestions on the best way to get this to work would be much appreciated. | If you want to retrieve the currently authenticated user from the SharePoint context, you need to remain within the SharePoint context. This means hosting your custom web application within SharePoint (see [http://msdn.microsoft.com/en-us/library/cc297200.aspx](http://msdn.microsoft.com/en-us/library/cc297200.aspx "Deploying ASP.NET Web Applications in the Windows SharePoint Services 3.0 _layouts Folder")). Then from your custom application reference Microsoft.SharePoint and use the SPContext object to retrieve the user name. For example:
```
SPContext.Current.Web.CurrentUser.LoginName
```
You can still use the Page Viewer Web Part to reference the URL of the site, now located within the SharePoint context. |
112,861 | <p>According to the documentation the return value from a slot doesn't mean anything.<br>
Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do?</p>
<hr>
<p>Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int.</p>
<pre><code>case 7: message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;
</code></pre>
| [
{
"answer_id": 112960,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 4,
"selected": false,
"text": "<p>Looking through the Qt source it seems that when a slot is called from QMetaObject::invokeMethod the return type can be specified and the return value obtained. (Have a look at invokeMethod in the Qt help)</p>\n\n<p>I could not find many examples of this actually being used in the Qt source. One I found was</p>\n\n<pre><code>bool QAbstractItemDelegate::helpEvent \n</code></pre>\n\n<p>which is a slot with a return type and is called from</p>\n\n<pre><code>QAbstractItemView::viewportEvent\n</code></pre>\n\n<p>using invokeMethod. </p>\n\n<p>I think that the return value for a slot is only available when the function is called directly (when it is a normal C++ function) or when using invokeMethod. I think this is really meant for internal Qt functions rather than for normal use in programs using Qt.</p>\n\n<p>Edit: \nFor the sample case:</p>\n\n<pre><code>case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])), *reinterpret_cast< int(*)>(_a[2])));\nif (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;\n</code></pre>\n\n<p>the vector _a is a list of arguments that is passed to qt_metacall. This is passed by QMetaObject::invokeMethod. So the return value in the moc generated code is saved and passed back to the caller. So for normal signal-slot interactions the return value is not used for anything at all. However, the mechanism exists so that return values from slots can be accessed if the slot is called via invokeMethod.</p>\n"
},
{
"answer_id": 154091,
"author": "Terence Simpson",
"author_id": 22395,
"author_profile": "https://Stackoverflow.com/users/22395",
"pm_score": 4,
"selected": false,
"text": "<p>The return value is only useful if you want to call the slot as a normal member function:\n<code><pre>class MyClass : public QObject {\n Q_OBJECT\npublic:\n MyClass(QObject* parent);\n void Something();\npublic Q_SLOTS:\n int Other();\n};</p>\n\n<p>void MyClass::Something() {\n int res = this->Other();\n ...\n}\n</pre></code>\n<strong>Edit:</strong> It seems that's not the only way the return value can be used, the QMetaObject::invokeMethod method can be used to call a slot and get a return value. Although it seems like it's a bit more complicated to do.</p>\n"
},
{
"answer_id": 2177532,
"author": "FxIII",
"author_id": 263595,
"author_profile": "https://Stackoverflow.com/users/263595",
"pm_score": 3,
"selected": false,
"text": "<p>It is Very useful when you deal with dynamic language such qtscript JavaScript QtPython and so on. With this language/bindings, you can use C++ QObject dinamically using the interface provided by MetaObject. As you probably know, just signals and slots are parsed by moc and generate MetaObject description. So if you are using a C++ QObject from a javascript binding, you will be able to call just slots and you will want the return value. Often Qt bindings for dynamic languages provides some facility to acces to normal method, but the process is definitely more triky.</p>\n"
},
{
"answer_id": 4625945,
"author": "Macke",
"author_id": 72312,
"author_profile": "https://Stackoverflow.com/users/72312",
"pm_score": 3,
"selected": false,
"text": "<p>All slots are exposed in QMetaObject, where the object can be accessed via a reflective interface. </p>\n\n<p>For instance, <a href=\"http://doc.qt.io/qt-4.8/qmetaobject.html#invokeMethod\" rel=\"nofollow\">QMetaObject::invokeMethod()</a> takes a <code>QGenericReturnArgument</code> parameter. So I belive this is not for explicit slot usage, but rather for dynamic invocation of methods in general. (There are other ways to expose methods to QMetaObject than making them into slots.)</p>\n\n<p>The <code>invokeMethod</code> function is, for example, used by various dynamic languages such as QML and Javascript to call methods of <code>QObject:s</code>. (There's also a Python-Qt bridge called <a href=\"http://pythonqt.sourceforge.net/\" rel=\"nofollow\">PythonQt</a> which uses this. Not to be confused with <a href=\"http://wiki.python.org/moin/PyQt4\" rel=\"nofollow\">PyQt</a>, which is a full wrapper.)</p>\n\n<p>The return value is used when making syncrhonous calls across threads inside a Qt application (supported via invokeMethod and setting connection type to <code>Qt::BlockingQueuedConnection</code>, which has the following documentation:</p>\n\n<blockquote>\n <p>Same as QueuedConnection, except the current thread blocks until the\n slot returns.\n This connection type should only be used where the emitter and receiver\n are in\n different threads. Note: Violating this rule can cause your application\n to deadlock.</p>\n</blockquote>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
]
| According to the documentation the return value from a slot doesn't mean anything.
Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do?
---
Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int.
```
case 7: message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;
``` | Looking through the Qt source it seems that when a slot is called from QMetaObject::invokeMethod the return type can be specified and the return value obtained. (Have a look at invokeMethod in the Qt help)
I could not find many examples of this actually being used in the Qt source. One I found was
```
bool QAbstractItemDelegate::helpEvent
```
which is a slot with a return type and is called from
```
QAbstractItemView::viewportEvent
```
using invokeMethod.
I think that the return value for a slot is only available when the function is called directly (when it is a normal C++ function) or when using invokeMethod. I think this is really meant for internal Qt functions rather than for normal use in programs using Qt.
Edit:
For the sample case:
```
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])), *reinterpret_cast< int(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;
```
the vector \_a is a list of arguments that is passed to qt\_metacall. This is passed by QMetaObject::invokeMethod. So the return value in the moc generated code is saved and passed back to the caller. So for normal signal-slot interactions the return value is not used for anything at all. However, the mechanism exists so that return values from slots can be accessed if the slot is called via invokeMethod. |
112,892 | <p>How would retrieve all customer's birthdays for a given month in SQL? What about MySQL?
I was thinking of using the following with SQL server.</p>
<pre><code>select c.name
from cust c
where datename(m,c.birthdate) = datename(m,@suppliedDate)
order by c.name
</code></pre>
| [
{
"answer_id": 112894,
"author": "rickripe",
"author_id": 20169,
"author_profile": "https://Stackoverflow.com/users/20169",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I would use DATEPART instead of DATENAME as DATENAME is open to interpretation depending on locale.</p>\n"
},
{
"answer_id": 112900,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": true,
"text": "<p>don't forget the 29th February...</p>\n\n<pre><code>SELECT c.name\nFROM cust c\nWHERE (\n MONTH(c.birthdate) = MONTH(@suppliedDate)\n AND DAY(c.birthdate) = DAY(@suppliedDate)\n) OR (\n MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29\n AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1\n AND (YEAR(@suppliedDate) % 4 = 0) AND ((YEAR(@suppliedDate) % 100 != 0) OR (YEAR(@suppliedDate) % 400 = 0))\n)\n</code></pre>\n"
},
{
"answer_id": 113062,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 1,
"selected": false,
"text": "<p>I'd actually be tempted to add a birthmonth column, if you expect the list of customers to get very large. So far, the queries I've seen (including the example) will require a full table scan, as you're passing the the data column to a function and comparing that. If the table is of any size, this could take a fair amount of time since no index is going to be able to help.</p>\n\n<p>So, I'd add the birthmonth column (indexed) and just do (with possible MySQLisms):</p>\n\n<pre><code>SELECT name\nFROM cust\nWHERE birthmonth = MONTH(NOW())\nORDER BY name;\n</code></pre>\n\n<p>Of course, it should be easy to set the birthmonth column either with a trigger or with your client code.</p>\n"
},
{
"answer_id": 113974,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<p>If you're asking for all birthdays in a given <em>month</em>, then you should supply the <em>month</em>, not a <em>date</em>: </p>\n\n<pre><code>SELECT c.name\nFROM cust c\nWHERE datepart(m,c.birthdate) = @SuppliedMonth\n</code></pre>\n"
},
{
"answer_id": 58663183,
"author": "ILIAS M. DOLAPO",
"author_id": 9050759,
"author_profile": "https://Stackoverflow.com/users/9050759",
"pm_score": 0,
"selected": false,
"text": "<pre><code> SELECT * FROM tbl_Employee WHERE DATEADD( Year, DATEPART( Year, GETDATE()) - DATEPART( Year, DOB), DOB) BETWEEN CONVERT( DATE, GETDATE()) AND CONVERT( DATE, GETDATE() + 30)\n</code></pre>\n\n<p>This can be use to get the upcoming Birthday by days</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618/"
]
| How would retrieve all customer's birthdays for a given month in SQL? What about MySQL?
I was thinking of using the following with SQL server.
```
select c.name
from cust c
where datename(m,c.birthdate) = datename(m,@suppliedDate)
order by c.name
``` | don't forget the 29th February...
```
SELECT c.name
FROM cust c
WHERE (
MONTH(c.birthdate) = MONTH(@suppliedDate)
AND DAY(c.birthdate) = DAY(@suppliedDate)
) OR (
MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29
AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1
AND (YEAR(@suppliedDate) % 4 = 0) AND ((YEAR(@suppliedDate) % 100 != 0) OR (YEAR(@suppliedDate) % 400 = 0))
)
``` |
112,897 | <p>The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a <code>file > 4GB</code>?</p>
<pre><code>fpos_t currentpos;
sok=fseek(fp,0,SEEK_END);
assert(sok==0,"Seek error!");
fgetpos(fp,&currentpos);
m_filesize=currentpos;
</code></pre>
| [
{
"answer_id": 112910,
"author": "Captain Segfault",
"author_id": 18408,
"author_profile": "https://Stackoverflow.com/users/18408",
"pm_score": 1,
"selected": false,
"text": "<p>On linux, at least, you could use lseek64 instead of fseek.</p>\n"
},
{
"answer_id": 112913,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 2,
"selected": false,
"text": "<p>(stolen from the glibc manual)</p>\n\n<p><code>int fgetpos64 (FILE *stream, fpos64_t *position)</code></p>\n\n<p>This function is similar to fgetpos but the file position is returned in a variable of type <code>fpos64_t</code> to which position points.</p>\n\n<p>If the sources are compiled with <code>_FILE_OFFSET_BITS == 64</code> on a 32 bits machine this function is available under the name <code>fgetpos</code> and so transparently replaces the old interface. </p>\n"
},
{
"answer_id": 112923,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 2,
"selected": false,
"text": "<p>Stat is always better than fseek to determine file size, it will fail safely on things that aren't a file.\n64 bit filesizes is an operating specific thing, on gcc you can put \"64\" on the end of the commands, or you can force it to make all the standard calls 64 by default. See your compiler manual for details.</p>\n"
},
{
"answer_id": 112942,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<p>This code works for me in Linux:</p>\n\n<pre><code>int64_t bigFileSize(const char *path)\n{\n struct stat64 S;\n\n if(-1 == stat64(path, &S))\n {\n printf(\"Error!\\r\\n\");\n return -1;\n }\n\n return S.st_size;\n}\n</code></pre>\n"
},
{
"answer_id": 113073,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 4,
"selected": true,
"text": "<p>If you're in Windows, you want <a href=\"http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx\" rel=\"noreferrer\">GetFileSizeEx (MSDN)</a>. The return value is a 64bit int.</p>\n\n<p>On linux <a href=\"http://www.manpagez.com/man/2/stat64/\" rel=\"noreferrer\">stat64 (manpage)</a> is correct. fstat if you're working with a FILE*.</p>\n"
},
{
"answer_id": 3399458,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 3,
"selected": false,
"text": "<p>Ignore all the answers with \"64\" appearing in them. On Linux, you should add <code>-D_FILE_OFFSET_BITS=64</code> to your CFLAGS and use the <code>fseeko</code> and <code>ftello</code> functions which take/return <code>off_t</code> values instead of <code>long</code>. These are not part of C but POSIX. Other (non-Linux) POSIX systems may need different options to ensure that <code>off_t</code> is 64-bit; check your documentation.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
]
| The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a `file > 4GB`?
```
fpos_t currentpos;
sok=fseek(fp,0,SEEK_END);
assert(sok==0,"Seek error!");
fgetpos(fp,¤tpos);
m_filesize=currentpos;
``` | If you're in Windows, you want [GetFileSizeEx (MSDN)](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx). The return value is a 64bit int.
On linux [stat64 (manpage)](http://www.manpagez.com/man/2/stat64/) is correct. fstat if you're working with a FILE\*. |
112,964 | <p>Ubuntu has 8 run levels (0-6 and S), I want to add the run level 7.</p>
<p>I have done the following:</p>
<p>1.- Created the folder <strong>/etc/rc7.d/</strong>, which contains some symbolic links to <strong>/etc/init.d/</strong></p>
<p>2.- Created the file <strong>/etc/event.d/rc7</strong> This is its content:</p>
<pre><code># rc7 - runlevel 7 compatibility
#
# This task runs the old sysv-rc runlevel 7 ("multi-user") scripts. It
# is usually started by the telinit compatibility wrapper.
start on runlevel 7
stop on runlevel [!7]
console output
script
set $(runlevel --set 7 || true)
if [ "$1" != "unknown" ]; then
PREVLEVEL=$1
RUNLEVEL=$2
export PREVLEVEL RUNLEVEL
fi
exec /etc/init.d/rc 7
end script
</code></pre>
<p>I thought that would be enough, but <strong>telinit 7</strong> still throws this error: <em>telinit: illegal runlevel: 7</em></p>
| [
{
"answer_id": 113005,
"author": "Zathrus",
"author_id": 16220,
"author_profile": "https://Stackoverflow.com/users/16220",
"pm_score": 3,
"selected": true,
"text": "<p>You cannot; the runlevels are hardcoded into the utilities. But why do you need to? Runlevel 4 is essentially unused. And while it's not the best idea, you could repurpose either runlevel 3 or runlevel 5 depending on if you always/never use X.</p>\n\n<p>Note that some *nix systems have support for more than 6 runlevels, but Linux is not one of them.</p>\n"
},
{
"answer_id": 113026,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure how to add them (never needed to), but I'm pretty sure <code>/etc/inittab</code> is where you'd add runlevels.</p>\n\n<p>Although I'd have to agree with Zathrus that other runlevels are available but unused. On Debian, only 1 and 2 are used, really. I'm not sure how Ubuntu has it set up, though. However, if you have a specific purpose, it should be possible to do. I've just never had to.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7852/"
]
| Ubuntu has 8 run levels (0-6 and S), I want to add the run level 7.
I have done the following:
1.- Created the folder **/etc/rc7.d/**, which contains some symbolic links to **/etc/init.d/**
2.- Created the file **/etc/event.d/rc7** This is its content:
```
# rc7 - runlevel 7 compatibility
#
# This task runs the old sysv-rc runlevel 7 ("multi-user") scripts. It
# is usually started by the telinit compatibility wrapper.
start on runlevel 7
stop on runlevel [!7]
console output
script
set $(runlevel --set 7 || true)
if [ "$1" != "unknown" ]; then
PREVLEVEL=$1
RUNLEVEL=$2
export PREVLEVEL RUNLEVEL
fi
exec /etc/init.d/rc 7
end script
```
I thought that would be enough, but **telinit 7** still throws this error: *telinit: illegal runlevel: 7* | You cannot; the runlevels are hardcoded into the utilities. But why do you need to? Runlevel 4 is essentially unused. And while it's not the best idea, you could repurpose either runlevel 3 or runlevel 5 depending on if you always/never use X.
Note that some \*nix systems have support for more than 6 runlevels, but Linux is not one of them. |
112,977 | <p>I want to implement Generics in my Page Class like :</p>
<pre><code>Public Class MyClass(Of TheClass)
Inherits System.Web.UI.Page
</code></pre>
<p>But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ?</p>
| [
{
"answer_id": 113080,
"author": "Costo",
"author_id": 1130,
"author_profile": "https://Stackoverflow.com/users/1130",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure to fully understand what you want to do.\nIf you want something like a generic Page, you can use a generic BasePage and put your generic methods into that BasePage:</p>\n\n<pre><code>Partial Public Class MyPage\n Inherits MyGenericBasePage(Of MyType)\n\nEnd Class\n\nPublic Class MyGenericBasePage(Of T As New)\n Inherits System.Web.UI.Page\n\n Public Function MyGenericMethod() As T\n Return New T()\n End Function\n\nEnd Class\n\nPublic Class MyType\n\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 113136,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 0,
"selected": false,
"text": "<p>The answer that says to derive a type from the generic type is a good one. However, if your solution involves grabbing a page based upon a type determined at runtime then you should be able to handle the PreRequestHandlerExecute event on the current HttpApplication.</p>\n\n<p>This event is called just before a Request is forwarded to a Handler, so I believe you can inject your page into the HttpContext.Current.Handler property. Then you can create the page however you wish.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to implement Generics in my Page Class like :
```
Public Class MyClass(Of TheClass)
Inherits System.Web.UI.Page
```
But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ? | I'm not sure to fully understand what you want to do.
If you want something like a generic Page, you can use a generic BasePage and put your generic methods into that BasePage:
```
Partial Public Class MyPage
Inherits MyGenericBasePage(Of MyType)
End Class
Public Class MyGenericBasePage(Of T As New)
Inherits System.Web.UI.Page
Public Function MyGenericMethod() As T
Return New T()
End Function
End Class
Public Class MyType
End Class
``` |
112,983 | <p>I want to display data like the following:</p>
<pre><code> Title Subject Summary Date
</code></pre>
<p>So my <code>HTML</code> looks like:</p>
<pre><code><div class="title"></div>
<div class="subject"></div>
<div class="summary"></div>
<div class="date"></div>
</code></pre>
<p>The problem is, all the text doesn't appear on a single line. I tried adding <code>display="block"</code> but that doesn't seem to work.</p>
<p>What am I doing wrong here?</p>
<p><strong>Important:</strong> In this instance I dont want to use a <code>table</code> element but stick with <code>div</code> tags.</p>
| [
{
"answer_id": 112994,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 5,
"selected": false,
"text": "<p>It looks like you're wanting to display a table, right? So go ahead and use the <table> tag.</p>\n"
},
{
"answer_id": 112995,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 3,
"selected": false,
"text": "<p>Is there a reason to not use tables? If you're displaying tabular data, it's best to use tables - that's what they're designed for.</p>\n\n<p>To answer your question, the best way is probably to assign a fixed width to each element, and set float:left. You'll need to have either a dummy element at the end that has clear:both, or you'll have to put clear:both on the first element in each row. This method is still not fool-proof, if the contents of one cell forces the div to be wider, it will not resize the whole column, only that cell. You maybe can avoid the resizing by using overflow:auto or overflow:hidden, but this won't work like regular tables at all.</p>\n"
},
{
"answer_id": 112997,
"author": "Matthew Encinas",
"author_id": 14433,
"author_profile": "https://Stackoverflow.com/users/14433",
"pm_score": 0,
"selected": false,
"text": "<p>For the text to appear on a single line you would have to use display=\"inline\"</p>\n\n<p>Moreover, you should really use lists to achieve this effect</p>\n\n<pre><code><ul class=\"headers\">\n <li>Title</li>\n <li>Subject</li>\n <li>Summary</li>\n <li>Date</li>\n</ul>\n</code></pre>\n\n<p>The style would look like this:</p>\n\n<p>.headers{padding:0; margin:0}</p>\n\n<p>.headers li{display:inline; padding:0 10px} /<em>The padding would control the space on the sides of the text in the header</em>/</p>\n"
},
{
"answer_id": 113021,
"author": "da5id",
"author_id": 14979,
"author_profile": "https://Stackoverflow.com/users/14979",
"pm_score": 3,
"selected": false,
"text": "<p>If there's a legitimate reason to not use a table then you could give each div a width and then float it. i.e.</p>\n\n<pre><code>div.title {\n width: 150 px;\n float: left;\n}\n</code></pre>\n"
},
{
"answer_id": 113034,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": false,
"text": "<p>I would use the following markup:</p>\n\n<pre><code><table>\n <tr>\n <th>Title</th>\n <th>Subject</th>\n <th>Summary</th>\n <th>Date</th>\n </tr>\n <!-- Data rows -->\n</table>\n</code></pre>\n\n<p>One other thing to keep in mind with all of these div and list based layouts, even the ones that specify fixed widths, is that if you have a bit of text that is wider than the width (say, a url), the layout will break. The nice thing about tables for tabular data is that they actually have the notion of a column, which no other html construct has.</p>\n\n<p>Even if this site has some things, like the front page, that are implemented with divs, I would argue that tabular data (such as votes, responses, title, etc) SHOULD be in a table. People that push divs tend to do it for semantic markup. You are pursuing the opposite of this.</p>\n"
},
{
"answer_id": 113037,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>display:block garauntees that the elements will <em>not</em> appear on the same line. Floating for layout is abuse just like tables for layout is abuse (but for the time being, it's necessary abuse). The only way to garauntee that they all appear on the same line is to use a table tag. That, or display:inline, and use only &nbsp; (Non-Breaking Space) between your elements and words, instead of a normal space. The &nbsp; will help you prevent word wrapping.</p>\n\n<p>But yea, if there's not a legitimate reason for avoiding tables, use tables for tabular data. That's what they're for.</p>\n"
},
{
"answer_id": 113048,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need to make sure that all your \"cells\" float either left or right (depending on their internal ordering), and they also need a fix width.</p>\n\n<p>Also, make sure that their \"row\" has a fixed width which is equal to the sum of the cell widths + margin + padding.</p>\n\n<p>Lastly make sure there is a fixed width on the \"table\" level div, which is the sum of the row width + margin + padding.</p>\n\n<p>But if you want to show tabular data you really should use a table, some browsers (more common with previous generation) handle floats, padding and margin differently (remember the famous IE 6 bug which doubled the margin?).</p>\n\n<p>There's been plenty of other questions on here about when to use and when not to use tables which may help explain when and where to uses divs and tables.</p>\n"
},
{
"answer_id": 113049,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>or indeed this, which is very literally using tables for tabular data:\n<a href=\"https://stackoverflow.com/badges\">https://stackoverflow.com/badges</a></p>\n"
},
{
"answer_id": 113058,
"author": "stalepretzel",
"author_id": 1615,
"author_profile": "https://Stackoverflow.com/users/1615",
"pm_score": 5,
"selected": false,
"text": "<p>I don't mean to sound patronizing; if I do, I've misunderstood you and I'm sorry.</p>\n\n<p>Most people frown upon tables because people use them for the wrong reason. Often, people use huge tables to position things in their website. <em>This</em> is what divs should be used for. Not tables!</p>\n\n<p>However, if you want to display <em>tabular data</em>, such as a list of football teams, wins, losses, and ties, you should most definitely use tables. It's almost unheard of (although not impossible) to use divs for this.</p>\n\n<p>Just remember, if it's for displaying data, you can definitely use a table!</p>\n"
},
{
"answer_id": 113094,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>Just to illustrate the remarks of the previous answers urging you to use table instead of div for <em>tabular</em> data:</p>\n\n<p><strong><a href=\"http://icant.co.uk/csstablegallery/\" rel=\"nofollow noreferrer\">CSS Table gallery</a></strong> is a great way to display beautiful tables in many many different visual styles.</p>\n"
},
{
"answer_id": 113119,
"author": "Jeffrey04",
"author_id": 5742,
"author_profile": "https://Stackoverflow.com/users/5742",
"pm_score": 2,
"selected": false,
"text": "<p>In the age of CSS frameworks, I really don't see a point of drifting away from table tag completely. While it is now possible to do <code>display: table-*</code> for whatever element you like, but table is still a preferred tag to format data in tabular form (not forgetting it is more semantically correct). Just pick one of the popular CSS framework to make tabular data looks nice instead of hacking the presentation of <code><div></code> tags to achieve whatever it is not designed to do.</p>\n\n<hr>\n\n<pre><code>display: block\n</code></pre>\n\n<p>will certainly not work, try </p>\n\n<pre><code>display: inline\n</code></pre>\n\n<p>or float everything to the left then position them accordingly</p>\n\n<p>but if you have tabular data, then it is the best to markup in <code><table></code> tag</p>\n\n<p>some reference: <a href=\"http://www.sitepoint.com/blogs/2008/09/09/rowspans-colspans-in-css-tables/\" rel=\"nofollow noreferrer\">from sitepoint</a></p>\n"
},
{
"answer_id": 113161,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 0,
"selected": false,
"text": "<p>I asked a similar question a while ago <a href=\"https://stackoverflow.com/questions/42169/if-you-were-programming-a-calendar-in-html-would-you-use-table-tags-or-div-tags\">Calendar in HTML</a> and everyone told me to use tables too. <p> If you have made an igoogle home page, just yoink their code. \nI made a system of columns and sections within the columns for a page. Notice with google you can't have an infinite number of columns and that offends our sensibilities as object people. Here's some of my findings:</p>\n\n<ul>\n<li>\nYou need to know the width of the columns\n<li>You need to know the number of columns\n<li>You need to know the width of the space the columns inhabit. \n<li>You need to ensure whitespace doesn't overflow \n</ul>\n\n<p>I made a calendar with DIV tags because it is impossible to get XSL to validate without hard coding a maximum number of weeks in the month, <em>which is very offensive</em>. \n<hr>\nThe biggest problem is every box has to be the same height, if you want any information to be associated with a field in your table with div tags you're going to have to make sure the <code>whitespace:scroll</code> or <code>whitespace:hidden</code> is in your CSS. </p>\n"
},
{
"answer_id": 113227,
"author": "Gavin M. Roy",
"author_id": 13203,
"author_profile": "https://Stackoverflow.com/users/13203",
"pm_score": 2,
"selected": false,
"text": "<p>The CSS property float is what you're looking for, if you want to stack div's horizontally.</p>\n\n<p>Here's a good tutorial on floats: <a href=\"http://css.maxdesign.com.au/floatutorial/\" rel=\"nofollow noreferrer\">http://css.maxdesign.com.au/floatutorial/</a></p>\n"
},
{
"answer_id": 113400,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 0,
"selected": false,
"text": "<p>Preface: I'm a little confused by the responses so far, as doing columns using DIVs and CSS is pretty well documented, but it doesn't look like any of the responses so far covered the way it's normally done. What you need is four separate DIVS, each one with a greater \"left:\" attribute. You add your data for each column into the corresponding DIV (column). </p>\n\n<p>Here's a website that should help you. They have many examples of doing columns with CSS/DIV tags:\n<a href=\"http://www.dynamicdrive.com/style/layouts/\" rel=\"nofollow noreferrer\">http://www.dynamicdrive.com/style/layouts/</a></p>\n\n<p>All you have to do is extrapolate from their 2-column examples to your 4-column needs.</p>\n"
},
{
"answer_id": 113905,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "<p>Using this code :</p>\n\n<pre><code><div class=\"title\">MyTitle</div><div class=\"subject\">MySubject</div><div class=\"Summary\">MySummary</div>\n</code></pre>\n\n<p>You have 2 solutions (adapt css selectors to you case):</p>\n\n<p>1 - Use inline blocks</p>\n\n<pre><code>div \n{\n display: inline;\n}\n</code></pre>\n\n<p>This will result in putting the blocks on the same line but remove the control you can have over their sizes.</p>\n\n<p>2 - Use float</p>\n\n<pre><code>div \n{\n width: 15%; /* size of each column : adapt */\n float: left; /* this make the block float at the left of the next one */\n}\n\ndiv.last_element /* last_element must be a class of the last div of your line */\n{\n clear: right; /* prevent your the next line to jump on the previous one */\n}\n</code></pre>\n\n<p>The float property is very useful for CSS positioning : <a href=\"http://www.w3schools.com/css/pr_class_float.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/css/pr_class_float.asp</a></p>\n"
},
{
"answer_id": 192969,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<p>The reason the questions page on stack overflow can use DIVs is because the vote/answers counter is a fixed width. </p>\n"
},
{
"answer_id": 193884,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry, but, I'm going to tell you to use tables. Because this is tabular data.</p>\n\n<p>Perhaps you could tell us why you <em>don't</em> want to use tables?</p>\n\n<p>It appears to me, and I'm sure to a lot of other people, that you're confused about the \"don't use tables\" idea. It's not \"don't use tables\", it's \"don't use tables to do page layout\". </p>\n\n<p>What you're doing here is laying out tabular data, so of course it should be in a table.</p>\n\n<p>In case you're unclear about the idea \"tabular data\", I define it like this: bits of data whose meaning isn't clear from the data alone, it has to be determined by looking at a header.</p>\n\n<p>Say you have a train or bus timetable. It will be a huge block of times. What does any particular time mean? You can't tell from looking at the time itself, but refer to the row or column headings and you'll see it's the time it departs from a certain station.</p>\n\n<p>You've got strings of text. Are they the title, the summary, or the date? People will tell that from checking the column headings. So it's a table.</p>\n"
},
{
"answer_id": 1769555,
"author": "SamGoody",
"author_id": 87520,
"author_profile": "https://Stackoverflow.com/users/87520",
"pm_score": 0,
"selected": false,
"text": "<p>You should use spans with:</p>\n\n<pre><code>display:inline-block\n</code></pre>\n\n<p>This will allow you to set a width for each of elements while still keeping them on the same line.\nSee <a href=\"http://siteroller.net/articles/3-column-no-tables-no-floats/\" rel=\"nofollow noreferrer\">here</a>, specifically <a href=\"http://siteroller.net/articles/3-column-no-tables-no-floats/pretty-forms-1.php\" rel=\"nofollow noreferrer\">this section</a>.</p>\n\n<p>Now, to appease the downvoters - of course tabular data should be in a table. But he very specifically does NOT WANT a table. The above is the answer to HIS QUESTION!!!</p>\n"
},
{
"answer_id": 1769638,
"author": "Darren Walker",
"author_id": 215335,
"author_profile": "https://Stackoverflow.com/users/215335",
"pm_score": 1,
"selected": false,
"text": "<p>Tabular data can also be represented as nested lists - i.e. lists of lists:</p>\n\n<pre><code><ul>\n <li>\n heading 1\n <ul>\n <li>row 1 data</li>\n <li>row 2 data</li>\n <ul>\n </li>\n <li>\n heading 2\n <ul>\n <li>row 1 data</li>\n <li>row 2 data</li>\n <ul>\n </li>\n</ul>\n</code></pre>\n\n<p>Which you can layout like a table and is also semantically correct(ish).</p>\n"
},
{
"answer_id": 12072406,
"author": "Sanuj",
"author_id": 1537696,
"author_profile": "https://Stackoverflow.com/users/1537696",
"pm_score": 0,
"selected": false,
"text": "<p>First <code>display:block</code> should be <code>display:inline-block</code> , Although you might have figured it out already.\nSecond you can also use <code>display:table</code> , <code>display:table-cell</code> , <code>display:table-row</code> and other properties.\nAlthough these are not as good as using table.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/112983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
| I want to display data like the following:
```
Title Subject Summary Date
```
So my `HTML` looks like:
```
<div class="title"></div>
<div class="subject"></div>
<div class="summary"></div>
<div class="date"></div>
```
The problem is, all the text doesn't appear on a single line. I tried adding `display="block"` but that doesn't seem to work.
What am I doing wrong here?
**Important:** In this instance I dont want to use a `table` element but stick with `div` tags. | It looks like you're wanting to display a table, right? So go ahead and use the <table> tag. |
113,033 | <p>I have three (C++) classes: Player, Hand, and Card.</p>
<p>Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand.</p>
<pre><code>Hand Player::getHand() {
return hand;
}
</code></pre>
<p>Hand has a method, addCard(Card c), that adds a card to the hand.</p>
<p>I want to do this:</p>
<p>player1.getHand().addCard(c);</p>
<p>but it doesn't work. It doesn't throw an error, so it's doing something. But if I examine the contents of player1's hand afterward, the card hasn't been added.</p>
<p>How can I get this to work?</p>
| [
{
"answer_id": 113035,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 2,
"selected": false,
"text": "<p>If getHand() returns by-value you're modifying a copy of the hand and not the original.</p>\n"
},
{
"answer_id": 113038,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>What is the declaration of getHand()? Is it returning a new Hand value, or is it returning a Hand& reference?</p>\n"
},
{
"answer_id": 113039,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 2,
"selected": true,
"text": "<p>If getHand() is not returning a reference you will be in trouble.</p>\n"
},
{
"answer_id": 113053,
"author": "metao",
"author_id": 11484,
"author_profile": "https://Stackoverflow.com/users/11484",
"pm_score": 0,
"selected": false,
"text": "<p>As has been stated, you're probably modifying a copy instead of the original.</p>\n\n<p>To prevent this kind of mistake, you can explicitly declare copy constructors and equals operators as private.</p>\n\n<pre><code> private:\n Hand(const Hand& rhs);\n Hand& operator=(const Hand& rhs);\n</code></pre>\n"
},
{
"answer_id": 113061,
"author": "metao",
"author_id": 11484,
"author_profile": "https://Stackoverflow.com/users/11484",
"pm_score": 1,
"selected": false,
"text": "<p>A Player.addCardToHand() method is not unreasonable, if you have no reason to otherwise expose a Hand. This is probably ideal in some ways, as you can still provide copies of the Hand for win-checking comparisons, and no-one can modify them.</p>\n"
},
{
"answer_id": 113070,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 1,
"selected": false,
"text": "<p>Your method needs to return a pointer or a refernce to the player's Hand object. You could then call it like \"player1.getHand()->addCard(c)\". Note that that is the syntax you'd use it it were a pointer.</p>\n"
},
{
"answer_id": 113074,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 1,
"selected": false,
"text": "<p>Return a reference to the hand object eg.</p>\n\n<pre><code>Hand &Player::getHand() {\n return hand;\n}\n</code></pre>\n\n<p>Now your addCard() function is operating on the correct object.</p>\n"
},
{
"answer_id": 113116,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 0,
"selected": false,
"text": "<p>getX() is often the name of an accessor function for member x, similar to your own usage. However, a \"getX\" accessor is also very often a read-only function, so that it may be surprising in other situations of your code base to see a call to \"getX\" that modifies X.</p>\n\n<p>So I would suggest, instead of just using a reference as a return value, to actually modify the code design a bit. Some alternatives:</p>\n\n<ul>\n<li>Expose a <strong>getMutableHand</strong> method that returns a pointer (or reference). By returning a pointer, you strongly suggest that the caller uses the pointer notation, so that anyone reading the code sees that this variable is changing values, and is not read-only.</li>\n<li>Make <strong>Player a subclass of Hand</strong>, so that anything that manipulates a Hand also works directly on the Player. Intuitively, you could say that a Player is not a Hand, but functionally they have the right relationship - every Player has exactly one hand, and it seems that you do want to be able to have the same access to a Hand via Player as you would directly.</li>\n<li>Directly implement an <strong>addCard</strong> method for your Player class.</li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18420/"
]
| I have three (C++) classes: Player, Hand, and Card.
Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand.
```
Hand Player::getHand() {
return hand;
}
```
Hand has a method, addCard(Card c), that adds a card to the hand.
I want to do this:
player1.getHand().addCard(c);
but it doesn't work. It doesn't throw an error, so it's doing something. But if I examine the contents of player1's hand afterward, the card hasn't been added.
How can I get this to work? | If getHand() is not returning a reference you will be in trouble. |
113,045 | <pre><code>SELECT GETDATE()
</code></pre>
<p>Returns: <code>2008-09-22 15:24:13.790</code></p>
<p>I want that date part without the time part: <code>2008-09-22 00:00:00.000</code></p>
<p>How can I get that?</p>
| [
{
"answer_id": 113051,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 6,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>SELECT CONVERT(VARCHAR(10),GETDATE(),111)\n</code></pre>\n\n<p>The above statement converts your current format to <code>YYYY/MM/DD</code>, please refer to <a href=\"https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/\" rel=\"noreferrer\">this link</a> to choose your preferable format.</p>\n"
},
{
"answer_id": 113054,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 6,
"selected": false,
"text": "<pre><code>SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101))\n</code></pre>\n"
},
{
"answer_id": 113055,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 12,
"selected": true,
"text": "<pre><code>SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))\n</code></pre>\n<p>for example</p>\n<pre><code>SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))\n</code></pre>\n<p>gives me</p>\n<pre><code>2008-09-22 00:00:00.000\n</code></pre>\n<p>Pros:</p>\n<ul>\n<li>No varchar<->datetime conversions required</li>\n<li>No need to think about locale</li>\n</ul>\n"
},
{
"answer_id": 113057,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 5,
"selected": false,
"text": "<p>You can use the <code>CONVERT</code> function to return only the date. See the link(s) below:</p>\n\n<p><a href=\"http://www.sqljunkies.ddj.com/Article/6676BEAE-1967-402D-9578-9A1C7FD826E5.scuk\" rel=\"noreferrer\">Date and Time Manipulation in SQL Server 2000 </a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"noreferrer\">CAST and CONVERT</a></p>\n\n<p>The syntax for using the convert function is: </p>\n\n<pre><code>CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) \n</code></pre>\n"
},
{
"answer_id": 113059,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), 0)\n\nSELECT DATEADD(DAY, 0, DATEDIFF(DAY,0, GETDATE()))\n\nSELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 101))\n</code></pre>\n\n<p>Edit: The first two methods are essentially the same, and out perform the convert to varchar method.</p>\n"
},
{
"answer_id": 113650,
"author": "DiGi",
"author_id": 12042,
"author_profile": "https://Stackoverflow.com/users/12042",
"pm_score": 4,
"selected": false,
"text": "<p>Using FLOOR() - just cut time part.</p>\n\n<pre><code>SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)\n</code></pre>\n"
},
{
"answer_id": 113733,
"author": "Ricardo C",
"author_id": 232589,
"author_profile": "https://Stackoverflow.com/users/232589",
"pm_score": 6,
"selected": false,
"text": "<p>DATEADD and DATEDIFF are better than CONVERTing to varchar. Both queries have the same execution plan, but execution plans are primarily about <strong>data</strong> access strategies and do not always reveal implicit costs involved in the CPU time taken to perform all the pieces. If both queries are run against a table with millions of rows, the CPU time using DateDiff can be close to 1/3rd of the Convert CPU time!</p>\n<p>To see execution plans for queries:</p>\n<pre><code>set showplan_text on\nGO \n</code></pre>\n<p>Both DATEADD and DATEDIFF will execute a CONVERT_IMPLICIT.</p>\n<p>Although the CONVERT solution is simpler and easier to read for some, it <em>is</em> slower. There is no need to cast back to DateTime (this is implicitly done by the server). There is also no real need in the DateDiff method for DateAdd afterward as the integer result will also be implicitly converted back to DateTime.</p>\n<hr />\n<p><strong>SELECT CONVERT(varchar, MyDate, 101) FROM DatesTable</strong></p>\n<pre><code> |--Compute Scalar(DEFINE:([Expr1004]=CONVERT(varchar(30),[TEST].[dbo].[DatesTable].[MyDate],101)))\n |--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))\n</code></pre>\n<hr />\n<p><strong>SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, MyDate)) FROM DatesTable</strong></p>\n<pre><code> |--Compute Scalar(DEFINE:([Expr1004]=dateadd(day,(0),CONVERT_IMPLICIT(datetime,datediff(day,'1900-01-01 00:00:00.000',CONVERT_IMPLICIT(datetime,[TEST].[dbo].[DatesTable].[MyDate],0)),0))))\n |--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))\n</code></pre>\n<p>Using FLOOR() as @digi suggested has performance closer to DateDiff, but is not recommended as casting the DateTime data type to float and back does not always yield the original value.</p>\n<p>Remember guys: Don't believe anyone. Look at the performance statistics, and test it yourself!</p>\n<p>Be careful when you're testing your results. Selecting many rows to the client will hide the performance difference because it takes longer to send the rows over the network than it does to perform the calculations. So make sure that the work for all the rows is done by the server but there is no row set sent to the client.</p>\n<p>There seems to be confusion for some people about when cache optimization affects queries. Running two queries in the same batch or in separate batches has no effect on caching. So you can either expire the cache manually or simply run the queries back and forth multiple times. Any optimization for query #2 would also affect any subsequent queries, so throw out execution #1 if you like.</p>\n<p>Here is <a href=\"https://stackoverflow.com/questions/2775/whats-the-best-way-to-remove-the-time-portion-of-a-datetime-value-sql-server/3696991#3696991\">full test script and performance results</a> that prove DateDiff is substantially faster than converting to varchar.</p>\n"
},
{
"answer_id": 126984,
"author": "BenR",
"author_id": 18039,
"author_profile": "https://Stackoverflow.com/users/18039",
"pm_score": 10,
"selected": false,
"text": "<p>SQLServer 2008 now has a 'date' data type which contains only a date with no time component. Anyone using SQLServer 2008 and beyond can do the following:</p>\n\n<pre><code>SELECT CONVERT(date, GETDATE())\n</code></pre>\n"
},
{
"answer_id": 4849412,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 8,
"selected": false,
"text": "<p>If using SQL 2008 and above:</p>\n\n<pre><code>select cast(getdate() as date)\n</code></pre>\n"
},
{
"answer_id": 7514630,
"author": "Rushda",
"author_id": 959076,
"author_profile": "https://Stackoverflow.com/users/959076",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),103) --21/09/2011\n\nSELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),101) --09/21/2011\n\nSELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),111) --2011/09/21\n\nSELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),107) --Sep 21, 2011\n</code></pre>\n"
},
{
"answer_id": 11677122,
"author": "Focusyn",
"author_id": 1555912,
"author_profile": "https://Stackoverflow.com/users/1555912",
"pm_score": 4,
"selected": false,
"text": "<p>IF you want to use CONVERT and get the same output as in the original question posed, that is, yyyy-mm-dd then use <code>CONVERT(varchar(10),[SourceDate as dateTime],121)</code> same code as the previous couple answers, but the code to convert to yyyy-mm-dd with dashes is 121.</p>\n\n<p>If I can get on my soapbox for a second, <strong><em>this kind of formatting doesn't belong in the data tier</em></strong>, and that's why it wasn't possible without silly high-overhead 'tricks' until SQL Server 2008 when actual datepart data types are introduced. Making such conversions in the data tier is a huge waste of overhead on your DBMS, but more importantly, the second you do something like this, you have basically created in-memory orphaned data that I assume you will then return to a program. You can't put it back in to another 3NF+ column or compare it to anything typed without reverting, so all you've done is introduced points of failure and removed relational reference. </p>\n\n<p>You should ALWAYS go ahead and return your dateTime data type to the calling program and <strong><em>in the PRESENTATION tier, make whatever adjustments are necessary.</em></strong> As soon as you go converting things before returning them to the caller, you are removing all hope of referential integrity from the application. This would prevent an UPDATE or DELETE operation, again, unless you do some sort of manual reversion, which again is exposing your data to human/code/gremlin error when there is no need.</p>\n"
},
{
"answer_id": 20033917,
"author": "Anderson Silva",
"author_id": 2966935,
"author_profile": "https://Stackoverflow.com/users/2966935",
"pm_score": 4,
"selected": false,
"text": "<p>To obtain the result indicated, I use the following command.</p>\n\n<pre><code>SELECT CONVERT(DATETIME,CONVERT(DATE,GETDATE()))\n</code></pre>\n\n<p>I holpe it is useful.</p>\n"
},
{
"answer_id": 20235233,
"author": "bishnu karki",
"author_id": 2513452,
"author_profile": "https://Stackoverflow.com/users/2513452",
"pm_score": 3,
"selected": false,
"text": "<p>I think this would work in your case:</p>\n\n<pre><code>CONVERT(VARCHAR(10),Person.DateOfBirth,111) AS BirthDate\n//here date is obtained as 1990/09/25\n</code></pre>\n"
},
{
"answer_id": 20675129,
"author": "Mahesh ML",
"author_id": 1786438,
"author_profile": "https://Stackoverflow.com/users/1786438",
"pm_score": 5,
"selected": false,
"text": "<p><strong>For return in date format</strong> </p>\n\n<blockquote>\n <p>CAST(OrderDate AS date)</p>\n</blockquote>\n\n<p>The above code will work in sql server 2010</p>\n\n<p>It will return like 12/12/2013</p>\n\n<p><strong>For SQL Server 2012 use the below code</strong></p>\n\n<pre><code>CONVERT(VARCHAR(10), OrderDate , 111)\n</code></pre>\n"
},
{
"answer_id": 22661348,
"author": "Stephon Johns",
"author_id": 3135742,
"author_profile": "https://Stackoverflow.com/users/3135742",
"pm_score": 5,
"selected": false,
"text": "<p>If you need the result as a <code>varchar</code>, you should go through</p>\n\n<pre><code>SELECT CONVERT(DATE, GETDATE()) --2014-03-26\nSELECT CONVERT(VARCHAR(10), GETDATE(), 111) --2014/03/26\n</code></pre>\n\n<p>which is already mentioned above.</p>\n\n<p>If you need result in date and time format, you should use any of the queries below</p>\n\n<ol>\n<li><pre><code>SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 111)) AS OnlyDate \n</code></pre>\n\n<blockquote>\n <p>2014-03-26 00:00:00.000</p>\n</blockquote></li>\n<li><pre><code>SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 112)) AS OnlyDate \n</code></pre>\n\n<blockquote>\n <p>2014-03-26 00:00:00.000</p>\n</blockquote></li>\n<li><pre><code>DECLARE @OnlyDate DATETIME\nSET @OnlyDate = DATEDIFF(DD, 0, GETDATE())\nSELECT @OnlyDate AS OnlyDate\n</code></pre>\n\n<blockquote>\n <p>2014-03-26 00:00:00.000</p>\n</blockquote></li>\n</ol>\n"
},
{
"answer_id": 22732953,
"author": "user1151326",
"author_id": 1151326,
"author_profile": "https://Stackoverflow.com/users/1151326",
"pm_score": 2,
"selected": false,
"text": "<p>You can use following for date part and formatting the date:</p>\n\n<p>DATENAME => Returns a character string that represents the specified datepart of the specified date</p>\n\n<p>DATEADD => The <code>DATEPART()</code> function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc.</p>\n\n<p>DATEPART =>Returns an integer that represents the specified datepart of the specified date.</p>\n\n<p><code>CONVERT()</code> = > The <code>CONVERT()</code> function is a general function that converts an expression of one data type to another.\nThe \n<code>CONVERT()</code> function can be used to display date/time data in different formats.</p>\n"
},
{
"answer_id": 23612056,
"author": "Ankit Khetan",
"author_id": 2847810,
"author_profile": "https://Stackoverflow.com/users/2847810",
"pm_score": 3,
"selected": false,
"text": "<pre><code> Convert(nvarchar(10), getdate(), 101) ---> 5/12/14\n\n Convert(nvarchar(12), getdate(), 101) ---> 5/12/2014\n</code></pre>\n"
},
{
"answer_id": 23708033,
"author": "Janaka R Rajapaksha",
"author_id": 2020193,
"author_profile": "https://Stackoverflow.com/users/2020193",
"pm_score": 3,
"selected": false,
"text": "<p>why don't you use DATE_FORMAT( your_datetiem_column, '%d-%m-%Y' ) ?</p>\n\n<p>EX: <code>select DATE_FORMAT( some_datetime_column, '%d-%m-%Y' ) from table_name</code></p>\n\n<p>you can change sequence of m,d and year by re-arranging <code>'%d-%m-%Y'</code> part</p>\n"
},
{
"answer_id": 27026637,
"author": "etni",
"author_id": 3191501,
"author_profile": "https://Stackoverflow.com/users/3191501",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DECLARE @yourdate DATETIME = '11/1/2014 12:25pm' \nSELECT CONVERT(DATE, @yourdate)\n</code></pre>\n"
},
{
"answer_id": 28774425,
"author": "tumultous_rooster",
"author_id": 2822004,
"author_profile": "https://Stackoverflow.com/users/2822004",
"pm_score": 3,
"selected": false,
"text": "<p>Even using the ancient MSSQL Server 7.0, the code here (courtesy of this <a href=\"http://www.dreamincode.net/forums/topic/42872-working-with-date-values-in-sql-server/\" rel=\"noreferrer\">link</a>) allowed me to get whatever date format I was looking for at the time: </p>\n\n<pre><code>PRINT '1) Date/time in format MON DD YYYY HH:MI AM (OR PM): ' + CONVERT(CHAR(19),GETDATE()) \nPRINT '2) Date/time in format MM-DD-YY: ' + CONVERT(CHAR(8),GETDATE(),10) \nPRINT '3) Date/time in format MM-DD-YYYY: ' + CONVERT(CHAR(10),GETDATE(),110) \nPRINT '4) Date/time in format DD MON YYYY: ' + CONVERT(CHAR(11),GETDATE(),106)\nPRINT '5) Date/time in format DD MON YY: ' + CONVERT(CHAR(9),GETDATE(),6) \nPRINT '6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): ' + CONVERT(CHAR(24),GETDATE(),113)\n</code></pre>\n\n<p>It produced this output: </p>\n\n<pre><code>1) Date/time in format MON DD YYYY HH:MI AM (OR PM): Feb 27 2015 1:14PM\n2) Date/time in format MM-DD-YY: 02-27-15\n3) Date/time in format MM-DD-YYYY: 02-27-2015\n4) Date/time in format DD MON YYYY: 27 Feb 2015\n5) Date/time in format DD MON YY: 27 Feb 15\n6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): 27 Feb 2015 13:14:46:630\n</code></pre>\n"
},
{
"answer_id": 29975670,
"author": "Gerard ONeill",
"author_id": 1331672,
"author_profile": "https://Stackoverflow.com/users/1331672",
"pm_score": 3,
"selected": false,
"text": "<p>I favor the following which wasn't mentioned:</p>\n\n<pre><code>DATEFROMPARTS(DATEPART(yyyy, @mydatetime), DATEPART(mm, @mydatetime), DATEPART(dd, @mydatetime))\n</code></pre>\n\n<p>It also doesn't care about local or do a double convert -- although each 'datepart' probably does math. So it may be a little slower than the datediff method, but to me it is much more clear. Especially when I want to group by just the year and month (set the day to 1).</p>\n"
},
{
"answer_id": 31285050,
"author": "Surekha",
"author_id": 4836250,
"author_profile": "https://Stackoverflow.com/users/4836250",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Date(date&time field)</strong> and <strong>DATE_FORMAT(date&time,'%Y-%m-%d')</strong> both returns <strong>only date</strong> from date&time </p>\n"
},
{
"answer_id": 32332424,
"author": "Binitta Mary",
"author_id": 5287922,
"author_profile": "https://Stackoverflow.com/users/5287922",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT * FROM tablename WHERE CAST ([my_date_time_var] AS DATE)= '8/5/2015'\n</code></pre>\n"
},
{
"answer_id": 34817244,
"author": "lit",
"author_id": 447901,
"author_profile": "https://Stackoverflow.com/users/447901",
"pm_score": 3,
"selected": false,
"text": "<p>I know this is old, but I do not see where anyone stated it this way. From what I can tell, this is ANSI standard.</p>\n\n<pre><code>SELECT CAST(CURRENT_TIMESTAMP AS DATE)\n</code></pre>\n\n<p>It would be good if Microsoft could also support the ANSI standard CURRENT_DATE variable.</p>\n"
},
{
"answer_id": 36296594,
"author": "Shyam Bhimani",
"author_id": 6030977,
"author_profile": "https://Stackoverflow.com/users/6030977",
"pm_score": -1,
"selected": false,
"text": "<p>You can simply use the code below to get only the date part and avoid the time part in SQL:</p>\n\n<pre><code>SELECT SYSDATE TODAY FROM DUAL; \n</code></pre>\n"
},
{
"answer_id": 36596046,
"author": "Krishnraj Rana",
"author_id": 748173,
"author_profile": "https://Stackoverflow.com/users/748173",
"pm_score": 3,
"selected": false,
"text": "<p>Okay, Though I'm bit late :), Here is the another solution.</p>\n\n<pre><code>SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DATETIME)\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>2008-09-22 00:00:00.000\n</code></pre>\n\n<p>And if you are using SQL Server 2012 and higher then you can use <code>FORMAT()</code> function like this -</p>\n\n<pre><code>SELECT FORMAT(GETDATE(), 'yyyy-MM-dd')\n</code></pre>\n"
},
{
"answer_id": 37219244,
"author": "Art Schmidt",
"author_id": 5522000,
"author_profile": "https://Stackoverflow.com/users/5522000",
"pm_score": 4,
"selected": false,
"text": "<p>If you are assigning the results to a column or variable, give it the DATE type, and the conversion is implicit.</p>\n\n<pre><code>DECLARE @Date DATE = GETDATE() \n\nSELECT @Date --> 2017-05-03\n</code></pre>\n"
},
{
"answer_id": 37361098,
"author": "Kris Khairallah",
"author_id": 1522660,
"author_profile": "https://Stackoverflow.com/users/1522660",
"pm_score": 3,
"selected": false,
"text": "<p>Date:</p>\n\n<pre>\nSELECT CONVERT(date, GETDATE())\nSELECT CAST(GETDATE() as date)\n</pre>\n\n<p>Time:</p>\n\n<pre>\nSELECT CONVERT(time , GETDATE() , 114)\nSELECT CAST(GETDATE() as time)\n</pre>\n"
},
{
"answer_id": 37409697,
"author": "r-magalhaes",
"author_id": 1774725,
"author_profile": "https://Stackoverflow.com/users/1774725",
"pm_score": 3,
"selected": false,
"text": "<p>On SQL Server 2000</p>\n\n<pre><code>CAST(\n(\n STR( YEAR( GETDATE() ) ) + '/' +\n STR( MONTH( GETDATE() ) ) + '/' +\n STR( DAY( GETDATE() ) )\n)\nAS DATETIME)\n</code></pre>\n"
},
{
"answer_id": 38485360,
"author": "xbb",
"author_id": 1566021,
"author_profile": "https://Stackoverflow.com/users/1566021",
"pm_score": 3,
"selected": false,
"text": "<p>Starting from SQL SERVER 2012, you can do this:</p>\n\n<p><code>SELECT FORMAT(GETDATE(), 'yyyy-MM-dd 00:00:00.000')</code></p>\n"
},
{
"answer_id": 39117132,
"author": "Somnath Muluk",
"author_id": 1045444,
"author_profile": "https://Stackoverflow.com/users/1045444",
"pm_score": 4,
"selected": false,
"text": "<h2>If you are using <strong>SQL Server 2012 or above versions</strong>,</h2>\n\n<p>Use <a href=\"https://msdn.microsoft.com/en-IN/library/hh213505.aspx\" rel=\"noreferrer\"><code>Format()</code></a> function.</p>\n\n<p>There are already multiple answers and formatting types for SQL server. \nBut most of the methods are somewhat ambiguous and it would be difficult for you to remember the numbers for format type or functions with respect to Specific Date Format. That's why in next versions of SQL server there is better option.</p>\n\n<pre><code>FORMAT ( value, format [, culture ] )\n</code></pre>\n\n<p>Culture option is very useful, as you can specify date as per your viewers.</p>\n\n<p>You have to remember d (for small patterns) and D (for long patterns).</p>\n\n<h2>1.\"d\" - Short date pattern.</h2>\n\n<pre><code>2009-06-15T13:45:30 -> 6/15/2009 (en-US)\n2009-06-15T13:45:30 -> 15/06/2009 (fr-FR)\n2009-06-15T13:45:30 -> 2009/06/15 (ja-JP)\n</code></pre>\n\n<h2>2.\"D\" - Long date pattern.</h2>\n\n<pre><code>2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US)\n2009-06-15T13:45:30 -> 15 июня 2009 г. (ru-RU)\n2009-06-15T13:45:30 -> Montag, 15. Juni 2009 (de-DE)\n</code></pre>\n\n<p>More examples in query.</p>\n\n<pre><code>DECLARE @d DATETIME = '10/01/2011';\nSELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'\n ,FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English Result'\n ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'\n ,FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result'; \n\nSELECT FORMAT ( @d, 'D', 'en-US' ) AS 'US English Result'\n ,FORMAT ( @d, 'D', 'en-gb' ) AS 'Great Britain English Result'\n ,FORMAT ( @d, 'D', 'de-de' ) AS 'German Result'\n ,FORMAT ( @d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';\n\nUS English Result Great Britain English Result German Result Simplified Chinese (PRC) Result\n---------------- ----------------------------- ------------- -------------------------------------\n10/1/2011 01/10/2011 01.10.2011 2011/10/1\n\nUS English Result Great Britain English Result German Result Chinese (Simplified PRC) Result\n---------------------------- ----------------------------- ----------------------------- ---------------------------------------\nSaturday, October 01, 2011 01 October 2011 Samstag, 1. Oktober 2011 2011年10月1日\n</code></pre>\n\n<p>If you want more formats, you can go to:</p>\n\n<ol>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx\" rel=\"noreferrer\">Standard Date and Time Format Strings</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx\" rel=\"noreferrer\">Custom Date and Time Format Strings</a></li>\n</ol>\n"
},
{
"answer_id": 46109193,
"author": "Amar Srivastava",
"author_id": 6505216,
"author_profile": "https://Stackoverflow.com/users/6505216",
"pm_score": 3,
"selected": false,
"text": "<p>Simply you can do this way:</p>\n\n<pre><code>SELECT CONVERT(date, getdate())\nSELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))\nSELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))\n</code></pre>\n\n<p>Outputs as:</p>\n\n<pre><code>2008-09-22 00:00:00.000\n</code></pre>\n\n<p>Or simply do like this:</p>\n\n<pre><code>SELECT CONVERT (DATE, GETDATE()) 'Date Part Only'\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Date Part Only\n--------------\n2013-07-14\n</code></pre>\n"
},
{
"answer_id": 46859925,
"author": "Spider",
"author_id": 3725288,
"author_profile": "https://Stackoverflow.com/users/3725288",
"pm_score": 2,
"selected": false,
"text": "<p>My common approach to get date without the time part.. </p>\n\n<pre><code> SELECT CONVERT(VARCHAR(MAX),GETDATE(),103)\n\n SELECT CAST(GETDATE() AS DATE)\n</code></pre>\n"
},
{
"answer_id": 52661269,
"author": "mokh223",
"author_id": 2748728,
"author_profile": "https://Stackoverflow.com/users/2748728",
"pm_score": -1,
"selected": false,
"text": "<pre><code>select convert(getdate() as date)\n\nselect CONVERT(datetime,CONVERT(date, getdate()))\n</code></pre>\n"
},
{
"answer_id": 53411273,
"author": "CAGDAS AYDIN",
"author_id": 10627992,
"author_profile": "https://Stackoverflow.com/users/10627992",
"pm_score": 2,
"selected": false,
"text": "<p>My Style</p>\n\n<pre><code> select Convert(smalldatetime,Convert(int,Convert(float,getdate())))\n</code></pre>\n"
},
{
"answer_id": 55326586,
"author": "karthik kasubha",
"author_id": 5486572,
"author_profile": "https://Stackoverflow.com/users/5486572",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select cast(createddate as date) as derivedate from table \n</code></pre>\n\n<p>createdate is your datetime column , this works for sqlserver</p>\n"
},
{
"answer_id": 55430749,
"author": "ankit soni",
"author_id": 8385887,
"author_profile": "https://Stackoverflow.com/users/8385887",
"pm_score": 1,
"selected": false,
"text": "<p>you can use like below for different different type of output for date only</p>\n\n<ol>\n<li><p><code>SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 103))</code> -----dd/mm/yyyy</p></li>\n<li><p><code>SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101))</code>------mm/dd/yyyy</p></li>\n<li><p><code>SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 102))</code></p></li>\n</ol>\n"
},
{
"answer_id": 55816901,
"author": "Aubrey Love",
"author_id": 7703803,
"author_profile": "https://Stackoverflow.com/users/7703803",
"pm_score": 1,
"selected": false,
"text": "<p>Wow, let me count the ways you can do this. (no pun intended)</p>\n\n<p>In order to get the results you want in this format specifically:</p>\n\n<p>2008-09-22</p>\n\n<p>Here are a few options. </p>\n\n<pre><code>SELECT CAST(GETDATE() AS DATE) AS 'Date1'\nSELECT Date2 = CONVERT(DATE, GETDATE())\nSELECT CONVERT(DATE, GETDATE()) AS 'Date3'\nSELECT CONVERT(CHAR(10), GETDATE(), 121) AS 'Date4'\nSELECT CONVERT(CHAR(10), GETDATE(), 126) AS 'Date5'\nSELECT CONVERT(CHAR(10), GETDATE(), 127) AS 'Date6'\n</code></pre>\n\n<p>So, I would suggest picking one you are comfortable with and using that method across the board in all your tables. </p>\n\n<p>All these options return the date in the exact same format. Why does SQL Server have such redundancy?</p>\n\n<p>I have no idea, but they do. Maybe somebody smarter than me can answer that question. </p>\n\n<p>Hope this helps someone. </p>\n"
},
{
"answer_id": 56338106,
"author": "Jithin Joy",
"author_id": 6898904,
"author_profile": "https://Stackoverflow.com/users/6898904",
"pm_score": -1,
"selected": false,
"text": "<p>The easiest way would be to use:\n<code>SELECT DATE(GETDATE())</code></p>\n"
},
{
"answer_id": 57269676,
"author": "ChrisM",
"author_id": 11760174,
"author_profile": "https://Stackoverflow.com/users/11760174",
"pm_score": 2,
"selected": false,
"text": "<p>If you want the date to show <code>2008-09-22 00:00:00.000</code></p>\n\n<p>then you can round it using</p>\n\n<pre><code>SELECT CONVERT(datetime, (ROUND(convert(float, getdate()-.5),0)))\n</code></pre>\n\n<p>This will show the date in the format in the question</p>\n"
},
{
"answer_id": 59015707,
"author": "Mohammad Neamul Islam",
"author_id": 8054013,
"author_profile": "https://Stackoverflow.com/users/8054013",
"pm_score": 3,
"selected": false,
"text": "<p><strong>In this case, date only, you we are gonna run this query:</strong></p>\n\n<p>SELECT CONVERT(VARCHAR(10), getdate(), 111);<a href=\"https://i.stack.imgur.com/DDheQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DDheQ.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 59749143,
"author": "John Sonnino",
"author_id": 6895162,
"author_profile": "https://Stackoverflow.com/users/6895162",
"pm_score": 5,
"selected": false,
"text": "<p>Just do:</p>\n<p><code>SELECT CAST(date_variable AS date)</code></p>\n<p>or with with PostgreSQL:</p>\n<p><code>SELECT date_variable::date</code></p>\n<p>This is called typecasting btw!</p>\n"
},
{
"answer_id": 60117817,
"author": "Christopher Warrington",
"author_id": 4679332,
"author_profile": "https://Stackoverflow.com/users/4679332",
"pm_score": -1,
"selected": false,
"text": "<p>As there has been many changes since this question had answers, I wanted to provide a new way to get the requested result. There are two ways to parse DATETIME data. First, to get the date as this question asks: </p>\n\n<pre><code>DATEVALUE([TableColumnName])\n</code></pre>\n\n<p>Second, to get the time from the value: </p>\n\n<pre><code>TIMEVALUE([TableColumnName])\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<p>Table: Customers</p>\n\n<p>Column: CreationDate as DateTime</p>\n\n<p>[Customers].[CreationDate]: 2/7/2020 09:50:00</p>\n\n<pre><code>DATEVALUE([Customers].[CreationDate]) '--> Output: 2/7/2020\nTIMEVALUE([Customers].[CreationDate]) '--> Output: 09:50:00\n</code></pre>\n\n<p>I hope that this helps as I was searching for a while and found many answers as seen in this question and none of those worked. IE <code>CAST</code> and <code>CONVERT</code>. </p>\n\n<p>Happy Coding!</p>\n"
},
{
"answer_id": 66546890,
"author": "yusuf hayırsever",
"author_id": 10238086,
"author_profile": "https://Stackoverflow.com/users/10238086",
"pm_score": 3,
"selected": false,
"text": "<p>Syntax:</p>\n<pre><code>SELECT CONVERT (data_type(length)),Date, DateFormatCode)\n</code></pre>\n<p>Ex:</p>\n<pre><code>Select CONVERT(varchar,GETDATE(),1) as [MM/DD/YY]\nSelect CONVERT(varchar,GETDATE(),2) as [YY.MM.DD]\n</code></pre>\n<p>all dateformatcodes about Date:</p>\n<pre><code>DateFormatCode Format\n1 [MM/DD/YY]\n2 [YY.MM.DD]\n3 [DD/MM/YY]\n4 [DD.MM.YY]\n5 [DD-MM-YY]\n6 [DD MMM YY]\n7 [MMM DD,YY]\n10 [MM-DD-YY]\n11 [YY/MM/DD]\n12 [YYMMDD]\n23 [yyyy-mm-dd]\n101 [MM/DD/YYYY]\n102 [YYYY.MM.DD]\n103 [DD/MM/YYYY]\n104 [DD/MM/YYYY]\n105 [DD/MM/YYYY]\n106 [DD MMM YYYY]\n107 [MMM DD,YYYY]\n110 [MM-DD-YYYY]\n111 [YYYY/MM/DD]\n112 [YYYYMMDD]\n</code></pre>\n"
},
{
"answer_id": 73565346,
"author": "Zhorov",
"author_id": 6578080,
"author_profile": "https://Stackoverflow.com/users/6578080",
"pm_score": 0,
"selected": false,
"text": "<p>Starting from SQL Server 2022 (16.x), another option is <code>DATETRUNC()</code> function using <code>day</code> as value of <code>datepart</code> parameter:</p>\n<pre><code>SELECT DATETRUNC(day, GETDATE());\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769/"
]
| ```
SELECT GETDATE()
```
Returns: `2008-09-22 15:24:13.790`
I want that date part without the time part: `2008-09-22 00:00:00.000`
How can I get that? | ```
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))
```
for example
```
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
```
gives me
```
2008-09-22 00:00:00.000
```
Pros:
* No varchar<->datetime conversions required
* No need to think about locale |
113,077 | <p>I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times.</p>
<p>Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)?</p>
<p>Thanks!</p>
| [
{
"answer_id": 113081,
"author": "da5id",
"author_id": 14979,
"author_profile": "https://Stackoverflow.com/users/14979",
"pm_score": 0,
"selected": false,
"text": "<p>In cases like that I write everything incrementally into a variable or sometimes an array and then echo the variable/array. It has the added advantage that the page always renders in one go, rather than progressively.</p>\n"
},
{
"answer_id": 113083,
"author": "Issac Kelly",
"author_id": 144,
"author_profile": "https://Stackoverflow.com/users/144",
"pm_score": 0,
"selected": false,
"text": "<p>What I end up doing in this situation is building 'template' files of HTML data that I Include, and then parse through with regular expressions. It keeps the code clean, and makes it easier to hand pieces off to a designer, or other HTML person.</p>\n\n<p>Check out the ideals behind MVC programming practices at <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow noreferrer\">Wikipedia</a></p>\n"
},
{
"answer_id": 113086,
"author": "jdelator",
"author_id": 438,
"author_profile": "https://Stackoverflow.com/users/438",
"pm_score": 3,
"selected": false,
"text": "<p>Use a mvc approach. </p>\n\n<p><a href=\"http://www.phpmvc.net/\" rel=\"noreferrer\">http://www.phpmvc.net/</a></p>\n\n<p>This is not something that you will pick up in a couple of hours. You really need to practice it. Main thing is the controller will access your model (the db layer), do stuff to your data and then send it to the view for rendering. This is oversimplified but you just need to read and practice it to understand it.</p>\n\n<p>This is something I used to help me learn it.\n<a href=\"http://www.onlamp.com/pub/a/php/2005/09/15/mvc_intro.html\" rel=\"noreferrer\">http://www.onlamp.com/pub/a/php/2005/09/15/mvc_intro.html</a></p>\n"
},
{
"answer_id": 113092,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 1,
"selected": false,
"text": "<p>From the sound of your problem, it seems you might not have much separation between logic and presentation in your code. When designing an application this is a very important consideration, for reasons exactly demonstrated by the situation your currently facing.</p>\n\n<p>If you haven't already I'd take a look at some PHP templating engines such as <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a>.</p>\n"
},
{
"answer_id": 113097,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>Try to separate your content and layout from your code as much as possible. Any time you write any HTML in a .php file, stop and think \"Does this <em>really</em> belong here?\"</p>\n\n<p>One solution is to use templates. Look at the <a href=\"http://www.smarty.net\" rel=\"nofollow noreferrer\">Smarty</a> templating system for a pretty easy-to-use option.</p>\n"
},
{
"answer_id": 113104,
"author": "Alex Weinstein",
"author_id": 16668,
"author_profile": "https://Stackoverflow.com/users/16668",
"pm_score": 0,
"selected": false,
"text": "<p>You need a framework. This will not only make your code pretty (because of the already-mentioned model-view-controller pattern, MVC) - it will save you time because of the components that are already written for it. </p>\n\n<p>I recommend QCodo, it's amazing; there are others - CakePHP, Symfony.</p>\n"
},
{
"answer_id": 113154,
"author": "Galen",
"author_id": 7894,
"author_profile": "https://Stackoverflow.com/users/7894",
"pm_score": 0,
"selected": false,
"text": "<p>If it's a big project a framework might be in order. If not, create some template files and at the top of the page decide which template file to include.</p>\n\n<p>for example</p>\n\n<pre><code>if ($_SESSION['logged_in'])\n include(TPL_DIR . 'main_logged_in.tpl'); \nelse\n include(tPL_DIR . 'main.tpl');\n</code></pre>\n\n<p>just a simple example</p>\n"
},
{
"answer_id": 113610,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 0,
"selected": false,
"text": "<p>as mentioned above.. you are fixing the symptom, not the problem.. </p>\n\n<p>What you need is the separation of logic and presentation. Which can be done with some sort of mvc framework. Even if you don't want to go all the way with a mvc framework.. A templating engine is a must at least if your logic is complicated enough that you have trouble with what you are explaining</p>\n"
},
{
"answer_id": 113851,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 6,
"selected": true,
"text": "<p>Don't panic, every fresh Web programmer face this problem.</p>\n\n<p>You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page :</p>\n\n<ul>\n<li>one with only PHP code (no HTML) that fills variables</li>\n<li>another with HTML and very few PHP : this is your page design</li>\n</ul>\n\n<p>Then include where / when you need it. E.G :</p>\n\n<p>myPageLogic.php</p>\n\n<pre><code><?php\n\n// pure PHP code, no HTML\n\n$name = htmlspecialchars($_GET['name']);\n$age = date('Y') - htmlspecialchars($_GET['age']);\n\n?>\n</code></pre>\n\n<p>myPageView.php</p>\n\n<pre><code>// very few php code\n// just enought to print variables\n// and some if / else, or foreach to manage the data stream\n\n<h1>Hello, <?php $name ?> !</h1>\n\n<p>So your are <?php $age?>, hu ?</p>\n</code></pre>\n\n<p>(You may want to use the <a href=\"http://php.mirror.camelnetwork.com/manual/en/control-structures.alternative-syntax.php\" rel=\"noreferrer\">alternative PHP syntax</a> for this one. But don't try to hard to make it perfect the first time, really.)</p>\n\n<p>myPage.php</p>\n\n<pre><code><?php\n\nrequire('myPageLogic.php');\nrequire('myPageView.php');\n?>\n</code></pre>\n\n<p><em>Don't bother about performance issues for now</em>. This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics.</p>\n\n<p>Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the <em>NEXT TIME</em>. Then you'll try some templating systems and frameworks, but <em>LATER</em>. For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine.</p>\n"
},
{
"answer_id": 113903,
"author": "yann.kmm",
"author_id": 15780,
"author_profile": "https://Stackoverflow.com/users/15780",
"pm_score": 0,
"selected": false,
"text": "<p>I strongly suggest <a href=\"http://phpsavant.com/\" rel=\"nofollow noreferrer\">savant</a> instead of smarty, </p>\n\n<ul>\n<li>you don't have to learn a new templating \"language\" in order to create templates, savant templates are written in php</li>\n<li>if you don't want to use php you can define your own template \"language\" with a compiler</li>\n<li>it's easily extendable by your own php objects</li>\n</ul>\n\n<p>Separating logic from presentation does not mean that all you business logic has to be in php and your presentation logic in something else, the separation is a conceptual thing, you hae to separate the logic that prepares data form the one that shows it. Obviously the business logic does not have to contain presentation elements.</p>\n"
},
{
"answer_id": 114141,
"author": "Twan",
"author_id": 6702,
"author_profile": "https://Stackoverflow.com/users/6702",
"pm_score": 0,
"selected": false,
"text": "<p>In stead of implementing templating systems on top of a templating system (PHP itself), creating overhead per default, you can go for a more robust solution like <a href=\"http://www.w3schools.com/xsl/\" rel=\"nofollow noreferrer\">XSL Transformations</a>, which also complies with the <a href=\"http://www.phpmvc.net/\" rel=\"nofollow noreferrer\">MVC princples</a> (provided you seperate your data-retrieval; plus, I personally split the logic from displaying the XML with different files).</p>\n\n<p>Imagine having the following information in an array, which you want to display in a table.</p>\n\n<pre><code>Array\n{\n [car] => green\n [bike] => red\n}\n</code></pre>\n\n<p>You easily create a script that outputs this information in XML:</p>\n\n<pre><code>echo \"<VEHICLES>\\n\";\nforeach(array_keys($aVehicles) as $sVehicle)\n echo \"\\t<VEHICLE>\".$sVehicle.\"</NAME><COLOR>\".$aVehicles[$sVehicle].\"</COLOR></VEHICLE>\\n\";\necho \"</VEHICLES>\\n\";\n</code></pre>\n\n<p>Resulting in the following XML:</p>\n\n<pre><code><VEHICLES>\n <VEHICLE>\n <NAME>car</NAME>\n <COLOR>green</COLOR>\n </VEHICLE>\n <VEHICLE>\n <NAME>bike</NAME>\n <COLOR>red</COLOR>\n </VEHICLE>\n</VEHICLES>\n</code></pre>\n\n<p>Now this is all excellent, but that won't display in a nice format. This is where XSLT comes in. With some simple code, you can transform this into a table:</p>\n\n<pre><code><xsl:template match=\"VEHICLES\">\n <TABLE>\n <xsl:apply-templates select=\"VEHICLE\">\n </TABLE>\n</xsl:template>\n\n<xsl:template match=\"VEHICLE\">\n <TR>\n <TD><xsl:value-of select=\"NAME\"></TD>\n <TD><xsl:value-of select=\"COLOR\"></TD>\n </TR>\n</xsl:template>\n</code></pre>\n\n<p>Et voila, you have:</p>\n\n<pre><code><TABLE>\n <TR>\n <TD>car</TD>\n <TD>green</TD>\n </TR>\n <TR>\n <TD>bike</TD>\n <TD>red</TD>\n </TR>\n</TABLE>\n</code></pre>\n\n<p>Now for this simple example, this is a bit of overkill; but for complex structures in big projects, this is an absolute way to keep your scripting logic away from your markup.</p>\n"
},
{
"answer_id": 114734,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 0,
"selected": false,
"text": "<p>Check this <a href=\"https://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html\">question</a> about separating PHP and HTML, there are various ways to do it, including self written templating systems, templating systems such as Smarty, PHP as a templating system on it's own, etc etc etc...</p>\n"
},
{
"answer_id": 115713,
"author": "Adam Gibbins",
"author_id": 20528,
"author_profile": "https://Stackoverflow.com/users/20528",
"pm_score": 0,
"selected": false,
"text": "<p>I think you've two options here, either use a MVC Framework or use the lazy templating way which would put significant overhead on your code. Obviously I'm with the former, I think learning MVC is one of the best web development tricks in the book.</p>\n"
},
{
"answer_id": 115887,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Doing that, however, makes my php code look horrific... it really messes with the formatting and \"shape\" of the code. How should I get around this?</p>\n</blockquote>\n\n<p>Treat your PHP and HTML as a single hierarchy, with a single, consistent indentation structure. So a PHP enclosing-structure such as an 'if' or 'for' introduces a new level of indentation, and its contents are always a balanced set of start and end-tags. Essentially you are making your PHP 'well-formed' in the XML sense of the term, whether or not you are actually using XHTML.</p>\n\n<p>Example:</p>\n\n<pre><code><div class=\"prettybox\">\n Hello <?php echo(htmlspecialchars($name)) ?>!\n Your food:\n <?php foreach($foods as $food) { ?>\n <a href=\"/food.php?food=<?php echo(urlencode($food)) ?>\">\n <?php echo(htmlspecialchars($food)) ?>\n </a>\n <?php } ?>\n <?php if (count($foods)==0) { ?>\n (no food today)\n <?php } ?>\n</div>\n</code></pre>\n\n<p>Be wary of the religious dogma around separating logic and markup rearing its head in the answers here again. Whilst certainly you want to keep your business-logic out of your page output code, this doesn't necessarily mean a load of overhead from using separate files, classes, templates and frameworks is really necessary for what you're doing. For a simple application, it is likely to be enough just to put the action/logic stuff at the top of the file and the page output below.</p>\n\n<p>(For example from one of the comments above, doing htmlspecialchars() is page-output functionality you definitely <em>don't</em> want to put in the action bit of your PHP, mixed up in all the business logic. Always keep text as plain, unescaped strings until the point where it leaves your application logic. If typing 'echo(htmlspecialchars(...))' all the time is too wordy, you can always make a function with a short name like 'h' that does the same.)</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
]
| I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times.
Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)?
Thanks! | Don't panic, every fresh Web programmer face this problem.
You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page :
* one with only PHP code (no HTML) that fills variables
* another with HTML and very few PHP : this is your page design
Then include where / when you need it. E.G :
myPageLogic.php
```
<?php
// pure PHP code, no HTML
$name = htmlspecialchars($_GET['name']);
$age = date('Y') - htmlspecialchars($_GET['age']);
?>
```
myPageView.php
```
// very few php code
// just enought to print variables
// and some if / else, or foreach to manage the data stream
<h1>Hello, <?php $name ?> !</h1>
<p>So your are <?php $age?>, hu ?</p>
```
(You may want to use the [alternative PHP syntax](http://php.mirror.camelnetwork.com/manual/en/control-structures.alternative-syntax.php) for this one. But don't try to hard to make it perfect the first time, really.)
myPage.php
```
<?php
require('myPageLogic.php');
require('myPageView.php');
?>
```
*Don't bother about performance issues for now*. This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics.
Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the *NEXT TIME*. Then you'll try some templating systems and frameworks, but *LATER*. For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine. |
113,103 | <p>Can anyone explain the difference between the "name" property of a display object and the value found by <em>getChildByName("XXX")</em> function? They're the same 90% of the time, until they aren't, and things fall apart.</p>
<p>For example, in the code below, I find an object by instance name only by directly examining the child's name property; <em>getChildByName()</em> fails. </p>
<pre><code>var gfx:MovieClip = new a_Character(); //(a library object exported for Actionscript)
var do1:DisplayObject = null;
var do2:DisplayObject = null;
for( var i:int = 0 ; i < gfx.amSword.numChildren ; i++ )
{
var child:DisplayObject = gfx.amSword.getChildAt(i);
if( child.name == "amWeaponExchange" ) //An instance name set in the IDE
{
do2 = child;
}
}
trace("do2:", do2 );
var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange");
</code></pre>
<p>Generates the following output:</p>
<pre><code>do2: [object MovieClip]
ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value.
</code></pre>
<p>Any ideas what Flash is thinking?</p>
| [
{
"answer_id": 113603,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't really managed to understand what it is you're doing. But one thing I've found is that accessing MovieClip's children in the very first frame is a bit unreliable. For instance you can't gotoAndStop() and then access whatever children is on that frame, you have to wait a frame before they will be available. </p>\n"
},
{
"answer_id": 114389,
"author": "Iain",
"author_id": 11911,
"author_profile": "https://Stackoverflow.com/users/11911",
"pm_score": 0,
"selected": false,
"text": "<p>In one place you are looping through gfx.amSword and in another e.gfx.amSword - are you missing the e. ?</p>\n\n<p>Also, it's not the cause of your problem, but class names should start a with capital letter and not include underscores. \"a_Character\" should just be \"Character\".</p>\n"
},
{
"answer_id": 115255,
"author": "Matt W",
"author_id": 4969,
"author_profile": "https://Stackoverflow.com/users/4969",
"pm_score": 0,
"selected": false,
"text": "<p>Oops, you're right about the e, Iain, but that's not the problem, I removed the e from the code to focus on the problem, but didn't catch that one. </p>\n\n<p>I think I should post a clearer example of the failure. The funny class name is just my personal naming convention for classes auto-generated by the Flash IDE with \"export for Actionscript\", but it's confusing the issue. </p>\n"
},
{
"answer_id": 115302,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": -1,
"selected": false,
"text": "<p>I misunderstood with my first answer.</p>\n\n<p>This may have something to do with the Flash IDE Publish setting: \"Automatically declare stage instances\" in the ActionScript 3.0 Settings dialog.?? </p>\n"
},
{
"answer_id": 122029,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 2,
"selected": false,
"text": "<p>It seems you fixed it yourself! </p>\n\n<p>With:</p>\n\n<pre><code>var do1:DisplayObject = gfx.amSword.getChildByName[\"amWeaponExchange\"];\n</code></pre>\n\n<p>You get the error:</p>\n\n<pre><code>ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value.\n</code></pre>\n\n<p>Because the compiler is looking for the property \"amWeaponExchange\" on the actual getChildByName <strong>method</strong>.</p>\n\n<p>When you change it to:</p>\n\n<pre><code>var do1:DisplayObject = gfx.amSword.getChildByName(\"amWeaponExchange\");\n</code></pre>\n\n<p>As you did in your edit, it successfully finds the child and compiles.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4969/"
]
| Can anyone explain the difference between the "name" property of a display object and the value found by *getChildByName("XXX")* function? They're the same 90% of the time, until they aren't, and things fall apart.
For example, in the code below, I find an object by instance name only by directly examining the child's name property; *getChildByName()* fails.
```
var gfx:MovieClip = new a_Character(); //(a library object exported for Actionscript)
var do1:DisplayObject = null;
var do2:DisplayObject = null;
for( var i:int = 0 ; i < gfx.amSword.numChildren ; i++ )
{
var child:DisplayObject = gfx.amSword.getChildAt(i);
if( child.name == "amWeaponExchange" ) //An instance name set in the IDE
{
do2 = child;
}
}
trace("do2:", do2 );
var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange");
```
Generates the following output:
```
do2: [object MovieClip]
ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value.
```
Any ideas what Flash is thinking? | It seems you fixed it yourself!
With:
```
var do1:DisplayObject = gfx.amSword.getChildByName["amWeaponExchange"];
```
You get the error:
```
ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value.
```
Because the compiler is looking for the property "amWeaponExchange" on the actual getChildByName **method**.
When you change it to:
```
var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange");
```
As you did in your edit, it successfully finds the child and compiles. |
113,131 | <p>What WPF Calendar control would you recommend? I am looking for something that will let me display a variable amount of weeks potentially spanning multiple months.</p>
| [
{
"answer_id": 113188,
"author": "Dominic Hopton",
"author_id": 9475,
"author_profile": "https://Stackoverflow.com/users/9475",
"pm_score": 0,
"selected": false,
"text": "<p>I would take a look at <a href=\"http://j832.com/BagOTricks/\" rel=\"nofollow noreferrer\">Kevin's Bag-o-tricks</a></p>\n"
},
{
"answer_id": 1421799,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": true,
"text": "<p>Microsoft has now released a WPF calendar control.</p>\n<pre><code><c:Calendar>\n <c:DatePicker.BlackoutDates>\n <c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/>\n <c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/>\n </c:DatePicker.BlackoutDates>\n</c:Calendar>\n<c:DatePicker>\n <c:DatePicker.BlackoutDates>\n <c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/>\n <c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/>\n </c:DatePicker.BlackoutDates>\n</c:DatePicker>\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/7WmdW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7WmdW.png\" alt=\"\" /></a><br />\n<sub>(source: <a href=\"http://windowsclient.net/SiteFiles/1000/wpfsp1/wpf-35sp1-toolkit/110-1.png\" rel=\"nofollow noreferrer\">windowsclient.net</a>)</sub></p>\n<ul>\n<li><a href=\"http://www.codeplex.com/wpf\" rel=\"nofollow noreferrer\">http://www.codeplex.com/wpf</a></li>\n<li><a href=\"http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx\" rel=\"nofollow noreferrer\">http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx</a></li>\n</ul>\n<p>Charles Petzold wrote a <a href=\"http://msdn.microsoft.com/en-us/magazine/dd882520.aspx\" rel=\"nofollow noreferrer\">good article about customising the WPF calendar control</a> too.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618/"
]
| What WPF Calendar control would you recommend? I am looking for something that will let me display a variable amount of weeks potentially spanning multiple months. | Microsoft has now released a WPF calendar control.
```
<c:Calendar>
<c:DatePicker.BlackoutDates>
<c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/>
<c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/>
</c:DatePicker.BlackoutDates>
</c:Calendar>
<c:DatePicker>
<c:DatePicker.BlackoutDates>
<c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/>
<c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/>
</c:DatePicker.BlackoutDates>
</c:DatePicker>
```
[](https://i.stack.imgur.com/7WmdW.png)
(source: [windowsclient.net](http://windowsclient.net/SiteFiles/1000/wpfsp1/wpf-35sp1-toolkit/110-1.png))
* <http://www.codeplex.com/wpf>
* <http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx>
Charles Petzold wrote a [good article about customising the WPF calendar control](http://msdn.microsoft.com/en-us/magazine/dd882520.aspx) too. |
113,150 | <p>I have the following situation:</p>
<pre><code>
class A
{
public:
A(int whichFoo);
int foo1();
int foo2();
int foo3();
int callFoo(); // cals one of the foo's depending on the value of whichFoo
};
</code></pre>
<p>In my current implementation I save the value of <code>whichFoo</code> in a data member in the constructor and use a <code>switch</code> in <code>callFoo()</code> to decide which of the foo's to call. Alternatively, I can use a <code>switch</code> in the constructor to save a pointer to the right <code>fooN()</code> to be called in <code>callFoo()</code>. </p>
<p>My question is which way is more efficient if an object of class A is only constructed once, while <code>callFoo()</code> is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a <code>switch</code>?</p>
<p>Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. </p>
<p>Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) </p>
| [
{
"answer_id": 113155,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "<p>How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?</p>\n\n<p>In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually <em>measure</em> the different choices. You may be surprised!</p>\n\n<p>More info: There is an excellent article <a href=\"http://www.codeproject.com/KB/cpp/FastDelegate.aspx\" rel=\"noreferrer\">Member Function Pointers and the Fastest Possible C++ Delegates</a> which goes into very deep detail about the implementation of member function pointers.</p>\n"
},
{
"answer_id": 113158,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like you should make <code>callFoo</code> a pure virtual function and create some subclasses of <code>A</code>.</p>\n\n<p>Unless you really need the speed, have done extensive profiling and instrumenting, and determined that the calls to <code>callFoo</code> are really the bottleneck. Have you?</p>\n"
},
{
"answer_id": 113162,
"author": "DocMax",
"author_id": 6234,
"author_profile": "https://Stackoverflow.com/users/6234",
"pm_score": 2,
"selected": false,
"text": "<p>To answer the asked question: at the finest-grained level, the pointer to the member function will perform better.</p>\n\n<p>To address the unasked question: what does \"better\" mean here? In most cases I would expect the difference to be negligible. Depending on what the class it doing, however, the difference may be significant. Performance testing before worrying about the difference is obviously the right first step.</p>\n"
},
{
"answer_id": 113168,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 1,
"selected": false,
"text": "<p>Function pointers are almost always better than chained-ifs. They make cleaner code, and are nearly always faster (except perhaps in a case where its only a choice between two functions and is always correctly predicted).</p>\n"
},
{
"answer_id": 113169,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 2,
"selected": false,
"text": "<p>If you are going to keep using a switch, which is perfectly fine, then you probably should put the logic in a helper method and call if from the constructor. Alternatively, this is a classic case of the <a href=\"http://www.dofactory.com/Patterns/PatternStrategy.aspx\" rel=\"nofollow noreferrer\">Strategy Pattern</a>. You could create an interface (or abstract class) named IFoo which has one method with Foo's signature. You would have the constructor take in an instance of IFoo (constructor <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependancy Injection</a> that implemented the foo method that you want. You would have a private IFoo that would be set with this constructor, and every time you wanted to call Foo you would call your IFoo's version.</p>\n\n<p>Note: I haven't worked with C++ since college, so my lingo might be off here, ut the general ideas hold for most OO languages.</p>\n"
},
{
"answer_id": 113171,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 1,
"selected": false,
"text": "<p>I should think that the pointer would be faster.</p>\n\n<p>Modern CPUs prefetch instructions; mis-predicted branches flush the cache, which means it stalls while it refills the cache. A pointer doens't do that.</p>\n\n<p>Of course, you should measure both.</p>\n"
},
{
"answer_id": 113329,
"author": "cos",
"author_id": 14535,
"author_profile": "https://Stackoverflow.com/users/14535",
"pm_score": 3,
"selected": false,
"text": "<p>You can write this:</p>\n\n<pre><code>class Foo {\npublic:\n Foo() {\n calls[0] = &Foo::call0;\n calls[1] = &Foo::call1;\n calls[2] = &Foo::call2;\n calls[3] = &Foo::call3;\n }\n void call(int number, int arg) {\n assert(number < 4);\n (this->*(calls[number]))(arg);\n }\n void call0(int arg) {\n cout<<\"call0(\"<<arg<<\")\\n\";\n }\n void call1(int arg) {\n cout<<\"call1(\"<<arg<<\")\\n\";\n }\n void call2(int arg) {\n cout<<\"call2(\"<<arg<<\")\\n\";\n }\n void call3(int arg) {\n cout<<\"call3(\"<<arg<<\")\\n\";\n }\nprivate:\n FooCall calls[4];\n};\n</code></pre>\n\n<p>The computation of the actual function pointer is linear and fast: </p>\n\n<pre><code> (this->*(calls[number]))(arg);\n004142E7 mov esi,esp \n004142E9 mov eax,dword ptr [arg] \n004142EC push eax \n004142ED mov edx,dword ptr [number] \n004142F0 mov eax,dword ptr [this] \n004142F3 mov ecx,dword ptr [this] \n004142F6 mov edx,dword ptr [eax+edx*4] \n004142F9 call edx \n</code></pre>\n\n<p>Note that you don't even have to fix the actual function number in the constructor. </p>\n\n<p>I've compared this code to the asm generated by a <code>switch</code>. The <code>switch</code> version doesn't provide any performance increase.</p>\n"
},
{
"answer_id": 113532,
"author": "Greg Whitfield",
"author_id": 2102,
"author_profile": "https://Stackoverflow.com/users/2102",
"pm_score": 2,
"selected": false,
"text": "<p>If your example is real code, then I think you should revisit your class design. Passing in a value to the constructor, and using that to change behaviour is really equivalent to creating a subclass. Consider refactoring to make it more explicit. The effect of doing so is that your code will end up using a function pointer (all virtual methods are, really, are function pointers in jump tables).</p>\n\n<p>If, however your code was just a simplified example to ask whether, in general, jump tables are faster than switch statements, then my intuition would say that jump tables are quicker, but you are dependent on the compiler's optimisation step. But if performance is really such a concern, never rely on intuition - knock up a test program and test it, or look at the generated assembler.</p>\n\n<p>One thing is certain, a switch statement will never be slower than a jump table. The reason being that the best a compiler's optimiser can do will be too turn a series of conditional tests (i.e. a switch) into a jump table. So if you really want to be certain, take the compiler out of the decision process and use a jump table.</p>\n"
},
{
"answer_id": 113955,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 1,
"selected": false,
"text": "<h2>Optimize only when needed</h2>\n\n<p>First: Most of the time you most likely do not care, the difference will be very small. Make sure optimizing this call really makes sense first. Only if your measurements show there is really significant time spent in the call overhead, proceed to optimizing it (shameless plug - Cf. <a href=\"https://stackoverflow.com/questions/93479/how-to-optimize-an-application-to-make-it-faster\">How to optimize an application to make it faster?</a>) If the optimization is not significant, prefer the more readable code.</p>\n\n<h2>Indirect call cost depends on target platform</h2>\n\n<p>Once you have determined it is worth to apply low-level optimization, then it is a time to understand your target platform. The cost you can avoid here is the branch misprediction penalty. On modern x86/x64 CPU this misprediction is likely to be very small (they can predict indirect calls quite well most of the time), but when targeting PowerPC or other RISC platforms, the indirect calls/jumps are often not predicted at all and avoiding them can cause significant performance gain. See also <a href=\"https://stackoverflow.com/questions/113830/performance-penalty-for-working-with-interfaces-in-c#114000\">Virtual call cost depends on platform</a>.</p>\n\n<h2>Compiler can implement switch using jump table as well</h2>\n\n<p>One gotcha: Switch can sometimes be implemented as an indirect call (using a table) as well, especially when switching between many possible values. Such switch exhibits the same misprediction as a virtual function. To make this optimization reliable, one would probably prefer using if instead of switch for the most common case.</p>\n"
},
{
"answer_id": 114877,
"author": "Dynite",
"author_id": 16177,
"author_profile": "https://Stackoverflow.com/users/16177",
"pm_score": 1,
"selected": false,
"text": "<p>Use timers to see which is quicker. Although unless this code is going to be over and over then it's unlikely that you'll notice any difference.</p>\n\n<p>Be sure that if you are running code from the constructor that if the contruction fails that you wont leak memory.</p>\n\n<p>This technique is used heavily with Symbian OS:\n<a href=\"http://www.titu.jyu.fi/modpa/Patterns/pattern-TwoPhaseConstruction.html\" rel=\"nofollow noreferrer\">http://www.titu.jyu.fi/modpa/Patterns/pattern-TwoPhaseConstruction.html</a></p>\n"
},
{
"answer_id": 114908,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>If you are only calling callFoo() once, than <em>most likely</em> the function pointer will be slower by an insignificant amount. If you are calling it many times than <em>most likely</em> the function pointer will be faster by an insignificant amount (because it doesn't need to keep going through the switch).</p>\n\n<p>Either way look at the assembled code to find out for sure it is doing what you think it is doing.</p>\n"
},
{
"answer_id": 114948,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "<p>One often overlooked advantage to switch (even over sorting and indexing) is if you know that a particular value is used in the vast majority of cases.\nIt's easy to order the switch so that the most common are checked first.</p>\n\n<p>ps. To reinforce greg's answer, if you care about speed - measure.\nLooking at assembler doesn't help when CPUs have prefetch / predictive branching and pipeline stalls etc</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13313/"
]
| I have the following situation:
```
class A
{
public:
A(int whichFoo);
int foo1();
int foo2();
int foo3();
int callFoo(); // cals one of the foo's depending on the value of whichFoo
};
```
In my current implementation I save the value of `whichFoo` in a data member in the constructor and use a `switch` in `callFoo()` to decide which of the foo's to call. Alternatively, I can use a `switch` in the constructor to save a pointer to the right `fooN()` to be called in `callFoo()`.
My question is which way is more efficient if an object of class A is only constructed once, while `callFoo()` is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a `switch`?
Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it.
Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) | How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?
In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually *measure* the different choices. You may be surprised!
More info: There is an excellent article [Member Function Pointers and the Fastest Possible C++ Delegates](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) which goes into very deep detail about the implementation of member function pointers. |
113,185 | <p>I've installed <a href="http://www.owfs.org/" rel="nofollow noreferrer"><code>owfs</code></a> and am trying to read the data off a <a href="http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088" rel="nofollow noreferrer">iButton temperature logger</a>.</p>
<p><code>owfs</code> lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by <code>cat</code>ting the files, e.g. <code>cat onewire/{deviceid}/log/temperature.1</code>, but the <code>onewire/{deviceid}/log/temperature.ALL</code> file is "broken" (possible too large, as <code>histogram/temperature.ALL</code> work fine). </p>
<p>A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?</p>
<p>I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.</p>
<p><strong>Update</strong>: Using <a href="http://owfs.sourceforge.net/owpython.html" rel="nofollow noreferrer"><code>owpython</code></a> (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:</p>
<pre><code>>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
</code></pre>
<p><code>x.log</code> gives an <code>AttributeError</code>.</p>
| [
{
"answer_id": 117532,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there is a clever way. owpython doesn't support that telling from the API documentation. I guess <code>/proc</code> is your safest bet. Maybe have a look at the source of the owpython module and check if you can find out how it works.</p>\n"
},
{
"answer_id": 181511,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 2,
"selected": false,
"text": "<p>I've also had problems with owfs. I found it to be an overengineered solution to what is a simple problem. Now I'm using the <a href=\"http://www.digitemp.com/\" rel=\"nofollow noreferrer\">DigiTemp</a> code without a problem. I found it to be flexible and reliable. For instance, I store the room's temperature in a log file every minute by running</p>\n\n<pre><code>/usr/local/bin/digitemp_DS9097U -c /usr/local/etc/digitemp.conf \\\n -q -t0 -n0 -d60 -l/var/log/temperature\n</code></pre>\n\n<p>To reach that point I downloaded the source file, untarred it and then did the following.</p>\n\n<pre><code># Compile the hardware-specific command\nmake ds9097u\n# Initialize the configuration file\n./digitemp_DS9097U -s/dev/ttyS0 -i\n# Run command to obtain temperature, and verify your setup\n./digitemp_DS9097U -a \n# Copy the configuration file to an accessible place\ncp .digitemprc /usr/local/etc/digitemp.conf\n</code></pre>\n\n<p>I also hand-edited my configuration file to adjust it to my setup. This is how it ended-up.</p>\n\n<pre><code>TTY /dev/ttyS0\nREAD_TIME 1000\nLOG_TYPE 1\nLOG_FORMAT \"%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F\"\nCNT_FORMAT \"%b %d %H:%M:%S Sensor %s #%n %C\"\nHUM_FORMAT \"%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F H: %h%%\"\nSENSORS 1\nROM 0 0x10 0xD3 0x5B 0x07 0x00 0x00 0x00 0x05 \n</code></pre>\n\n<p>In my case I also created a /etc/init.d/digitemp file and enabled it to run at startup.</p>\n\n<pre><code>#! /bin/sh\n#\n# System startup script for the temperature monitoring daemon\n#\n### BEGIN INIT INFO\n# Provides: digitemp\n# Required-Start:\n# Should-Start:\n# Required-Stop:\n# Should-Stop:\n# Default-Start: 2 3 5\n# Default-Stop: 0 1 6\n# Description: Start the temperature monitoring daemon\n### END INIT INFO\n\nDIGITEMP=/usr/local/bin/digitemp_DS9097U\ntest -x $DIGITEMP || exit 5\n\nDIGITEMP_CONFIG=/root/digitemp.conf\ntest -f $DIGITEMP_CONFIG || exit 6\n\nDIGITEMP_LOGFILE=/var/log/temperature\n\n# Source SuSE config\n. /etc/rc.status\n\nrc_reset\ncase \"$1\" in\n start)\n echo -n \"Starting temperature monitoring daemon\"\n startproc $DIGITEMP -c $DIGITEMP_CONFIG -q -t0 -n0 -d60 -l$DIGITEMP_LOGFILE\n rc_status -v\n ;;\n stop)\n echo -n \"Shutting down temperature monitoring daemon\"\n killproc -TERM $DIGITEMP\n rc_status -v\n ;;\n try-restart)\n $0 status >/dev/null && $0 restart\n rc_status\n ;;\n restart)\n $0 stop\n $0 start\n rc_status\n ;;\n force-reload)\n $0 try-restart\n rc_status\n ;;\n reload)\n $0 try-restart\n rc_status\n ;;\n status)\n echo -n \"Checking for temperature monitoring service\"\n checkproc $DIGITEMP\n rc_status -v\n ;;\n *)\n echo \"Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}\"\n exit 1\n ;;\nesac\nrc_exit\n</code></pre>\n"
},
{
"answer_id": 3383201,
"author": "Buteman",
"author_id": 408056,
"author_profile": "https://Stackoverflow.com/users/408056",
"pm_score": 2,
"selected": false,
"text": "<p>Well I have just started to look at ibuttons and want to use python.</p>\n\n<p>This looks more promising:</p>\n\n<p><a href=\"http://www.ohloh.net/p/pyonewire\" rel=\"nofollow noreferrer\">http://www.ohloh.net/p/pyonewire</a></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
]
| I've installed [`owfs`](http://www.owfs.org/) and am trying to read the data off a [iButton temperature logger](http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088).
`owfs` lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by `cat`ting the files, e.g. `cat onewire/{deviceid}/log/temperature.1`, but the `onewire/{deviceid}/log/temperature.ALL` file is "broken" (possible too large, as `histogram/temperature.ALL` work fine).
A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?
I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.
**Update**: Using [`owpython`](http://owfs.sourceforge.net/owpython.html) (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:
```
>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
```
`x.log` gives an `AttributeError`. | I don't think there is a clever way. owpython doesn't support that telling from the API documentation. I guess `/proc` is your safest bet. Maybe have a look at the source of the owpython module and check if you can find out how it works. |
113,218 | <p>I'm trying to build a web page with a number of drop-down select boxes that load their options asynchronously when the box is first opened. This works very well under Firefox, but not under Internet Explorer.</p>
<p>Below is a small example of what I'm trying to achieve. Basically, there is a select box (with the id "selectBox"), which contains just one option ("Any"). Then there is an <code>onmousedown</code> handler that loads the other options when the box is clicked.</p>
<pre><code><html>
<head>
<script type="text/javascript">
function appendOption(select,option) {
try {
selectBox.add(option,null); // Standards compliant.
} catch (e) {
selectBox.add(option); // IE only version.
}
}
function loadOptions() {
// Simulate an AJAX request that will call the
// loadOptionsCallback function after 500ms.
setTimeout(loadOptionsCallback,500);
}
function loadOptionsCallback() {
var selectBox = document.getElementById('selectBox');
var option = document.createElement('option');
option.text = 'new option';
appendOption(selectBox,option);
}
</script>
</head>
<body>
<select id="selectBox" onmousedown="loadOptions();">
<option>Any</option>
</select>
</body>
</html>
</code></pre>
<p>The desired behavior (which Firefox does) is:</p>
<ol>
<li>the user see's a closed select box containing "Any".</li>
<li>the user clicks on the select box.</li>
<li>the select box opens to reveal the one and only option ("Any").</li>
<li>500ms later (or when the AJAX call has returned) the dropped-down list expands to include the new options (hard coded to 'new option' in this example).</li>
</ol>
<p>So that's exactly what Firefox does, which is great. However, in Internet Explorer, as soon as the new option is added in "4" the browser closes the select box. The select box does contain the correct options, but the box is closed, requiring the user to click to re-open it.</p>
<p>So, does anyone have any suggestions for how I can load the select control's options asynchronously without IE closing the drop-down box?</p>
<p>I know that I can load the list <em>before</em> the box is even clicked, but the real form I'm developing contains many such select boxes, which are all interrelated, so it will be <strong>much</strong> better for both the client and server if I can load each set of options only when needed.</p>
<p>Also, if the results are loaded synchronously, before the select box's <code>onmousedown</code> handler completes, then IE will show the full list as expected - however, synchronous loading is a <strong>bad</strong> idea here, since it will completely "lock" the browser while the network requests are taking place.</p>
<p>Finally, I've also tried using IE's <code>click()</code> method to open the select box once the new options have been added, but that does not re-open the select box.</p>
<p>Any ideas or suggestions would be really appreciated!! :)</p>
<p>Thanks!</p>
<p>Paul.</p>
| [
{
"answer_id": 113211,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<p>I like <a href=\"http://www.gtk.org/\" rel=\"nofollow noreferrer\">GTK+</a> personally but that or any of the ones you mentioned should be OK. I don't know which is the best in terms of least RAM usage.</p>\n"
},
{
"answer_id": 113213,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 2,
"selected": false,
"text": "<p>Both wx and QT have embedded/universal versions where the widgets are drawn directly.\nThey can both be called from python,but if you have a very small system python or py2exe might not be available.</p>\n"
},
{
"answer_id": 113214,
"author": "Krirk",
"author_id": 17521,
"author_profile": "https://Stackoverflow.com/users/17521",
"pm_score": -1,
"selected": false,
"text": "<p>I think you should try Html Application.It is something like web page it contain DHTML,java script,ActiveX but it is execute like .exe .</p>\n\n<p><strong>Edit:</strong>\nSorry for advice you html application.I just know it can run on windows only.</p>\n"
},
{
"answer_id": 113222,
"author": "Svet",
"author_id": 8934,
"author_profile": "https://Stackoverflow.com/users/8934",
"pm_score": 0,
"selected": false,
"text": "<p>What kind of application is it going to be? Have you considered a web-based application instead? Web-based apps can be super flexible in that sense - you can run them on any platform that has a modern browser.</p>\n"
},
{
"answer_id": 113234,
"author": "prasanna",
"author_id": 18501,
"author_profile": "https://Stackoverflow.com/users/18501",
"pm_score": 2,
"selected": false,
"text": "<p>Unless you want to embed HtmlWindow I'd go with wxWindows... works everywhere without problems so far for me.</p>\n"
},
{
"answer_id": 113330,
"author": "user11323",
"author_id": 11323,
"author_profile": "https://Stackoverflow.com/users/11323",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://trolltech.com/downloads\" rel=\"nofollow noreferrer\">Qt</a> is a good choice to start with. In my opinion it has a best (easy to use, simple & informative) API Documentation. Package also includes many examples - from very basic to complex. And, yep, it`s truly crossplatform.</p>\n\n<p>Check <a href=\"http://trolltech.com/products/qt/learnmore/licensing-pricing/licensing\" rel=\"nofollow noreferrer\">Qt Licensing</a> page, the library is free only for GPL projects.</p>\n\n<p>I`m using <a href=\"http://qdevelop.free.fr/\" rel=\"nofollow noreferrer\">QDevelop</a> as text editor, but there are many other alternatives - <a href=\"http://www.eclipse.org/cdt/\" rel=\"nofollow noreferrer\">Eclipse</a>, <a href=\"http://www.kdevelop.org/\" rel=\"nofollow noreferrer\">KDevelop</a>, <a href=\"http://www.codeblocks.org/\" rel=\"nofollow noreferrer\">Code:Blocks</a>, VS plugin & etc.</p>\n"
},
{
"answer_id": 113331,
"author": "Anurag Uniyal",
"author_id": 6946,
"author_profile": "https://Stackoverflow.com/users/6946",
"pm_score": 2,
"selected": true,
"text": "<p>I have both worked with PyQt and wxPython extensively.\nPyQt is better designed and comes with very good UI designer so that you can quickly assemble your UI</p>\n\n<p>wxPython has a very good demo and it can do pretty much anything which PyQT can do, I would anyday prefer PyQt but it may bot be free for commercial purpose but wxPython is free and is decent cross platform library.</p>\n"
},
{
"answer_id": 113677,
"author": "Chii",
"author_id": 17335,
"author_profile": "https://Stackoverflow.com/users/17335",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use swing and java? It is quite cross platform, and looks reasonable for form apps. If you squint a bit and ignore the java, its quite pleasant - or alternatively, use one of them dynamic languages on the JVM (<a href=\"http://groovy.codehaus.org/GUI+Programming+with+Groovy\" rel=\"nofollow noreferrer\">Groovy</a> is my recommended one). </p>\n"
},
{
"answer_id": 176087,
"author": "Paul Lefebvre",
"author_id": 25615,
"author_profile": "https://Stackoverflow.com/users/25615",
"pm_score": 0,
"selected": false,
"text": "<p>By far the simplest choice for creating native cross-platform applications is <a href=\"http://www.realsoftware.com\" rel=\"nofollow noreferrer\">REALbasic</a>. Give it a try and you'll have a working app for Mac OS X, Windows and Linux in minutes. No run-times or other stuff to worry about.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm trying to build a web page with a number of drop-down select boxes that load their options asynchronously when the box is first opened. This works very well under Firefox, but not under Internet Explorer.
Below is a small example of what I'm trying to achieve. Basically, there is a select box (with the id "selectBox"), which contains just one option ("Any"). Then there is an `onmousedown` handler that loads the other options when the box is clicked.
```
<html>
<head>
<script type="text/javascript">
function appendOption(select,option) {
try {
selectBox.add(option,null); // Standards compliant.
} catch (e) {
selectBox.add(option); // IE only version.
}
}
function loadOptions() {
// Simulate an AJAX request that will call the
// loadOptionsCallback function after 500ms.
setTimeout(loadOptionsCallback,500);
}
function loadOptionsCallback() {
var selectBox = document.getElementById('selectBox');
var option = document.createElement('option');
option.text = 'new option';
appendOption(selectBox,option);
}
</script>
</head>
<body>
<select id="selectBox" onmousedown="loadOptions();">
<option>Any</option>
</select>
</body>
</html>
```
The desired behavior (which Firefox does) is:
1. the user see's a closed select box containing "Any".
2. the user clicks on the select box.
3. the select box opens to reveal the one and only option ("Any").
4. 500ms later (or when the AJAX call has returned) the dropped-down list expands to include the new options (hard coded to 'new option' in this example).
So that's exactly what Firefox does, which is great. However, in Internet Explorer, as soon as the new option is added in "4" the browser closes the select box. The select box does contain the correct options, but the box is closed, requiring the user to click to re-open it.
So, does anyone have any suggestions for how I can load the select control's options asynchronously without IE closing the drop-down box?
I know that I can load the list *before* the box is even clicked, but the real form I'm developing contains many such select boxes, which are all interrelated, so it will be **much** better for both the client and server if I can load each set of options only when needed.
Also, if the results are loaded synchronously, before the select box's `onmousedown` handler completes, then IE will show the full list as expected - however, synchronous loading is a **bad** idea here, since it will completely "lock" the browser while the network requests are taking place.
Finally, I've also tried using IE's `click()` method to open the select box once the new options have been added, but that does not re-open the select box.
Any ideas or suggestions would be really appreciated!! :)
Thanks!
Paul. | I have both worked with PyQt and wxPython extensively.
PyQt is better designed and comes with very good UI designer so that you can quickly assemble your UI
wxPython has a very good demo and it can do pretty much anything which PyQT can do, I would anyday prefer PyQt but it may bot be free for commercial purpose but wxPython is free and is decent cross platform library. |
113,253 | <p>My web page sits in a DIV that is 960px wide, I center this DIV in the middle of the page by using the code: </p>
<pre><code>html,body{background: url(images/INF_pageBg.gif) center top repeat-y #777777;text-align:center;}
#container{background-color:#ffffff;width:960px;text-align:left;margin:0 auto 0 auto;}
</code></pre>
<p>I need the background image of the html/body to tile down the middle of the page, which it does, however if the viewable pane in the browser is an odd number of pixels width then the centered background and centered DIV don't align together.</p>
<p>This is only happening in FF.</p>
<p>Does anybody know of a workaround?</p>
| [
{
"answer_id": 113268,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 3,
"selected": true,
"text": "<p>Yeah, it's known issue. Unfortunately you only can fix div and image width, or use script to dynamically change stye.backgroundPosition property. Another trick is to put expression to the CSS class definition.</p>\n"
},
{
"answer_id": 234045,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The (most) common problem is that your background image has an odd number while your container is an even number.\nI have wrote an article in my best English about where I also explain how the browser positioned your picture: <a href=\"http://www.blacktower.nl/2008/03/19/center-div-with-center-background/\" rel=\"nofollow noreferrer\">check it out here</a>.</p>\n"
},
{
"answer_id": 1544631,
"author": "cmc",
"author_id": 187273,
"author_profile": "https://Stackoverflow.com/users/187273",
"pm_score": 2,
"selected": false,
"text": "<p>I found that by making the background image on odd number of pixels wide, the problem goes away for Firefox.</p>\n\n<p>Setting padding:0px 0px 0px 1px; fixes the problem for IE.</p>\n\n<p>Carlo Capocasa, Travian Games</p>\n"
},
{
"answer_id": 4747476,
"author": "Tom",
"author_id": 415721,
"author_profile": "https://Stackoverflow.com/users/415721",
"pm_score": 1,
"selected": false,
"text": "<p>I was able to resolve this with jQuery:</p>\n\n<pre><code>$(document).ready(function(){\n $('body').css({\n 'margin-left': $(document).width()%2\n });\n});\n</code></pre>\n"
},
{
"answer_id": 10725514,
"author": "SequenceDigitale.com",
"author_id": 489281,
"author_profile": "https://Stackoverflow.com/users/489281",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem. </p>\n\n<p>To get the <em>background centered</em>, you need to have a <strong>background-image wider than the viewport</strong>. Try to use a background <strong>2500px</strong> wide. It will force the browser to center the part of image that is viewable.</p>\n\n<p>Let me know if it works for you.</p>\n"
},
{
"answer_id": 17254430,
"author": "SequenceDigitale.com",
"author_id": 489281,
"author_profile": "https://Stackoverflow.com/users/489281",
"pm_score": 0,
"selected": false,
"text": "<p>What about creating a wrapper div with the same background-image.</p>\n\n<pre><code>body{ background: url(your-image.jpg) no-repeat center top; }\n#wrapper{ background: url(your-image.jpg) no-repeat center top; margin: 0 auto; width: 984px; }\n</code></pre>\n\n<p>The wrapper has an even number, the background will keep the same position on any screen size.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/910/"
]
| My web page sits in a DIV that is 960px wide, I center this DIV in the middle of the page by using the code:
```
html,body{background: url(images/INF_pageBg.gif) center top repeat-y #777777;text-align:center;}
#container{background-color:#ffffff;width:960px;text-align:left;margin:0 auto 0 auto;}
```
I need the background image of the html/body to tile down the middle of the page, which it does, however if the viewable pane in the browser is an odd number of pixels width then the centered background and centered DIV don't align together.
This is only happening in FF.
Does anybody know of a workaround? | Yeah, it's known issue. Unfortunately you only can fix div and image width, or use script to dynamically change stye.backgroundPosition property. Another trick is to put expression to the CSS class definition. |
113,275 | <p>Here is what I have:</p>
<pre><code> context "Create ingredient from string" do
context "1 cups butter" do
setup do
@ingredient = Ingredient.create(:ingredient_string => "1 cups butter")
end
should "return unit" do
assert_equal @ingredient.unit, 'cups'
end
should "return amount" do
assert_equal @ingredient.amount, 1.0
end
should "return name" do
assert_equal @ingredient.name, 'butter'
end
end
context "1 (18.25 ounce) package devil's food cake mix with pudding" do
setup do
@ingredient = Ingredient.create(:ingredient_string => "1 (18.25 ounce) package devil's food cake mix with pudding")
end
should "return unit" do
assert_equal @ingredient.unit, '(18.25 ounce) package'
end
should "return amount" do
assert_equal @ingredient.amount, 1.0
end
should "return name" do
assert_equal @ingredient.name, 'devil\'s food cake mix with pudding'
end
end
end
</code></pre>
<p>Clearly there is a lot of duplication there. Any thoughts on how to remove it, if only at the very least the context and the string?</p>
| [
{
"answer_id": 113359,
"author": "Andrew",
"author_id": 17408,
"author_profile": "https://Stackoverflow.com/users/17408",
"pm_score": 0,
"selected": false,
"text": "<p>Personally for this test, I wouldn't use Shoulda.\nYou can easily remove duplication by using dynamic method creation as follows:</p>\n\n<pre><code>class DefineMethodTest < Test::Unit::TestCase\n [{:string => '1 cups butter', :unit => 'cups', :amount => 1.0, :name => 'butter'},{:string => '1 (18.25 ounce) package devil's food cake mix with pudding', :unit => '(18.25 ounce) package', :unit => 1.0, :name => \"devil's food cake mix with pudding\"}].each do |t|\n define_method \"test_create_ingredient_from_string_#{t[:string].downcase.gsub(/[^a-z0-9]+/, '_')}\" do\n @ingredient = Ingredient.create(:ingredient_string => t[:string])\n\n assert_equal @ingredient.unit, t[:unit], \"Should return unit #{t[:unit]}\"\n assert_equal @ingredient.amount, t[:amount], \"Should return amount #{t[:amount]}\"\n assert_equal @ingredient.name, t[:name], \"Should return name #{t[:name]}\"\n end\n end\nend\n</code></pre>\n"
},
{
"answer_id": 113798,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 2,
"selected": false,
"text": "<p>Duplication in tests is not necessarily a Bad Thing(tm)</p>\n\n<p>I suggest you read the following articles from Jay Field</p>\n\n<p><a href=\"http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html\" rel=\"nofollow noreferrer\">http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html</a></p>\n\n<p><a href=\"http://blog.jayfields.com/2008/05/testing-duplicate-code-in-your-tests.html\" rel=\"nofollow noreferrer\">http://blog.jayfields.com/2008/05/testing-duplicate-code-in-your-tests.html</a></p>\n\n<p>They make a convinving case for code duplication in the tests and keeping one assertion per test.</p>\n"
},
{
"answer_id": 114776,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 3,
"selected": true,
"text": "<p>Here's a solution to your specific problem. The idea is to create a class method (like Shoulda's context, setup and should).</p>\n\n<p>Encapsulate the repetition in a class method accepting all varying parts as arguments like this:</p>\n\n<pre><code>def self.should_get_unit_amount_and_name_from_string(unit, amount, name, string_to_analyze)\n context string_to_analyze do\n setup do\n @ingredient = Ingredient.create(:ingredient_string => string_to_analyze)\n end\n\n should \"return unit\" do\n assert_equal @ingredient.unit, unit\n end\n\n should \"return amount\" do\n assert_equal @ingredient.amount, amount\n end\n\n should \"return name\" do\n assert_equal @ingredient.name, name\n end\n end\nend\n</code></pre>\n\n<p>Now you can call all these encapsulated tests with one liners (5-liners here for readability ;-)</p>\n\n<pre><code>context \"Create ingredient from string\" do\n should_get_unit_amount_and_name_from_string(\n 'cups', \n 1.0, \n 'butter', \n \"1 cups butter\")\n should_get_unit_amount_and_name_from_string(\n '(18.25 ounce) package', \n 1.0, \n 'devil\\'s food cake mix with pudding', \n \"1 (18.25 ounce) package devil's food cake mix with pudding\")\nend\n</code></pre>\n\n<p>In some cases, you may want to accept a block which could serve as your Shoulda setup.</p>\n"
},
{
"answer_id": 119292,
"author": "fatgeekuk",
"author_id": 17518,
"author_profile": "https://Stackoverflow.com/users/17518",
"pm_score": 1,
"selected": false,
"text": "<p>Tests/specs are not production code and so being dry is not a priority.</p>\n\n<p>The principle is that the specs should be clear to read, even if it means there is duplication of text across tests.</p>\n\n<p>Don't be too concerned about specs being dry. Overemphasis of dry tests tends to make things more difficult as you have to jump around to the definitions of things to understand what is happening.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
]
| Here is what I have:
```
context "Create ingredient from string" do
context "1 cups butter" do
setup do
@ingredient = Ingredient.create(:ingredient_string => "1 cups butter")
end
should "return unit" do
assert_equal @ingredient.unit, 'cups'
end
should "return amount" do
assert_equal @ingredient.amount, 1.0
end
should "return name" do
assert_equal @ingredient.name, 'butter'
end
end
context "1 (18.25 ounce) package devil's food cake mix with pudding" do
setup do
@ingredient = Ingredient.create(:ingredient_string => "1 (18.25 ounce) package devil's food cake mix with pudding")
end
should "return unit" do
assert_equal @ingredient.unit, '(18.25 ounce) package'
end
should "return amount" do
assert_equal @ingredient.amount, 1.0
end
should "return name" do
assert_equal @ingredient.name, 'devil\'s food cake mix with pudding'
end
end
end
```
Clearly there is a lot of duplication there. Any thoughts on how to remove it, if only at the very least the context and the string? | Here's a solution to your specific problem. The idea is to create a class method (like Shoulda's context, setup and should).
Encapsulate the repetition in a class method accepting all varying parts as arguments like this:
```
def self.should_get_unit_amount_and_name_from_string(unit, amount, name, string_to_analyze)
context string_to_analyze do
setup do
@ingredient = Ingredient.create(:ingredient_string => string_to_analyze)
end
should "return unit" do
assert_equal @ingredient.unit, unit
end
should "return amount" do
assert_equal @ingredient.amount, amount
end
should "return name" do
assert_equal @ingredient.name, name
end
end
end
```
Now you can call all these encapsulated tests with one liners (5-liners here for readability ;-)
```
context "Create ingredient from string" do
should_get_unit_amount_and_name_from_string(
'cups',
1.0,
'butter',
"1 cups butter")
should_get_unit_amount_and_name_from_string(
'(18.25 ounce) package',
1.0,
'devil\'s food cake mix with pudding',
"1 (18.25 ounce) package devil's food cake mix with pudding")
end
```
In some cases, you may want to accept a block which could serve as your Shoulda setup. |
113,341 | <p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p>
<p>Here is an example of what I have:</p>
<pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
</code></pre>
<p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p>
<p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p>
<p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p>
<p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p>
<p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
| [
{
"answer_id": 113374,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 0,
"selected": false,
"text": "<p>If I understood you correctly, then the answer is: You can't.</p>\n\n<p>intelligence should be an attribute of WizardPageSimple, if you'd want both classes to inherit it.</p>\n\n<p>Depending on your situation, you might try to extract intelligence and related attributes into another baseclass. Then you could inherit from both:</p>\n\n<pre><code>class MOS(wiz.WizardPageSimple, wiz.IntelligenceAttributes): # Or something like that.\n</code></pre>\n\n<p>In that case you <strong>must</strong> use the co-operative super. In fact, you should be using it already. Instead of calling </p>\n\n<pre><code>wiz.WizardPageSimple.__init__(self, parent)\n</code></pre>\n\n<p>call</p>\n\n<pre><code>super(MOS, self).__init__(self, parent)\n</code></pre>\n"
},
{
"answer_id": 113388,
"author": "Devin Jeanpierre",
"author_id": 18515,
"author_profile": "https://Stackoverflow.com/users/18515",
"pm_score": 1,
"selected": false,
"text": "<p>All you need is a reference. It's not really a simple problem that I can give some one-line solution to (other than a simple ugly global that would probably break something else), but one of program structure. You don't magically get access to a variable that was created on another instance of another class. You have to either give the intelligence reference to MOS, or take it from BasicInfoPage, however that might happen. It seems to me that the classes are designed rather oddly-- an information page, for one thing, should not generate anything, and if it does, it should give it back to whatever needs to know-- some sort of central place, which should have been the one generating it in the first place. Ordinarily, you'd set the variables there, and get them from there. Or at least, I would.</p>\n\n<p>If you want the basic answer of \"how do I pass variables between different classes\", then here you go, but I doubt it's exactly what you want, as you look to be using some sort of controlling framework:</p>\n\n<pre><code>class Foo(object):\n def __init__(self, var):\n self.var = var\n\nclass Bar(object):\n def do_something(self, var):\n print var*3\n\nif __name__ == '__main__':\n f = Foo(3)\n b = Bar()\n # look, I'm using the variable from one instance in another!\n b.do_something(f.var)\n</code></pre>\n"
},
{
"answer_id": 114114,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": true,
"text": "<p>You may have \"Class\" and \"Instance\" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes.</p>\n\n<p>Classes don't really have usable attribute values. A class is just a common set of definitions for a collection of objects. You should think of of classes as definitions, not actual things.</p>\n\n<p>Instances of classes, \"objects\", are actual things that have actual attribute values and execute method functions.</p>\n\n<p>You don't pass variables among <em>classes</em>. You pass variables among <em>instances</em>. As a practical matter only instance variables matter. [Yes, there are class variables, but they're a fairly specialized and often confusing thing, best avoided.]</p>\n\n<p>When you create an object (an instance of a class)</p>\n\n<pre><code>b= BasicInfoPage(...)\n</code></pre>\n\n<p>Then <code>b.intelligence</code> is the value of intelligence for the <code>b</code> instance of <code>BasicInfoPage</code>.</p>\n\n<p>A really common thing is </p>\n\n<pre><code>class MOS( wx.wizard.PageSimple ):\n def __init__( self, parent, title, basicInfoPage ):\n <snip>\n self.basicInfo= basicInfoPage\n</code></pre>\n\n<p>Now, within MOS methods, you can say <code>self.basicInfo.intelligence</code> because MOS has an object that's a BasicInfoPage available to it.</p>\n\n<p>When you build MOS, you provide it with the instance of BasicInfoPage that it's supposed to use.</p>\n\n<pre><code>someBasicInfoPage= BasicInfoPage( ... ) \nm= MOS( ..., someBasicInfoPage )\n</code></pre>\n\n<p>Now, the object <code>m</code> can examine <code>someBasicInfoPage.intelligence</code> </p>\n"
},
{
"answer_id": 114128,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Each page of a Wizard -- by itself -- shouldn't actually be the container for the information you're gathering.</p>\n\n<p>Read up on the <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow noreferrer\">Model-View-Control</a> design pattern. Your pages have the View and Control parts of the design. They aren't the data model, however.</p>\n\n<p>You'll be happier if you have a separate object that is \"built\" by the pages. Each page will set some attributes of that underlying model object. Then, the pages are independent of each other, since the pages all get and set values of this underlying model object.</p>\n\n<p>Since you're building a character, you'd have some class like this</p>\n\n<pre><code>class Character( object ):\n def __init__( self ):\n self.intelligence= 10\n <default values for all attributes.>\n</code></pre>\n\n<p>Then your various Wizard instances just need to be given the underlying Character object as a place to put and get values.</p>\n"
},
{
"answer_id": 120109,
"author": "crystalattice",
"author_id": 18676,
"author_profile": "https://Stackoverflow.com/users/18676",
"pm_score": 2,
"selected": false,
"text": "<p>My problem was indeed the confusion of classes vs. instances. I was trying to do everything via classes without ever creating an actual instance. Plus, I was forcing the \"BasicInfoPage\" class to do too much work.</p>\n\n<p>Ultimately, I created a new class (<strong>BaseAttribs</strong>) to hold all the variables I need. I then created in instance of that class when I run the wizard and pass that instance as an argument to the classes that need it, as shown below:</p>\n\n<pre><code>#---Run the wizard\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n wizard = wiz.Wizard(None, -1, \"TW2K Character Creation\")\n attribs = BaseAttribs\n\n#---Create each page\n page1 = IntroPage(wizard, \"Introduction\")\n page2 = BasicInfoPage(wizard, \"Basic Info\", attribs)\n page3 = Ethnicity(wizard, \"Ethnicity\")\n page4 = MOS(wizard, \"Military Occupational Specialty\", attribs)\n</code></pre>\n\n<p>I then used the information S.Lott provided and created individual instances (if that's what it's called) within each class; each class is accessing the same variables though.</p>\n\n<p>Everything works, as far as I can tell. Thanks.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
]
| I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.
Here is an example of what I have:
```
class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
```
The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?
**Edit** I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.
I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.
I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.
It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. | You may have "Class" and "Instance" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes.
Classes don't really have usable attribute values. A class is just a common set of definitions for a collection of objects. You should think of of classes as definitions, not actual things.
Instances of classes, "objects", are actual things that have actual attribute values and execute method functions.
You don't pass variables among *classes*. You pass variables among *instances*. As a practical matter only instance variables matter. [Yes, there are class variables, but they're a fairly specialized and often confusing thing, best avoided.]
When you create an object (an instance of a class)
```
b= BasicInfoPage(...)
```
Then `b.intelligence` is the value of intelligence for the `b` instance of `BasicInfoPage`.
A really common thing is
```
class MOS( wx.wizard.PageSimple ):
def __init__( self, parent, title, basicInfoPage ):
<snip>
self.basicInfo= basicInfoPage
```
Now, within MOS methods, you can say `self.basicInfo.intelligence` because MOS has an object that's a BasicInfoPage available to it.
When you build MOS, you provide it with the instance of BasicInfoPage that it's supposed to use.
```
someBasicInfoPage= BasicInfoPage( ... )
m= MOS( ..., someBasicInfoPage )
```
Now, the object `m` can examine `someBasicInfoPage.intelligence` |
113,349 | <p>I have an AdvancedDataGrid with a GroupingCollection and a SummaryRow. How do I display the summary row data in bold? Below is my code:</p>
<pre><code><mx:AdvancedDataGrid width="100%" height="100%" id="adg" defaultLeafIcon="{null}" >
<mx:dataProvider>
<mx:GroupingCollection id="gc" source="{dataProvider}">
<mx:Grouping>
<mx:GroupingField name="bankType">
<mx:summaries>
<mx:SummaryRow summaryPlacement="group" id="summaryRow">
<mx:fields>
<mx:SummaryField dataField="t0"
label="t0" operation="SUM" />
</mx:fields>
</mx:SummaryRow>
</mx:summaries>
</mx:GroupingField>
</mx:Grouping>
</mx:GroupingCollection>
</mx:dataProvider>
<mx:columns>
<mx:AdvancedDataGridColumn dataField="GroupLabel"
headerText=""/>
<mx:AdvancedDataGridColumn dataField="name"
headerText="Bank" />
<mx:AdvancedDataGridColumn dataField="t0"
headerText="Amount" formatter="{formatter}"/>
</mx:columns>
</mx:AdvancedDataGrid>
</code></pre>
| [
{
"answer_id": 114323,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 0,
"selected": false,
"text": "<p>If I've understood <a href=\"http://livedocs.adobe.com/flex/3/html/advdatagrid_10.html\" rel=\"nofollow noreferrer\">the documentation</a> correctly, you should be able to do this by specifying the item renderer in the <code>rendererProviders</code> property, and linking the summary to the rendererProvider using a dummy dataField name.</p>\n"
},
{
"answer_id": 374724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=advdatagrid_04.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/html/help.html?content=advdatagrid_04.html</a> should help.</p>\n"
},
{
"answer_id": 469697,
"author": "Ryan Guill",
"author_id": 7186,
"author_profile": "https://Stackoverflow.com/users/7186",
"pm_score": 3,
"selected": true,
"text": "<p>in the past when I have need to do this I had to put a condition in my style function to try and determine if it is a summary row or not. </p>\n\n<pre><code>public function dataGrid_styleFunction (data:Object, column:AdvancedDataGridColumn) : Object \n{ \n var output:Object; \n\n if ( data.children != null ) \n { \n output = {color:0x081EA6, fontWeight:\"bold\", fontSize:14} \n } \n\n\n return output; \n } \n</code></pre>\n\n<p>if it has children, it should be a summary row. I am not sure this is the quote/unquote right way of doing this, but it does work, at least in my uses.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 1465133,
"author": "cloverink",
"author_id": 151940,
"author_profile": "https://Stackoverflow.com/users/151940",
"pm_score": 0,
"selected": false,
"text": "<pre><code> private function styleCallback(data:Object, col:AdvancedDataGridColumn):Object\n {\n if (data[\"city\"] == citySel) \n return {color:0xFF0000,backgroundColor:0xFFF552,\n fontWeight:'bold',fontStyle:'italic'}; \n\n // Return null if the Artist name does not match.\n return null; \n }\n</code></pre>\n"
},
{
"answer_id": 2028932,
"author": "molaro",
"author_id": 413901,
"author_profile": "https://Stackoverflow.com/users/413901",
"pm_score": 0,
"selected": false,
"text": "<p>I wanted to format ONLY my grouping filed, so I set the styleFunction on my ADG, then in my styleCallback() method I checked for a piece of data that exists in my sub rows, but doesn't exist in my group heading. </p>\n\n<p>For example I have Major headings as my groups and then rows of data with Minor headings, and descriptions, etc. So in my function I check for:</p>\n\n<p>if (data[\"MinorHeading\"] == null) return {color:0xFF0000,backgroundColor:0xFFF552,fontWeight:'bold'};</p>\n\n<p>That way only my group headings get formatted in red and bold.<br>\nFYI, the backgroundColor style doesn't apply (I assume I would need a solid color Graphic Renderer to do that)</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16534/"
]
| I have an AdvancedDataGrid with a GroupingCollection and a SummaryRow. How do I display the summary row data in bold? Below is my code:
```
<mx:AdvancedDataGrid width="100%" height="100%" id="adg" defaultLeafIcon="{null}" >
<mx:dataProvider>
<mx:GroupingCollection id="gc" source="{dataProvider}">
<mx:Grouping>
<mx:GroupingField name="bankType">
<mx:summaries>
<mx:SummaryRow summaryPlacement="group" id="summaryRow">
<mx:fields>
<mx:SummaryField dataField="t0"
label="t0" operation="SUM" />
</mx:fields>
</mx:SummaryRow>
</mx:summaries>
</mx:GroupingField>
</mx:Grouping>
</mx:GroupingCollection>
</mx:dataProvider>
<mx:columns>
<mx:AdvancedDataGridColumn dataField="GroupLabel"
headerText=""/>
<mx:AdvancedDataGridColumn dataField="name"
headerText="Bank" />
<mx:AdvancedDataGridColumn dataField="t0"
headerText="Amount" formatter="{formatter}"/>
</mx:columns>
</mx:AdvancedDataGrid>
``` | in the past when I have need to do this I had to put a condition in my style function to try and determine if it is a summary row or not.
```
public function dataGrid_styleFunction (data:Object, column:AdvancedDataGridColumn) : Object
{
var output:Object;
if ( data.children != null )
{
output = {color:0x081EA6, fontWeight:"bold", fontSize:14}
}
return output;
}
```
if it has children, it should be a summary row. I am not sure this is the quote/unquote right way of doing this, but it does work, at least in my uses.
HTH |
113,376 | <p>How do you impose a character limit on a text input in HTML?</p>
| [
{
"answer_id": 113379,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 5,
"selected": false,
"text": "<p>there's a maxlength attribute</p>\n\n<pre><code><input type=\"text\" name=\"textboxname\" maxlength=\"100\" />\n</code></pre>\n"
},
{
"answer_id": 113393,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>use the \"maxlength\" attribute as others have said.</p>\n\n<p>if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: <a href=\"https://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript\">How to impose maxlength on textArea in HTML using JavaScript</a></p>\n"
},
{
"answer_id": 113397,
"author": "Devin Jeanpierre",
"author_id": 18515,
"author_profile": "https://Stackoverflow.com/users/18515",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to the above, I would like to point out that client-side validation (HTML code, javascript, etc.) is never enough. Also check the length server-side, or just don't check at all (if it's not so important that people can be allowed to get around it, then it's not important enough to really warrant any steps to prevent that, either).</p>\n\n<p>Also, fellows, he (or she) said HTML, not XHTML. ;)</p>\n"
},
{
"answer_id": 113408,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 1,
"selected": false,
"text": "<p>For the <input> element there's the maxlength attribute:</p>\n\n<pre><code><input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n</code></pre>\n\n<p>(by the way, the type is \"text\", not \"textbox\" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.</p>\n"
},
{
"answer_id": 113814,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": true,
"text": "<p>There are 2 main solutions:</p>\n\n<p>The pure HTML one:</p>\n\n<pre><code><input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n</code></pre>\n\n<p>The JavaScript one (attach it to a onKey Event):</p>\n\n<pre><code>function limitText(limitField, limitNum) {\n if (limitField.value.length > limitNum) {\n limitField.value = limitField.value.substring(0, limitNum);\n } \n}\n</code></pre>\n\n<p>But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.</p>\n"
},
{
"answer_id": 32886542,
"author": "shekh danishuesn",
"author_id": 5291660,
"author_profile": "https://Stackoverflow.com/users/5291660",
"pm_score": 0,
"selected": false,
"text": "<p>you can set maxlength with jquery which is very fast</p>\n\n<pre><code>jQuery(document).ready(function($){ //fire on DOM ready\n setformfieldsize(jQuery('#comment'), 50, 'charsremain')\n})\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5509/"
]
| How do you impose a character limit on a text input in HTML? | There are 2 main solutions:
The pure HTML one:
```
<input type="text" id="Textbox" name="Textbox" maxlength="10" />
```
The JavaScript one (attach it to a onKey Event):
```
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
```
But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script. |
113,384 | <p>I have a marker interface defined as</p>
<pre><code>public interface IExtender<T>
{
}
</code></pre>
<p>I have a class that implements IExtender</p>
<pre><code>public class UserExtender : IExtender<User>
</code></pre>
<p>At runtime I recieve the UserExtender type as a parameter to my evaluating method</p>
<pre><code>public Type Evaluate(Type type) // type == typeof(UserExtender)
</code></pre>
<p>How do I make my Evaluate method return </p>
<pre><code>typeof(User)
</code></pre>
<p>based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it.</p>
<p>(I was unsure how to word this question. I hope it is clear enough.)</p>
| [
{
"answer_id": 113379,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 5,
"selected": false,
"text": "<p>there's a maxlength attribute</p>\n\n<pre><code><input type=\"text\" name=\"textboxname\" maxlength=\"100\" />\n</code></pre>\n"
},
{
"answer_id": 113393,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>use the \"maxlength\" attribute as others have said.</p>\n\n<p>if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: <a href=\"https://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript\">How to impose maxlength on textArea in HTML using JavaScript</a></p>\n"
},
{
"answer_id": 113397,
"author": "Devin Jeanpierre",
"author_id": 18515,
"author_profile": "https://Stackoverflow.com/users/18515",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to the above, I would like to point out that client-side validation (HTML code, javascript, etc.) is never enough. Also check the length server-side, or just don't check at all (if it's not so important that people can be allowed to get around it, then it's not important enough to really warrant any steps to prevent that, either).</p>\n\n<p>Also, fellows, he (or she) said HTML, not XHTML. ;)</p>\n"
},
{
"answer_id": 113408,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 1,
"selected": false,
"text": "<p>For the <input> element there's the maxlength attribute:</p>\n\n<pre><code><input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n</code></pre>\n\n<p>(by the way, the type is \"text\", not \"textbox\" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.</p>\n"
},
{
"answer_id": 113814,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": true,
"text": "<p>There are 2 main solutions:</p>\n\n<p>The pure HTML one:</p>\n\n<pre><code><input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n</code></pre>\n\n<p>The JavaScript one (attach it to a onKey Event):</p>\n\n<pre><code>function limitText(limitField, limitNum) {\n if (limitField.value.length > limitNum) {\n limitField.value = limitField.value.substring(0, limitNum);\n } \n}\n</code></pre>\n\n<p>But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.</p>\n"
},
{
"answer_id": 32886542,
"author": "shekh danishuesn",
"author_id": 5291660,
"author_profile": "https://Stackoverflow.com/users/5291660",
"pm_score": 0,
"selected": false,
"text": "<p>you can set maxlength with jquery which is very fast</p>\n\n<pre><code>jQuery(document).ready(function($){ //fire on DOM ready\n setformfieldsize(jQuery('#comment'), 50, 'charsremain')\n})\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884/"
]
| I have a marker interface defined as
```
public interface IExtender<T>
{
}
```
I have a class that implements IExtender
```
public class UserExtender : IExtender<User>
```
At runtime I recieve the UserExtender type as a parameter to my evaluating method
```
public Type Evaluate(Type type) // type == typeof(UserExtender)
```
How do I make my Evaluate method return
```
typeof(User)
```
based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it.
(I was unsure how to word this question. I hope it is clear enough.) | There are 2 main solutions:
The pure HTML one:
```
<input type="text" id="Textbox" name="Textbox" maxlength="10" />
```
The JavaScript one (attach it to a onKey Event):
```
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
```
But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script. |
113,385 | <p>Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.</p>
| [
{
"answer_id": 113391,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "<p>You can't declare an instance of an undefined class but you can declare a <strong>pointer</strong> to one:</p>\n\n<pre><code>class A; // Declare that we have a class A without defining it yet.\n\nclass B\n{\npublic:\n A *itemA;\n};\n\nclass A\n{\npublic:\n B *itemB;\n};\n</code></pre>\n"
},
{
"answer_id": 113398,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>Is this close to what you want: The first class contains the second class, but the second class (that is to be created first) just has a reference to the first class?</p>\n"
},
{
"answer_id": 113399,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>You can't do something like this:</p>\n\n<pre><code>class A {\n B b;\n};\nclass B {\n A a;\n};\n</code></pre>\n\n<p>The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!</p>\n\n<p>You can, however, do this:</p>\n\n<pre><code>class B; // this is a \"forward declaration\"\nclass A {\n B *b;\n};\nclass B {\n A a;\n};\n</code></pre>\n\n<p>Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.</p>\n"
},
{
"answer_id": 113403,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 0,
"selected": false,
"text": "<p>This is called cross reference. See <a href=\"http://www.daniweb.com/forums/thread97195.html\" rel=\"nofollow noreferrer\">here</a> an example.</p>\n"
},
{
"answer_id": 115767,
"author": "tfinniga",
"author_id": 9042,
"author_profile": "https://Stackoverflow.com/users/9042",
"pm_score": 2,
"selected": false,
"text": "<p>There's <a href=\"http://acius2.blogspot.com/2007/11/breaking-return-by-value-recursive.html\" rel=\"nofollow noreferrer\">an elegant solution</a> using templates.</p>\n\n<blockquote>\n<pre><code>template< int T > class BaseTemplate {};\ntypedef BaseTemplate< 0 > A;\ntypedef BaseTemplate< 1 > B;\n// A\ntemplate<> class BaseTemplate< 0 >\n{\npublic:\n BaseTemplate() {} // A constructor\n B getB();\n}\n\n// B\ntemplate<> class BaseTemplate< 1 >\n{\npublic:\n BaseTemplate() {} // B constructor\n A getA();\n}\n\ninline B A::getB() { return A(); }\ninline A B::getA() { return B(); }\n</code></pre>\n \n <p>This code will work! So, why does it\n work? The reason has to do with how\n templates are compiled. Templates\n delay the creation of function\n signatures until you actually use the\n template somewhere. This means that\n neither getA() nor getB() will have\n their signatures analyzed until after\n both classes A and B have already been\n fully declared. That's the magic of\n this method.</p>\n</blockquote>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
]
| Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class. | You can't do something like this:
```
class A {
B b;
};
class B {
A a;
};
```
The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!
You can, however, do this:
```
class B; // this is a "forward declaration"
class A {
B *b;
};
class B {
A a;
};
```
Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition. |
113,392 | <p>I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)</p>
<p>My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page_init as it is dependent on values from at previous PostBack.</p>
<p>A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").</p>
<p>Am I going down the wrong path here?</p>
| [
{
"answer_id": 113411,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 0,
"selected": false,
"text": "<p>Well. If you can get out of creating controls dynamicly, then do so - otherwise, what i whould do is to use Page_Load instead of Page_Init, but instead of placing stuff inside the If Not IsPostBack, then set i just directly in the method.</p>\n"
},
{
"answer_id": 113412,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 0,
"selected": false,
"text": "<p>I think the answer here is in the <code>MultiView</code> control, so that for example the dropdown switches between different views in the multi-view.</p>\n\n<p>You can probably even data-bind the current view property of the multiview to the value of the dropdown!</p>\n"
},
{
"answer_id": 113415,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 0,
"selected": false,
"text": "<p>Ah, that's the problem with the leaky abstraction of ASP.NET web forms.</p>\n\n<p>Maybe you'll be interested to look at ASP.NET MVC, which was used for the creation of this stackoverflow.com web site? That should be an easier fit for you, coming from a PHP (thus, pedal-to-the-metal when it comes to HTML and Javascript) background.</p>\n"
},
{
"answer_id": 113445,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 2,
"selected": false,
"text": "<p>You must add your control inside OnInit event and viewstate will be preserved. Don't use if(ispostback), because controls must be added every time, event in postback!<br>\n(De)Serialization of viewstate happens after OnInit and before OnLoad, so your viewstate persistence provider will see dynamically added controls if they are added in OnInit.</p>\n\n<p>But in scenario you're describing, probably multiview or simple hide/show (visible property) will be better solution.<br>\nIt's because in OnInit event, when you must read dropdown and add new controls, viewstate isn't read (deserialized) yet and you don't know what did user choose! (you can do request.form(), but that feels kinda wrong)</p>\n"
},
{
"answer_id": 113499,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 1,
"selected": false,
"text": "<p>If you truly need to use dynamic controls, the following should work:</p>\n<ul>\n<li>In OnInit, recreate the exact same control hierarchy that was on the page when the previous request was fulfilled. (If this isn't the initial request, of course)</li>\n<li>After OnInit, the framework will load the viewstate from the previous request and all your controls should be in a stable state now.</li>\n<li>In OnLoad, remove the controls that are not required and add the necessary ones. You will also have to somehow save the current control tree at this point, to be used in the first step during the following request. You could use a session variable that dictates how the dynamic control tree was created. I even stored the whole Controls collection in the session once (<em>put aside your pitchforks, it was just for a demo</em>).</li>\n</ul>\n<p>Re-adding the "stale" controls that you will not need and will be removed at OnLoad anyway seems a bit quirky, but Asp.Net was not really designed with dynamic control creation in mind. If the exact same control hierarchy is not preserved during viewstate loading, all kinds of hard-to find bugs begin lurking in the page, because states of older controls are loaded into newly added ones.</p>\n<p>Read up on Asp.Net page life cycle and especially on how the viewstate works and it will become clear.</p>\n<p>Edit: This is a very good article about how viewstate behaves and what you should consider while dealing with dynamic controls: <<a href=\"https://web.archive.org/web/20201025173747/http://geekswithblogs.net/FrostRed/archive/2007/02/17/106547.aspx\" rel=\"nofollow noreferrer\">Link</a>></p>\n"
},
{
"answer_id": 113515,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 4,
"selected": true,
"text": "<p>I agree with the other points made here \"If you can get out of creating controls dynamically, then do so...\" (by @<a href=\"https://stackoverflow.com/users/11559/jesper-blad-jensen-aka-deldy\">Jesper Blad Jenson aka</a>) but here is a trick I worked out with dynamically created controls in the past.</p>\n\n<p>The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values <i>just before</i> the rest of the tree is populated. That is by overriding <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadviewstate.aspx\" rel=\"nofollow noreferrer\" title=\"MSDN - Control.LoadViewState Method\"><code>LoadViewState(...)</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.saveviewstate.aspx\" rel=\"nofollow noreferrer\" title=\"MSDN - Control.SaveViewState Method\"><code>SaveViewState(...)</code></a>.</p>\n\n<p>In SaveViewState store the control you wish to create:</p>\n\n<pre><code>protected override object SaveViewState()\n{\n object[] myState = new object[2];\n myState[0] = base.SaveViewState();\n myState[1] = controlPickerDropDown.SelectedValue;\n\n return myState\n}\n</code></pre>\n\n<p>When the framework calls your \"LoadViewState\" override you'll get back the exact object you returned from \"SaveViewState\":</p>\n\n<pre><code>protected override void LoadViewState(object savedState) \n{\n object[] myState = (object[])savedState;\n\n // Here is the trick, use the value you saved here to create your control tree.\n CreateControlBasedOnDropDownValue(myState[1]);\n\n // Call the base method to ensure everything works correctly.\n base.LoadViewState(myState[0]);\n}\n</code></pre>\n\n<p>I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single \"Save\" operation.</p>\n"
},
{
"answer_id": 121607,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "<p>The only correct answer was given by Aydsman. LoadViewState is the only place to add dynamic controls where their viewstate values will be restored when recreated and you can access the viewstate in order to determine which controls to add.</p>\n"
},
{
"answer_id": 124370,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I ran across this in the book \"Pro ASP.NET 3.5 in C# 2008\" under the section Dynamic Control Creation:</p>\n\n<blockquote>\n <p>If you need to re-create a control multiple times, you should perform the control creation in the Page.Load event handler. This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the Page.Load event, ASP.NET will apply any view state information that it has after the Page.Load event handler ends. This process is automatic.</p>\n</blockquote>\n\n<p>I have not tested this, but you might look into it.</p>\n"
},
{
"answer_id": 152179,
"author": "mlarsen",
"author_id": 17700,
"author_profile": "https://Stackoverflow.com/users/17700",
"pm_score": 2,
"selected": false,
"text": "<p>After having wrestled with this problem for at while I have come up with these groundrules which seems to work, but YMMV.</p>\n\n<ul>\n<li>Use declarative controls whenever possible</li>\n<li>Use databinding where possible</li>\n<li>Understand how ViewState works</li>\n<li>The Visibilty property can go a long way</li>\n<li>If you must use add controls in an event handler use Aydsman's tip and recreate the controls in an overridden LoadViewState.</li>\n</ul>\n\n<p><a href=\"http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx\" rel=\"nofollow noreferrer\">TRULY Understanding ViewState</a> is a must-read.</p>\n\n<p><a href=\"http://weblogs.asp.net/infinitiesloop/archive/2008/04/23/truly-understanding-dynamic-controls-by-example.aspx\" rel=\"nofollow noreferrer\">Understanding Dynamic Controls By Example</a> shows some techniques on how to use databinding instead of dynamic controls.</p>\n\n<p><a href=\"http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_.aspx\" rel=\"nofollow noreferrer\">TRULY Understanding Dynamic Controls</a> also clarifies techniques which can be used to avoid dynamic controls.</p>\n\n<p>Hope this helps others with same problems.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17700/"
]
| I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)
My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page\_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page\_init as it is dependent on values from at previous PostBack.
A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").
Am I going down the wrong path here? | I agree with the other points made here "If you can get out of creating controls dynamically, then do so..." (by @[Jesper Blad Jenson aka](https://stackoverflow.com/users/11559/jesper-blad-jensen-aka-deldy)) but here is a trick I worked out with dynamically created controls in the past.
The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values *just before* the rest of the tree is populated. That is by overriding [`LoadViewState(...)`](http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadviewstate.aspx "MSDN - Control.LoadViewState Method") and [`SaveViewState(...)`](http://msdn.microsoft.com/en-us/library/system.web.ui.control.saveviewstate.aspx "MSDN - Control.SaveViewState Method").
In SaveViewState store the control you wish to create:
```
protected override object SaveViewState()
{
object[] myState = new object[2];
myState[0] = base.SaveViewState();
myState[1] = controlPickerDropDown.SelectedValue;
return myState
}
```
When the framework calls your "LoadViewState" override you'll get back the exact object you returned from "SaveViewState":
```
protected override void LoadViewState(object savedState)
{
object[] myState = (object[])savedState;
// Here is the trick, use the value you saved here to create your control tree.
CreateControlBasedOnDropDownValue(myState[1]);
// Call the base method to ensure everything works correctly.
base.LoadViewState(myState[0]);
}
```
I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single "Save" operation. |
113,395 | <p>Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:</p>
<pre><code>[TestMethod]
[ExpectedException(typeof(CriticalException))]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
</code></pre>
<p>You can also check for the message contained within the ExpectedException like this:</p>
<pre><code>[TestMethod]
[ExpectedException(typeof(CriticalException), "An error occured")]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
</code></pre>
<p>But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:</p>
<pre><code>[TestMethod]
[ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
</code></pre>
<p>The compiler will give the following error:</p>
<blockquote>
<p>An attribute argument must be a
constant expression, typeof expression
or array creation expression of an
attribute</p>
</blockquote>
<p>Does anybody know how to test for an exception that has a message from a resource file?</p>
<hr>
<p>One option I have considered is using custom exception classes, but based on often heard advice such as:</p>
<blockquote>
<p>"Do create and throw custom exceptions
if you have an error condition that
can be programmatically handled in a
different way than any other existing
exception. Otherwise, throw one of the
existing exceptions." <a href="http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx" rel="noreferrer">Source</a></p>
</blockquote>
<p>I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?</p>
| [
{
"answer_id": 113420,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can just do an explicit try-catch in your test code instead of relying on the ExpectedException attribute to do it for you. Then you can come up with some helper method that will read the resource file and compare the error message to the one that comes with the exception that was caught. (of course if there wasn't an exception then the test case should be considered a fail)</p>\n"
},
{
"answer_id": 113421,
"author": "Jedidja",
"author_id": 9913,
"author_profile": "https://Stackoverflow.com/users/9913",
"pm_score": 2,
"selected": false,
"text": "<p>If you switch over to using the very nice <a href=\"http://codeplex.com/xunit\" rel=\"nofollow noreferrer\">xUnit.Net</a> testing library, you can replace [ExpectedException] with something like this:</p>\n\n<pre><code>[Fact]\npublic void TestException()\n{\n Exception ex = Record.Exception(() => myClass.DoSomethingExceptional());\n // Assert whatever you like about the exception here.\n}\n</code></pre>\n"
},
{
"answer_id": 113466,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 4,
"selected": true,
"text": "<p><em>Just</em> an opinion, but I would say the error text:</p>\n\n<ul>\n<li>is part of the test, in which case getting it from the resource would be 'wrong' (otherwise you could end up with a consistantly mangled resource), so just update the test when you change the resource (or the test fails)</li>\n<li>is not part of the test, and you should only care that it throws the exception.</li>\n</ul>\n\n<p>Note that the first option should let you test multiple languages, given the ability to run with a locale.</p>\n\n<p>As for multiple exceptions, I'm from C++ land, where creating loads and loads of exceptions (to the point of one per 'throw' statement!) in big heirachies is acceptable (if not common), but .Net's metadata system probably doesn't like that, hence that advice.</p>\n"
},
{
"answer_id": 113496,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "<p>I wonder if NUnit is moving down the path away from simplicity... but here you go.</p>\n\n<p><strong>New enhancements (2.4.3 and up?) to the ExpectedException attribute allow you more control on the checks to be performed on the expected Exception via a Handler method</strong>. More Details on the <a href=\"http://www.nunit.org/index.php?p=exception&r=2.4.3\" rel=\"nofollow noreferrer\">official NUnit doc page</a>.. towards the end of the page.</p>\n\n<pre><code>[ExpectedException( Handler=\"HandlerMethod\" )]\npublic void TestMethod()\n{\n...\n}\n\npublic void HandlerMethod( System.Exception ex )\n{\n...\n}\n</code></pre>\n\n<p><em>Note: Something doesn't feel right here.. Why are your exceptions messages internationalized.. Are you using exceptions for things that need to be handled or notified to the user. Unless you have a bunch of culturally diverse developers fixing bugs.. you shouldn't be needing this. Exceptions in English or a common accepted language would suffice. But in case you have to have this.. its possible :)</em></p>\n"
},
{
"answer_id": 113616,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 6,
"selected": false,
"text": "<p>I would recommend using a helper method instead of an attribute. Something like this:</p>\n\n<pre><code>public static class ExceptionAssert\n{\n public static T Throws<T>(Action action) where T : Exception\n {\n try\n {\n action();\n }\n catch (T ex)\n {\n return ex;\n }\n Assert.Fail(\"Exception of type {0} should be thrown.\", typeof(T));\n\n // The compiler doesn't know that Assert.Fail\n // will always throw an exception\n return null;\n }\n}\n</code></pre>\n\n<p>Then you can write your test something like this:</p>\n\n<pre><code>[TestMethod]\npublic void GetOrganisation_MultipleOrganisations_ThrowsException()\n{\n OrganizationList organizations = new Organizations();\n organizations.Add(new Organization());\n organizations.Add(new Organization());\n\n var ex = ExceptionAssert.Throws<CriticalException>(\n () => organizations.GetOrganization());\n Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);\n}\n</code></pre>\n\n<p>This also has the benefit that it verifies that the exception is thrown on the line you were expecting it to be thrown instead of anywhere in your test method.</p>\n"
},
{
"answer_id": 449610,
"author": "user53794",
"author_id": 53794,
"author_profile": "https://Stackoverflow.com/users/53794",
"pm_score": 4,
"selected": false,
"text": "<p>The ExpectedException Message argument does not match against the message of the exception. Rather this is the message that is printed in the test results if the expected exception did not in fact occur.</p>\n"
},
{
"answer_id": 563033,
"author": "Peter Bernier",
"author_id": 6112,
"author_profile": "https://Stackoverflow.com/users/6112",
"pm_score": 0,
"selected": false,
"text": "<p>I came across this question while trying to resolve a similar issue on my own. (I'll detail the solution that I settled on below.)</p>\n\n<p>I have to agree with Gishu's comments about internationalizing the exception messages being a code smell. </p>\n\n<p>I had done this initially in my own project so that I could have consistency between the error messages throw by my application and in my unit tests. ie, to only have to define my exception messages in one place and at the time, the Resource file seemed like a sensible place to do this since I was already using it for various labels and strings (and since it made sense to add a reference to it in my test code to verify that those same labels showed in the appropriate places).</p>\n\n<p>At one point I had considered (and tested) using try/catch blocks to avoid the requirement of a constant by the ExpectedException attribute, but this seemed like it would lead to quite a lot of extra code if applied on a large scale.</p>\n\n<p>In the end, the solution that I settled on was to create a static class in my Resource library and store my exception messages in that. This way there's no need to internationalize them (which I'll agree doesn't make sense) and they're made accessible anytime that a resource string would be accessible since they're in the same namespace. (This fits with my desire not to make verifying the exception text a complex process.)</p>\n\n<p>My test code then simply boils down to (pardon the mangling...):</p>\n\n<pre><code>[Test, \n ExpectedException(typeof(System.ArgumentException),\n ExpectedException=ProductExceptionMessages.DuplicateProductName)]\npublic void TestCreateDuplicateProduct()\n{\n _repository.CreateProduct(\"TestCreateDuplicateProduct\");\n _repository.CreateProduct(\"TestCreateDuplicateProduct\");\n} \n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5790/"
]
| Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:
```
[TestMethod]
[ExpectedException(typeof(CriticalException))]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
```
You can also check for the message contained within the ExpectedException like this:
```
[TestMethod]
[ExpectedException(typeof(CriticalException), "An error occured")]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
```
But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:
```
[TestMethod]
[ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
```
The compiler will give the following error:
>
> An attribute argument must be a
> constant expression, typeof expression
> or array creation expression of an
> attribute
>
>
>
Does anybody know how to test for an exception that has a message from a resource file?
---
One option I have considered is using custom exception classes, but based on often heard advice such as:
>
> "Do create and throw custom exceptions
> if you have an error condition that
> can be programmatically handled in a
> different way than any other existing
> exception. Otherwise, throw one of the
> existing exceptions." [Source](http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx)
>
>
>
I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions? | *Just* an opinion, but I would say the error text:
* is part of the test, in which case getting it from the resource would be 'wrong' (otherwise you could end up with a consistantly mangled resource), so just update the test when you change the resource (or the test fails)
* is not part of the test, and you should only care that it throws the exception.
Note that the first option should let you test multiple languages, given the ability to run with a locale.
As for multiple exceptions, I'm from C++ land, where creating loads and loads of exceptions (to the point of one per 'throw' statement!) in big heirachies is acceptable (if not common), but .Net's metadata system probably doesn't like that, hence that advice. |
113,504 | <p>Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.</p>
| [
{
"answer_id": 113512,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately there is no way to 100% guarantee that a pointer to anything is still valid, except by meticolously writing the correct code.</p>\n"
},
{
"answer_id": 113514,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 4,
"selected": true,
"text": "<p>If you're using FastMM4 as your Memory Manager, you can check that the class is not <strong>TFreeObject</strong>.<br>\nOr, in a more standard case, use a routine that will verify that your object is what it says it is by <strong>checking the class VMT</strong>.</p>\n\n<p>There have been such ValidateObj functions hannging around for some time (by Ray Lischner and Hallvard Vassbotn: <a href=\"http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html\" rel=\"nofollow noreferrer\">http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html</a>)</p>\n\n<p>Here's another: </p>\n\n<pre><code>function ValidateObj(Obj: TObject): Pointer;\n// see { Virtual method table entries } in System.pas\nbegin\n Result := Obj;\n if Assigned(Result) then\n try\n if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then\n // object not valid anymore\n Result := nil;\n except\n Result := nil;\n end;\nend;\n</code></pre>\n\n<p>Update: A bit of caution... The above function will ensure that the result is either nil or a valid non nil Object. It does not guarantee that the Obj is still what you think it is, in case where the Memory Manager has already reallocated that previously freed memory.</p>\n"
},
{
"answer_id": 113523,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": false,
"text": "<p>No. Unless you use something like reference counting or a garbage collector to make sure no object will be freeed before they have zero references.</p>\n\n<p>Delphi can do reference counting for you if you use interfaces. Of course Delphi for .Net has a gargage collector.</p>\n\n<p>As mentioned you could use the knowledege of Delphi or the memory manager internals to check for valid pointers or objects, but they are not the only ones that can give you pointers. So you can't cover all pointers even with those methods. And there also is a chance that your pointer happens to be valid again, but given to somebody else. So it is not the pointer you are looking for. Your design should not rely on them. Use a tool to detect any reference bugs you make.</p>\n"
},
{
"answer_id": 113527,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 1,
"selected": false,
"text": "<p>Standard, no...</p>\n\n<p>That's why VCL components can register themselves to be notified of the destruction of an object, so that they can remove the reference from there internal list of components or just reset their property.</p>\n\n<p>So if you'd want to make sure you haven't got any invalid references their are two options:</p>\n\n<ul>\n<li>Implement a destruction notification handler which every class can subscribe to.</li>\n<li>Fix your code in a way that the references aren't spread around trough different object. You could for instance only provide the access to the reference via a property of another object. And instead of copying the reference to a private field you access the property of the other object.</li>\n</ul>\n"
},
{
"answer_id": 113725,
"author": "mj2008",
"author_id": 5544,
"author_profile": "https://Stackoverflow.com/users/5544",
"pm_score": 1,
"selected": false,
"text": "<p>As others have said, no definitive way, but if you manage the ownership well, then the FreeAndNil routine will ensure that your variable is nil if it doesn't point to anything. </p>\n"
},
{
"answer_id": 114405,
"author": "Otherside",
"author_id": 18697,
"author_profile": "https://Stackoverflow.com/users/18697",
"pm_score": 1,
"selected": false,
"text": "<p>It's usually not a good idea to check a reference is valid anyway. If a reference is not valid, your program will crash at the place where it is using the invalid reference. Otherwise the invalid reference might survive longer and debugging becomes harder.</p>\n\n<p>Here are some references to why it's better to crash on an invalid reference. (They talk about pointers in Win32, but the ideas are still relevant):</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx\" rel=\"nofollow noreferrer\">IsBadXxxPtr should really be called CrashProgramRandomly</a></li>\n<li><a href=\"http://blogs.msdn.com/larryosterman/archive/2004/05/18/134471.aspx\" rel=\"nofollow noreferrer\">Should I check the parameters to my function?</a></li>\n</ul>\n"
},
{
"answer_id": 4146019,
"author": "mjn",
"author_id": 80901,
"author_profile": "https://Stackoverflow.com/users/80901",
"pm_score": 0,
"selected": false,
"text": "<p>With the usage of interface references (instead of object references) it is possible to avoid these invalid pointer problems because there is no explicit call to Free in your code anymore.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling. | If you're using FastMM4 as your Memory Manager, you can check that the class is not **TFreeObject**.
Or, in a more standard case, use a routine that will verify that your object is what it says it is by **checking the class VMT**.
There have been such ValidateObj functions hannging around for some time (by Ray Lischner and Hallvard Vassbotn: <http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html>)
Here's another:
```
function ValidateObj(Obj: TObject): Pointer;
// see { Virtual method table entries } in System.pas
begin
Result := Obj;
if Assigned(Result) then
try
if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then
// object not valid anymore
Result := nil;
except
Result := nil;
end;
end;
```
Update: A bit of caution... The above function will ensure that the result is either nil or a valid non nil Object. It does not guarantee that the Obj is still what you think it is, in case where the Memory Manager has already reallocated that previously freed memory. |
113,507 | <p>I've written a control in C# that overrides the built-in DropDownList control. For this I need a javascript resource included, which I'm including as an embedded resource then adding the <code>WebResource</code> attribute, which works fine.</p>
<p>However, I also need to reference a webservice, which I would normally include in the scriptmanager on the page like this</p>
<pre><code><asp:scriptmanager id="scriptmanager" runat="server">
<Services>
<asp:ServiceReference Path="~/Path/To/Service.asmx" />
</Services>
</asp:scriptmanager>
</code></pre>
<p>Is there any way to make the page include this reference in the code behind on the control I've created, similar to how it includes the embedded javascript file?</p>
| [
{
"answer_id": 113535,
"author": "Dested",
"author_id": 11137,
"author_profile": "https://Stackoverflow.com/users/11137",
"pm_score": 0,
"selected": false,
"text": "<p>If you know the page the usercontrol is in you can do a ((PageName)this.Page).scriptmanager.Services.Add() from the user control</p>\n"
},
{
"answer_id": 193379,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 0,
"selected": false,
"text": "<p>You can just add the javascript to call the webservice yourself:</p>\n\n<p>Sys.Net.WebServiceProxy.invoke(url, methodName, useHttpGet, parameters, succeededCallback, failedCallback, userContext, timeOut);</p>\n\n<p><a href=\"http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx</a></p>\n\n<p>The docs are for asp.net Ajax 1.0, but it's the same .net 3.5.</p>\n"
},
{
"answer_id": 210769,
"author": "Rob Windsor",
"author_id": 28785,
"author_profile": "https://Stackoverflow.com/users/28785",
"pm_score": 3,
"selected": true,
"text": "<p>You can add a ScriptManagerProxy in the code or the markup of your control and add the service reference through it. The settings in the ScriptManagerProxy are merged with the \"real\" ScriptManager at compile time.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
| I've written a control in C# that overrides the built-in DropDownList control. For this I need a javascript resource included, which I'm including as an embedded resource then adding the `WebResource` attribute, which works fine.
However, I also need to reference a webservice, which I would normally include in the scriptmanager on the page like this
```
<asp:scriptmanager id="scriptmanager" runat="server">
<Services>
<asp:ServiceReference Path="~/Path/To/Service.asmx" />
</Services>
</asp:scriptmanager>
```
Is there any way to make the page include this reference in the code behind on the control I've created, similar to how it includes the embedded javascript file? | You can add a ScriptManagerProxy in the code or the markup of your control and add the service reference through it. The settings in the ScriptManagerProxy are merged with the "real" ScriptManager at compile time. |
113,511 | <p>How do we decide on the best implementation of <code>hashCode()</code> method for a collection (assuming that equals method has been overridden correctly) ?</p>
| [
{
"answer_id": 113530,
"author": "Chris Carruthers",
"author_id": 1119,
"author_profile": "https://Stackoverflow.com/users/1119",
"pm_score": -1,
"selected": false,
"text": "<p>For a simple class it is often easiest to implement hashCode() based on the class fields which are checked by the equals() implementation.</p>\n\n<pre><code>public class Zam {\n private String foo;\n private String bar;\n private String somethingElse;\n\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n\n if (obj == null) {\n return false;\n }\n\n if (getClass() != obj.getClass()) {\n return false;\n }\n\n Zam otherObj = (Zam)obj;\n\n if ((getFoo() == null && otherObj.getFoo() == null) || (getFoo() != null && getFoo().equals(otherObj.getFoo()))) {\n if ((getBar() == null && otherObj. getBar() == null) || (getBar() != null && getBar().equals(otherObj. getBar()))) {\n return true;\n }\n }\n\n return false;\n }\n\n public int hashCode() {\n return (getFoo() + getBar()).hashCode();\n }\n\n public String getFoo() {\n return foo;\n }\n\n public String getBar() {\n return bar;\n }\n}\n</code></pre>\n\n<p>The most important thing is to keep hashCode() and equals() consistent: if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values.</p>\n"
},
{
"answer_id": 113548,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 2,
"selected": false,
"text": "<p>@about8 : there is a pretty serious bug there. </p>\n\n<pre><code>Zam obj1 = new Zam(\"foo\", \"bar\", \"baz\");\nZam obj2 = new Zam(\"fo\", \"obar\", \"baz\");\n</code></pre>\n\n<p>same hashcode</p>\n\n<p>you probably want something like</p>\n\n<pre><code>public int hashCode() {\n return (getFoo().hashCode() + getBar().hashCode()).toString().hashCode();\n</code></pre>\n\n<p>(can you get hashCode directly from int in Java these days? I think it does some autocasting.. if that's the case, skip the toString, it's ugly.)</p>\n"
},
{
"answer_id": 113556,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 4,
"selected": false,
"text": "<p>First make sure that equals is implemented correctly. From <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp05273.html#N10184\" rel=\"noreferrer\">an IBM DeveloperWorks article</a>:</p>\n\n<blockquote>\n <ul>\n <li>Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)</li>\n <li>Reflexivity: For all non-null references, a.equals(a)</li>\n <li>Transitivity: If a.equals(b) and b.equals(c), then a.equals(c) </li>\n </ul>\n</blockquote>\n\n<p>Then make sure that their relation with hashCode respects the contact (from the same article):</p>\n\n<blockquote>\n <ul>\n <li>Consistency with hashCode(): Two equal objects must have the same hashCode() value</li>\n </ul>\n</blockquote>\n\n<p>Finally a good hash function should strive to approach the <a href=\"http://en.wikipedia.org/wiki/Hash_function#Properties\" rel=\"noreferrer\">ideal hash function</a>.</p>\n"
},
{
"answer_id": 113557,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>Just a quick note for completing other more detailed answer (in term of code):</p>\n\n<p>If I consider the question <a href=\"https://stackoverflow.com/questions/29324/how-do-i-create-a-hash-table-in-java\">how-do-i-create-a-hash-table-in-java</a> and especially the <a href=\"http://www.jguru.com/faq/view.jsp?EID=430247\" rel=\"nofollow noreferrer\">jGuru FAQ entry</a>, I believe some other criteria upon which a hash code could be judged are:</p>\n\n<ul>\n<li>synchronization (does the algo support concurrent access or not) ?</li>\n<li>fail safe iteration (does the algo detect a collection which changes during iteration)</li>\n<li>null value (does the hash code support null value in the collection)</li>\n</ul>\n"
},
{
"answer_id": 113581,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 2,
"selected": false,
"text": "<p>As you specifically asked for collections, I'd like to add an aspect that the other answers haven't mentioned yet: A HashMap doesn't expect their keys to change their hashcode once they are added to the collection. Would defeat the whole purpose...</p>\n"
},
{
"answer_id": 113583,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand your question correctly, you have a custom collection class (i.e. a new class that extends from the Collection interface) and you want to implement the hashCode() method.</p>\n\n<p>If your collection class extends AbstractList, then you don't have to worry about it, there is already an implementation of equals() and hashCode() that works by iterating through all the objects and adding their hashCodes() together.</p>\n\n<pre><code> public int hashCode() {\n int hashCode = 1;\n Iterator i = iterator();\n while (i.hasNext()) {\n Object obj = i.next();\n hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());\n }\n return hashCode;\n }\n</code></pre>\n\n<p>Now if what you want is the best way to calculate the hash code for a specific class, I normally use the ^ (bitwise exclusive or) operator to process all fields that I use in the equals method:</p>\n\n<pre><code>public int hashCode(){\n return intMember ^ (stringField != null ? stringField.hashCode() : 0);\n}\n</code></pre>\n"
},
{
"answer_id": 113595,
"author": "Chii",
"author_id": 17335,
"author_profile": "https://Stackoverflow.com/users/17335",
"pm_score": 1,
"selected": false,
"text": "<p>any hashing method that evenly distributes the hash value over the possible range is a good implementation. See effective java ( <a href=\"http://books.google.com.au/books?id=ZZOiqZQIbRMC&dq=effective+java&pg=PP1&ots=UZMZ2siN25&sig=kR0n73DHJOn-D77qGj0wOxAxiZw&hl=en&sa=X&oi=book_result&resnum=1&ct=result\" rel=\"nofollow noreferrer\">http://books.google.com.au/books?id=ZZOiqZQIbRMC&dq=effective+java&pg=PP1&ots=UZMZ2siN25&sig=kR0n73DHJOn-D77qGj0wOxAxiZw&hl=en&sa=X&oi=book_result&resnum=1&ct=result</a> ) , there is a good tip in there for hashcode implementation (item 9 i think...). </p>\n"
},
{
"answer_id": 113600,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 10,
"selected": true,
"text": "<p>The best implementation? That is a hard question because it depends on the usage pattern.</p>\n\n<p>A for nearly all cases reasonable good implementation was proposed in <em>Josh Bloch</em>'s <strong><em>Effective Java</em></strong> in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good.</p>\n\n<h3>A short version</h3>\n\n<ol>\n<li><p>Create a <code>int result</code> and assign a <strong>non-zero</strong> value.</p></li>\n<li><p>For <em>every field</em> <code>f</code> tested in the <code>equals()</code> method, calculate a hash code <code>c</code> by:</p>\n\n<ul>\n<li>If the field f is a <code>boolean</code>: \ncalculate <code>(f ? 0 : 1)</code>;</li>\n<li>If the field f is a <code>byte</code>, <code>char</code>, <code>short</code> or <code>int</code>: calculate <code>(int)f</code>;</li>\n<li>If the field f is a <code>long</code>: calculate <code>(int)(f ^ (f >>> 32))</code>;</li>\n<li>If the field f is a <code>float</code>: calculate <code>Float.floatToIntBits(f)</code>;</li>\n<li>If the field f is a <code>double</code>: calculate <code>Double.doubleToLongBits(f)</code> and handle the return value like every long value;</li>\n<li>If the field f is an <em>object</em>: Use the result of the <code>hashCode()</code> method or 0 if <code>f == null</code>;</li>\n<li>If the field f is an <em>array</em>: see every field as separate element and calculate the hash value in a <em>recursive fashion</em> and combine the values as described next.</li>\n</ul></li>\n<li><p>Combine the hash value <code>c</code> with <code>result</code>:</p>\n\n<pre><code>result = 37 * result + c\n</code></pre></li>\n<li><p>Return <code>result</code></p></li>\n</ol>\n\n<p>This should result in a proper distribution of hash values for most use situations.</p>\n"
},
{
"answer_id": 113815,
"author": "Rudi Adianto",
"author_id": 18467,
"author_profile": "https://Stackoverflow.com/users/18467",
"pm_score": 3,
"selected": false,
"text": "<p>There's a good implementation of the <em>Effective Java</em>'s <code>hashcode()</code> and <code>equals()</code> logic in <a href=\"https://commons.apache.org/proper/commons-lang/\" rel=\"nofollow noreferrer\">Apache Commons Lang</a>. Checkout <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html\" rel=\"nofollow noreferrer\">HashCodeBuilder</a> and <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html\" rel=\"nofollow noreferrer\">EqualsBuilder</a>.</p>\n"
},
{
"answer_id": 113852,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>about8.blogspot.com, you said </p>\n\n<blockquote>\n <p>if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values</p>\n</blockquote>\n\n<p>I cannot agree with you. If two objects have the same hashcode it doesn't have to mean that they are equal. </p>\n\n<p>If A equals B then A.hashcode must be equal to B.hascode</p>\n\n<p>but</p>\n\n<p>if A.hashcode equals B.hascode it does not mean that A must equals B</p>\n"
},
{
"answer_id": 113867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer using utility methods fromm <em>Google Collections lib from class Objects</em> that helps me to keep my code clean. Very often <code>equals</code> and <code>hashcode</code> methods are made from IDE's template, so their are not clean to read. </p>\n"
},
{
"answer_id": 114123,
"author": "Vihung",
"author_id": 15452,
"author_profile": "https://Stackoverflow.com/users/15452",
"pm_score": 2,
"selected": false,
"text": "<p>Use the reflection methods on Apache Commons <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/EqualsBuilder.html\" rel=\"nofollow noreferrer\">EqualsBuilder</a> and <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/HashCodeBuilder.html\" rel=\"nofollow noreferrer\">HashCodeBuilder</a>.</p>\n"
},
{
"answer_id": 114672,
"author": "Johannes K. Lehnert",
"author_id": 2367,
"author_profile": "https://Stackoverflow.com/users/2367",
"pm_score": 3,
"selected": false,
"text": "<p>If you use eclipse, you can generate <code>equals()</code> and <code>hashCode()</code> using:</p>\n\n<blockquote>\n <p>Source -> Generate hashCode() and equals(). </p>\n</blockquote>\n\n<p>Using this function you can decide <em>which fields</em> you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.</p>\n"
},
{
"answer_id": 327264,
"author": "Warrior",
"author_id": 40933,
"author_profile": "https://Stackoverflow.com/users/40933",
"pm_score": 6,
"selected": false,
"text": "<p>It is better to use the functionality provided by Eclipse which does a pretty good job and you can put your efforts and energy in developing the business logic.</p>\n"
},
{
"answer_id": 12711577,
"author": "Edward Loper",
"author_id": 222329,
"author_profile": "https://Stackoverflow.com/users/222329",
"pm_score": 0,
"selected": false,
"text": "<p>When combining hash values, I usually use the combining method that's used in the boost c++ library, namely:</p>\n\n<pre><code>seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n</code></pre>\n\n<p>This does a fairly good job of ensuring an even distribution. For some discussion of how this formula works, see the StackOverflow post: <a href=\"https://stackoverflow.com/questions/4948780/magic-numbers-in-boosthash-combine\">Magic number in boost::hash_combine</a></p>\n\n<p>There's a good discussion of different hash functions at: <a href=\"http://burtleburtle.net/bob/hash/doobs.html\" rel=\"nofollow noreferrer\">http://burtleburtle.net/bob/hash/doobs.html</a></p>\n"
},
{
"answer_id": 18066516,
"author": "bacar",
"author_id": 37941,
"author_profile": "https://Stackoverflow.com/users/37941",
"pm_score": 7,
"selected": false,
"text": "<p>If you're happy with the Effective Java implementation recommended by dmeister, you can use a library call instead of rolling your own:</p>\n<pre><code>@Override\npublic int hashCode() {\n return Objects.hash(this.firstName, this.lastName);\n}\n</code></pre>\n<p>This requires either Guava (<code>com.google.common.base.Objects.hashCode</code>) or the standard library in Java 7 (<code>java.util.Objects.hash</code>) but works the same way.</p>\n"
},
{
"answer_id": 31220250,
"author": "Christopher Rucinski",
"author_id": 2333021,
"author_profile": "https://Stackoverflow.com/users/2333021",
"pm_score": 6,
"selected": false,
"text": "<p>Although this is linked to <a href=\"http://web.archive.org/web/20150207205800/https://developer.android.com/reference/java/lang/Object.html\" rel=\"noreferrer\"><code>Android</code> documentation (Wayback Machine)</a> and <a href=\"https://github.com/ciscorucinski/HashcodeAndEqual/blob/master/src/io/github/ciscorucinski/hashcodeandequal/MyType.java\" rel=\"noreferrer\">My own code on Github</a>, it will work for Java in general. My answer is an extension of <a href=\"https://stackoverflow.com/a/113600/2333021\">dmeister's Answer</a> with just code that is much easier to read and understand.</p>\n\n<pre><code>@Override \npublic int hashCode() {\n\n // Start with a non-zero constant. Prime is preferred\n int result = 17;\n\n // Include a hash for each field.\n\n // Primatives\n\n result = 31 * result + (booleanField ? 1 : 0); // 1 bit » 32-bit\n\n result = 31 * result + byteField; // 8 bits » 32-bit \n result = 31 * result + charField; // 16 bits » 32-bit\n result = 31 * result + shortField; // 16 bits » 32-bit\n result = 31 * result + intField; // 32 bits » 32-bit\n\n result = 31 * result + (int)(longField ^ (longField >>> 32)); // 64 bits » 32-bit\n\n result = 31 * result + Float.floatToIntBits(floatField); // 32 bits » 32-bit\n\n long doubleFieldBits = Double.doubleToLongBits(doubleField); // 64 bits (double) » 64-bit (long) » 32-bit (int)\n result = 31 * result + (int)(doubleFieldBits ^ (doubleFieldBits >>> 32));\n\n // Objects\n\n result = 31 * result + Arrays.hashCode(arrayField); // var bits » 32-bit\n\n result = 31 * result + referenceField.hashCode(); // var bits » 32-bit (non-nullable) \n result = 31 * result + // var bits » 32-bit (nullable) \n (nullableReferenceField == null\n ? 0\n : nullableReferenceField.hashCode());\n\n return result;\n\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Typically, when you override <code>hashcode(...)</code>, you also want to override <code>equals(...)</code>. So for those that will or has already implemented <code>equals</code>, here is a good reference <a href=\"https://github.com/ciscorucinski/HashcodeAndEqual/blob/master/src/io/github/ciscorucinski/hashcodeandequal/MyType.java\" rel=\"noreferrer\">from my Github</a>...</p>\n\n<pre><code>@Override\npublic boolean equals(Object o) {\n\n // Optimization (not required).\n if (this == o) {\n return true;\n }\n\n // Return false if the other object has the wrong type, interface, or is null.\n if (!(o instanceof MyType)) {\n return false;\n }\n\n MyType lhs = (MyType) o; // lhs means \"left hand side\"\n\n // Primitive fields\n return booleanField == lhs.booleanField\n && byteField == lhs.byteField\n && charField == lhs.charField\n && shortField == lhs.shortField\n && intField == lhs.intField\n && longField == lhs.longField\n && floatField == lhs.floatField\n && doubleField == lhs.doubleField\n\n // Arrays\n\n && Arrays.equals(arrayField, lhs.arrayField)\n\n // Objects\n\n && referenceField.equals(lhs.referenceField)\n && (nullableReferenceField == null\n ? lhs.nullableReferenceField == null\n : nullableReferenceField.equals(lhs.nullableReferenceField));\n}\n</code></pre>\n"
},
{
"answer_id": 34395373,
"author": "starikoff",
"author_id": 2369544,
"author_profile": "https://Stackoverflow.com/users/2369544",
"pm_score": 2,
"selected": false,
"text": "<p>I use a tiny wrapper around <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepHashCode(java.lang.Object[])\" rel=\"nofollow\"><code>Arrays.deepHashCode(...)</code></a> because it handles arrays supplied as parameters correctly</p>\n\n<pre><code>public static int hash(final Object... objects) {\n return Arrays.deepHashCode(objects);\n}\n</code></pre>\n"
},
{
"answer_id": 41396936,
"author": "Roman Nikitchenko",
"author_id": 204665,
"author_profile": "https://Stackoverflow.com/users/204665",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another JDK 1.7+ approach demonstration with superclass logics accounted. I see it as pretty convinient with Object class hashCode() accounted, pure JDK dependency and no extra manual work. Please note <code>Objects.hash()</code> is null tolerant.</p>\n\n<p>I have not include any <code>equals()</code> implementation but in reality you will of course need it.</p>\n\n<pre><code>import java.util.Objects;\n\npublic class Demo {\n\n public static class A {\n\n private final String param1;\n\n public A(final String param1) {\n this.param1 = param1;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n super.hashCode(),\n this.param1);\n }\n\n }\n\n public static class B extends A {\n\n private final String param2;\n private final String param3;\n\n public B(\n final String param1,\n final String param2,\n final String param3) {\n\n super(param1);\n this.param2 = param2;\n this.param3 = param3;\n }\n\n @Override\n public final int hashCode() {\n return Objects.hash(\n super.hashCode(),\n this.param2,\n this.param3);\n }\n }\n\n public static void main(String [] args) {\n\n A a = new A(\"A\");\n B b = new B(\"A\", \"B\", \"C\");\n\n System.out.println(\"A: \" + a.hashCode());\n System.out.println(\"B: \" + b.hashCode());\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 47741808,
"author": "maaartinus",
"author_id": 581205,
"author_profile": "https://Stackoverflow.com/users/581205",
"pm_score": 1,
"selected": false,
"text": "<p>The standard implementation is weak and using it leads to unnecessary collisions. Imagine a</p>\n\n<pre><code>class ListPair {\n List<Integer> first;\n List<Integer> second;\n\n ListPair(List<Integer> first, List<Integer> second) {\n this.first = first;\n this.second = second;\n }\n\n public int hashCode() {\n return Objects.hashCode(first, second);\n }\n\n ...\n}\n</code></pre>\n\n<p>Now,</p>\n\n<pre><code>new ListPair(List.of(a), List.of(b, c))\n</code></pre>\n\n<p>and</p>\n\n<pre><code>new ListPair(List.of(b), List.of(a, c))\n</code></pre>\n\n<p>have the same <code>hashCode</code>, namely <code>31*(a+b) + c</code> as the multiplier used for <code>List.hashCode</code> gets reused here. Obviously, collisions are unavoidable, but producing needless collisions is just... needless.</p>\n\n<p>There's nothing substantially smart about using <code>31</code>. The multiplier must be odd in order to avoid losing information (any even multiplier loses at least the most significant bit, multiples of four lose two, etc.). Any odd multiplier is usable. Small multipliers may lead to faster computation (the JIT can use shifts and additions), but given that multiplication has latency of only three cycles on modern Intel/AMD, this hardly matters. Small multipliers also leads to more collision for small inputs, which may be a problem sometimes.</p>\n\n<p>Using a prime is pointless as primes have no meaning in the ring Z/(2**32).</p>\n\n<p>So, I'd recommend using a randomly chosen big odd number (feel free to take a prime). As i86/amd64 CPUs can use a shorter instruction for operands fitting in a single signed byte, there is a tiny speed advantage for multipliers like 109. For minimizing collisions, take something like 0x58a54cf5.</p>\n\n<p>Using different multipliers in different places is helpful, but probably not enough to justify the additional work.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
| How do we decide on the best implementation of `hashCode()` method for a collection (assuming that equals method has been overridden correctly) ? | The best implementation? That is a hard question because it depends on the usage pattern.
A for nearly all cases reasonable good implementation was proposed in *Josh Bloch*'s ***Effective Java*** in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good.
### A short version
1. Create a `int result` and assign a **non-zero** value.
2. For *every field* `f` tested in the `equals()` method, calculate a hash code `c` by:
* If the field f is a `boolean`:
calculate `(f ? 0 : 1)`;
* If the field f is a `byte`, `char`, `short` or `int`: calculate `(int)f`;
* If the field f is a `long`: calculate `(int)(f ^ (f >>> 32))`;
* If the field f is a `float`: calculate `Float.floatToIntBits(f)`;
* If the field f is a `double`: calculate `Double.doubleToLongBits(f)` and handle the return value like every long value;
* If the field f is an *object*: Use the result of the `hashCode()` method or 0 if `f == null`;
* If the field f is an *array*: see every field as separate element and calculate the hash value in a *recursive fashion* and combine the values as described next.
3. Combine the hash value `c` with `result`:
```
result = 37 * result + c
```
4. Return `result`
This should result in a proper distribution of hash values for most use situations. |
113,534 | <p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p>
<p>E.g:</p>
<pre><code>s="This is the string I want to split".split()
</code></pre>
<p>gives me</p>
<pre><code>>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
</code></pre>
<p>I want something like</p>
<pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....]
</code></pre>
| [
{
"answer_id": 113554,
"author": "rossp",
"author_id": 612,
"author_profile": "https://Stackoverflow.com/users/612",
"pm_score": 1,
"selected": false,
"text": "<p>The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.</p>\n\n<p>Perhaps this may help:</p>\n\n<pre><code>s = \"String to split\"\nmylist = []\nfor item in s.split():\n mylist.append(item)\n mylist.append(' ')\nmylist = mylist[:-1]\n</code></pre>\n\n<p>Messy, but it'll do the trick for you...</p>\n"
},
{
"answer_id": 113555,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<pre><code>>>> import re\n>>> re.split(r\"(\\s+)\", \"This is the string I want to split\")\n['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']\n</code></pre>\n\n<p>Using the capturing parentheses in re.split() causes the function to return the separators as well.</p>\n"
},
{
"answer_id": 113558,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there is a function in the standard library that does that by itself, but \"partition\" comes close</p>\n\n<p>The best way is probably to use regular expressions (which is how I'd do this in any language!)</p>\n\n<pre><code>import re\nprint re.split(r\"(\\s+)\", \"Your string here\")\n</code></pre>\n"
},
{
"answer_id": 16123808,
"author": "Foon",
"author_id": 755851,
"author_profile": "https://Stackoverflow.com/users/755851",
"pm_score": 2,
"selected": false,
"text": "<p>Silly answer just for the heck of it:</p>\n\n<pre><code>mystring.replace(\" \",\"! !\").split(\"!\")\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211/"
]
| Is there a function in Python to split a string without ignoring the spaces in the resulting list?
E.g:
```
s="This is the string I want to split".split()
```
gives me
```
>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
```
I want something like
```
['This',' ','is',' ', 'the',' ','string', ' ', .....]
``` | ```
>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']
```
Using the capturing parentheses in re.split() causes the function to return the separators as well. |
113,542 | <p>Is there a simple way to hook into the standard '<strong>Add or Remove Programs</strong>' functionality using PowerShell to <strong>uninstall an existing application</strong>? Or to check if the application is installed?</p>
| [
{
"answer_id": 113584,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 8,
"selected": true,
"text": "<pre class=\"lang-ps prettyprint-override\"><code>$app = Get-WmiObject -Class Win32_Product | Where-Object { \n $_.Name -match \"Software Name\" \n}\n\n$app.Uninstall()\n</code></pre>\n\n<p><strong>Edit:</strong> Rob found another way to do it with the Filter parameter:</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>$app = Get-WmiObject -Class Win32_Product `\n -Filter \"Name = 'Software Name'\"\n</code></pre>\n"
},
{
"answer_id": 490727,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 5,
"selected": false,
"text": "<p>To fix up the second method in Jeff Hillman's post, you could either do a:</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>$app = Get-WmiObject \n -Query \"SELECT * FROM Win32_Product WHERE Name = 'Software Name'\"\n</code></pre>\n\n<p>Or</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>$app = Get-WmiObject -Class Win32_Product `\n -Filter \"Name = 'Software Name'\"\n</code></pre>\n"
},
{
"answer_id": 16679066,
"author": "David Stetler",
"author_id": 1429895,
"author_profile": "https://Stackoverflow.com/users/1429895",
"pm_score": 3,
"selected": false,
"text": "<p>To add a little to this post, I needed to be able to remove software from multiple Servers. I used Jeff's answer to lead me to this:</p>\n\n<p>First I got a list of servers, I used an <a href=\"http://en.wikipedia.org/wiki/Active_Directory\" rel=\"nofollow noreferrer\">AD</a> query, but you can provide the array of computer names however you want:</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>$computers = @(\"computer1\", \"computer2\", \"computer3\")\n</code></pre>\n\n<p>Then I looped through them, adding the -computer parameter to the gwmi query:</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>foreach($server in $computers){\n $app = Get-WmiObject -Class Win32_Product -computer $server | Where-Object {\n $_.IdentifyingNumber -match \"5A5F312145AE-0252130-432C34-9D89-1\"\n }\n $app.Uninstall()\n}\n</code></pre>\n\n<p>I used the IdentifyingNumber property to match against instead of name, just to be sure I was uninstalling the correct application.</p>\n"
},
{
"answer_id": 20342722,
"author": "Ben Key",
"author_id": 2532437,
"author_profile": "https://Stackoverflow.com/users/2532437",
"pm_score": 2,
"selected": false,
"text": "<p>I will make my own little contribution. I needed to remove a list of packages from the same computer. This is the script I came up with.</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>$packages = @(\"package1\", \"package2\", \"package3\")\nforeach($package in $packages){\n $app = Get-WmiObject -Class Win32_Product | Where-Object {\n $_.Name -match \"$package\"\n }\n $app.Uninstall()\n}\n</code></pre>\n\n<p>I hope this proves to be useful.</p>\n\n<p>Note that I owe David Stetler the credit for this script since it is based on his.</p>\n"
},
{
"answer_id": 22353483,
"author": "user3410872",
"author_id": 3410872,
"author_profile": "https://Stackoverflow.com/users/3410872",
"pm_score": 0,
"selected": false,
"text": "<p>Use:</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>function remove-HSsoftware{\n[cmdletbinding()]\nparam(\n[parameter(Mandatory=$true,\nValuefromPipeline = $true,\nHelpMessage=\"IdentifyingNumber can be retrieved with `\"get-wmiobject -class win32_product`\"\")]\n[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]\n[string[]]$ids,\n[parameter(Mandatory=$false,\n ValuefromPipeline=$true,\n ValueFromPipelineByPropertyName=$true,\n HelpMessage=\"Computer name or IP adress to query via WMI\")]\n[Alias('hostname,CN,computername')]\n[string[]]$computers\n)\nbegin {}\nprocess{\n if($computers -eq $null){\n $computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}\n }\n foreach($computer in $computers){\n foreach($id in $ids){\n write-host \"Trying to uninstall sofware with ID \", \"$id\", \"from computer \", \"$computer\"\n $app = Get-WmiObject -class Win32_Product -Computername \"$computer\" -Filter \"IdentifyingNumber = '$id'\"\n $app | Remove-WmiObject\n\n }\n }\n}\nend{}}\n remove-hssoftware -ids \"{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}\",\"{5A9C53A5-FF48-497D-AB86-1F6418B569B9}\",\"{62092246-CFA2-4452-BEDB-62AC4BCE6C26}\"\n</code></pre>\n\n<p>It's not fully tested, but it ran under PowerShell 4.</p>\n\n<p>I've run the PS1 file as it is seen here. Letting it retrieve all the Systems from the <a href=\"http://en.wikipedia.org/wiki/Active_Directory\" rel=\"nofollow noreferrer\">AD</a> and trying to uninstall multiple applications on all systems.</p>\n\n<p>I've used the IdentifyingNumber to search for the Software cause of David Stetlers input.</p>\n\n<p>Not tested:</p>\n\n<ol>\n<li>Not adding ids to the call of the function in the script, instead starting the script with parameter IDs</li>\n<li>Calling the script with more then 1 computer name <strong>not</strong> automatically retrieved from the function</li>\n<li>Retrieving data from the pipe</li>\n<li>Using IP addresses to connect to the system</li>\n</ol>\n\n<p>What it does not:</p>\n\n<ol>\n<li>It doesn't give any information if the software actually was found on any given system.</li>\n<li>It does not give any information about failure or success of the deinstallation.</li>\n</ol>\n\n<p>I wasn't able to use uninstall(). Trying that I got an error telling me that calling a method for an expression that has a value of NULL is not possible. Instead I used Remove-WmiObject, which seems to accomplish the same.</p>\n\n<p><strong>CAUTION</strong>: Without a computer name given it removes the software from <strong>ALL</strong> systems in the Active Directory.</p>\n"
},
{
"answer_id": 25449234,
"author": "Ricardo",
"author_id": 1703691,
"author_profile": "https://Stackoverflow.com/users/1703691",
"pm_score": 3,
"selected": false,
"text": "<p>I found out that Win32_Product class is not recommended because it triggers repairs and is not query optimized. <a href=\"http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/13/use-powershell-to-quickly-find-installed-software.aspx\" rel=\"noreferrer\">Source</a></p>\n\n<p>I found <a href=\"http://techibee.com/powershell/powershell-uninstall-software-on-remote-computer/1400\" rel=\"noreferrer\">this post</a> from Sitaram Pamarthi with a script to uninstall if you know the app guid. He also supplies another script to search for apps really fast <a href=\"http://techibee.com/powershell/powershell-script-to-query-softwares-installed-on-remote-computer/1389\" rel=\"noreferrer\">here</a>.</p>\n\n<blockquote>\n <p>Use like this: .\\uninstall.ps1 -GUID\n {C9E7751E-88ED-36CF-B610-71A1D262E906}</p>\n</blockquote>\n\n<pre><code>[cmdletbinding()] \n\nparam ( \n\n [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]\n [string]$ComputerName = $env:computername,\n [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]\n [string]$AppGUID\n) \n\n try {\n $returnval = ([WMICLASS]\"\\\\$computerName\\ROOT\\CIMV2:win32_process\").Create(\"msiexec `/x$AppGUID `/norestart `/qn\")\n } catch {\n write-error \"Failed to trigger the uninstallation. Review the error message\"\n $_\n exit\n }\n switch ($($returnval.returnvalue)){\n 0 { \"Uninstallation command triggered successfully\" }\n 2 { \"You don't have sufficient permissions to trigger the command on $Computer\" }\n 3 { \"You don't have sufficient permissions to trigger the command on $Computer\" }\n 8 { \"An unknown error has occurred\" }\n 9 { \"Path Not Found\" }\n 9 { \"Invalid Parameter\"}\n }\n</code></pre>\n"
},
{
"answer_id": 25546511,
"author": "nickdnk",
"author_id": 1650180,
"author_profile": "https://Stackoverflow.com/users/1650180",
"pm_score": 6,
"selected": false,
"text": "<p>EDIT: Over the years this answer has gotten quite a few upvotes. I would like to add some comments. I have not used PowerShell since, but I remember observing some issues:</p>\n\n<ol>\n<li>If there are more matches than 1 for the below script, it does not work and you must append the PowerShell filter that limits results to 1. I believe it's <code>-First 1</code> but I'm not sure. Feel free to edit.</li>\n<li>If the application is not installed by MSI it does not work. The reason it was written as below is because it modifies the MSI to uninstall without intervention, which is not always the default case when using the native uninstall string.</li>\n</ol>\n\n<hr>\n\n<p>Using the WMI object takes forever. This is very fast if you just know the name of the program you want to uninstall.</p>\n\n<pre class=\"lang-ps prettyprint-override\"><code>$uninstall32 = gci \"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match \"SOFTWARE NAME\" } | select UninstallString\n$uninstall64 = gci \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match \"SOFTWARE NAME\" } | select UninstallString\n\nif ($uninstall64) {\n$uninstall64 = $uninstall64.UninstallString -Replace \"msiexec.exe\",\"\" -Replace \"/I\",\"\" -Replace \"/X\",\"\"\n$uninstall64 = $uninstall64.Trim()\nWrite \"Uninstalling...\"\nstart-process \"msiexec.exe\" -arg \"/X $uninstall64 /qb\" -Wait}\nif ($uninstall32) {\n$uninstall32 = $uninstall32.UninstallString -Replace \"msiexec.exe\",\"\" -Replace \"/I\",\"\" -Replace \"/X\",\"\"\n$uninstall32 = $uninstall32.Trim()\nWrite \"Uninstalling...\"\nstart-process \"msiexec.exe\" -arg \"/X $uninstall32 /qb\" -Wait}\n</code></pre>\n"
},
{
"answer_id": 40391299,
"author": "Kellen Stuart",
"author_id": 5361412,
"author_profile": "https://Stackoverflow.com/users/5361412",
"pm_score": 2,
"selected": false,
"text": "<p>Based on Jeff Hillman's answer:</p>\n\n<p>Here's a function you can just add to your <code>profile.ps1</code> or define in current PowerShell session:</p>\n\n<pre><code># Uninstall a Windows program\nfunction uninstall($programName)\n{\n $app = Get-WmiObject -Class Win32_Product -Filter (\"Name = '\" + $programName + \"'\")\n if($app -ne $null)\n {\n $app.Uninstall()\n }\n else {\n echo (\"Could not find program '\" + $programName + \"'\")\n }\n}\n</code></pre>\n\n<p>Let's say you wanted to uninstall <a href=\"http://en.wikipedia.org/wiki/Notepad%2B%2B\" rel=\"nofollow noreferrer\">Notepad++</a>. Just type this into PowerShell:</p>\n\n<p><code>> uninstall(\"notepad++\")</code></p>\n\n<p>Just be aware that <code>Get-WmiObject</code> can take some time, so be patient!</p>\n"
},
{
"answer_id": 44755102,
"author": "dsaydon",
"author_id": 4875299,
"author_profile": "https://Stackoverflow.com/users/4875299",
"pm_score": 0,
"selected": false,
"text": "<p>For Most of my programs the scripts in this Post did the job.\nBut I had to face a legacy program that I couldn't remove using msiexec.exe or Win32_Product class. (from some reason I got exit 0 but the program was still there)</p>\n\n<p>My solution was to use Win32_Process class:</p>\n\n<p>with the help from <a href=\"https://stackoverflow.com/users/1650180/nickdnk\">nickdnk</a> this command is to get the uninstall exe file path:</p>\n\n<p>64bit:</p>\n\n<pre><code>[array]$unInstallPathReg= gci \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString\n</code></pre>\n\n<p>32bit:</p>\n\n<pre><code> [array]$unInstallPathReg= gci \"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString\n</code></pre>\n\n<p>you will have to clean the the result string:</p>\n\n<pre><code>$uninstallPath = $unInstallPathReg[0].UninstallString\n$uninstallPath = $uninstallPath -Replace \"msiexec.exe\",\"\" -Replace \"/I\",\"\" -Replace \"/X\",\"\"\n$uninstallPath = $uninstallPath .Trim()\n</code></pre>\n\n<p>now when you have the relevant <strong>program uninstall exe file path</strong> you can use this command:</p>\n\n<pre><code>$uninstallResult = (Get-WMIObject -List -Verbose | Where-Object {$_.Name -eq \"Win32_Process\"}).InvokeMethod(\"Create\",\"$unInstallPath\")\n</code></pre>\n\n<blockquote>\n <p>$uninstallResult - will have the exit code. 0 is success</p>\n</blockquote>\n\n<p>the above commands can also run remotely - I did it using invoke command but I believe that adding the argument -computername can work</p>\n"
},
{
"answer_id": 45080738,
"author": "RBT",
"author_id": 465053,
"author_profile": "https://Stackoverflow.com/users/465053",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the PowerShell script using msiexec:</p>\n\n<pre><code>echo \"Getting product code\"\n$ProductCode = Get-WmiObject win32_product -Filter \"Name='Name of my Software in Add Remove Program Window'\" | Select-Object -Expand IdentifyingNumber\necho \"removing Product\"\n# Out-Null argument is just for keeping the power shell command window waiting for msiexec command to finish else it moves to execute the next echo command\n& msiexec /x $ProductCode | Out-Null\necho \"uninstallation finished\"\n</code></pre>\n"
},
{
"answer_id": 52750001,
"author": "Ehsan Iran-Nejad",
"author_id": 2350244,
"author_profile": "https://Stackoverflow.com/users/2350244",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function Uninstall-App {\n Write-Output \"Uninstalling $($args[0])\"\n foreach($obj in Get-ChildItem \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\") {\n $dname = $obj.GetValue(\"DisplayName\")\n if ($dname -contains $args[0]) {\n $uninstString = $obj.GetValue(\"UninstallString\")\n foreach ($line in $uninstString) {\n $found = $line -match '(\\{.+\\}).*'\n If ($found) {\n $appid = $matches[1]\n Write-Output $appid\n start-process \"msiexec.exe\" -arg \"/X $appid /qb\" -Wait\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Call it this way:</p>\n\n<pre><code>Uninstall-App \"Autodesk Revit DB Link 2019\"\n</code></pre>\n"
},
{
"answer_id": 54839876,
"author": "Francesco Mantovani",
"author_id": 4652358,
"author_profile": "https://Stackoverflow.com/users/4652358",
"pm_score": 4,
"selected": false,
"text": "<p>One line of code:</p>\n\n<pre><code>get-package *notepad* |% { & $_.Meta.Attributes[\"UninstallString\"]}\n</code></pre>\n"
},
{
"answer_id": 71665423,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "<p>For msi installs, "uninstall-package whatever" works fine. For non-msi installs (Programs provider), it takes more string parsing. This should also take into account if the uninstall exe is in a path with spaces and is double quoted. Install-package works with msi's as well.</p>\n<pre><code>$uninstall = get-package whatever | % { $_.metadata['uninstallstring'] }\n# split quoted and unquoted things on whitespace\n$prog, $myargs = $uninstall | select-string '("[^"]*"|\\S)+' -AllMatches | \n % matches | % value\n$prog = $prog -replace '"',$null # call & operator doesn't like quotes\n$silentoption = '/S'\n$myargs += $silentoption # add whatever silent uninstall option\n& $prog $myargs # run uninstaller silently\n</code></pre>\n<p>Start-process doesn't mind the double quotes, if you need to wait anyway:</p>\n<pre><code># "C:\\Program Files (x86)\\myapp\\unins000.exe"\nget-package myapp | foreach { start -wait $_.metadata['uninstallstring'] /SILENT }\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571/"
]
| Is there a simple way to hook into the standard '**Add or Remove Programs**' functionality using PowerShell to **uninstall an existing application**? Or to check if the application is installed? | ```ps
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match "Software Name"
}
$app.Uninstall()
```
**Edit:** Rob found another way to do it with the Filter parameter:
```ps
$app = Get-WmiObject -Class Win32_Product `
-Filter "Name = 'Software Name'"
``` |
113,565 | <p>I've seen the following code many times:</p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
// or
// throw;
// or
// throw ex;
}
</code></pre>
<p>Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)</p>
| [
{
"answer_id": 113568,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 0,
"selected": false,
"text": "<p>Until I started using the EntLib ExceptionBlock, I was using them to log errors before throwing them. Kind of nasty when you think I could have handled them at that point, but at the time it was better to have them fail nastily in UAT (after logging them) rather than cover a flow-on bug.</p>\n"
},
{
"answer_id": 113574,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 0,
"selected": false,
"text": "<p>The application will most probably be catching those re-thrown exceptions higher up the call stack and so re-throwing them allows that higher up handler to intercept and process them as appropriate. It is quite common for application to have a top-level exception handler that logs or reports the expections.</p>\n\n<p>Another alternative is that the coder was lazy and instead of catching just the set of exceptions they want to handle they have caught everything and then re-thrown only the ones they cannot actually handle.</p>\n"
},
{
"answer_id": 113577,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": true,
"text": "<p>Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it.</p>\n\n<p>Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead.</p>\n"
},
{
"answer_id": 113578,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 1,
"selected": false,
"text": "<p>Generally the \"Do Something\" either involves better explaining the exception (For instance, wrapping it in another exception), or tracing information through a certain source.</p>\n\n<p>Another possibility is if the exception type is not enough information to know if an exception needs to be caught, in which case catching it an examining it will provide more information.</p>\n\n<p>This is not to say that method is used for purely good reasons, many times it is used when a developer thinks tracing information may be needed at some future point, in which case you get try {} catch {throw;} style, which is not helpful at all.</p>\n"
},
{
"answer_id": 113579,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>I think it depends on what you are trying to do with the exception.</p>\n\n<p>One good reason would be to log the error first in the catch, and then throw it up to the UI to generate a friendly error message with the option to see a more \"advanced/detailed\" view of the error, which contains the original error.</p>\n\n<p>Another approach is a \"retry\" approach, e.g., an error count is kept, and after a certain amount of retries that's the only time the error is sent up the stack (this is sometimes done for database access for database calls that timeout, or in accessing web services over slow networks).</p>\n\n<p>There will be a bunch of other reasons to do it though.</p>\n"
},
{
"answer_id": 113587,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<p>THE MAIN REASON of re-throwing exceptions is to leave Call Stack untouched, so you can get more complete picture of what happens and calls sequence.</p>\n"
},
{
"answer_id": 113588,
"author": "tghoang",
"author_id": 14611,
"author_profile": "https://Stackoverflow.com/users/14611",
"pm_score": 1,
"selected": false,
"text": "<p>FYI, this is a related question about each type of re-throw:\n<a href=\"https://stackoverflow.com/questions/6891/performance-considerations-for-throwing-exceptions#6978\">Performance Considerations for throwing Exceptions</a></p>\n<p>My question focuses on "Why" we re-throw exceptions and its usage in application exception handling strategy.</p>\n"
},
{
"answer_id": 113614,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 3,
"selected": false,
"text": "<p>You typically catch and re-throw for one of two reasons, depending on where the code sits architecturally within an application.</p>\n\n<p>At the core of an application you typically catch and re-throw to translate an exception into something more meaningful. For example if you're writing a data access layer and using custom error codes with SQL Server, you might translate SqlException into things like ObjectNotFoundException. This is useful because (a) it makes it easier for callers to handle specific types of exception, and (b) because it prevents implementation details of that layer such as the fact you're using SQL Server for persistence leaking into other layers, which allows you to change things in the future more easily.</p>\n\n<p>At boundaries of applications it's common to catch and re-throw without translating an exception so that you can log details of it, aiding in debugging and diagnosing live issues. Ideally you want to publish error somewhere that the operations team can easily monitor (e.g. the event log) as well as somewhere that gives context around where the exception happened in the control flow for developers (typically tracing).</p>\n"
},
{
"answer_id": 113615,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 5,
"selected": false,
"text": "<p>Actually there is a difference between</p>\n\n<pre><code>throw new CustomException(ex);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>The second will preserve the stack information.</p>\n\n<p>But sometimes you want to make the Exception more \"friendly\" to your application domain, instead of letting the DatabaseException reach your GUI, you'll raise your custom exception which contains the original exception.</p>\n\n<p>For instance:</p>\n\n<pre><code>try\n{\n\n}\ncatch (SqlException ex)\n{\n switch (ex.Number) {\n case 17:\n case 4060:\n case 18456:\n throw new InvalidDatabaseConnectionException(\"The database does not exists or cannot be reached using the supplied connection settings.\", ex);\n case 547:\n throw new CouldNotDeleteException(\"There is a another object still using this object, therefore it cannot be deleted.\", ex);\n default:\n throw new UnexpectedDatabaseErrorException(\"There was an unexpected error from the database.\", ex);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 113630,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": false,
"text": "<p>I can think of the following reasons:</p>\n\n<ul>\n<li><p>Keeping the set of thrown exception types fixed, as part of the API, so that the callers only have to worry about the fixed set of exceptions. In Java, you are practically forced to do that, because of the checked exceptions mechanism.</p></li>\n<li><p>Adding some context information to the exception. For example, instead of letting the bare \"record not found\" pass through from the DB, you might want to catch it and add \"... while processing order no XXX, looking for product YYY\". </p></li>\n<li><p>Doing some cleanup - closing files, rolling back transactions, freeing some handles.</p></li>\n</ul>\n"
},
{
"answer_id": 113675,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 4,
"selected": false,
"text": "<p>Sometimes you want to hide the implementation details of a method or improve\nthe level of abstraction of a problem so that it’s more meaningful to the caller\nof a method. To do this, you can intercept the original exception and substitute\na custom exception that’s better suited for explaining the problem.</p>\n\n<p>Take for example a method that loads the requested user’s details from a text file. The method assumes that a text file exists named with the user’s ID and a suffix of “.data”. When that file doesn’t actually exist, it doesn’t make much sense to throw a FileNotFoundException because the fact that each user’s details are stored in a text file is an implementation detail internal to the method. So this method could instead wrap the original exception in a custom exception with an explanatory message. </p>\n\n<p>Unlike the code you're shown, best practice is that the original exception should be kept by loading it as the InnerException property of your new exception. This means that a developer can still analyze the underlying problem if necessary.</p>\n\n<p>When you're creating a custom exception, here's a useful checklist:</p>\n\n<p>• Find a good name that conveys why the exception was thrown and make sure that the name ends with the word “Exception”.</p>\n\n<p>• Ensure that you implement the three standard exception constructors.</p>\n\n<p>• Ensure that you mark your exception with the Serializable attribute.</p>\n\n<p>• Ensure that you implement the deserialization constructor.</p>\n\n<p>• Add any custom exception properties that might help developers to understand and handle your exception better.</p>\n\n<p>• If you add any custom properties, make sure that you implement and override GetObjectData to serialize your custom properties.</p>\n\n<p>• If you add any custom properties, override the Message property so that you can add your properties to the standard exception message.</p>\n\n<p>• Remember to attach the original exception using the InnerException property of your custom exception.</p>\n"
},
{
"answer_id": 3373667,
"author": "Deanna Gelbart",
"author_id": 370707,
"author_profile": "https://Stackoverflow.com/users/370707",
"pm_score": 0,
"selected": false,
"text": "<p>As Rafal mentioned, sometimes this is done to convert a checked exception to an unchecked exception, or to a checked exception that's more suitable for an API. There is an example here:</p>\n\n<p><a href=\"http://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html\" rel=\"nofollow noreferrer\">http://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html</a></p>\n"
},
{
"answer_id": 19825002,
"author": "Andrey Chaschev",
"author_id": 1851024,
"author_profile": "https://Stackoverflow.com/users/1851024",
"pm_score": 0,
"selected": false,
"text": "<p>If you look at exceptions as on <strong>an alternative way to get a method result</strong>, then re-throwing an exception is like wrapping your result into some other object. </p>\n\n<p>And this is a common operation in a non-exceptional world. Usually this happens on a border of two application layers - when a function from layer <code>B</code> calls a function from layer <code>C</code>, it transforms <code>C</code>'s result into <code>B</code>'s internal form. </p>\n\n<p><code>A -- calls --> B -- calls --> C</code></p>\n\n<p>If it doesn't, then at the layer <code>A</code> which calls the layer <code>B</code> there will be a full set of JDK exceptions to handle. :-)</p>\n\n<p>As also the accepted answer points out, layer <code>A</code> might not even be aware of <code>C</code>'s exception.</p>\n\n<p><strong>Example</strong></p>\n\n<p><em>Layer A</em>, servlet: retrieves an image and it's meta information<br>\n<em>Layer B</em>, JPEG library: collects available DCIM tags to parse a JPEG file<br>\n<em>Layer C</em>, a simple DB: a class reading string records from a random access file. Some bytes are broken, so it throws an exception saying \"can't read UTF-8 string for record 'bibliographicCitation'\".</p>\n\n<p>So <code>A</code> won't understand the meaning of 'bibliographicCitation'. So <code>B</code> should translate this exception for <code>A</code> into <code>TagsReadingException</code> which wraps the original.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14611/"
]
| I've seen the following code many times:
```
try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
// or
// throw;
// or
// throw ex;
}
```
Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?) | Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it.
Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead. |
113,640 | <p>I want to create a box like this with title:</p>
<p><img src="https://i.stack.imgur.com/2rip1.gif" alt="CSS box with title"></p>
<p>Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style?</p>
| [
{
"answer_id": 113656,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know (correct me if I'm wrong!), there isn't.</p>\n\n<p>I'd recommend you to use a div with a negative-margin-h1 inside. Depending on the semantic structure of your document, you could also use a fieldset (HTML) with one legend (HTML) inside which approximately looks like this by default.</p>\n"
},
{
"answer_id": 113667,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 7,
"selected": true,
"text": "<p>I believe you are looking for the <code>fieldset</code> HTML tag, which you can then style with CSS. E.g.,</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-html lang-html prettyprint-override\"><code> \n <fieldset style=\"border: 1px black solid\">\n\n <legend style=\"border: 1px black solid;margin-left: 1em; padding: 0.2em 0.8em \">title</legend>\n\n Text within the box <br />\n Etc\n </fieldset></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 113674,
"author": "AlexWilson",
"author_id": 2240,
"author_profile": "https://Stackoverflow.com/users/2240",
"pm_score": 3,
"selected": false,
"text": "<p>from <a href=\"http://www.pixy.cz/blogg/clanky/css-fieldsetandlabels.html\" rel=\"nofollow noreferrer\">http://www.pixy.cz/blogg/clanky/css-fieldsetandlabels.html</a></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-css lang-css prettyprint-override\"><code>fieldset {\n border: 1px solid green\n}\n\nlegend {\n padding: 0.2em 0.5em;\n border: 1px solid green;\n color: green;\n font-size: 90%;\n text-align: right;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n <fieldset>\n <legend>Subscription info</legend>\n <label for=\"name\">Username:</label>\n <input type=\"text\" name=\"name\" id=\"name\" />\n <br />\n <label for=\"mail\">E-mail:</label>\n <input type=\"text\" name=\"mail\" id=\"mail\" />\n <br />\n <label for=\"address\">Address:</label>\n <input type=\"text\" name=\"address\" id=\"address\" size=\"40\" />\n </fieldset>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 113676,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 2,
"selected": false,
"text": "<p>This will give you what you want</p>\n\n<pre><code><head>\n <title></title>\n <style type=\"text/css\">\n legend {border:solid 1px;}\n </style>\n</head>\n<body>\n <fieldset>\n <legend>Test</legend>\n <br /><br />\n </fieldset>\n</body>\n</code></pre>\n"
},
{
"answer_id": 2936888,
"author": "Jagath",
"author_id": 353786,
"author_profile": "https://Stackoverflow.com/users/353786",
"pm_score": 4,
"selected": false,
"text": "<p>If you are not using it in forms, and instead want to use it in an non-editable form, you can do this via the following code -</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-css lang-css prettyprint-override\"><code>.title_box {\n border: #3c5a86 1px dotted;\n}\n\n.title_box #title {\n position: relative;\n top: -0.5em;\n margin-left: 1em;\n display: inline;\n background-color: white;\n}\n\n.title_box #content {}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"title_box\" id=\"bill_to\">\n <div id=\"title\">Bill To</div>\n <div id=\"content\">\n Stuff goes here.<br> For example, a bill-to address\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 32266876,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this out.</p>\n\n<pre><code><fieldset class=\"fldset-class\">\n <legend class=\"legend-class\">Your Personal Information</legend>\n\n <table>\n <tr>\n <td><label>Name</label></td>\n <td><input type='text' name='name'></td>\n </tr>\n <tr>\n <td><label>Address</label></td>\n <td><input type='text' name='Address'></td>\n </tr>\n <tr>\n <td><label>City</label></td>\n <td><input type='text' name='City'></td>\n </tr>\n </table>\n</fieldset>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/3tnqgLr5/1/\" rel=\"nofollow noreferrer\">DEMO</a></p>\n"
},
{
"answer_id": 42719047,
"author": "riwex",
"author_id": 6154891,
"author_profile": "https://Stackoverflow.com/users/6154891",
"pm_score": 1,
"selected": false,
"text": "<p>I think this example can also be useful to someone:</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>.fldset-class {\r\n border: 1px solid #0099dd;\r\n margin: 3pt;\r\n border-top: 15px solid #0099dd\r\n}\r\n\r\n.legend-class {\r\n color: #0099dd;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><fieldset class=\"fldset-class\">\r\n <legend class=\"legend-class\">Your Personal Information</legend>\r\n\r\n <table>\r\n <tr>\r\n <td><label>Name</label></td>\r\n <td><input type='text' name='name'></td>\r\n </tr>\r\n <tr>\r\n <td><label>Address</label></td>\r\n <td><input type='text' name='Address'></td>\r\n </tr>\r\n <tr>\r\n <td><label>City</label></td>\r\n <td><input type='text' name='City'></td>\r\n </tr>\r\n </table>\r\n</fieldset></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20165/"
]
| I want to create a box like this with title:

Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style? | I believe you are looking for the `fieldset` HTML tag, which you can then style with CSS. E.g.,
```html
<fieldset style="border: 1px black solid">
<legend style="border: 1px black solid;margin-left: 1em; padding: 0.2em 0.8em ">title</legend>
Text within the box <br />
Etc
</fieldset>
``` |
113,655 | <p>Is there a function in python to split a word into a list of single letters? e.g:</p>
<pre><code>s = "Word to Split"
</code></pre>
<p>to get</p>
<pre><code>wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
</code></pre>
| [
{
"answer_id": 113662,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 9,
"selected": true,
"text": "<pre><code>>>> list(\"Word to Split\")\n['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']\n</code></pre>\n"
},
{
"answer_id": 113680,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": false,
"text": "<p>The easiest way is probably just to use <code>list()</code>, but there is at least one other option as well:</p>\n\n<pre><code>s = \"Word to Split\"\nwordlist = list(s) # option 1, \nwordlist = [ch for ch in s] # option 2, list comprehension.\n</code></pre>\n\n<p>They should <em>both</em> give you what you need:</p>\n\n<pre><code>['W','o','r','d',' ','t','o',' ','S','p','l','i','t']\n</code></pre>\n\n<p>As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:</p>\n\n<pre><code>[doSomethingWith(ch) for ch in s]\n</code></pre>\n"
},
{
"answer_id": 113681,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 3,
"selected": false,
"text": "<p>The list function will do this</p>\n\n<pre><code>>>> list('foo')\n['f', 'o', 'o']\n</code></pre>\n"
},
{
"answer_id": 115195,
"author": "Tim Ottinger",
"author_id": 15929,
"author_profile": "https://Stackoverflow.com/users/15929",
"pm_score": 2,
"selected": false,
"text": "<p>Abuse of the rules, same result:\n (x for x in 'Word to split')</p>\n\n<p>Actually an iterator, not a list. But it's likely you won't really care.</p>\n"
},
{
"answer_id": 55100297,
"author": "Iris Chen",
"author_id": 9644311,
"author_profile": "https://Stackoverflow.com/users/9644311",
"pm_score": 2,
"selected": false,
"text": "<pre><code>text = "just trying out"\n\nword_list = []\n\nfor i in range(len(text)):\n word_list.append(text[i])\n\nprint(word_list)\n</code></pre>\n<p>Output:</p>\n<pre><code>['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']\n</code></pre>\n"
},
{
"answer_id": 58569455,
"author": "pratiksha",
"author_id": 12251557,
"author_profile": "https://Stackoverflow.com/users/12251557",
"pm_score": 0,
"selected": false,
"text": "<p>def count():\n list = 'oixfjhibokxnjfklmhjpxesriktglanwekgfvnk'</p>\n\n<pre><code>word_list = []\n# dict = {}\nfor i in range(len(list)):\n word_list.append(list[i])\n# word_list1 = sorted(word_list)\nfor i in range(len(word_list) - 1, 0, -1):\n for j in range(i):\n if word_list[j] > word_list[j + 1]:\n temp = word_list[j]\n word_list[j] = word_list[j + 1]\n word_list[j + 1] = temp\nprint(\"final count of arrival of each letter is : \\n\", dict(map(lambda x: (x, word_list.count(x)), word_list)))\n</code></pre>\n"
},
{
"answer_id": 62895686,
"author": "Random 375",
"author_id": 13928828,
"author_profile": "https://Stackoverflow.com/users/13928828",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest option is to just use the list() command. However, if you don't want to use it or it dose not work for some bazaar reason, you can always use this method.</p>\n<pre><code>word = 'foo'\nsplitWord = []\n\nfor letter in word:\n splitWord.append(letter)\n\nprint(splitWord) #prints ['f', 'o', 'o']\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211/"
]
| Is there a function in python to split a word into a list of single letters? e.g:
```
s = "Word to Split"
```
to get
```
wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
``` | ```
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
``` |
113,664 | <p>I want to install PowerShell to 600 Window XP computers, and use it as the main processing shell. For example, for replacing batch scripts, VB scripts, and some other little programs. The installation process is not a problem. Some issues I think I'm going to come across are:</p>
<ol>
<li><p>Changing permissions to allow PowerShell to run scripts</p>
</li>
<li><p>The speed of PowerShell starting</p>
</li>
<li><p>Using PowerShell for logon/logoff scripts with GPO</p>
</li>
</ol>
<p>Problem 2: There is a script that is supposed to speed up PowerShell, but it seems to need to be run as administrator (which of course isn't something that normal users do).
Has anyone had any experience with using PowerShell in this way?</p>
| [
{
"answer_id": 114634,
"author": "Tubs",
"author_id": 11924,
"author_profile": "https://Stackoverflow.com/users/11924",
"pm_score": 0,
"selected": false,
"text": "<p>Changing permissions to allow Powershell scripts is possible to do via group policy. </p>\n\n<p>Microsoft provide ADM templates <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=2917a564-dbbc-4da7-82c8-fe08b3ef4e6d&DisplayLang=en\" rel=\"nofollow noreferrer\">here</a>, there is only one option \"Turn on Script Execution\" and can be assigned at a user or computer level.</p>\n"
},
{
"answer_id": 114677,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "<p>To speed up the start of PowerShell, Jeffrey Snover (the partner/architect responsible for PowerShell) provides an \"Update-GAC\" script <a href=\"http://blogs.msdn.com/powershell/archive/2008/09/02/speeding-up-powershell-startup-updating-update-gac-ps1.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Basically, it is just running through the assemblies that are loaded for PowerShell and NGen'ing (pre-compiling the IL to machine code) them. This does speed up the start of PowerShell.</p>\n\n<p>Another trick is to run PowerShell with the -nologo and -noprofile switches.</p>\n\n<p>This will skip the profile scripts and splash logo.</p>\n\n<p>There is a <a href=\"http://www.specopssoft.com/powershell/\" rel=\"nofollow noreferrer\">product for using PowerShell for logon/logoff scripts</a> from Special Operations Software. There are other ways to do it also.</p>\n\n<pre><code>%windir%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -nologo -noprofile\n</code></pre>\n"
},
{
"answer_id": 162091,
"author": "Tubs",
"author_id": 11924,
"author_profile": "https://Stackoverflow.com/users/11924",
"pm_score": 0,
"selected": false,
"text": "<p>It seems it's possible to run poweshell silently, but not just by calling itself. This <a href=\"http://blog.integrii.net/?p=45\" rel=\"nofollow noreferrer\">article</a> has more information.</p>\n\n<p>So answering my own questions</p>\n\n<ol>\n<li>This can be done via GPOs </li>\n<li>First run takes at least 10 seconds\n on our computers. this could add\n that time onto the logon time which\n is unacceptable.</li>\n<li>This seems fairly simple to do, using the\n scripts above is invisibility is\n needed, or by calling the powershell\n exe and passing it startup options.</li>\n</ol>\n\n<p>On our computers, to use powershell for logon seems not to be worthwhile just because of the logon time increase.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924/"
]
| I want to install PowerShell to 600 Window XP computers, and use it as the main processing shell. For example, for replacing batch scripts, VB scripts, and some other little programs. The installation process is not a problem. Some issues I think I'm going to come across are:
1. Changing permissions to allow PowerShell to run scripts
2. The speed of PowerShell starting
3. Using PowerShell for logon/logoff scripts with GPO
Problem 2: There is a script that is supposed to speed up PowerShell, but it seems to need to be run as administrator (which of course isn't something that normal users do).
Has anyone had any experience with using PowerShell in this way? | To speed up the start of PowerShell, Jeffrey Snover (the partner/architect responsible for PowerShell) provides an "Update-GAC" script [here](http://blogs.msdn.com/powershell/archive/2008/09/02/speeding-up-powershell-startup-updating-update-gac-ps1.aspx).
Basically, it is just running through the assemblies that are loaded for PowerShell and NGen'ing (pre-compiling the IL to machine code) them. This does speed up the start of PowerShell.
Another trick is to run PowerShell with the -nologo and -noprofile switches.
This will skip the profile scripts and splash logo.
There is a [product for using PowerShell for logon/logoff scripts](http://www.specopssoft.com/powershell/) from Special Operations Software. There are other ways to do it also.
```
%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -nologo -noprofile
``` |
113,702 | <p>How do I add a "last" class on the last <code><li></code> within a Views-generated list?</p>
| [
{
"answer_id": 113740,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 4,
"selected": true,
"text": "<p>You could use the <strong>last-child</strong> pseudo-class on the li element to achieve this</p>\n\n<pre><code><html>\n<head>\n<style type=\"text/css\">\nul li:last-child\n{\nfont-weight:bold\n}\n</style>\n</head>\n<body>\n<ul>\n<li>IE</li>\n<li>Firefox</li>\n<li>Safari</li>\n</ul>\n</body>\n</html>\n</code></pre>\n\n<p>There is also a first-child pseudo class available.</p>\n\n<p>I am not sure the last-child element works in IE though.</p>\n"
},
{
"answer_id": 113756,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 0,
"selected": false,
"text": "<p>Does jquery come bundled with drupal, if so you could use </p>\n\n<pre><code>$('ul>li:last').addClass('last');\n</code></pre>\n\n<p>to achieve this</p>\n"
},
{
"answer_id": 113783,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, you could achieve this via JavaScript if certain browsers don't support the last-child class. For example, this script sets the class name for the last 'li' element in all 'ul' tags, although it could easily be adapted for other tags, or specific elements.</p>\n\n<pre><code>function highlightLastLI()\n{\n var liList, ulTag, liTag;\n var ulList = document.getElementsByTagName(\"ul\");\n for (var i = 0; i < ulList.length; i++)\n {\n ulTag = ulList[i];\n liList = ulTag.getElementsByTagName(\"li\");\n liTag = liList[liList.length - 1];\n liTag.className = \"lastchild\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32328721,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 0,
"selected": false,
"text": "<p>You can use that pesudo-class <strong>last-child</strong>, <strong>first-child</strong> for first or <strong>nth-child</strong> for any number of child</p>\n\n<pre><code>li:last-child{\n color:red;\n font-weight:bold;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20273/"
]
| How do I add a "last" class on the last `<li>` within a Views-generated list? | You could use the **last-child** pseudo-class on the li element to achieve this
```
<html>
<head>
<style type="text/css">
ul li:last-child
{
font-weight:bold
}
</style>
</head>
<body>
<ul>
<li>IE</li>
<li>Firefox</li>
<li>Safari</li>
</ul>
</body>
</html>
```
There is also a first-child pseudo class available.
I am not sure the last-child element works in IE though. |
113,712 | <p>Is there a way to combine a previous translation when extracting the csv file from an application?
Or any other tool that could do this job for me? </p>
<p>I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.</p>
| [
{
"answer_id": 113740,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 4,
"selected": true,
"text": "<p>You could use the <strong>last-child</strong> pseudo-class on the li element to achieve this</p>\n\n<pre><code><html>\n<head>\n<style type=\"text/css\">\nul li:last-child\n{\nfont-weight:bold\n}\n</style>\n</head>\n<body>\n<ul>\n<li>IE</li>\n<li>Firefox</li>\n<li>Safari</li>\n</ul>\n</body>\n</html>\n</code></pre>\n\n<p>There is also a first-child pseudo class available.</p>\n\n<p>I am not sure the last-child element works in IE though.</p>\n"
},
{
"answer_id": 113756,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 0,
"selected": false,
"text": "<p>Does jquery come bundled with drupal, if so you could use </p>\n\n<pre><code>$('ul>li:last').addClass('last');\n</code></pre>\n\n<p>to achieve this</p>\n"
},
{
"answer_id": 113783,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, you could achieve this via JavaScript if certain browsers don't support the last-child class. For example, this script sets the class name for the last 'li' element in all 'ul' tags, although it could easily be adapted for other tags, or specific elements.</p>\n\n<pre><code>function highlightLastLI()\n{\n var liList, ulTag, liTag;\n var ulList = document.getElementsByTagName(\"ul\");\n for (var i = 0; i < ulList.length; i++)\n {\n ulTag = ulList[i];\n liList = ulTag.getElementsByTagName(\"li\");\n liTag = liList[liList.length - 1];\n liTag.className = \"lastchild\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32328721,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 0,
"selected": false,
"text": "<p>You can use that pesudo-class <strong>last-child</strong>, <strong>first-child</strong> for first or <strong>nth-child</strong> for any number of child</p>\n\n<pre><code>li:last-child{\n color:red;\n font-weight:bold;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15228/"
]
| Is there a way to combine a previous translation when extracting the csv file from an application?
Or any other tool that could do this job for me?
I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application. | You could use the **last-child** pseudo-class on the li element to achieve this
```
<html>
<head>
<style type="text/css">
ul li:last-child
{
font-weight:bold
}
</style>
</head>
<body>
<ul>
<li>IE</li>
<li>Firefox</li>
<li>Safari</li>
</ul>
</body>
</html>
```
There is also a first-child pseudo class available.
I am not sure the last-child element works in IE though. |
113,728 | <p>Basically I am trying to restart a service from a php web page.</p>
<p>Here is the code:</p>
<pre><code><?php
exec ('/usr/bin/sudo /etc/init.d/portmap restart');
?>
</code></pre>
<p>But, in <code>/var/log/httpd/error_log</code>, I get </p>
<blockquote>
<p>unable to change to sudoers gid: Operation not permitted</p>
</blockquote>
<p>and in /var/log/messages, I get</p>
<blockquote>
<p>Sep 22 15:01:56 ri kernel: audit(1222063316.536:777): avc: denied { getattr } for pid=4851 comm="sh" name="var" dev=dm-0 ino=114241 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:var_t tclass=dir<br>
Sep 22 15:01:56 ri kernel: audit(1222063316.549:778): avc: denied { setrlimit } for pid=4851 comm="sudo" scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=process<br>
Sep 22 15:01:56 ri kernel: audit(1222063316.565:779): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:shadow_t tclass=file<br>
Sep 22 15:01:56 ri kernel: audit(1222063316.568:780): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:shadow_t tclass=file<br>
Sep 22 15:01:56 ri kernel: audit(1222063316.571:781): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability<br>
Sep 22 15:01:56 ri kernel: audit(1222063316.574:782): avc: denied { setuid } for pid=4851 comm="sudo" capability=7 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability<br>
Sep 22 15:01:56 ri kernel: audit(1222063316.577:783): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability</p>
</blockquote>
<p>In my visudo, I added those lines</p>
<blockquote>
<p>User_Alias WWW=apache </p>
<p>WWW ALL=(ALL) NOPASSWD:ALL</p>
</blockquote>
<p>Can you please help me ? Am I doing something wrong ?</p>
<p>Thanks for your help,</p>
<p>tiBoun</p>
| [
{
"answer_id": 113764,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 3,
"selected": false,
"text": "<p>The error you are getting seems to be related to your SELinux configuration. You might try temporarily disabling that.</p>\n\n<p>As an aside, I would strongly suggest that you adjust your sudo configuration to be more restrictive. </p>\n\n<pre><code>User_Alias WWW=apache\nCmnd_Alias WEBCMDS=/etc/init.d/portmap\nWWW ALL=NOPASSWD: WEBCMDS\n</code></pre>\n"
},
{
"answer_id": 113773,
"author": "flungabunga",
"author_id": 11000,
"author_profile": "https://Stackoverflow.com/users/11000",
"pm_score": -1,
"selected": false,
"text": "<p>This is probably down to something like trying to execute sudo in a non-interactive shell.</p>\n\n<p>If you do a grep for 'sudo' in your apache users mail log you might find things like this </p>\n\n<blockquote>\n <p>sudo: sorry, you must have a tty to run sudo</p>\n</blockquote>\n"
},
{
"answer_id": 113774,
"author": "Hasturkun",
"author_id": 20270,
"author_profile": "https://Stackoverflow.com/users/20270",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is not with sudo at the moment, but with <a href=\"http://en.wikipedia.org/wiki/Selinux\" rel=\"noreferrer\">SELinux</a>, which is (reasonably) set to deny the HTTPD from gaining root privileges.<br>\nYou will need to either explicitly allow this (you can use <a href=\"http://fedoraproject.org/wiki/SELinux/audit2allow\" rel=\"noreferrer\">audit2allow</a> for this), or set SELinux to be permissive instead. I'd suggest the former.</p>\n"
},
{
"answer_id": 32269804,
"author": "Soumya Kanti",
"author_id": 1632556,
"author_profile": "https://Stackoverflow.com/users/1632556",
"pm_score": 1,
"selected": false,
"text": "<p>I encountered the problem recently and the accepted answer above helped. However, I would like to post this answer to elaborate the same, so that the next person does not need to spend time much, like me!</p>\n\n<p>Follow section 7 of the following link: <a href=\"https://wiki.centos.org/HowTos/SELinux\" rel=\"nofollow\">https://wiki.centos.org/HowTos/SELinux</a>.</p>\n\n<p>Do grep with <code>httpd_sys_script_t</code>.</p>\n\n<p>Basically the steps are:</p>\n\n<pre><code># grep httpd_sys_script_t /var/log/audit/audit.log | audit2allow -M httpdallowsudo\n# semodule -i httpdallowsudo.pp\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Basically I am trying to restart a service from a php web page.
Here is the code:
```
<?php
exec ('/usr/bin/sudo /etc/init.d/portmap restart');
?>
```
But, in `/var/log/httpd/error_log`, I get
>
> unable to change to sudoers gid: Operation not permitted
>
>
>
and in /var/log/messages, I get
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.536:777): avc: denied { getattr } for pid=4851 comm="sh" name="var" dev=dm-0 ino=114241 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:var\_t tclass=dir
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.549:778): avc: denied { setrlimit } for pid=4851 comm="sudo" scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=process
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.565:779): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:shadow\_t tclass=file
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.568:780): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:shadow\_t tclass=file
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.571:781): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.574:782): avc: denied { setuid } for pid=4851 comm="sudo" capability=7 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability
>
> Sep 22 15:01:56 ri kernel: audit(1222063316.577:783): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability
>
>
>
In my visudo, I added those lines
>
> User\_Alias WWW=apache
>
>
> WWW ALL=(ALL) NOPASSWD:ALL
>
>
>
Can you please help me ? Am I doing something wrong ?
Thanks for your help,
tiBoun | The problem is not with sudo at the moment, but with [SELinux](http://en.wikipedia.org/wiki/Selinux), which is (reasonably) set to deny the HTTPD from gaining root privileges.
You will need to either explicitly allow this (you can use [audit2allow](http://fedoraproject.org/wiki/SELinux/audit2allow) for this), or set SELinux to be permissive instead. I'd suggest the former. |
113,731 | <p>We have CC.NET setup on our ASP.NET app. When we build the project, the ASP.NET app is pre-compiled and copied to a network share, from which a server runs the application.</p>
<p>The server is a bit different from development box'es, and the next server in our staging environment differs even more. The difference is specific config files and so on - so I want to exclude some files - or delete them before the pre-compiled app is copied to a network share.</p>
<p>My config file looks like this:</p>
<pre><code> <project name="Assembly.Web.project">
<triggers>
<intervalTrigger seconds="3600" />
</triggers>
<sourcecontrol type="svn">
<trunkUrl>svn://svn-server/MyApp/Web/Trunk</trunkUrl>
<workingDirectory>C:\build-server\Assembly\Web\TEST-HL</workingDirectory>
<executable>C:\Program Files (x86)\SVN 1.5 bin\svn.exe</executable>
<username>uid</username>
<password>pwd</password>
</sourcecontrol>
<tasks>
<msbuild>
<executable>C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe</executable>
<workingDirectory>C:\build-server\Assembly\Web\TEST-HL</workingDirectory>
<projectFile>C:\build-server\Assembly\Web\TEST-HL\Web\Web.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
<targets>Build</targets>
<timeout>900</timeout>
<logger>C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
</msbuild>
</tasks>
<publishers>
<buildpublisher>
<sourceDir>C:\build-server\Assembly\Web\PrecompiledWeb</sourceDir>
<publishDir>\\test-web01\Web</publishDir>
<useLabelSubDirectory>false</useLabelSubDirectory>
<alwaysPublish>false</alwaysPublish>
</buildpublisher>
</publishers>
</project>
</code></pre>
<p>As you can see, I use a buildPublisher to copy the pre-compiled files to the network share. What I want to do here, is either 1) delete certain files before they are copied or 2) replace those files after they have been copied.</p>
<p>I DO NOT want to have some app running watching specific files for change, and then after that replace the files with other ones. I want something to be either done by CC.NET, or triggered by CC.NET.</p>
<p>Can you launch a .bat file with CC.NET?</p>
| [
{
"answer_id": 113743,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>I use a <a href=\"http://nant.sourceforge.net/\" rel=\"nofollow noreferrer\">NAnt</a> <a href=\"http://www.cruisecontrolnet.org/projects/ccnet/wiki/NAnt_Task\" rel=\"nofollow noreferrer\">task</a> for all publishing, deploying, cleaning and so on.</p>\n"
},
{
"answer_id": 113759,
"author": "spinodal",
"author_id": 11374,
"author_profile": "https://Stackoverflow.com/users/11374",
"pm_score": 1,
"selected": true,
"text": "<p>You have to use <a href=\"http://nant.sourceforge.net/\" rel=\"nofollow noreferrer\">NAnt</a> for those kind of stuff. \nHere is the <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/\" rel=\"nofollow noreferrer\">Task Reference of Nant</a>..</p>\n"
},
{
"answer_id": 114004,
"author": "Paul Shannon",
"author_id": 11503,
"author_profile": "https://Stackoverflow.com/users/11503",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at <a href=\"http://blogs.iis.net/msdeploy/archive/2008/01/22/welcome-to-the-web-deployment-team-blog.aspx\" rel=\"nofollow noreferrer\">MSDEPLOY</a> or <a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/28/vs-2008-web-deployment-project-support-released.aspx\" rel=\"nofollow noreferrer\">Web Deployment Projects</a>. There is a question that will provide <a href=\"https://stackoverflow.com/questions/45783/automate-deployment-for-web-application\">more detail here</a></p>\n"
},
{
"answer_id": 117155,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Of course CruiseControl.NET can run a batch file, simply use the exec task. However, an easier answer might just be to have MSBuild do the task for you. It should be simple to add a few steps in the postcompile target.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
]
| We have CC.NET setup on our ASP.NET app. When we build the project, the ASP.NET app is pre-compiled and copied to a network share, from which a server runs the application.
The server is a bit different from development box'es, and the next server in our staging environment differs even more. The difference is specific config files and so on - so I want to exclude some files - or delete them before the pre-compiled app is copied to a network share.
My config file looks like this:
```
<project name="Assembly.Web.project">
<triggers>
<intervalTrigger seconds="3600" />
</triggers>
<sourcecontrol type="svn">
<trunkUrl>svn://svn-server/MyApp/Web/Trunk</trunkUrl>
<workingDirectory>C:\build-server\Assembly\Web\TEST-HL</workingDirectory>
<executable>C:\Program Files (x86)\SVN 1.5 bin\svn.exe</executable>
<username>uid</username>
<password>pwd</password>
</sourcecontrol>
<tasks>
<msbuild>
<executable>C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe</executable>
<workingDirectory>C:\build-server\Assembly\Web\TEST-HL</workingDirectory>
<projectFile>C:\build-server\Assembly\Web\TEST-HL\Web\Web.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
<targets>Build</targets>
<timeout>900</timeout>
<logger>C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
</msbuild>
</tasks>
<publishers>
<buildpublisher>
<sourceDir>C:\build-server\Assembly\Web\PrecompiledWeb</sourceDir>
<publishDir>\\test-web01\Web</publishDir>
<useLabelSubDirectory>false</useLabelSubDirectory>
<alwaysPublish>false</alwaysPublish>
</buildpublisher>
</publishers>
</project>
```
As you can see, I use a buildPublisher to copy the pre-compiled files to the network share. What I want to do here, is either 1) delete certain files before they are copied or 2) replace those files after they have been copied.
I DO NOT want to have some app running watching specific files for change, and then after that replace the files with other ones. I want something to be either done by CC.NET, or triggered by CC.NET.
Can you launch a .bat file with CC.NET? | You have to use [NAnt](http://nant.sourceforge.net/) for those kind of stuff.
Here is the [Task Reference of Nant](http://nant.sourceforge.net/release/latest/help/tasks/).. |
113,737 | <p>How do I use PowerShell to stop and start a "Generic Service" as seen in the Microsoft "Cluster Administrator" software?</p>
| [
{
"answer_id": 113797,
"author": "Rob Paterson",
"author_id": 11571,
"author_profile": "https://Stackoverflow.com/users/11571",
"pm_score": 2,
"selected": false,
"text": "<p>It turns out the answer is to simply use the command line tool CLUSTER.EXE to do this:</p>\n\n<p>cluster RES MyGenericServiceName /OFF</p>\n\n<p>cluster RES MyGenericServiceName /ON</p>\n"
},
{
"answer_id": 140989,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 4,
"selected": true,
"text": "<p>You can also use WMI. You can get all the Generic Services with:</p>\n\n<pre><code>$services = Get-WmiObject -Computer \"Computer\" -namespace 'root\\mscluster' `\nMSCluster_Resource | Where {$_.Type -eq \"Generic Service\"}\n</code></pre>\n\n<p>To stop and start a service:</p>\n\n<pre><code>$timeout = 15\n$services[0].TakeOffline($timeout)\n$services[0].BringOnline($timeout)\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571/"
]
| How do I use PowerShell to stop and start a "Generic Service" as seen in the Microsoft "Cluster Administrator" software? | You can also use WMI. You can get all the Generic Services with:
```
$services = Get-WmiObject -Computer "Computer" -namespace 'root\mscluster' `
MSCluster_Resource | Where {$_.Type -eq "Generic Service"}
```
To stop and start a service:
```
$timeout = 15
$services[0].TakeOffline($timeout)
$services[0].BringOnline($timeout)
``` |
113,750 | <p>I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu. </p>
<p>What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling <code>$(this).preventDefault()</code>) prevents the user from selecting at all, and the obvious <code>$().trigger('mouseup')</code> doesn't doesn't do anything with the selection at all.</p>
<ul>
<li>This is in the general context of a page, not particular to a textarea or other text field.</li>
<li><code>e.stopPropogation()</code> doesn't cancel text-selection.</li>
<li>I'm not looking to <em>prevent</em> text selections, but rather to <em>veto</em> them after some short period of time, if certain conditions are met.</li>
</ul>
| [
{
"answer_id": 113771,
"author": "Craig Francis",
"author_id": 6632,
"author_profile": "https://Stackoverflow.com/users/6632",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>var input = document.getElementById('myInputField');\nif (input) {\n input.onmousedown = function(e) {\n\n if (!e) e = window.event;\n e.cancelBubble = true;\n if (e.stopPropagation) e.stopPropagation();\n\n }\n}\n</code></pre>\n\n<p>And if not, have a read of:</p>\n\n<p><a href=\"http://www.quirksmode.org/js/introevents.html\" rel=\"noreferrer\">http://www.quirksmode.org/js/introevents.html</a></p>\n"
},
{
"answer_id": 113778,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><code>$(this).focus()</code> (or anything along the lines of <code>document.body.focus()</code>) seems to do the trick, although I haven't tested it much beyond ff3.</p>\n"
},
{
"answer_id": 114027,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if this will help, exactly, but here is some code to de-select text:</p>\n\n<pre><code>// onselectstart is IE-only\nif ('undefined' !== typeof this.onselectstart) {\n this.onselectstart = function () { return false; };\n} else {\n this.onmousedown = function () { return false; };\n this.onclick = function () { return true; };\n}\n</code></pre>\n\n<p>\"this\" in this context would be the element for which you want to prevent text selections.</p>\n"
},
{
"answer_id": 2944003,
"author": "knight",
"author_id": 330447,
"author_profile": "https://Stackoverflow.com/users/330447",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the top thread, there is an official way to implement what I think you want in DOM. What you can use in lieu of events is something called a range object.</p>\n\n<p>Consider, (which works definitively on FF3)</p>\n\n<pre>\nwindow.onclick = function(evt)\n{\n // retrieves the selection and displays its content\n var selectObj = window.getSelection();\n alert(selectObj);\n\n // now collapse the selection to the initial point of the selection\n var rangeObj = selectObj.getRangeAt(0);\n rangeObj.collapse(true);\n}\n</pre>\n\n<p>Unfortunately, this doesn't quite fly with IE, Opera, Chrome, or Safari; not sure why, because in Opera, Chrome, or Safari, there is something associated with the collapse and getRangeAt methods. If I know more, I'll let you know.</p>\n\n<hr>\n\n<p>An update on my previous answer, one that works more universally is the selection object and collapse, collapseToStart, collapseToEnd methods. (<a href=\"https://developer.mozilla.org/en/DOM/Selection#Properties\" rel=\"nofollow noreferrer\">link text</a>)</p>\n\n<p>Now consider the 2.0 of the above:</p>\n\n<pre>\n\nwindow.onmouseup = function(evt)\n{\n var selectObj = window.getSelection();\n alert(selectObj); // to get a flavor of what you selected\n\n // works in FF3, Safari, Opera, and Chrome\n selectObj.collapseToStart();\n\n // works in FF3, Safari, Chrome (but not opera)\n /* selectObj.collapse(document.body, 0); */\n\n // and as the code is native, I have no idea why...\n // ...and it makes me sad\n}\n\n</pre>\n"
},
{
"answer_id": 9108578,
"author": "KajMagnus",
"author_id": 694469,
"author_profile": "https://Stackoverflow.com/users/694469",
"pm_score": 0,
"selected": false,
"text": "<p>An answer to this question works for me:\n <a href=\"https://stackoverflow.com/a/2700029/694469\">How to disable text selection using jquery?</a></p>\n\n<p>(It not only disables, but also <em>cancels</em>, any text selection.<br>\nAt least on my computer in FF and Chrome.)</p>\n\n<p>Here is what the answer does:</p>\n\n<pre><code> .attr('unselectable', 'on')\n\n '-ms-user-select': 'none',\n '-moz-user-select': 'none',\n '-webkit-user-select': 'none',\n 'user-select': 'none'\n\n .each(function() { // for IE\n this.onselectstart = function() { return false; };\n });\n</code></pre>\n"
},
{
"answer_id": 15955648,
"author": "nothingisnecessary",
"author_id": 403959,
"author_profile": "https://Stackoverflow.com/users/403959",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to knight for the beginnings of a universal solution. This slight modification also includes support for IE 7-10 (and probably 6).</p>\n\n<p>I had a similar prob as cwillu-gmail.. needed to attach to the shift-click event (click on label while holding shift key) to perform some alternate functionality when in a specific \"design\" mode. (Yeah, sounds weird, but it's what the client wanted.) That part was easy, but had the annoying effect of selecting text. This worked for me: (I used onclick but you could use onmouseup.. depends on what you are trying to do and when)</p>\n\n<pre><code>var element = document.getElementById(\"myElementId\");\nelement.onclick = function (event)\n{\n // if (event.shiftKey) // uncomment this line to only deselect text when clicking while holding shift key\n {\n if (document.selection)\n {\n document.selection.empty(); // works in IE (7/8/9/10)\n }\n else if (window.getSelection)\n {\n window.getSelection().collapseToStart(); // works in chrome/safari/opera/FF\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu.
What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling `$(this).preventDefault()`) prevents the user from selecting at all, and the obvious `$().trigger('mouseup')` doesn't doesn't do anything with the selection at all.
* This is in the general context of a page, not particular to a textarea or other text field.
* `e.stopPropogation()` doesn't cancel text-selection.
* I'm not looking to *prevent* text selections, but rather to *veto* them after some short period of time, if certain conditions are met. | Try this:
```
var input = document.getElementById('myInputField');
if (input) {
input.onmousedown = function(e) {
if (!e) e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
}
```
And if not, have a read of:
<http://www.quirksmode.org/js/introevents.html> |
113,755 | <p>I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's <em>invisible</em> to the end user?</p>
<p>(The application is written in C#)</p>
| [
{
"answer_id": 113781,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": false,
"text": "<p>Not sure if this is the best way, but running <a href=\"https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490617(v=technet.10)\" rel=\"nofollow noreferrer\">netsh</a> should work:</p>\n\n<blockquote>\n <p>netsh firewall add allowedprogram C:\\MyApp\\MyApp.exe MyApp ENABLE</p>\n</blockquote>\n\n<p>I think this requires Administrator Permissions though,for obvious reasons :)</p>\n\n<p>Edit: I just don't know enough about ClickOnce to know whether or not you can run external programs through it.</p>\n"
},
{
"answer_id": 113794,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 4,
"selected": false,
"text": "<p>It's possible to access the data from the firewall, look at the following articles.</p>\n\n<ul>\n<li><a href=\"https://www.codeproject.com/Articles/10911/Windows-XP-SP2-Firewall-Controller\" rel=\"nofollow noreferrer\">Windows XP SP2 Firewall Controller</a></li>\n<li><a href=\"http://www.shafqatahmed.com/2008/01/controlling-win.html\" rel=\"nofollow noreferrer\">Controlling Windows Firewall using C# via COM Interop</a></li>\n</ul>\n\n<p>The real question is does the ClickOnce sandbox allows this kind of access? My guess would be that it doesn't. Maybe you could use a webservice? (For more information about the data access methods in ClickOnce see <a href=\"https://learn.microsoft.com/en-gb/visualstudio/deployment/accessing-local-and-remote-data-in-clickonce-applications?view=vs-2015\" rel=\"nofollow noreferrer\">Accessing Local and Remote Data in ClickOnce Applications</a>)</p>\n"
},
{
"answer_id": 113796,
"author": "Hasturkun",
"author_id": 20270,
"author_profile": "https://Stackoverflow.com/users/20270",
"pm_score": 3,
"selected": false,
"text": "<p>The easiest way I know would be to use <a href=\"http://en.wikipedia.org/wiki/Netsh\" rel=\"noreferrer\">netsh</a>, you can simply delete the rule and re-create it, or set up a port rule, if yours is fixed.<br>\n<a href=\"http://technet.microsoft.com/en-us/library/bb490617.aspx\" rel=\"noreferrer\" title=\"Appendix B: Netsh Command Syntax for the Netsh Firewall Context\">Here</a> is a page describing the options for its firewall context.</p>\n"
},
{
"answer_id": 114484,
"author": "Richard C",
"author_id": 6389,
"author_profile": "https://Stackoverflow.com/users/6389",
"pm_score": 5,
"selected": true,
"text": "<p>I found this article, which has a complete wrapper class included for manipulating the windows firewall. <a href=\"http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8\" rel=\"noreferrer\">Adding an Application to the Exception list on the Windows Firewall</a></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// \n\n/// Allows basic access to the windows firewall API.\n/// This can be used to add an exception to the windows firewall\n/// exceptions list, so that our programs can continue to run merrily\n/// even when nasty windows firewall is running.\n///\n/// Please note: It is not enforced here, but it might be a good idea\n/// to actually prompt the user before messing with their firewall settings,\n/// just as a matter of politeness.\n/// \n\n/// \n/// To allow the installers to authorize idiom products to work through\n/// the Windows Firewall.\n/// \npublic class FirewallHelper\n{\n #region Variables\n /// \n\n /// Hooray! Singleton access.\n /// \n\n private static FirewallHelper instance = null;\n\n /// \n\n /// Interface to the firewall manager COM object\n /// \n\n private INetFwMgr fwMgr = null;\n #endregion\n #region Properties\n /// \n\n /// Singleton access to the firewallhelper object.\n /// Threadsafe.\n /// \n\n public static FirewallHelper Instance\n {\n get\n {\n lock (typeof(FirewallHelper))\n {\n if (instance == null)\n instance = new FirewallHelper();\n return instance;\n }\n }\n }\n #endregion\n #region Constructivat0r\n /// \n\n /// Private Constructor. If this fails, HasFirewall will return\n /// false;\n /// \n\n private FirewallHelper()\n {\n // Get the type of HNetCfg.FwMgr, or null if an error occurred\n Type fwMgrType = Type.GetTypeFromProgID(\"HNetCfg.FwMgr\", false);\n\n // Assume failed.\n fwMgr = null;\n\n if (fwMgrType != null)\n {\n try\n {\n fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType);\n }\n // In all other circumnstances, fwMgr is null.\n catch (ArgumentException) { }\n catch (NotSupportedException) { }\n catch (System.Reflection.TargetInvocationException) { }\n catch (MissingMethodException) { }\n catch (MethodAccessException) { }\n catch (MemberAccessException) { }\n catch (InvalidComObjectException) { }\n catch (COMException) { }\n catch (TypeLoadException) { }\n }\n }\n #endregion\n #region Helper Methods\n /// \n\n /// Gets whether or not the firewall is installed on this computer.\n /// \n\n /// \n public bool IsFirewallInstalled\n {\n get\n {\n if (fwMgr != null &&\n fwMgr.LocalPolicy != null &&\n fwMgr.LocalPolicy.CurrentProfile != null)\n return true;\n else\n return false;\n }\n }\n\n /// \n\n /// Returns whether or not the firewall is enabled.\n /// If the firewall is not installed, this returns false.\n /// \n\n public bool IsFirewallEnabled\n {\n get\n {\n if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled)\n return true;\n else\n return false;\n }\n }\n\n /// \n\n /// Returns whether or not the firewall allows Application \"Exceptions\".\n /// If the firewall is not installed, this returns false.\n /// \n\n /// \n /// Added to allow access to this metho\n /// \n public bool AppAuthorizationsAllowed\n {\n get\n {\n if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed)\n return true;\n else\n return false;\n }\n }\n\n /// \n\n /// Adds an application to the list of authorized applications.\n /// If the application is already authorized, does nothing.\n /// \n\n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// This is the name of the application, purely for display\n /// puposes in the Microsoft Security Center.\n /// \n /// \n /// When applicationFullPath is null OR\n /// When appName is null.\n /// \n /// \n /// When applicationFullPath is blank OR\n /// When appName is blank OR\n /// applicationFullPath contains invalid path characters OR\n /// applicationFullPath is not an absolute path\n /// \n /// \n /// If the firewall is not installed OR\n /// If the firewall does not allow specific application 'exceptions' OR\n /// Due to an exception in COM this method could not create the\n /// necessary COM types\n /// \n /// \n /// If no file exists at the given applicationFullPath\n /// \n public void GrantAuthorization(string applicationFullPath, string appName)\n {\n #region Parameter checking\n if (applicationFullPath == null)\n throw new ArgumentNullException(\"applicationFullPath\");\n if (appName == null)\n throw new ArgumentNullException(\"appName\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"applicationFullPath must not be blank\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"appName must not be blank\");\n if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)\n throw new ArgumentException(\"applicationFullPath must not contain invalid path characters\");\n if (!Path.IsPathRooted(applicationFullPath))\n throw new ArgumentException(\"applicationFullPath is not an absolute path\");\n if (!File.Exists(applicationFullPath))\n throw new FileNotFoundException(\"File does not exist\", applicationFullPath);\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot grant authorization: Firewall is not installed.\");\n if (!AppAuthorizationsAllowed)\n throw new FirewallHelperException(\"Application exemptions are not allowed.\");\n #endregion\n\n if (!HasAuthorization(applicationFullPath))\n {\n // Get the type of HNetCfg.FwMgr, or null if an error occurred\n Type authAppType = Type.GetTypeFromProgID(\"HNetCfg.FwAuthorizedApplication\", false);\n\n // Assume failed.\n INetFwAuthorizedApplication appInfo = null;\n\n if (authAppType != null)\n {\n try\n {\n appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType);\n }\n // In all other circumnstances, appInfo is null.\n catch (ArgumentException) { }\n catch (NotSupportedException) { }\n catch (System.Reflection.TargetInvocationException) { }\n catch (MissingMethodException) { }\n catch (MethodAccessException) { }\n catch (MemberAccessException) { }\n catch (InvalidComObjectException) { }\n catch (COMException) { }\n catch (TypeLoadException) { }\n }\n\n if (appInfo == null)\n throw new FirewallHelperException(\"Could not grant authorization: can't create INetFwAuthorizedApplication instance.\");\n\n appInfo.Name = appName;\n appInfo.ProcessImageFileName = applicationFullPath;\n // ...\n // Use defaults for other properties of the AuthorizedApplication COM object\n\n // Authorize this application\n fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo);\n }\n // otherwise it already has authorization so do nothing\n }\n /// \n\n /// Removes an application to the list of authorized applications.\n /// Note that the specified application must exist or a FileNotFound\n /// exception will be thrown.\n /// If the specified application exists but does not current have\n /// authorization, this method will do nothing.\n /// \n\n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// When applicationFullPath is null\n /// \n /// \n /// When applicationFullPath is blank OR\n /// applicationFullPath contains invalid path characters OR\n /// applicationFullPath is not an absolute path\n /// \n /// \n /// If the firewall is not installed.\n /// \n /// \n /// If the specified application does not exist.\n /// \n public void RemoveAuthorization(string applicationFullPath)\n {\n\n #region Parameter checking\n if (applicationFullPath == null)\n throw new ArgumentNullException(\"applicationFullPath\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"applicationFullPath must not be blank\");\n if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)\n throw new ArgumentException(\"applicationFullPath must not contain invalid path characters\");\n if (!Path.IsPathRooted(applicationFullPath))\n throw new ArgumentException(\"applicationFullPath is not an absolute path\");\n if (!File.Exists(applicationFullPath))\n throw new FileNotFoundException(\"File does not exist\", applicationFullPath);\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot remove authorization: Firewall is not installed.\");\n #endregion\n\n if (HasAuthorization(applicationFullPath))\n {\n // Remove Authorization for this application\n fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath);\n }\n // otherwise it does not have authorization so do nothing\n }\n /// \n\n /// Returns whether an application is in the list of authorized applications.\n /// Note if the file does not exist, this throws a FileNotFound exception.\n /// \n\n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// When applicationFullPath is null\n /// \n /// \n /// When applicationFullPath is blank OR\n /// applicationFullPath contains invalid path characters OR\n /// applicationFullPath is not an absolute path\n /// \n /// \n /// If the firewall is not installed.\n /// \n /// \n /// If the specified application does not exist.\n /// \n public bool HasAuthorization(string applicationFullPath)\n {\n #region Parameter checking\n if (applicationFullPath == null)\n throw new ArgumentNullException(\"applicationFullPath\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"applicationFullPath must not be blank\");\n if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)\n throw new ArgumentException(\"applicationFullPath must not contain invalid path characters\");\n if (!Path.IsPathRooted(applicationFullPath))\n throw new ArgumentException(\"applicationFullPath is not an absolute path\");\n if (!File.Exists(applicationFullPath))\n throw new FileNotFoundException(\"File does not exist.\", applicationFullPath);\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot remove authorization: Firewall is not installed.\");\n\n #endregion\n\n // Locate Authorization for this application\n foreach (string appName in GetAuthorizedAppPaths())\n {\n // Paths on windows file systems are not case sensitive.\n if (appName.ToLower() == applicationFullPath.ToLower())\n return true;\n }\n\n // Failed to locate the given app.\n return false;\n\n }\n\n /// \n\n /// Retrieves a collection of paths to applications that are authorized.\n /// \n\n /// \n /// \n /// If the Firewall is not installed.\n /// \n public ICollection GetAuthorizedAppPaths()\n {\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot remove authorization: Firewall is not installed.\");\n\n ArrayList list = new ArrayList();\n // Collect the paths of all authorized applications\n foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)\n list.Add(app.ProcessImageFileName);\n\n return list;\n }\n #endregion\n}\n\n/// \n\n/// Describes a FirewallHelperException.\n/// \n\n/// \n///\n/// \npublic class FirewallHelperException : System.Exception\n{\n /// \n\n /// Construct a new FirewallHelperException\n /// \n\n /// \n public FirewallHelperException(string message)\n : base(message)\n { }\n}\n</code></pre>\n\n<p>The ClickOnce sandbox did not present any problems.</p>\n"
},
{
"answer_id": 2457504,
"author": "Rick",
"author_id": 295081,
"author_profile": "https://Stackoverflow.com/users/295081",
"pm_score": 3,
"selected": false,
"text": "<p>The dead link to \"Adding an Application to the Exception list on the Windows Firewall\" can be found on The Wayback Machine:</p>\n\n<p><a href=\"http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8\" rel=\"noreferrer\">http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8</a></p>\n"
},
{
"answer_id": 2891995,
"author": "Tim",
"author_id": 348286,
"author_profile": "https://Stackoverflow.com/users/348286",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is you only allow trusted software to run with Admin privileges. From time to time SOME software has to have admin privileges and make sensitive changes to your system. You might as well have a read only hard disk otherwise...</p>\n"
},
{
"answer_id": 13618538,
"author": "Tono Nam",
"author_id": 637142,
"author_profile": "https://Stackoverflow.com/users/637142",
"pm_score": 2,
"selected": false,
"text": "<p>This answer might be to late. This is what I ended up using:</p>\n\n<p><a href=\"https://support.microsoft.com/en-gb/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh\" rel=\"nofollow noreferrer\">https://support.microsoft.com/en-gb/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh</a></p>\n"
},
{
"answer_id": 44364591,
"author": "Chamath Viduranga",
"author_id": 4710997,
"author_profile": "https://Stackoverflow.com/users/4710997",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming we're using a Visual Studio Installer->Setup Project - You need an installer class like this inside an assembly that's being installed, and then make sure you add a custom action for the \"Primary output\" in the install phase.</p>\n\n<pre><code>using System.Collections;\nusing System.ComponentModel;\nusing System.Configuration.Install;\nusing System.IO;\nusing System.Diagnostics;\n\nnamespace YourNamespace\n{\n [RunInstaller(true)]\n public class AddFirewallExceptionInstaller : Installer\n {\n protected override void OnAfterInstall(IDictionary savedState)\n {\n base.OnAfterInstall(savedState);\n\n var path = Path.GetDirectoryName(Context.Parameters[\"assemblypath\"]);\n OpenFirewallForProgram(Path.Combine(path, \"YourExe.exe\"),\n \"Your program name for display\");\n }\n\n private static void OpenFirewallForProgram(string exeFileName, string displayName)\n {\n var proc = Process.Start(\n new ProcessStartInfo\n {\n FileName = \"netsh\",\n Arguments =\n string.Format(\n \"firewall add allowedprogram program=\\\"{0}\\\" name=\\\"{1}\\\" profile=\\\"ALL\\\"\",\n exeFileName, displayName),\n WindowStyle = ProcessWindowStyle.Hidden\n });\n proc.WaitForExit();\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
]
| I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's *invisible* to the end user?
(The application is written in C#) | I found this article, which has a complete wrapper class included for manipulating the windows firewall. [Adding an Application to the Exception list on the Windows Firewall](http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8)
```cs
///
/// Allows basic access to the windows firewall API.
/// This can be used to add an exception to the windows firewall
/// exceptions list, so that our programs can continue to run merrily
/// even when nasty windows firewall is running.
///
/// Please note: It is not enforced here, but it might be a good idea
/// to actually prompt the user before messing with their firewall settings,
/// just as a matter of politeness.
///
///
/// To allow the installers to authorize idiom products to work through
/// the Windows Firewall.
///
public class FirewallHelper
{
#region Variables
///
/// Hooray! Singleton access.
///
private static FirewallHelper instance = null;
///
/// Interface to the firewall manager COM object
///
private INetFwMgr fwMgr = null;
#endregion
#region Properties
///
/// Singleton access to the firewallhelper object.
/// Threadsafe.
///
public static FirewallHelper Instance
{
get
{
lock (typeof(FirewallHelper))
{
if (instance == null)
instance = new FirewallHelper();
return instance;
}
}
}
#endregion
#region Constructivat0r
///
/// Private Constructor. If this fails, HasFirewall will return
/// false;
///
private FirewallHelper()
{
// Get the type of HNetCfg.FwMgr, or null if an error occurred
Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
// Assume failed.
fwMgr = null;
if (fwMgrType != null)
{
try
{
fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType);
}
// In all other circumnstances, fwMgr is null.
catch (ArgumentException) { }
catch (NotSupportedException) { }
catch (System.Reflection.TargetInvocationException) { }
catch (MissingMethodException) { }
catch (MethodAccessException) { }
catch (MemberAccessException) { }
catch (InvalidComObjectException) { }
catch (COMException) { }
catch (TypeLoadException) { }
}
}
#endregion
#region Helper Methods
///
/// Gets whether or not the firewall is installed on this computer.
///
///
public bool IsFirewallInstalled
{
get
{
if (fwMgr != null &&
fwMgr.LocalPolicy != null &&
fwMgr.LocalPolicy.CurrentProfile != null)
return true;
else
return false;
}
}
///
/// Returns whether or not the firewall is enabled.
/// If the firewall is not installed, this returns false.
///
public bool IsFirewallEnabled
{
get
{
if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled)
return true;
else
return false;
}
}
///
/// Returns whether or not the firewall allows Application "Exceptions".
/// If the firewall is not installed, this returns false.
///
///
/// Added to allow access to this metho
///
public bool AppAuthorizationsAllowed
{
get
{
if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed)
return true;
else
return false;
}
}
///
/// Adds an application to the list of authorized applications.
/// If the application is already authorized, does nothing.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// This is the name of the application, purely for display
/// puposes in the Microsoft Security Center.
///
///
/// When applicationFullPath is null OR
/// When appName is null.
///
///
/// When applicationFullPath is blank OR
/// When appName is blank OR
/// applicationFullPath contains invalid path characters OR
/// applicationFullPath is not an absolute path
///
///
/// If the firewall is not installed OR
/// If the firewall does not allow specific application 'exceptions' OR
/// Due to an exception in COM this method could not create the
/// necessary COM types
///
///
/// If no file exists at the given applicationFullPath
///
public void GrantAuthorization(string applicationFullPath, string appName)
{
#region Parameter checking
if (applicationFullPath == null)
throw new ArgumentNullException("applicationFullPath");
if (appName == null)
throw new ArgumentNullException("appName");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("applicationFullPath must not be blank");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("appName must not be blank");
if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
throw new ArgumentException("applicationFullPath must not contain invalid path characters");
if (!Path.IsPathRooted(applicationFullPath))
throw new ArgumentException("applicationFullPath is not an absolute path");
if (!File.Exists(applicationFullPath))
throw new FileNotFoundException("File does not exist", applicationFullPath);
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed.");
if (!AppAuthorizationsAllowed)
throw new FirewallHelperException("Application exemptions are not allowed.");
#endregion
if (!HasAuthorization(applicationFullPath))
{
// Get the type of HNetCfg.FwMgr, or null if an error occurred
Type authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);
// Assume failed.
INetFwAuthorizedApplication appInfo = null;
if (authAppType != null)
{
try
{
appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType);
}
// In all other circumnstances, appInfo is null.
catch (ArgumentException) { }
catch (NotSupportedException) { }
catch (System.Reflection.TargetInvocationException) { }
catch (MissingMethodException) { }
catch (MethodAccessException) { }
catch (MemberAccessException) { }
catch (InvalidComObjectException) { }
catch (COMException) { }
catch (TypeLoadException) { }
}
if (appInfo == null)
throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance.");
appInfo.Name = appName;
appInfo.ProcessImageFileName = applicationFullPath;
// ...
// Use defaults for other properties of the AuthorizedApplication COM object
// Authorize this application
fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo);
}
// otherwise it already has authorization so do nothing
}
///
/// Removes an application to the list of authorized applications.
/// Note that the specified application must exist or a FileNotFound
/// exception will be thrown.
/// If the specified application exists but does not current have
/// authorization, this method will do nothing.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// When applicationFullPath is null
///
///
/// When applicationFullPath is blank OR
/// applicationFullPath contains invalid path characters OR
/// applicationFullPath is not an absolute path
///
///
/// If the firewall is not installed.
///
///
/// If the specified application does not exist.
///
public void RemoveAuthorization(string applicationFullPath)
{
#region Parameter checking
if (applicationFullPath == null)
throw new ArgumentNullException("applicationFullPath");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("applicationFullPath must not be blank");
if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
throw new ArgumentException("applicationFullPath must not contain invalid path characters");
if (!Path.IsPathRooted(applicationFullPath))
throw new ArgumentException("applicationFullPath is not an absolute path");
if (!File.Exists(applicationFullPath))
throw new FileNotFoundException("File does not exist", applicationFullPath);
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
#endregion
if (HasAuthorization(applicationFullPath))
{
// Remove Authorization for this application
fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath);
}
// otherwise it does not have authorization so do nothing
}
///
/// Returns whether an application is in the list of authorized applications.
/// Note if the file does not exist, this throws a FileNotFound exception.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// When applicationFullPath is null
///
///
/// When applicationFullPath is blank OR
/// applicationFullPath contains invalid path characters OR
/// applicationFullPath is not an absolute path
///
///
/// If the firewall is not installed.
///
///
/// If the specified application does not exist.
///
public bool HasAuthorization(string applicationFullPath)
{
#region Parameter checking
if (applicationFullPath == null)
throw new ArgumentNullException("applicationFullPath");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("applicationFullPath must not be blank");
if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
throw new ArgumentException("applicationFullPath must not contain invalid path characters");
if (!Path.IsPathRooted(applicationFullPath))
throw new ArgumentException("applicationFullPath is not an absolute path");
if (!File.Exists(applicationFullPath))
throw new FileNotFoundException("File does not exist.", applicationFullPath);
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
#endregion
// Locate Authorization for this application
foreach (string appName in GetAuthorizedAppPaths())
{
// Paths on windows file systems are not case sensitive.
if (appName.ToLower() == applicationFullPath.ToLower())
return true;
}
// Failed to locate the given app.
return false;
}
///
/// Retrieves a collection of paths to applications that are authorized.
///
///
///
/// If the Firewall is not installed.
///
public ICollection GetAuthorizedAppPaths()
{
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
ArrayList list = new ArrayList();
// Collect the paths of all authorized applications
foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
list.Add(app.ProcessImageFileName);
return list;
}
#endregion
}
///
/// Describes a FirewallHelperException.
///
///
///
///
public class FirewallHelperException : System.Exception
{
///
/// Construct a new FirewallHelperException
///
///
public FirewallHelperException(string message)
: base(message)
{ }
}
```
The ClickOnce sandbox did not present any problems. |
113,780 | <p>I don’t think I’ve grokked currying yet. I understand what it does, and how to do it. I just can’t think of a situation I would use it.</p>
<p>Where are you using currying in JavaScript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome.</p>
<p><a href="https://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications#113799">One of the answers</a> mentions animation. Functions like <code>slideUp</code>, <code>fadeIn</code> take an element as an arguments and are normally a curried function returning the high order function with the default “animation function” built-in. Why is that better than just applying the higher-up function with some defaults?</p>
<p>Are there any drawbacks to using it?</p>
<p>As requested here are some good resources on JavaScript currying:</p>
<ul>
<li><a href="http://www.dustindiaz.com/javascript-curry/" rel="noreferrer">http://www.dustindiaz.com/javascript-curry/</a></li>
<li>Crockford, Douglas (2008) <em>JavaScript: The Good Parts</em></li>
<li><a href="http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html" rel="noreferrer">http://www.svendtofte.com/code/curried_javascript/</a>
(Takes a detour into ML so skip the whole section from “A crash course in ML” and start again at “How to write curried JavaScript”)</li>
<li><a href="http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies" rel="noreferrer">http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies</a></li>
<li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How do JavaScript closures work?</a></li>
<li><strong><a href="http://ejohn.org/blog/partial-functions-in-javascript/" rel="noreferrer">http://ejohn.org/blog/partial-functions-in-javascript</a> (Mr. Resig on the money as per usual)</strong></li>
<li><a href="http://benalman.com/news/2010/09/partial-application-in-javascript/" rel="noreferrer">http://benalman.com/news/2010/09/partial-application-in-javascript/</a></li>
</ul>
<p>I’ll add more as they crop up in the comments.</p>
<hr>
<p>So, according to the answers, currying and partial application in general are convenience techniques.</p>
<p>If you are frequently “refining” a high-level function by calling it with same configuration, you can curry (or use Resig’s partial) the higher-level function to create simple, concise helper methods.</p>
| [
{
"answer_id": 113790,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 1,
"selected": false,
"text": "<p>As for libraries using it, there's always <a href=\"http://osteele.com/sources/javascript/functional/\" rel=\"nofollow noreferrer\">Functional</a>.</p>\n\n<p>When is it useful in JS? Probably the same times it is useful in other modern languages, but the only time I can see myself using it is in conjunction with partial application.</p>\n"
},
{
"answer_id": 113799,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that, most probably, all the animation library in JS are using currying. Rather than having to pass for each call a set of impacted elements and a function, describing how the element should behave, to a higher order function that will ensure all the timing stuff, its generally easier for the customer to release, as public API some function like \"slideUp\", \"fadeIn\" that takes only elements as arguments, and that are just some curried function returning the high order function with the default \"animation function\" built-in.</p>\n"
},
{
"answer_id": 113847,
"author": "Marijn",
"author_id": 12038,
"author_profile": "https://Stackoverflow.com/users/12038",
"pm_score": 2,
"selected": false,
"text": "<p>It's no magic or anything... just a pleasant shorthand for anonymous functions.</p>\n\n<p><code>partial(alert, \"FOO!\")</code> is equivalent to <code>function(){alert(\"FOO!\");}</code></p>\n\n<p><code>partial(Math.max, 0)</code> corresponds to <code>function(x){return Math.max(0, x);}</code></p>\n\n<p>The calls to partial (<a href=\"http://mochikit.com\" rel=\"nofollow noreferrer\">MochiKit</a> terminology. I think some other libraries give functions a .curry method which does the same thing) look slightly nicer and less noisy than the anonymous functions.</p>\n"
},
{
"answer_id": 113857,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 3,
"selected": false,
"text": "<p>I found functions that resemble python's <code>functools.partial</code> more useful in JavaScript:</p>\n\n<pre><code>function partial(fn) {\n return partialWithScope.apply(this,\n Array.prototype.concat.apply([fn, this],\n Array.prototype.slice.call(arguments, 1)));\n}\n\nfunction partialWithScope(fn, scope) {\n var args = Array.prototype.slice.call(arguments, 2);\n return function() {\n return fn.apply(scope, Array.prototype.concat.apply(args, arguments));\n };\n}\n</code></pre>\n\n<p>Why would you want to use it? A common situation where you want to use this is when you want to bind <code>this</code> in a function to a value:</p>\n\n<pre><code>var callback = partialWithScope(Object.function, obj);\n</code></pre>\n\n<p>Now when callback is called, <code>this</code> points to <code>obj</code>. This is useful in event situations or to save some space because it usually makes code shorter.</p>\n\n<p>Currying is similar to partial with the difference that the function the currying returns just accepts one argument (as far as I understand that).</p>\n"
},
{
"answer_id": 114030,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 6,
"selected": true,
"text": "<p>@Hank Gay</p>\n\n<p>In response to EmbiggensTheMind's comment:</p>\n\n<p>I can't think of an instance where <a href=\"http://en.wikipedia.org/wiki/Currying\" rel=\"noreferrer\">currying</a>—by itself—is useful in JavaScript; it is a technique for converting function calls with multiple arguments into chains of function calls with a single argument for each call, but JavaScript supports multiple arguments in a single function call. </p>\n\n<p>In JavaScript—and I assume most other actual languages (not lambda calculus)—it is commonly associated with partial application, though. John Resig <a href=\"http://ejohn.org/blog/partial-functions-in-javascript/#postcomment\" rel=\"noreferrer\">explains it better</a>, but the gist is that have some logic that will be applied to two or more arguments, and you only know the value(s) for some of those arguments. </p>\n\n<p>You can use partial application/currying to fix those known values and return a function that only accepts the unknowns, to be invoked later when you actually have the values you wish to pass. This provides a nifty way to avoid repeating yourself when you would have been calling the same JavaScript built-ins over and over with all the same values but one. To steal John's example:</p>\n\n<pre><code>String.prototype.csv = String.prototype.split.partial(/,\\s*/);\nvar results = \"John, Resig, Boston\".csv();\nalert( (results[1] == \"Resig\") + \" The text values were split properly\" );\n</code></pre>\n"
},
{
"answer_id": 3322715,
"author": "William Pietri",
"author_id": 123248,
"author_profile": "https://Stackoverflow.com/users/123248",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an example.</p>\n\n<p>I'm instrumenting a bunch of fields with JQuery so I can see what users are up to. The code looks like this:</p>\n\n<pre><code>$('#foo').focus(trackActivity);\n$('#foo').blur(trackActivity);\n$('#bar').focus(trackActivity);\n$('#bar').blur(trackActivity);\n</code></pre>\n\n<p>(For non-JQuery users, I'm saying that any time a couple of fields get or lose focus, I want the trackActivity() function to be called. I could also use an anonymous function, but I'd have to duplicate it 4 times, so I pulled it out and named it.)</p>\n\n<p>Now it turns out that one of those fields needs to be handled differently. I'd like to be able to pass a parameter in on one of those calls to be passed along to our tracking infrastructure. With currying, I can.</p>\n"
},
{
"answer_id": 4923899,
"author": "Clarence Fredericks",
"author_id": 606743,
"author_profile": "https://Stackoverflow.com/users/606743",
"pm_score": 0,
"selected": false,
"text": "<p>I agree that at times you would like to get the ball rolling by creating a pseudo-function that will always have the value of the first argument filled in. Fortunately, I came across a brand new JavaScript library called jPaq (h<a href=\"http://jpaq.org/\" rel=\"nofollow\">ttp://jpaq.org/</a>) which provides this functionality. The best thing about the library is the fact that you can download your own build which contains only the code that you will need.</p>\n"
},
{
"answer_id": 5370631,
"author": "Fred Yang",
"author_id": 282756,
"author_profile": "https://Stackoverflow.com/users/282756",
"pm_score": 1,
"selected": false,
"text": "<p>JavaScript functions is called lamda in other functional language. It can be used to compose a new api (more powerful or complext function) to based on another developer's simple input. Curry is just one of the techniques. You can use it to create a simplified api to call a complex api. If you are the develper who use the simplified api (for example you use jQuery to do simple manipulation), you don't need to use curry. But if you want to create the simplified api, curry is your friend. You have to write a javascript framework (like jQuery, mootools) or library, then you can appreciate its power. I wrote a enhanced curry function, at <a href=\"http://blog.semanticsworks.com/2011/03/enhanced-curry-method.html\" rel=\"nofollow\">http://blog.semanticsworks.com/2011/03/enhanced-curry-method.html</a> . You don't need to the curry method to do currying, it just help to do currying, but you can always do it manually by writing a function A(){} to return another function B(){}. To make it more interesting, use function B() to return another function C().</p>\n"
},
{
"answer_id": 6861858,
"author": "Prisoner ZERO",
"author_id": 312317,
"author_profile": "https://Stackoverflow.com/users/312317",
"pm_score": 7,
"selected": false,
"text": "<p>Here's an <a href=\"http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/\" rel=\"noreferrer\"><strong>interesting AND practical use of currying in JavaScript that uses closures</strong></a>:</p>\n\n<blockquote>\n<pre><code>function converter(toUnit, factor, offset, input) {\n offset = offset || 0;\n return [((offset + input) * factor).toFixed(2), toUnit].join(\" \");\n}\n\nvar milesToKm = converter.curry('km', 1.60936, undefined);\nvar poundsToKg = converter.curry('kg', 0.45460, undefined);\nvar farenheitToCelsius = converter.curry('degrees C', 0.5556, -32);\n\nmilesToKm(10); // returns \"16.09 km\"\npoundsToKg(2.5); // returns \"1.14 kg\"\nfarenheitToCelsius(98); // returns \"36.67 degrees C\"\n</code></pre>\n</blockquote>\n\n<p>This relies on a <code>curry</code> extension of <code>Function</code>, although as you can see it only uses <code>apply</code> (nothing too fancy):</p>\n\n<blockquote>\n<pre><code>Function.prototype.curry = function() {\n if (arguments.length < 1) {\n return this; //nothing to curry with - return function\n }\n var __method = this;\n var args = toArray(arguments);\n return function() {\n return __method.apply(this, args.concat([].slice.apply(null, arguments)));\n }\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 16875840,
"author": "megawac",
"author_id": 1517919,
"author_profile": "https://Stackoverflow.com/users/1517919",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to add some resources for Functional.js:</p>\n\n<p>Lecture/conference explaining some applications\n<a href=\"http://www.youtube.com/watch?v=HAcN3JyQoyY\" rel=\"nofollow\">http://www.youtube.com/watch?v=HAcN3JyQoyY</a></p>\n\n<p>Updated Functional.js library:\n<a href=\"https://github.com/loop-recur/FunctionalJS\" rel=\"nofollow\">https://github.com/loop-recur/FunctionalJS</a>\nSome nice helpers (sorry new here, no reputation :p):\n/loop-recur/PreludeJS</p>\n\n<p>I've been using this library a lot recently to reduce the repetition in an js IRC clients helper library. It's great stuff - really helps clean up and simplify code. </p>\n\n<p>In addition, if performance becomes an issue (but this lib is pretty light), it's easy to just rewrite using a native function.</p>\n"
},
{
"answer_id": 31560758,
"author": "Shishir Arora",
"author_id": 3221274,
"author_profile": "https://Stackoverflow.com/users/3221274",
"pm_score": 2,
"selected": false,
"text": "<p>I know its old thread but I will have to show how this is being used in javascript libraries:</p>\n\n<p>I will use lodash.js library to describe these concepts concretely.</p>\n\n<p>Example:</p>\n\n<pre><code>var fn = function(a,b,c){ \nreturn a+b+c+(this.greet || ‘'); \n}\n</code></pre>\n\n<p>Partial Application:</p>\n\n<pre><code>var partialFnA = _.partial(fn, 1,3);\n</code></pre>\n\n<p>Currying: </p>\n\n<pre><code>var curriedFn = _.curry(fn);\n</code></pre>\n\n<p>Binding: </p>\n\n<pre><code>var boundFn = _.bind(fn,object,1,3 );//object= {greet: ’!'}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>curriedFn(1)(3)(5); // gives 9 \nor \ncurriedFn(1,3)(5); // gives 9 \nor \ncurriedFn(1)(_,3)(2); //gives 9\n\n\npartialFnA(5); //gives 9\n\nboundFn(5); //gives 9!\n</code></pre>\n\n<p>difference:</p>\n\n<p>after currying we get a new function with no parameters pre bound.</p>\n\n<p>after partial application we get a function which is bound with some parameters prebound.</p>\n\n<p>in binding we can bind a context which will be used to replace ‘this’, if not bound default of any function will be window scope.</p>\n\n<p>Advise: There is no need to reinvent the wheel. Partial application/binding/currying are very much related. You can see the difference above. Use this meaning anywhere and people will recognise what you are doing without issues in understanding plus you will have to use less code.</p>\n"
},
{
"answer_id": 32116810,
"author": "cstuncsik",
"author_id": 3579966,
"author_profile": "https://Stackoverflow.com/users/3579966",
"pm_score": 0,
"selected": false,
"text": "<p>You can use native bind for quick, one line solution</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 clampAngle(min, max, angle) {\r\n var result, delta;\r\n delta = max - min;\r\n result = (angle - min) % delta;\r\n if (result < 0) {\r\n result += delta;\r\n }\r\n return min + result;\r\n};\r\n\r\nvar clamp0To360 = clampAngle.bind(null, 0, 360);\r\n\r\nconsole.log(clamp0To360(405)) // 45</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 32379766,
"author": "Byron Katz",
"author_id": 713809,
"author_profile": "https://Stackoverflow.com/users/713809",
"pm_score": 3,
"selected": false,
"text": "<p>Agreeing with Hank Gay - It's extremely useful in certain true functional programming languages - because it's a necessary part. For example, in Haskell you simply cannot take multiple parameters to a function - you cannot do that in pure functional programming. You take one param at a time and build up your function. In JavaScript it's simply unnecessary, despite contrived examples like \"converter\". Here's that same converter code, without the need for currying:</p>\n\n<pre><code>var converter = function(ratio, symbol, input) {\n return (input*ratio).toFixed(2) + \" \" + symbol;\n}\n\nvar kilosToPoundsRatio = 2.2;\nvar litersToUKPintsRatio = 1.75;\nvar litersToUSPintsRatio = 1.98;\nvar milesToKilometersRatio = 1.62;\n\nconverter(kilosToPoundsRatio, \"lbs\", 4); //8.80 lbs\nconverter(litersToUKPintsRatio, \"imperial pints\", 2.4); //4.20 imperial pints\nconverter(litersToUSPintsRatio, \"US pints\", 2.4); //4.75 US pints\nconverter(milesToKilometersRatio, \"km\", 34); //55.08 km\n</code></pre>\n\n<p>I badly wish Douglas Crockford, in \"JavaScript: The Good Parts\", had given some mention of the history and actual use of currying rather than his offhanded remarks. For the longest time after reading that, I was boggled, until I was studying Functional programming and realized that's where it came from.</p>\n\n<p>After some more thinking, I posit there is one valid use case for currying in JavaScript: if you are trying to write using pure functional programming techniques using JavaScript. Seems like a rare use case though.</p>\n"
},
{
"answer_id": 36505248,
"author": "JL Peyret",
"author_id": 1394353,
"author_profile": "https://Stackoverflow.com/users/1394353",
"pm_score": 0,
"selected": false,
"text": "<p>Another stab at it, from working with promises.</p>\n\n<p><em>(Disclaimer: JS noob, coming from the Python world. Even there, <strong>currying</strong> is not used all that much, but it can come in handy on occasion. So I cribbed the currying function - see links)</em></p>\n\n<p>First, I am starting with an ajax call. I have some specific processing to do on success, but on failure, I just want to give the user the feedback that calling <em>something</em> resulted in <em>some error</em>. In my actual code, I display the error feedback in a bootstrap panel, but am just using logging here.</p>\n\n<p>I've modified my live url to make this fail.</p>\n\n<pre><code>function ajax_batch(e){\n var url = $(e.target).data(\"url\");\n\n //induce error\n url = \"x\" + url;\n\n var promise_details = $.ajax(\n url,\n {\n headers: { Accept : \"application/json\" },\n // accepts : \"application/json\",\n beforeSend: function (request) {\n if (!this.crossDomain) {\n request.setRequestHeader(\"X-CSRFToken\", csrf_token);\n }\n },\n dataType : \"json\",\n type : \"POST\"}\n );\n promise_details.then(notify_batch_success, fail_status_specific_to_batch);\n}\n</code></pre>\n\n<p>Now, here in order to tell the user that a batch failed, I need to write that info in the error handler, because all it is getting is a response from the server.</p>\n\n<p>I still only have the info available at coding time - in my case I have a number of possible batches, but I don't know which one has failed w.o. parsing the server response about the failed url.</p>\n\n<pre><code>function fail_status_specific_to_batch(d){\n console.log(\"bad batch run, dude\");\n console.log(\"response.status:\" + d.status);\n}\n</code></pre>\n\n<p>Let's do it. Console output is:</p>\n\n<p>console:</p>\n\n<p><code>bad batch run, dude\nutility.js (line 109)\nresponse.status:404</code></p>\n\n<p>Now, let's change things a bit and use a reusable generic failure handler, but also one that is <em>curried</em> at runtime with both the known-at-code-time calling context and the run-time info available from event.</p>\n\n<pre><code> ... rest is as before...\n var target = $(e.target).text();\n var context = {\"user_msg\": \"bad batch run, dude. you were calling :\" + target};\n var contexted_fail_notification = curry(generic_fail, context); \n\n promise_details.then(notify_batch_success, contexted_fail_notification);\n}\n\nfunction generic_fail(context, d){\n console.log(context);\n console.log(\"response.status:\" + d.status);\n}\n\nfunction curry(fn) {\n var slice = Array.prototype.slice,\n stored_args = slice.call(arguments, 1);\n return function () {\n var new_args = slice.call(arguments),\n args = stored_args.concat(new_args);\n return fn.apply(null, args);\n };\n}\n</code></pre>\n\n<p>console:</p>\n\n<p><code>Object { user_msg=\"bad batch run, dude. you were calling :Run ACL now\"}\nutility.js (line 117)\nresponse.status:404\nutility.js (line 118)</code></p>\n\n<p>More generally, given how widespread callback usage is in JS, currying seems like a quite useful tool to have.</p>\n\n<p><a href=\"https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/\" rel=\"nofollow\">https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/</a>\n<a href=\"http://www.drdobbs.com/open-source/currying-and-partial-functions-in-javasc/231001821?pgno=2\" rel=\"nofollow\">http://www.drdobbs.com/open-source/currying-and-partial-functions-in-javasc/231001821?pgno=2</a></p>\n"
},
{
"answer_id": 65180031,
"author": "Qiulang",
"author_id": 301513,
"author_profile": "https://Stackoverflow.com/users/301513",
"pm_score": 0,
"selected": false,
"text": "<p>I asked a similar question at <a href=\"https://softwareengineering.stackexchange.com/questions/384529/a-real-life-example-of-using-curry-function\">https://softwareengineering.stackexchange.com/questions/384529/a-real-life-example-of-using-curry-function</a></p>\n<p>But only after I use <a href=\"https://ramdajs.com/\" rel=\"nofollow noreferrer\">ramda</a> do I finally appreciate the usefulness of curry. So I will argue that if we need to chain functions together to process some input data one step a time, e.g. the promise chain example in the article <a href=\"https://fr.umio.us/favoring-curry/\" rel=\"nofollow noreferrer\">Favoring Curry</a>, using curry by "function first,data last", the code does look clean!</p>\n"
},
{
"answer_id": 68580704,
"author": "Giorgi Moniava",
"author_id": 3963067,
"author_profile": "https://Stackoverflow.com/users/3963067",
"pm_score": 2,
"selected": false,
"text": "<p>Consider <code>filter</code> function. And you want to write a callback for it.</p>\n<pre><code>let x = [1,2,3,4,5,6,7,11,12,14,15];\nlet results = x.filter(callback);\n</code></pre>\n<p>Assume want to output only even numbers, so:</p>\n<pre><code>let callback = x => x % 2 === 0;\n</code></pre>\n<p>Now imagine we want to implement our <code>callback</code> such that\ndepending on scenario it outputs even numbers which are above some <strong>threshold number</strong> (such\nnumber should be configurable).</p>\n<p>We can't easily make such threshold number a parameter to <code>callback</code> function, because <code>filter</code> invokes <code>callback</code> and by default passes it array elements and index.</p>\n<p>How would you implement this?</p>\n<p>This is a good use case for currying:</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>let x = [1,2,3,4,5,6,7,11,12,14,15];\nlet callback = (threshold) => (x) => (x % 2==0 && x > threshold);\n\nlet results1 = x.filter(callback(5)); // Even numbers higher than 5\nlet results2 = x.filter(callback(10)); // Even numbers higher than 10\n\nconsole.log(results1,results2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73404393,
"author": "Andre Lopes",
"author_id": 10992558,
"author_profile": "https://Stackoverflow.com/users/10992558",
"pm_score": 0,
"selected": false,
"text": "<p>Here you have a practical example of were currying is being used at the moment.\n<a href=\"https://www.joshwcomeau.com/react/demystifying-styled-components/\" rel=\"nofollow noreferrer\">https://www.joshwcomeau.com/react/demystifying-styled-components/</a></p>\n<p>Basically he is creating a poor man styled components and uses currying to "preload" the name of the tag when creating a new style for it.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9474/"
]
| I don’t think I’ve grokked currying yet. I understand what it does, and how to do it. I just can’t think of a situation I would use it.
Where are you using currying in JavaScript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome.
[One of the answers](https://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications#113799) mentions animation. Functions like `slideUp`, `fadeIn` take an element as an arguments and are normally a curried function returning the high order function with the default “animation function” built-in. Why is that better than just applying the higher-up function with some defaults?
Are there any drawbacks to using it?
As requested here are some good resources on JavaScript currying:
* <http://www.dustindiaz.com/javascript-curry/>
* Crockford, Douglas (2008) *JavaScript: The Good Parts*
* [http://www.svendtofte.com/code/curried\_javascript/](http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html)
(Takes a detour into ML so skip the whole section from “A crash course in ML” and start again at “How to write curried JavaScript”)
* <http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies>
* [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work)
* **[http://ejohn.org/blog/partial-functions-in-javascript](http://ejohn.org/blog/partial-functions-in-javascript/) (Mr. Resig on the money as per usual)**
* <http://benalman.com/news/2010/09/partial-application-in-javascript/>
I’ll add more as they crop up in the comments.
---
So, according to the answers, currying and partial application in general are convenience techniques.
If you are frequently “refining” a high-level function by calling it with same configuration, you can curry (or use Resig’s partial) the higher-level function to create simple, concise helper methods. | @Hank Gay
In response to EmbiggensTheMind's comment:
I can't think of an instance where [currying](http://en.wikipedia.org/wiki/Currying)—by itself—is useful in JavaScript; it is a technique for converting function calls with multiple arguments into chains of function calls with a single argument for each call, but JavaScript supports multiple arguments in a single function call.
In JavaScript—and I assume most other actual languages (not lambda calculus)—it is commonly associated with partial application, though. John Resig [explains it better](http://ejohn.org/blog/partial-functions-in-javascript/#postcomment), but the gist is that have some logic that will be applied to two or more arguments, and you only know the value(s) for some of those arguments.
You can use partial application/currying to fix those known values and return a function that only accepts the unknowns, to be invoked later when you actually have the values you wish to pass. This provides a nifty way to avoid repeating yourself when you would have been calling the same JavaScript built-ins over and over with all the same values but one. To steal John's example:
```
String.prototype.csv = String.prototype.split.partial(/,\s*/);
var results = "John, Resig, Boston".csv();
alert( (results[1] == "Resig") + " The text values were split properly" );
``` |
113,803 | <p>If I have a table in MySQL which represents a base class, and I have a bunch of tables which represent the fields in the derived classes, each of which refers back to the base table with a foreign key, is there any way to get MySQL to enforce the one-to-one relationship between the derived table and the base table, or does this have to be done in code?</p>
<p>Using the following quick 'n' dirty schema as an example, is there any way to get MySQL to ensure that rows in both product_cd and product_dvd cannot share the same product_id? Is there a better way to design the schema to allow the database to enforce this relationship, or is it simply not possible?</p>
<pre><code>CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(10) unsigned NOT NULL auto_increment,
`product_name` varchar(50) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE = InnoDB;
CREATE TABLE `product_cd` (
`product_cd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`product_id` INT UNSIGNED NOT NULL ,
`artist_name` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `product_cd_id` ) ,
INDEX ( `product_id` )
) ENGINE = InnoDB;
ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id` )
REFERENCES `product` (`product_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT ;
CREATE TABLE `product_dvd` (
`product_dvd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`product_id` INT UNSIGNED NOT NULL ,
`director` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `product_dvd_id` ) ,
INDEX ( `product_id` )
) ENGINE = InnoDB;
ALTER TABLE `product_dvd` ADD FOREIGN KEY ( `product_id` )
REFERENCES `product` (`product_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT ;
</code></pre>
<p>@<a href="https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113811">Skliwz</a>, can you please provide more detail about how triggers can be used to enforce this constraint with the schema provided?</p>
<p>@<a href="https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113858">boes</a>, that sounds great. How does it work in situations where you have a child of a child? For example, if we added product_movie and made product_dvd a child of product_movie? Would it be a maintainability nightmare to make the check constraint for product_dvd have to factor in all child types as well?</p>
| [
{
"answer_id": 113811,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "<p>If you use MySQL 5.x you can use triggers for these kinds of constraints.</p>\n\n<p>Another (suboptimal) option would be to use a \"type\" column in the parent table to silently ignore duplication, and to be able to choose the correct \"extension table\".</p>\n"
},
{
"answer_id": 113813,
"author": "Ikke",
"author_id": 20261,
"author_profile": "https://Stackoverflow.com/users/20261",
"pm_score": 2,
"selected": false,
"text": "<p>You could just add a foreign key from one primary key to the other primary key. Because PK's have to be unique, you automaticly get a one-to-one relation.</p>\n"
},
{
"answer_id": 113822,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 2,
"selected": false,
"text": "<p>If you got rid of <em>product-dvd-id</em> and <em>product-cd-id</em>, and used the <em>product-id</em> as the primary key for all three tables, you could at least make sure that no two DVD or no two CD use the same <em>product-id</em>. Plus there would be less ids to keep track of. </p>\n\n<p>And you maybe need some kind of <em>type</em> column in the products table.</p>\n"
},
{
"answer_id": 113850,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 3,
"selected": false,
"text": "<p>Enforcing a 1:0-1 or 1:1 relationship can be achieved by defining a unique constraint on the foreign key's columns, so only one combination can exist. Normally this would be the primary key of the child table.</p>\n\n<p>If the FK is on a primary or unique key of the referenced tables it will constrain them to values present in the parent and the unique constraint on the column or columns restricts them to uniqueness. This means that the child table can only have values corresponding to the parent in the constrained columns and each row must have a unique value. Doing this enforces that the child table will have at most one row corresponding to the parent record.</p>\n"
},
{
"answer_id": 113858,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 3,
"selected": true,
"text": "<p>To make sure that a product is or a cd or a dvd I would add a type column and make it part of the primary key. In the derived column you add a check constraint for the type. In the example I set cd to 1 and you could make dvd = 2 and so on for each derived table.</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS `product` (\n`product_id` int(10) unsigned NOT NULL auto_increment,\n'product_type' int not null,\n`product_name` varchar(50) NOT NULL,\n`description` text NOT NULL,\nPRIMARY KEY (`product_id`, 'product_type')\n) ENGINE = InnoDB;\n\nCREATE TABLE `product_cd` (\n`product_id` INT UNSIGNED NOT NULL ,\n'product_type' int not null default(1) check ('product_type' = 1)\n`artist_name` VARCHAR( 50 ) NOT NULL ,\nPRIMARY KEY ( `product_id`, 'product_type' ) ,\n) ENGINE = InnoDB;\n\nALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id`, 'product_type' ) \nREFERENCES `product` (`product_id`, 'product_type') \nON DELETE RESTRICT ON UPDATE RESTRICT ;\n</code></pre>\n"
},
{
"answer_id": 6793850,
"author": "Hanynowsky",
"author_id": 754756,
"author_profile": "https://Stackoverflow.com/users/754756",
"pm_score": 2,
"selected": false,
"text": "<p>The only effective way to maintain a one-to-one relationship is to set the foreign-key column to <strong>UNIQUE</strong>; this way we're sure only one record will be created for it. And if you try to violate this constraint you get the following error (MySQL 5.1): </p>\n\n<pre><code>`1 error(s) saving changes to table testdb`.table4: INSERT INTO testdb.table4 (idtable4, label, table3_idtable3) VALUES (0, 'soso', 0) 1062: Duplicate entry '0' for key 'table3_idtable3_UNIQUE' Rollback complete\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15004/"
]
| If I have a table in MySQL which represents a base class, and I have a bunch of tables which represent the fields in the derived classes, each of which refers back to the base table with a foreign key, is there any way to get MySQL to enforce the one-to-one relationship between the derived table and the base table, or does this have to be done in code?
Using the following quick 'n' dirty schema as an example, is there any way to get MySQL to ensure that rows in both product\_cd and product\_dvd cannot share the same product\_id? Is there a better way to design the schema to allow the database to enforce this relationship, or is it simply not possible?
```
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(10) unsigned NOT NULL auto_increment,
`product_name` varchar(50) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE = InnoDB;
CREATE TABLE `product_cd` (
`product_cd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`product_id` INT UNSIGNED NOT NULL ,
`artist_name` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `product_cd_id` ) ,
INDEX ( `product_id` )
) ENGINE = InnoDB;
ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id` )
REFERENCES `product` (`product_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT ;
CREATE TABLE `product_dvd` (
`product_dvd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`product_id` INT UNSIGNED NOT NULL ,
`director` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `product_dvd_id` ) ,
INDEX ( `product_id` )
) ENGINE = InnoDB;
ALTER TABLE `product_dvd` ADD FOREIGN KEY ( `product_id` )
REFERENCES `product` (`product_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT ;
```
@[Skliwz](https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113811), can you please provide more detail about how triggers can be used to enforce this constraint with the schema provided?
@[boes](https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113858), that sounds great. How does it work in situations where you have a child of a child? For example, if we added product\_movie and made product\_dvd a child of product\_movie? Would it be a maintainability nightmare to make the check constraint for product\_dvd have to factor in all child types as well? | To make sure that a product is or a cd or a dvd I would add a type column and make it part of the primary key. In the derived column you add a check constraint for the type. In the example I set cd to 1 and you could make dvd = 2 and so on for each derived table.
```
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(10) unsigned NOT NULL auto_increment,
'product_type' int not null,
`product_name` varchar(50) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`product_id`, 'product_type')
) ENGINE = InnoDB;
CREATE TABLE `product_cd` (
`product_id` INT UNSIGNED NOT NULL ,
'product_type' int not null default(1) check ('product_type' = 1)
`artist_name` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `product_id`, 'product_type' ) ,
) ENGINE = InnoDB;
ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id`, 'product_type' )
REFERENCES `product` (`product_id`, 'product_type')
ON DELETE RESTRICT ON UPDATE RESTRICT ;
``` |
113,824 | <p>Is it possible to automount a TrueCrypt volume when logging in to Ubuntu 8.04? It's already storing the wireless network keys using the Seahorse password manager. Could TrueCrypt be made to fetch its volume password from the same keyring? Currently this would seem like the most convenient way to store my source code on the USB stick I carry around to boot from.</p>
| [
{
"answer_id": 114176,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": "<p>Although I'm currently not a Gentoo user (on Ubuntu now), I used to be one, for years, and had learned, that it's a good thing to search for linux answers on <a href=\"http://forums.gentoo.org\" rel=\"nofollow noreferrer\">forums.gentoo.org</a>\nand the <a href=\"http://gentoo-wiki.com\" rel=\"nofollow noreferrer\">Gentoo wiki</a>.\nI had found these, HTH:</p>\n\n<ul>\n<li><a href=\"http://forums.gentoo.org/viewtopic-t-691788-highlight-truecrypt.html\" rel=\"nofollow noreferrer\">http://forums.gentoo.org/viewtopic-t-691788-highlight-truecrypt.html</a></li>\n<li><a href=\"http://forums.gentoo.org/viewtopic-t-657404-highlight-truecrypt.html\" rel=\"nofollow noreferrer\">http://forums.gentoo.org/viewtopic-t-657404-highlight-truecrypt.html</a> </li>\n</ul>\n"
},
{
"answer_id": 177574,
"author": "jjrv",
"author_id": 16509,
"author_profile": "https://Stackoverflow.com/users/16509",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently one solution will be to update to Ubuntu 8.10 which by default supports an encrypted directory for each user, mounted at login. It's not the same as TrueCrypt but has other strengths and weaknesses.</p>\n\n<p>There's also a way to <a href=\"http://blog.littleimpact.de/index.php/2008/07/12/automatic-encryption-of-home-directories-using-truecrypt/\" rel=\"nofollow noreferrer\">get TrueCrypt working with the login password</a>.</p>\n"
},
{
"answer_id": 177577,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know much about Truecrypt, but if it can be mounted with a script, you could write such a script and place it in your session startup (System -> Preferences -> Session, I think). If it needs a password on the command line you could have the script launch gnome-terminal for you.</p>\n"
},
{
"answer_id": 10216328,
"author": "swizzly",
"author_id": 1317491,
"author_profile": "https://Stackoverflow.com/users/1317491",
"pm_score": 3,
"selected": true,
"text": "<p>I can't really remember where I found this solution, but it was working for me on Ubuntu Karmic with gdm. \nYou have to edit the <code>/etc/gdm/Init</code> file and add the following:</p>\n\n<pre><code>if !(echo `mount` | grep -q \"/home/your_username type\")\nthen\n truecrypt /dev/sdaxxx /home/your_username\nfi\n</code></pre>\n\n<p>Unfortunately it doesn't work in the new Precious Penguin Ubuntu release, since it doesn't come with the gmd package. Does anybody know how to init truecrypt for this Ubuntu release?</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16509/"
]
| Is it possible to automount a TrueCrypt volume when logging in to Ubuntu 8.04? It's already storing the wireless network keys using the Seahorse password manager. Could TrueCrypt be made to fetch its volume password from the same keyring? Currently this would seem like the most convenient way to store my source code on the USB stick I carry around to boot from. | I can't really remember where I found this solution, but it was working for me on Ubuntu Karmic with gdm.
You have to edit the `/etc/gdm/Init` file and add the following:
```
if !(echo `mount` | grep -q "/home/your_username type")
then
truecrypt /dev/sdaxxx /home/your_username
fi
```
Unfortunately it doesn't work in the new Precious Penguin Ubuntu release, since it doesn't come with the gmd package. Does anybody know how to init truecrypt for this Ubuntu release? |
113,829 | <p>How do I get timestamp from e.g. <code>22-09-2008</code>?</p>
| [
{
"answer_id": 113836,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 5,
"selected": false,
"text": "<p>Using <a href=\"http://php.net/mktime\" rel=\"noreferrer\">mktime</a>:</p>\n\n<pre><code>list($day, $month, $year) = explode('-', '22-09-2008');\necho mktime(0, 0, 0, $month, $day, $year);\n</code></pre>\n"
},
{
"answer_id": 113841,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 9,
"selected": false,
"text": "<p><br/></p>\n\n<p><em>This method works on <strong>both</strong> Windows and Unix <strong>and</strong> is <strong>time-zone</strong> aware, which is probably what you want if you work with <a href=\"https://unix4lyfe.org/time/\" rel=\"noreferrer\">dates</a>.</em></p>\n\n<p>If you don't care about timezone, or want to use the time zone your server uses:</p>\n\n<pre><code>$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n</code></pre>\n\n<p><strong>1222093324</strong> <sub>(This will differ depending on your server time zone...)</sub></p>\n\n<p><br/></p>\n\n<p>If you want to specify in which time zone, here EST. (Same as New York.)</p>\n\n<pre><code>$d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('EST')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n</code></pre>\n\n<p><strong>1222093305</strong></p>\n\n<p><br/></p>\n\n<p>Or if you want to use <a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time\" rel=\"noreferrer\">UTC</a>. (Same as \"<a href=\"https://en.wikipedia.org/wiki/Greenwich_Mean_Time\" rel=\"noreferrer\">GMT</a>\".)</p>\n\n<pre><code>$d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('UTC')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n</code></pre>\n\n<p><strong>1222093289</strong></p>\n\n<p><br/></p>\n\n<p>Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.</p>\n"
},
{
"answer_id": 113871,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 8,
"selected": false,
"text": "<p>There is also <strong>strptime()</strong> which expects exactly one format:</p>\n\n<pre><code>$a = strptime('22-09-2008', '%d-%m-%Y');\n$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);\n</code></pre>\n"
},
{
"answer_id": 115864,
"author": "daremon",
"author_id": 6346,
"author_profile": "https://Stackoverflow.com/users/6346",
"pm_score": 7,
"selected": false,
"text": "<p>Be careful with functions like <code>strtotime()</code> that try to \"guess\" what you mean (it doesn't guess of course, the <a href=\"https://stackoverflow.com/questions/113829/date-to-timestamp-php#113871\">rules are here</a>).</p>\n\n<p>Indeed <code>22-09-2008</code> will be parsed as <em>22 September 2008</em>, as it is the only reasonable thing. </p>\n\n<p>How will <code>08-09-2008</code> be parsed? Probably <em>09 August 2008</em>. </p>\n\n<p>What about <code>2008-09-50</code>? Some versions of PHP parse this as <em>20 October 2008</em>.</p>\n\n<p>So, if you are sure your input is in <code>DD-MM-YYYY</code> format, it's better to use the solution offered by <a href=\"https://stackoverflow.com/questions/113829/date-to-timestamp-php#113871\">@Armin Ronacher</a>.</p>\n"
},
{
"answer_id": 2020557,
"author": "blavla",
"author_id": 138844,
"author_profile": "https://Stackoverflow.com/users/138844",
"pm_score": 3,
"selected": false,
"text": "<p>If you know the format use <code>strptime</code> because <code>strtotime</code> does a guess for the format, which might not always be correct. Since <code>strptime</code> is not implemented in Windows there is a custom function</p>\n\n<ul>\n<li><a href=\"http://nl3.php.net/manual/en/function.strptime.php#86572\" rel=\"nofollow noreferrer\">http://nl3.php.net/manual/en/function.strptime.php#86572</a></li>\n</ul>\n\n<p>Remember that the returnvalue <code>tm_year</code> is from 1900! and <code>tm_month</code> is 0-11</p>\n\n<p>Example:</p>\n\n<pre><code>$a = strptime('22-09-2008', '%d-%m-%Y');\n$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)\n</code></pre>\n"
},
{
"answer_id": 3032302,
"author": "Julijan Anđelić",
"author_id": 365679,
"author_profile": "https://Stackoverflow.com/users/365679",
"pm_score": 2,
"selected": false,
"text": "<p>Here is how I'd do it:</p>\n\n<pre><code>function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')\n{\n //returns an array containing day start and day end timestamps\n $old_timezone=date_timezone_get();\n date_default_timezone_set($timezone);\n $date=strptime($date,$format);\n $day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));\n $day_end=$day_start+(60*60*24);\n date_default_timezone_set($old_timezone);\n return array('day_start'=>$day_start, 'day_end'=>$day_end);\n}\n\n$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');\n$day_start=$timestamps['day_start'];\n</code></pre>\n\n<p>This way, you let the function know what date format you are using and even specify the timezone.</p>\n"
},
{
"answer_id": 3669713,
"author": "Victor Bojica",
"author_id": 442612,
"author_profile": "https://Stackoverflow.com/users/442612",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a very simple and effective solution using the <code>split</code> and <code>mtime</code> functions:</p>\n\n<pre><code>$date=\"30/07/2010 13:24\"; //Date example\nlist($day, $month, $year, $hour, $minute) = split('[/ :]', $date); \n\n//The variables should be arranged according to your date format and so the separators\n$timestamp = mktime($hour, $minute, 0, $month, $day, $year);\necho date(\"r\", $timestamp);\n</code></pre>\n\n<p>It worked like a charm for me.</p>\n"
},
{
"answer_id": 6028533,
"author": "Gordon",
"author_id": 208809,
"author_profile": "https://Stackoverflow.com/users/208809",
"pm_score": 7,
"selected": false,
"text": "<p>With <a href=\"http://php.net/manual/en/class.datetime.php\" rel=\"noreferrer\"><code>DateTime</code> API</a>:</p>\n\n<pre><code>$dateTime = new DateTime('2008-09-22'); \necho $dateTime->format('U'); \n\n// or \n\n$date = new DateTime('2008-09-22');\necho $date->getTimestamp();\n</code></pre>\n\n<p>The same with the procedural API:</p>\n\n<pre><code>$date = date_create('2008-09-22');\necho date_format($date, 'U');\n\n// or\n\n$date = date_create('2008-09-22');\necho date_timestamp_get($date);\n</code></pre>\n\n<p>If the above fails because you are using a <a href=\"http://www.php.net/manual/de/datetime.formats.php\" rel=\"noreferrer\">unsupported format</a>, you can use</p>\n\n<pre><code>$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');\necho $dateTime->format('U'); \n\n// or\n\n$date = date_parse_from_format('!d-m-Y', '22-09-2008');\necho date_format($date, 'U');\n</code></pre>\n\n<p>Note that if you do not set the <code>!</code>, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.</p>\n\n<p>Yet another alternative is to use the <a href=\"http://php.net/manual/en/class.intldateformatter.php\" rel=\"noreferrer\"><code>IntlDateFormatter</code></a> API:</p>\n\n<pre><code>$formatter = new IntlDateFormatter(\n 'en_US',\n IntlDateFormatter::FULL,\n IntlDateFormatter::FULL,\n 'GMT',\n IntlDateFormatter::GREGORIAN,\n 'dd-MM-yyyy'\n);\necho $formatter->parse('22-09-2008');\n</code></pre>\n\n<p>Unless you are working with localized date strings, the easier choice is likely DateTime.</p>\n"
},
{
"answer_id": 9239828,
"author": "Phil Jackson",
"author_id": 201469,
"author_profile": "https://Stackoverflow.com/users/201469",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = \"#^\\d{2}([^\\d]*)\\d{2}([^\\d]*)\\d{4}$#is\" ) {\n $return = false;\n $_timezone = date_default_timezone_get();\n date_default_timezone_set( $timezone );\n if( preg_match( $expression, $date, $matches ) )\n $return = date( \"Y-m-d \" . ( $slash_time ? '00:00:00' : \"h:i:s\" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date(\"h:i:s\") ) );\n date_default_timezone_set( $_timezone );\n return $return;\n}\n\n// expression may need changing in relation to timezone\necho date_to_stamp('19/03/1986', false) . '<br />';\necho date_to_stamp('19**03**1986', false) . '<br />';\necho date_to_stamp('19.03.1986') . '<br />';\necho date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';\necho date('Y-m-d h:i:s') . '<br />';\n\n//1986-03-19 02:37:30\n//1986-03-19 02:37:30\n//1986-03-19 00:00:00\n//1986-03-19 05:37:30\n//2012-02-12 02:37:30\n</code></pre>\n"
},
{
"answer_id": 10978523,
"author": "Victor",
"author_id": 230983,
"author_profile": "https://Stackoverflow.com/users/230983",
"pm_score": 3,
"selected": false,
"text": "<p>Given that the function <code>strptime()</code> does not work for Windows and <code>strtotime()</code> can return unexpected results, I recommend using <code>date_parse_from_format()</code>:</p>\n\n<pre><code>$date = date_parse_from_format('d-m-Y', '22-09-2008');\n$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);\n</code></pre>\n"
},
{
"answer_id": 13852410,
"author": "insign",
"author_id": 530197,
"author_profile": "https://Stackoverflow.com/users/530197",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php echo date('U') ?>\n</code></pre>\n\n<p>If you want, put it in a <a href=\"http://en.wikipedia.org/wiki/MySQL\" rel=\"nofollow\">MySQL</a> input type timestamp. The above works very well (only in PHP 5 or later):</p>\n\n<pre><code><?php $timestamp_for_mysql = date('c') ?>\n</code></pre>\n"
},
{
"answer_id": 13852501,
"author": "Ja͢ck",
"author_id": 1338292,
"author_profile": "https://Stackoverflow.com/users/1338292",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to know for sure whether a date gets parsed into something you expect, you can use <code>DateTime::createFromFormat()</code>:</p>\n\n<pre><code>$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');\nif ($d === false) {\n die(\"Woah, that date doesn't look right!\");\n}\necho $d->format('Y-m-d'), PHP_EOL;\n// prints 2008-09-22\n</code></pre>\n\n<p>It's obvious in this case, but e.g. <code>03-04-2008</code> could be 3rd of April or 4th of March depending on where you come from :)</p>\n"
},
{
"answer_id": 19320524,
"author": "Prof. Falken",
"author_id": 193892,
"author_profile": "https://Stackoverflow.com/users/193892",
"pm_score": 6,
"selected": false,
"text": "<p><br/></p>\n\n<p><em>This method works on <strong>both</strong> Windows and Unix <strong>and</strong> is <strong>time-zone</strong> aware, which is probably what you want if you work with <a href=\"https://unix4lyfe.org/time/\" rel=\"noreferrer\">dates</a>.</em></p>\n\n<p>If you don't care about timezone, or want to use the time zone your server uses:</p>\n\n<pre><code>$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n</code></pre>\n\n<p><strong>1222093324</strong> <sub>(This will differ depending on your server time zone...)</sub></p>\n\n<p><br/></p>\n\n<p>If you want to specify in which time zone, here EST. (Same as New York.)</p>\n\n<pre><code>$d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('EST')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n</code></pre>\n\n<p><strong>1222093305</strong></p>\n\n<p><br/></p>\n\n<p>Or if you want to use <a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time\" rel=\"noreferrer\">UTC</a>. (Same as \"<a href=\"https://en.wikipedia.org/wiki/Greenwich_Mean_Time\" rel=\"noreferrer\">GMT</a>\".)</p>\n\n<pre><code>$d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('UTC')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n</code></pre>\n\n<p><strong>1222093289</strong></p>\n\n<p><br/></p>\n\n<p>Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.</p>\n"
},
{
"answer_id": 19991236,
"author": "Michael Chambers",
"author_id": 2221694,
"author_profile": "https://Stackoverflow.com/users/2221694",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.date.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.date.php</a></p>\n"
},
{
"answer_id": 25053154,
"author": "Praveen Srinivasan",
"author_id": 3432786,
"author_profile": "https://Stackoverflow.com/users/3432786",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$time = '22-09-2008';\necho strtotime($time);\n</code></pre>\n"
},
{
"answer_id": 29480669,
"author": "klit67",
"author_id": 4756371,
"author_profile": "https://Stackoverflow.com/users/4756371",
"pm_score": 4,
"selected": false,
"text": "<p>Using strtotime() function you can easily convert date to timestamp </p>\n\n<pre><code><?php\n// set default timezone\ndate_default_timezone_set('America/Los_Angeles');\n\n//define date and time\n$date = date(\"d M Y H:i:s\");\n\n// output\necho strtotime($date);\n?> \n</code></pre>\n\n<p>More info: <a href=\"http://php.net/manual/en/function.strtotime.php\">http://php.net/manual/en/function.strtotime.php</a></p>\n\n<p>Online conversion tool: <a href=\"http://freeonlinetools24.com/\">http://freeonlinetools24.com/</a></p>\n"
},
{
"answer_id": 35671836,
"author": "ObiHill",
"author_id": 310139,
"author_profile": "https://Stackoverflow.com/users/310139",
"pm_score": -1,
"selected": false,
"text": "<p>If you're looking to convert a UTC datetime (<code>2016-02-14T12:24:48.321Z</code>) to timestamp, here's how you'd do it:</p>\n\n<pre><code>function UTCToTimestamp($utc_datetime_str)\n{\n preg_match_all('/(.+?)T(.+?)\\.(.*?)Z/i', $utc_datetime_str, $matches_arr);\n $datetime_str = $matches_arr[1][0].\" \".$matches_arr[2][0];\n\n return strtotime($datetime_str);\n}\n\n$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';\n$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);\n</code></pre>\n"
},
{
"answer_id": 37322349,
"author": "Akam",
"author_id": 3599237,
"author_profile": "https://Stackoverflow.com/users/3599237",
"pm_score": 0,
"selected": false,
"text": "<p>Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to <code>timestamp</code> using <code>strtotime</code>. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.</p>\n\n<p>Please see this example: <a href=\"https://3v4l.org/BRlmV\" rel=\"nofollow noreferrer\">https://3v4l.org/BRlmV</a></p>\n\n<pre><code>function getthistime($type, $modify = null) {\n $now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));\n if($modify) {\n $now->modify($modify);\n }\n if(!isset($type) || $type == 'datetime') {\n return $now->format('Y-m-d H:i:s');\n }\n if($type == 'time') {\n return $now->format('H:i:s');\n }\n if($type == 'timestamp') {\n return $now->getTimestamp();\n }\n}\nfunction timestampfromdate($date) {\n return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();\n}\n\necho getthistime('timestamp').\"--\".\n timestampfromdate(getthistime('datetime')).\"--\".\n strtotime(getthistime('datetime'));\n\n//getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)\n//getthistime('timestamp') == strtotime(getthistime('datetime')) (false)\n</code></pre>\n"
},
{
"answer_id": 48703270,
"author": "Gurpreet Singh",
"author_id": 8920307,
"author_profile": "https://Stackoverflow.com/users/8920307",
"pm_score": 3,
"selected": false,
"text": "<p>Use PHP function <code>strtotime()</code></p>\n\n<pre><code>echo strtotime('2019/06/06');\n</code></pre>\n\n<p><a href=\"https://www.w3schools.com/php/func_date_strtotime.asp\" rel=\"noreferrer\">date — Format a local time/date</a></p>\n"
},
{
"answer_id": 71606568,
"author": "Raju Ahmed",
"author_id": 12174834,
"author_profile": "https://Stackoverflow.com/users/12174834",
"pm_score": 0,
"selected": false,
"text": "<p>For PHP >=5.3, 7 & 8 the this may work-</p>\n<pre><code>$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format. \n //just need to keep in mind that date and format matches.\n\n$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp\n\n$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.\n</code></pre>\n"
},
{
"answer_id": 73337131,
"author": "J.C.",
"author_id": 7282094,
"author_profile": "https://Stackoverflow.com/users/7282094",
"pm_score": 0,
"selected": false,
"text": "<p>If you already have the date in that format, you only need to call the "<em><strong>strtotime</strong></em>" function in PHP.</p>\n<pre><code>$date = '22-09-2008';\n$timestamp = strtotime($date);\necho $timestamp; // 1222041600\n</code></pre>\n<p>Or in a single line:</p>\n<pre><code>echo strtotime('22-09-2008');\n</code></pre>\n<p>Short and simple.</p>\n"
},
{
"answer_id": 74626019,
"author": "Omar Faruk",
"author_id": 5778851,
"author_profile": "https://Stackoverflow.com/users/5778851",
"pm_score": -1,
"selected": false,
"text": "<p>I have used this format:\n$presentDateTime = strtotime(date('Y-m-d H:i:s'));</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205368/"
]
| How do I get timestamp from e.g. `22-09-2008`? | *This method works on **both** Windows and Unix **and** is **time-zone** aware, which is probably what you want if you work with [dates](https://unix4lyfe.org/time/).*
If you don't care about timezone, or want to use the time zone your server uses:
```
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
```
**1222093324** (This will differ depending on your server time zone...)
If you want to specify in which time zone, here EST. (Same as New York.)
```
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
```
**1222093305**
Or if you want to use [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time). (Same as "[GMT](https://en.wikipedia.org/wiki/Greenwich_Mean_Time)".)
```
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
```
**1222093289**
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format. |
113,860 | <p>How can I make sure that a certain OLEDB driver is installed when I start my application? I use ADO from Delphi and would like to display a descriptive error message if the driver is missing. The error that's returned from ADO isn't always that user-friendly.</p>
<p>There are probably a nice little function that returns all installed drivers but I haven't found it.</p>
| [
{
"answer_id": 114072,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 1,
"selected": false,
"text": "<p>Wouldn't the easiest way just be trying to make a connection at start-up and catching the error?</p>\n\n<p>I mean you might get a few different errors back depending on, for example, the user is online, but they're cases that you should be able to test for.</p>\n"
},
{
"answer_id": 115024,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the OLEDB objects in question are buried someplace in the registry, since OLEDB / ADO is a COM solution. My guess would be to see if you can find the GUID that your driver is installed as in the registry.</p>\n"
},
{
"answer_id": 154559,
"author": "Jeremy Mullin",
"author_id": 7893,
"author_profile": "https://Stackoverflow.com/users/7893",
"pm_score": 3,
"selected": true,
"text": "<p>Each provider has a GUID associated with its class. To find the guid, open regedit and search the registry for the provider name. For example, search for \"Microsoft Jet 4.0 OLE DB Provider\". When you find it, copy the key (the GUID value) and use that in a registry search in your application. </p>\n\n<pre><code>function OleDBExists : boolean;\nvar\n reg : TRegistry;\nbegin\n Result := false;\n\n // See if Advantage OLE DB Provider is on this PC\n reg := TRegistry.Create;\n try\n reg.RootKey := HKEY_LOCAL_MACHINE;\n Result := reg.OpenKeyReadOnly( '\\SOFTWARE\\Classes\\CLSID\\{C1637B2F-CA37-11D2-AE5C-00609791DC73}' );\n finally\n reg.Free;\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 165780,
"author": "CoolMagic",
"author_id": 22641,
"author_profile": "https://Stackoverflow.com/users/22641",
"pm_score": 2,
"selected": false,
"text": "<p>You can get a ADO provider name and check it in registry at path HKEY_CLASSES_ROOT\\[Provider_Name].</p>\n"
},
{
"answer_id": 3363273,
"author": "Adrian",
"author_id": 405760,
"author_profile": "https://Stackoverflow.com/users/405760",
"pm_score": 0,
"selected": false,
"text": "<pre><code>namespace Common {\n public class CLSIDHelper {\n\n [DllImport(\"ole32.dll\")]\n static extern int CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid);\n\n\n public static Guid RetrieveGUID(string Provider) {\n Guid CLSID = Guid.Empty;\n int Ok = CLSIDFromProgID(Provider, out CLSID);\n if (Ok == 0)\n return CLSID;\n return null;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12642324,
"author": "Rogerio Ueda",
"author_id": 1706541,
"author_profile": "https://Stackoverflow.com/users/1706541",
"pm_score": 4,
"selected": false,
"text": "<p>This is an old question but I had the same problem now and maybe this can help others.</p>\n\n<p>In Delphi 7 there is an procedure in ADODB that return a TStringList with the provider names.</p>\n\n<p>Usage example:</p>\n\n<pre><code>names := TStringList.Create;\nADODB.GetProviderNames(names);\n\nif names.IndexOf('SQLNCLI10')<>-1 then\n st := 'Provider=SQLNCLI10;'\nelse if names.IndexOf('SQLNCLI')<>-1 then\n st := 'Provider=SQLNCLI;'\nelse if names.IndexOf('SQLOLEDB')<>-1 then\n st := 'Provider=SQLOLEDB;';\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4101/"
]
| How can I make sure that a certain OLEDB driver is installed when I start my application? I use ADO from Delphi and would like to display a descriptive error message if the driver is missing. The error that's returned from ADO isn't always that user-friendly.
There are probably a nice little function that returns all installed drivers but I haven't found it. | Each provider has a GUID associated with its class. To find the guid, open regedit and search the registry for the provider name. For example, search for "Microsoft Jet 4.0 OLE DB Provider". When you find it, copy the key (the GUID value) and use that in a registry search in your application.
```
function OleDBExists : boolean;
var
reg : TRegistry;
begin
Result := false;
// See if Advantage OLE DB Provider is on this PC
reg := TRegistry.Create;
try
reg.RootKey := HKEY_LOCAL_MACHINE;
Result := reg.OpenKeyReadOnly( '\SOFTWARE\Classes\CLSID\{C1637B2F-CA37-11D2-AE5C-00609791DC73}' );
finally
reg.Free;
end;
end;
``` |
113,873 | <p>I want to extend the basic <code>ControlCollection</code> in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables.</p>
<p>So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality.</p>
<p>But when I run the example, it gives a <code>NullReferenceException</code>.</p>
<p>Here is the code:</p>
<pre><code> Shadows Sub add(ByVal text As String)
Dim LB As New Label
LB.AutoSize = True
LB.Text = text
MyBase.Add(LB) 'Here it gives the exception.
End Sub
</code></pre>
<p>I searched on Google, and someone said that the <code>CreateControlsInstance</code> method needs to be overriden. So I did that, but then it gives <code>InvalidOperationException</code> with an <code>innerException</code> message of <code>NullReferenceException</code>.</p>
<p>How do I to implement this?</p>
| [
{
"answer_id": 113891,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 3,
"selected": true,
"text": "<p>Why not inherit from <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx\" rel=\"nofollow noreferrer\">UserControl</a> to define a custom control that has properties like Text and Image?</p>\n"
},
{
"answer_id": 113913,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>You are probably better off using just a generic collection anyways. Bieng Control Collection doesnt really do anything special for it.</p>\n\n<pre><code>puclic class MyCollection : Collection<Control>\n</code></pre>\n"
},
{
"answer_id": 114338,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 0,
"selected": false,
"text": "<p>If you're inheriting from Control.ControlCollection then you need to provide a New method in your class. Your New method must call ControlCollection's constructor (MyBase.New) and pass it a valid parent control.</p>\n\n<p>If you haven't done this correctly, the NullReferenceException will be thrown in the Add method.</p>\n\n<p>This could also be causing the InvalidOperationException in your CreateControlsInstance method</p>\n\n<p>The following code calls the constructor incorrectly causing the Add method to throw a NullReferenceException...</p>\n\n<pre><code>Public Class MyControlCollection\n Inherits Control.ControlCollection\n\n Sub New()\n 'Bad - you need to pass a valid control instance\n 'to the constructor\n MyBase.New(Nothing)\n End Sub\n\n Public Shadows Sub Add(ByVal text As String)\n Dim LB As New Label()\n LB.AutoSize = True\n LB.Text = text\n 'The next line will throw a NullReferenceException\n MyBase.Add(LB)\n End Sub\nEnd Class\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20261/"
]
| I want to extend the basic `ControlCollection` in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables.
So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality.
But when I run the example, it gives a `NullReferenceException`.
Here is the code:
```
Shadows Sub add(ByVal text As String)
Dim LB As New Label
LB.AutoSize = True
LB.Text = text
MyBase.Add(LB) 'Here it gives the exception.
End Sub
```
I searched on Google, and someone said that the `CreateControlsInstance` method needs to be overriden. So I did that, but then it gives `InvalidOperationException` with an `innerException` message of `NullReferenceException`.
How do I to implement this? | Why not inherit from [UserControl](http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx) to define a custom control that has properties like Text and Image? |
113,886 | <p>I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files. </p>
| [
{
"answer_id": 113892,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>If you can use <code>scp</code> instead of <code>ftp</code>, the <code>-r</code> option will do this for you. I would check to see whether you can use a more modern file transfer mechanism than FTP.</p>\n"
},
{
"answer_id": 113900,
"author": "Thibaut Barrère",
"author_id": 20302,
"author_profile": "https://Stackoverflow.com/users/20302",
"pm_score": 10,
"selected": true,
"text": "<p>You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:</p>\n<pre><code>wget -r ftp://user:[email protected]/\n</code></pre>\n<p>You can also use <code>-m</code> which is suitable for mirroring. It is currently equivalent to <code>-r -N -l inf</code>.</p>\n<p>If you've some special characters in the credential details, you can specify the <code>--user</code> and <code>--password</code> arguments to get it to work. Example with custom login with specific characters:</p>\n<pre><code>wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/\n</code></pre>\n<p>As pointed out by @asmaier, watch out that even if <code>-r</code> is for recursion, it has a default max level of 5:</p>\n<blockquote>\n<pre><code>-r\n--recursive\n Turn on recursive retrieving.\n\n-l depth\n--level=depth\n Specify recursion maximum depth level depth. The default maximum depth is 5.\n</code></pre>\n</blockquote>\n<p>If you don't want to miss out subdirs, better use the mirroring option, <code>-m</code>:</p>\n<blockquote>\n<pre><code>-m\n--mirror\n Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite\n recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf\n --no-remove-listing.\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 113902,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "<pre><code>ncftp -u <user> -p <pass> <server>\nncftp> mget directory\n</code></pre>\n"
},
{
"answer_id": 113904,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>If you can, I strongly suggest you <code>tar</code> and <code>bzip</code> (or <code>gzip</code>, whatever floats your boat) the directory on the remote machine—for a directory of any significant size, the bandwidth savings will probably be worth the time to zip/unzip.</p>\n"
},
{
"answer_id": 113910,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 4,
"selected": false,
"text": "<p>Use WGet instead. It supports HTTP and FTP protocols.</p>\n\n<pre><code>wget -r ftp://mydomain.com/mystuff\n</code></pre>\n\n<p>Good Luck!</p>\n\n<p>reference: <a href=\"http://linux.about.com/od/commands/l/blcmdl1_wget.htm\" rel=\"noreferrer\">http://linux.about.com/od/commands/l/blcmdl1_wget.htm</a></p>\n"
},
{
"answer_id": 113911,
"author": "Cypher",
"author_id": 20311,
"author_profile": "https://Stackoverflow.com/users/20311",
"pm_score": 3,
"selected": false,
"text": "<p>There is 'ncftp' which is available for installation in linux. This works on the FTP protocol and can be used to download files and folders recursively. works on linux. Has been used and is working fine for recursive folder/file transfer.</p>\n\n<p>Check this link... <a href=\"http://www.ncftp.com/\" rel=\"noreferrer\">http://www.ncftp.com/</a></p>\n"
},
{
"answer_id": 113920,
"author": "Jazz",
"author_id": 14443,
"author_profile": "https://Stackoverflow.com/users/14443",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to stick to command line FTP, you should try NcFTP. Then you can use get -R to recursively get a folder. You will also get completion.</p>\n"
},
{
"answer_id": 2791934,
"author": "Phillip",
"author_id": 335864,
"author_profile": "https://Stackoverflow.com/users/335864",
"pm_score": 2,
"selected": false,
"text": "<p><code>wget -r ftp://url</code></p>\n\n<p>Work perfectly for Redhat and Ubuntu</p>\n"
},
{
"answer_id": 5297285,
"author": "Rohit",
"author_id": 658580,
"author_profile": "https://Stackoverflow.com/users/658580",
"pm_score": -1,
"selected": false,
"text": "<p>toggle the prompt by PROMPT command.</p>\n\n<p>Usage:</p>\n\n<pre><code>ftp>cd /to/directory \nftp>prompt \nftp>mget *\n</code></pre>\n"
},
{
"answer_id": 5567776,
"author": "Ludovic Kuty",
"author_id": 452614,
"author_profile": "https://Stackoverflow.com/users/452614",
"pm_score": 8,
"selected": false,
"text": "<p>Just to complement the <a href=\"https://stackoverflow.com/a/113900/4298200\">answer given by Thibaut Barrère</a>.</p>\n<p>I used</p>\n<pre><code>wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory\n</code></pre>\n<p>Note the double slash after the server name. If you don't put an extra slash the path is relative to the home directory of user.</p>\n<ul>\n<li><code>-nH</code> avoids the creation of a directory named after the server name</li>\n<li><code>-nc</code> avoids creating a new file if it already exists on the destination (it is just skipped)</li>\n<li><code>--cut-dirs=5 </code> allows to take the content of /absolute/path/to/directory and to put it in the directory where you launch wget. The number 5 is used to filter out the 5 components of the path. The double slash means an extra component.</li>\n</ul>\n"
},
{
"answer_id": 13780413,
"author": "Dilawar",
"author_id": 1805129,
"author_profile": "https://Stackoverflow.com/users/1805129",
"pm_score": 5,
"selected": false,
"text": "<p>If <code>lftp</code> is installed on your machine, use <code>mirror dir</code>. And you are done. See the comment by Ciro below if you want to recursively download a directory. </p>\n"
},
{
"answer_id": 20035528,
"author": "Tilo",
"author_id": 677684,
"author_profile": "https://Stackoverflow.com/users/677684",
"pm_score": 2,
"selected": false,
"text": "<p>You should not use <code>ftp</code>. Like <code>telnet</code> it is not using secure protocols, and passwords are transmitted in clear text. This makes it very easy for third parties to capture your username and password.</p>\n<p>To copy remote directories remotely, these options are better:</p>\n<ul>\n<li><p><code>rsync</code> is the best-suited tool if you can login via <code>ssh</code>, because it copies only the differences, and can easily restart in the middle in case the connection breaks.</p>\n</li>\n<li><p><code>ssh -r</code> is the second-best option to recursively copy directory structures.</p>\n</li>\n</ul>\n<p>To fetch files recursively, you can use a script like this:\n<a href=\"https://gist.github.com/flibbertigibbet/8165881\" rel=\"nofollow noreferrer\">https://gist.github.com/flibbertigibbet/8165881</a></p>\n<p>See:</p>\n<ul>\n<li><p><a href=\"http://linux.die.net/man/1/rsync\" rel=\"nofollow noreferrer\">rsync</a> man page</p>\n</li>\n<li><p><a href=\"http://linux.die.net/man/1/ssh\" rel=\"nofollow noreferrer\">ssh</a> man page</p>\n</li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11708/"
]
| I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files. | You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:
```
wget -r ftp://user:[email protected]/
```
You can also use `-m` which is suitable for mirroring. It is currently equivalent to `-r -N -l inf`.
If you've some special characters in the credential details, you can specify the `--user` and `--password` arguments to get it to work. Example with custom login with specific characters:
```
wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/
```
As pointed out by @asmaier, watch out that even if `-r` is for recursion, it has a default max level of 5:
>
>
> ```
> -r
> --recursive
> Turn on recursive retrieving.
>
> -l depth
> --level=depth
> Specify recursion maximum depth level depth. The default maximum depth is 5.
>
> ```
>
>
If you don't want to miss out subdirs, better use the mirroring option, `-m`:
>
>
> ```
> -m
> --mirror
> Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite
> recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf
> --no-remove-listing.
>
> ```
>
> |
113,897 | <p>I have a quick question. How do I get the image generated by a JComponent.paint or paintComponent?</p>
<p>I have a JComponent which I use as a 'workspace' and where I have overwritten the paintComponent method to my own. The thing is that my workspace JComponent also has children which has their own paintComponent methods.</p>
<p>So when Swing renders my workspace component, it renders the workspace graphics and then its childrens'.</p>
<p>However, I want to get the image my workspace component generates (which includes the workspace graphics and the children's graphics).</p>
<p>How do I do that?</p>
<p>I tried to call the paintComponent/paint-method myself by using my own Graphics, but i just returned a black image. Here is what i tried;</p>
<pre><code>public void paintComponent(Graphics g) {
if (bufferedImage != null) {
g.drawImage(bufferedImage, 0, 0, this);
}
else {
g.setColor(Color.WHITE);
g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
}
}
public BufferedImage getImage() {
BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = hello.getGraphics();
paintComponent( g );
return hello;
}
</code></pre>
<p>Any thoughts or comments are welcome! :)</p>
| [
{
"answer_id": 113908,
"author": "Martijn",
"author_id": 17439,
"author_profile": "https://Stackoverflow.com/users/17439",
"pm_score": 2,
"selected": false,
"text": "<p>If you call getImage too early, your component will not have been displayed yet and will still have a 0 width and height. Have you made sure you're calling it at a sufficient late time? Try printing the component's size to stdout and see what its dimensions are.</p>\n"
},
{
"answer_id": 114026,
"author": "user20298",
"author_id": 20298,
"author_profile": "https://Stackoverflow.com/users/20298",
"pm_score": 1,
"selected": false,
"text": "<p>Seems like the problem was due to how the BufferedImage was created. When using:</p>\n\n<pre><code>BufferedImage hello = bufferedImage.getSubimage(0,0, getWidth(), getHeight());\n</code></pre>\n\n<p>Instead it worked. I also had to change switch from paintComponent to paint to render the children.</p>\n\n<p>Problem solved, but if anyone knows. Why did my:</p>\n\n<pre><code> BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);\n</code></pre>\n\n<p>Always render a black image? Offtopic, but could be interesting to know :)</p>\n"
},
{
"answer_id": 115019,
"author": "jmagica",
"author_id": 20412,
"author_profile": "https://Stackoverflow.com/users/20412",
"pm_score": 0,
"selected": false,
"text": "<p>Do not call paintComponent() or paint() from the outside. Instead, let your image be created within those (overwritten) methods. Then you can be sure that your image will actually contain the painted content of the component. </p>\n\n<p>Here is an example application. The ImagePanel will actually grab the graphics contents of the component every time it is painted, which might be a bit wasteful, so you may want to adjust the frequency with which this is done.</p>\n\n<pre><code>public class SomeApp extends JFrame {\n\n private static class ImagePanel extends JPanel {\n private BufferedImage currentImage;\n public BufferedImage getCurrentImage() {\n return currentImage;\n }\n @Override\n public void paint(Graphics g) {\n Rectangle tempBounds = g.getClipBounds();\n currentImage = new BufferedImage(tempBounds.width, tempBounds.height, BufferedImage.TYPE_INT_ARGB);\n super.paint(g);\n super.paint(currentImage.getGraphics());\n }\n }\n\n public SomeApp() {\n setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n setSize(800,600);\n int matrixSize = 4;\n setLayout(new BorderLayout());\n add(new JLabel(\"Wonderful Application\"), BorderLayout.NORTH);\n final ImagePanel imgPanel = new ImagePanel();\n imgPanel.setLayout(new GridLayout(matrixSize,matrixSize));\n for(int i=1; i<=matrixSize*matrixSize; i++) {\n imgPanel.add(new JButton(\"A Button\" + i));\n }\n add(imgPanel, BorderLayout.CENTER);\n final JPanel buttonPanel = new JPanel();\n buttonPanel.add(new JButton(new AbstractAction(\"get image\") {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n JOptionPane.showMessageDialog(SomeApp.this, new ImageIcon(imgPanel.getCurrentImage()));\n }\n\n }));\n add(buttonPanel, BorderLayout.SOUTH);\n }\n\n public static void main(String[] args) {\n System.setProperty(\"swing.defaultlaf\", UIManager.getSystemLookAndFeelClassName());\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n new SomeApp().setVisible(true);\n }\n });\n }\n}\n</code></pre>\n\n<p>Like Martijn said, your image was probably black because the component wasn't even painted/displayed yet. You could add a ComponentListener to be notified when it is displayed. Your \"solution\" with getSubimage has nothing to do with the actual problem. I recommend you remove it.</p>\n"
},
{
"answer_id": 3627900,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 0,
"selected": false,
"text": "<p>Changing the new BufferedImage to TYPE_INT_RGB solves this for me. I can't give an explanation though - just a Swing mystery.</p>\n\n<pre><code>public BufferedImage getImage() {\n\n BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);\n Graphics g = hello.getGraphics();\n paintComponent( g );\n\n return hello;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20298/"
]
| I have a quick question. How do I get the image generated by a JComponent.paint or paintComponent?
I have a JComponent which I use as a 'workspace' and where I have overwritten the paintComponent method to my own. The thing is that my workspace JComponent also has children which has their own paintComponent methods.
So when Swing renders my workspace component, it renders the workspace graphics and then its childrens'.
However, I want to get the image my workspace component generates (which includes the workspace graphics and the children's graphics).
How do I do that?
I tried to call the paintComponent/paint-method myself by using my own Graphics, but i just returned a black image. Here is what i tried;
```
public void paintComponent(Graphics g) {
if (bufferedImage != null) {
g.drawImage(bufferedImage, 0, 0, this);
}
else {
g.setColor(Color.WHITE);
g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
}
}
public BufferedImage getImage() {
BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = hello.getGraphics();
paintComponent( g );
return hello;
}
```
Any thoughts or comments are welcome! :) | If you call getImage too early, your component will not have been displayed yet and will still have a 0 width and height. Have you made sure you're calling it at a sufficient late time? Try printing the component's size to stdout and see what its dimensions are. |
113,899 | <p>I want to create a c# application with multiple windows that are all transparent with some text on.</p>
<p>The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?</p>
| [
{
"answer_id": 113933,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": true,
"text": "<p>Just making the window transparent is very straight forward:</p>\n\n<pre><code>this.BackColor = Color.Fuchsia;\nthis.TransparencyKey = Color.Fuchsia;\n</code></pre>\n\n<p>You can do something like this to make it so you can still interact with the desktop or anything else under your window:</p>\n\n<pre><code>public const int WM_NCHITTEST = 0x84;\npublic const int HTTRANSPARENT = -1;\n\nprotected override void WndProc(ref Message message)\n{\n if ( message.Msg == (int)WM_NCHITTEST )\n {\n message.Result = (IntPtr)HTTRANSPARENT;\n }\n else\n {\n base.WndProc( ref message );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 114218,
"author": "Andy",
"author_id": 3585,
"author_profile": "https://Stackoverflow.com/users/3585",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the tips Jeff. Its still not quite what I'm after. I would effectively like the window to appear as if it was part of the desktop so icons could sit on top of my form.</p>\n\n<p>Maybe there is a different way to do it. Can I actually draw text and graphics directly on to the desktop?</p>\n"
},
{
"answer_id": 539278,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The method described above by Jeff Hillman is effective in making the window transparent, which should give you the ability to have it appear as though it's part of the desktop (which you mentioned is your goal.</p>\n\n<p>One issue you may run into, which I have just recently run into as well, is drawing to the window with any anti-aliasing flags set. Specifically, using DrawText, any text that's rendered with anti-aliasing flags set is rendered as though the background were NOT transparent. The end result is that you get text with a slight off-color border around it. I'm sure this would hold true for anything else as well, though I haven't tried.</p>\n\n<p>Are there any thoughts on how to resolve that?</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3585/"
]
| I want to create a c# application with multiple windows that are all transparent with some text on.
The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible? | Just making the window transparent is very straight forward:
```
this.BackColor = Color.Fuchsia;
this.TransparencyKey = Color.Fuchsia;
```
You can do something like this to make it so you can still interact with the desktop or anything else under your window:
```
public const int WM_NCHITTEST = 0x84;
public const int HTTRANSPARENT = -1;
protected override void WndProc(ref Message message)
{
if ( message.Msg == (int)WM_NCHITTEST )
{
message.Result = (IntPtr)HTTRANSPARENT;
}
else
{
base.WndProc( ref message );
}
}
``` |
113,901 | <p>In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.</p>
<p>How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?</p>
| [
{
"answer_id": 113909,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' \n\nSELECT testColumn FROM testTable\n WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE' \n\nSELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' \n</code></pre>\n\n<p>Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course)</p>\n"
},
{
"answer_id": 113912,
"author": "Andrew Myhre",
"author_id": 5152,
"author_profile": "https://Stackoverflow.com/users/5152",
"pm_score": 3,
"selected": false,
"text": "<p>Determine whether the default collation is case-sensitive like this:</p>\n\n<p><code>select charindex('RESULT', 'If the result is 0 you are in a case-sensitive collation mode')</code></p>\n\n<p>A result of 0 indicates you are in a case-sensitive collation mode, 8 indicates it is case-insensitive.</p>\n\n<p>If the collation is case-insensitive, you need to explicitly declare the collation mode you want to use when performing a search/replace.</p>\n\n<p>Here's how to construct an UPDATE statement to perform a case-sensitive search/replace by specifying the collation mode to use:</p>\n\n<pre><code>update ContentTable\nset ContentValue = replace(ContentValue COLLATE Latin1_General_BIN, 'THECONTENT', 'TheContent')\nfrom StringResource\nwhere charindex('THECONTENT', ContentValue COLLATE Latin1_General_BIN) > 0\n</code></pre>\n\n<p>This will match and replace <code>'THECONTENT'</code>, but not <code>'TheContent'</code> or <code>'thecontent'</code>.</p>\n"
},
{
"answer_id": 113980,
"author": "user20323",
"author_id": 20323,
"author_profile": "https://Stackoverflow.com/users/20323",
"pm_score": 0,
"selected": false,
"text": "<p>First of all check this:\n<a href=\"http://technet.microsoft.com/en-us/library/ms180175(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/ms180175(SQL.90).aspx</a></p>\n\n<p>You will see that CI specifies case-insensitive and CS specifies case-sensitive.</p>\n"
},
{
"answer_id": 114053,
"author": "user20323",
"author_id": 20323,
"author_profile": "https://Stackoverflow.com/users/20323",
"pm_score": 0,
"selected": false,
"text": "<p>Also, this might be usefull.\nselect * from fn_helpcollations() - this gets all the collations your server supports.\nselect * from sys.databases - here there is a column that specifies what collation has every database on your server.</p>\n"
},
{
"answer_id": 232203,
"author": "nathan_jr",
"author_id": 3769,
"author_profile": "https://Stackoverflow.com/users/3769",
"pm_score": 0,
"selected": false,
"text": "<p>You can either specify the collation every time you query the table or you can apply the collation to the column(s) permanently by altering the table.</p>\n\n<p>If you do choose to do the query method its beneficial to include the case insensitive search arguments as well. You will see that SQL will choose a more efficient exec plan if you include them. For example:</p>\n\n<pre><code>SELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' \n and testColumn = 'eXaMpLe'\n</code></pre>\n"
},
{
"answer_id": 18743898,
"author": "Matas Vaitkevicius",
"author_id": 827051,
"author_profile": "https://Stackoverflow.com/users/827051",
"pm_score": 1,
"selected": false,
"text": "<p>Can be done in multiple statements.\nThis <strong>will not</strong> work if you have long strings that contain both capitalized an lowercase words you intend to replace.\nYou might also need to use different collation this is accent and case sensitive.</p>\n\n<pre><code>UPDATE T SET [String] = ReplacedString\nFROM [dbo].[TranslationText] T, \n (SELECT [LanguageCode]\n ,[StringNo]\n ,REPLACE([String], 'Favourite','Favorite') ReplacedString\n FROM [dbo].[TranslationText]\n WHERE \n [String] COLLATE Latin1_General_CS_AS like '%Favourite%'\n AND [LanguageCode] = 'en-us') US_STRINGS\nWHERE \nT.[LanguageCode] = US_STRINGS.[LanguageCode] \nAND T.[StringNo] = US_STRINGS.[StringNo]\n\nUPDATE T SET [String] = ReplacedString\nFROM [dbo].[TranslationText] T, \n (SELECT [LanguageCode]\n ,[StringNo]\n , REPLACE([String], 'favourite','favorite') ReplacedString \n FROM [dbo].[TranslationText]\n WHERE \n [String] COLLATE Latin1_General_CS_AS like '%favourite%'\n AND [LanguageCode] = 'en-us') US_STRINGS\nWHERE \nT.[LanguageCode] = US_STRINGS.[LanguageCode] \nAND T.[StringNo] = US_STRINGS.[StringNo]\n</code></pre>\n"
},
{
"answer_id": 42433809,
"author": "Sean",
"author_id": 214980,
"author_profile": "https://Stackoverflow.com/users/214980",
"pm_score": 3,
"selected": false,
"text": "<p>If you have <strong>different cases</strong> of the same word <strong>in the same field</strong>, and only want to <strong>replace specific cases</strong>, then you can use collation in your <code>REPLACE</code> function:</p>\n\n<pre><code>UPDATE tableName\nSET fieldName = \n REPLACE(\n REPLACE(\n fieldName COLLATE Latin1_General_CS_AS,\n 'camelCase' COLLATE Latin1_General_CS_AS,\n 'changedWord'\n ),\n 'CamelCase' COLLATE Latin1_General_CS_AS,\n 'ChangedWord'\n )\n</code></pre>\n\n<p>This will result in:</p>\n\n<pre><code>This is camelCase 1 and this is CamelCase 2\n</code></pre>\n\n<p>becoming:</p>\n\n<pre><code>This is changedWord 1 and this is ChangedWord 2\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152/"
]
| In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.
How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace? | ```
SELECT testColumn FROM testTable
WHERE testColumn COLLATE Latin1_General_CS_AS = 'example'
SELECT testColumn FROM testTable
WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE'
SELECT testColumn FROM testTable
WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe'
```
Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course) |
113,915 | <p>I'm getting a random unreproducible Error when initializing a JSplitPane in with JDK 1.5.0_08. Note that this does not occur every time, but about 80% of the time:</p>
<pre><code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.put(TreeMap.java:465)
at java.util.TreeSet.add(TreeSet.java:210)
at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364)
at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300)
at javax.swing.JComponent.setUI(JComponent.java:652)
at javax.swing.JSplitPane.setUI(JSplitPane.java:350)
at javax.swing.JSplitPane.updateUI(JSplitPane.java:378)
at javax.swing.JSplitPane.<init>(JSplitPane.java:332)
at javax.swing.JSplitPane.<init>(JSplitPane.java:287)
...
</code></pre>
<p>Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files.</p>
<p><strong>Edit #1</strong> See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148</a> - seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page.</p>
| [
{
"answer_id": 113924,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 3,
"selected": true,
"text": "<p>After doing some Googling on bugs.sun.com, this looks like this might be a JDK bug that was only fixed in JDK 6.</p>\n\n<p>See <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148\" rel=\"nofollow noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148</a></p>\n"
},
{
"answer_id": 22144026,
"author": "user1909533",
"author_id": 1909533,
"author_profile": "https://Stackoverflow.com/users/1909533",
"pm_score": 1,
"selected": false,
"text": "<p>Same exception had got thrown when i had upgraded java verion and db visualizer dint support jre7. and since \nSupport for Java 7 was introduced in DbVisualizer 8.0 for Windows and Linux/UNIX.</p>\n\n<p>Support for Java 7 on Mac OS X was introduced in DbVisualizer 9.1.</p>\n\n<p>So Solution that worked for me : \n<strong>Windows/Unix/Linux:</strong>\n In the DbVisualizer installation directory there is an .install4j directory,\n In this directory create a file named pref_jre.cfg if it doesn't already exist,\n Open the file in a text editor,\n Add the complete path to the root directory for the Java installation you want to use. \n Example: C:\\Program Files\\Java\\jre7</p>\n"
},
{
"answer_id": 34129765,
"author": "Shree",
"author_id": 5649198,
"author_profile": "https://Stackoverflow.com/users/5649198",
"pm_score": -1,
"selected": false,
"text": "<pre><code>java.lang.ClassCastException: javax.swing.KeyStroke cannot be cast to java.lang.Comparable....\n</code></pre>\n\n<p>If you are getting above error after installing java 7 in dbviz\nthen add Environment variabbles like: \n'DBVIS_JAVA_HOME' as a 'Variable Name' and java path like \nfor ex. \"C:\\SWDTOOLS\\IBM\\RAD85\\runtimes\\base_v7\\java\"</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
]
| I'm getting a random unreproducible Error when initializing a JSplitPane in with JDK 1.5.0\_08. Note that this does not occur every time, but about 80% of the time:
```
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.put(TreeMap.java:465)
at java.util.TreeSet.add(TreeSet.java:210)
at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364)
at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300)
at javax.swing.JComponent.setUI(JComponent.java:652)
at javax.swing.JSplitPane.setUI(JSplitPane.java:350)
at javax.swing.JSplitPane.updateUI(JSplitPane.java:378)
at javax.swing.JSplitPane.<init>(JSplitPane.java:332)
at javax.swing.JSplitPane.<init>(JSplitPane.java:287)
...
```
Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files.
**Edit #1** See <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148> - seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page. | After doing some Googling on bugs.sun.com, this looks like this might be a JDK bug that was only fixed in JDK 6.
See <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148> |
113,916 | <p>If I need to choose a collation mode to work with, how do I know what collations are available?</p>
| [
{
"answer_id": 113917,
"author": "Andrew Myhre",
"author_id": 5152,
"author_profile": "https://Stackoverflow.com/users/5152",
"pm_score": 3,
"selected": false,
"text": "<p>Use this query to list the available collation modes:</p>\n\n<p>SELECT *\nFROM fn_helpcollations()</p>\n"
},
{
"answer_id": 118419,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": true,
"text": "<pre><code>select distinct COLLATION_NAME from INFORMATION_SCHEMA.COLUMNS order by 1\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152/"
]
| If I need to choose a collation mode to work with, how do I know what collations are available? | ```
select distinct COLLATION_NAME from INFORMATION_SCHEMA.COLUMNS order by 1
``` |
113,928 | <p>When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how. </p>
| [
{
"answer_id": 113948,
"author": "Germstorm",
"author_id": 18631,
"author_profile": "https://Stackoverflow.com/users/18631",
"pm_score": 9,
"selected": true,
"text": "<p>After you commit your object into the db the object receives a value in its ID field.</p>\n\n<p>So:</p>\n\n<pre><code>myObject.Field1 = \"value\";\n\n// Db is the datacontext\ndb.MyObjects.InsertOnSubmit(myObject);\ndb.SubmitChanges();\n\n// You can retrieve the id from the object\nint id = myObject.ID;\n</code></pre>\n"
},
{
"answer_id": 113949,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 4,
"selected": false,
"text": "<p>When inserting the generated ID is saved into the instance of the object being saved (see below):</p>\n\n<pre><code>protected void btnInsertProductCategory_Click(object sender, EventArgs e)\n{\n ProductCategory productCategory = new ProductCategory();\n productCategory.Name = “Sample Category”;\n productCategory.ModifiedDate = DateTime.Now;\n productCategory.rowguid = Guid.NewGuid();\n int id = InsertProductCategory(productCategory);\n lblResult.Text = id.ToString();\n}\n\n//Insert a new product category and return the generated ID (identity value)\nprivate int InsertProductCategory(ProductCategory productCategory)\n{\n ctx.ProductCategories.InsertOnSubmit(productCategory);\n ctx.SubmitChanges();\n return productCategory.ProductCategoryID;\n}\n</code></pre>\n\n<p>reference: <a href=\"http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4\" rel=\"noreferrer\">http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4</a></p>\n"
},
{
"answer_id": 54693243,
"author": "Khalid Salameh",
"author_id": 6492784,
"author_profile": "https://Stackoverflow.com/users/6492784",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>MyContext Context = new MyContext(); \nContext.YourEntity.Add(obj);\nContext.SaveChanges();\nint ID = obj._ID;\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14777/"
]
| When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how. | After you commit your object into the db the object receives a value in its ID field.
So:
```
myObject.Field1 = "value";
// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();
// You can retrieve the id from the object
int id = myObject.ID;
``` |
113,951 | <p>I am creating an appcation on Vista,which include a service and a Console application .Both running in same user account</p>
<p>In service i am creating an event and waits for that event.In console application i am opening the same event (problem starts here) and calling <em>SetEvent</em> function. I can not open the event (getting error 5,Access is denied) in the console application.I searched in the net and saw something about integrity level (I am not sure that the problem is related to integrity level).Its telling that service and applicaation got differnt integrity levels.</p>
<p>here is the part of the code,where IPC occures</p>
<p><strong>service</strong> </p>
<pre><code>DWORD
WINAPI IpcThread(LPVOID lpParam)
{
HANDLE ghRequestEvent = NULL ;
ghRequestEvent = CreateEvent(NULL, FALSE,
FALSE, "Global\\Event1") ; //creating the event
if(NULL == ghRequestEvent)
{
//error
}
while(1)
{
WaitForSingleObject(ghRequestEvent, INFINITE) //waiting for the event
//here some action related to event
}
}
</code></pre>
<p><strong>Console Application</strong></p>
<p>Here in application ,opening the event and seting the event</p>
<pre><code>unsigned int
event_notification()
{
HANDLE ghRequestEvent = NULL ;
ghRequestEvent = OpenEvent(SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, "Global\\Event1") ;
if(NULL == ghRequestEvent)
{
//error
}
SetEvent(ghRequestEvent) ;
}
</code></pre>
<p>I am running both application (serivce and console application) with administrative privilege (i logged in as Administraor and running the console application by right clicking and using the option "run as administrator") .</p>
<p>The error i am getting in console application (where i am opening the event) is error no 5(Access is denied. ) .</p>
<p>So it will be very helpfull if you tell how to do the IPC between a service and an application in Vista</p>
<p>Thanks in advance</p>
<p>Navaneeth</p>
| [
{
"answer_id": 114009,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>Are the service and the application running as the same user with different integrity levels, or are they running as different users?</p>\n\n<p>If it is the former, then this article from MSDN <a href=\"http://msdn.microsoft.com/en-us/library/bb250462.aspx\" rel=\"nofollow noreferrer\">which talks about integrity levels might help</a>. They have some sample code for lowering the integrity level of a file. I'm not sure that this could be relevant for an event though.</p>\n\n<pre><code>#include <sddl.h>\n#include <AccCtrl.h>\n#include <Aclapi.h>\n\nvoid SetLowLabelToFile()\n{\n // The LABEL_SECURITY_INFORMATION SDDL SACL to be set for low integrity \n #define LOW_INTEGRITY_SDDL_SACL_W L\"S:(ML;;NW;;;LW)\"\n DWORD dwErr = ERROR_SUCCESS;\n PSECURITY_DESCRIPTOR pSD = NULL; \n\n PACL pSacl = NULL; // not allocated\n BOOL fSaclPresent = FALSE;\n BOOL fSaclDefaulted = FALSE;\n LPCWSTR pwszFileName = L\"Sample.txt\";\n\n if (ConvertStringSecurityDescriptorToSecurityDescriptorW(\n LOW_INTEGRITY_SDDL_SACL_W, SDDL_REVISION_1, &pSD;, NULL)) \n {\n if (GetSecurityDescriptorSacl(pSD, &fSaclPresent;, &pSacl;, \n &fSaclDefaulted;))\n {\n // Note that psidOwner, psidGroup, and pDacl are \n // all NULL and set the new LABEL_SECURITY_INFORMATION\n dwErr = SetNamedSecurityInfoW((LPWSTR) pwszFileName, \n SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION, \n NULL, NULL, NULL, pSacl);\n }\n LocalFree(pSD);\n }\n}\n</code></pre>\n\n<p>If it is the latter you might look at this link which <a href=\"http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2007-04/msg00086.html\" rel=\"nofollow noreferrer\">suggests creating a NULL ACL</a> and associating it with the object (in the example it is a named pipe, but the approach is similar for an event I'm sure:</p>\n\n<pre><code>BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];\nSECURITY_ATTRIBUTES sa;\n\nsa.nLength = sizeof(sa);\nsa.bInheritHandle = TRUE;\nsa.lpSecurityDescriptor = &sd;\n\nInitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);\nSetSecurityDescriptorDacl(&sd, TRUE, (PACL) 0, FALSE);\n\nCreateNamedPipe(..., &sa);\n</code></pre>\n"
},
{
"answer_id": 114091,
"author": "Ignas Limanauskas",
"author_id": 2877,
"author_profile": "https://Stackoverflow.com/users/2877",
"pm_score": 0,
"selected": false,
"text": "<p>First, it is important to conceptually understand what is required. Once that is understood we can take it from there.</p>\n\n<p>On the server, it should look something similar to:</p>\n\n<pre><code>{\n HANDLE hEvent;\n hEvent = CreateEvent(null, true, false, TEXT(\"MyEvent\"));\n while (1)\n {\n WaitForSingleObject (hEvent);\n ResetEvent (hEvent);\n /* Do something -- start */\n /* Processing 1 */\n /* Processing 2 */\n /* Do something -- end */\n }\n}\n</code></pre>\n\n<p>On the client:</p>\n\n<pre><code>{\n HANDLE hEvent;\n hEvent = OpenEvent(0, false, TEXT(\"MyEvent\"));\n SetEvent (hEvent);\n}\n</code></pre>\n\n<p>Several points to note:</p>\n\n<ul>\n<li>ResetEvent should be as early as possible, right after WaitForSingleObject or WaitForMultipleObjects. If multiple clients are using the server and first client's processing takes time, second client might set the event and it might not be caught while server processes the first request.</li>\n<li>You should implement some mechanism that would notify the client that server finished processing.</li>\n<li>Before doing any win32 service mumbo-jumbo, have server running as simple application. This will eliminate any security-related problems.</li>\n</ul>\n"
},
{
"answer_id": 114122,
"author": "Jere.Jones",
"author_id": 19476,
"author_profile": "https://Stackoverflow.com/users/19476",
"pm_score": 1,
"selected": false,
"text": "<p>I notice that you are creating the object in the \"Global\" namespace but are trying to open it in a local namespace. Does adding \"Global\\\" to the name in the open call help?</p>\n\n<p>Also, in the //error area, is there anything there to let you know it wasn't created?</p>\n"
},
{
"answer_id": 121375,
"author": "Jere.Jones",
"author_id": 19476,
"author_profile": "https://Stackoverflow.com/users/19476",
"pm_score": 0,
"selected": false,
"text": "<p>@Navaneeth:</p>\n\n<p>Excellent feedback. Since your error is Access Denied, then I would change the desired access from EVENT_ALL_ACCESS, which you really don't need, to </p>\n\n<pre><code>(SYNCHRONIZE | EVENT_MODIFY_STATE)\n</code></pre>\n\n<p>SYNCHRONIZE lets you wait on the event and EVENT_MODIFY_STATE lets you call SetEvent, ResetEvent and PulseEvent.</p>\n\n<p>It is possible that you might need more access, but that is highly unusual.</p>\n"
},
{
"answer_id": 125513,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 0,
"selected": false,
"text": "<p>\"1800 INFORMATION\" is right - this is a UIPI issue; don't use Events in new code anyways, the event signal can be lost if the target blocking on the event happens to be in user-mode APC code when it is fired. The canonical way in Win32 to write a service/application is to use RPC calls to cross the UIPI boundary.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20316/"
]
| I am creating an appcation on Vista,which include a service and a Console application .Both running in same user account
In service i am creating an event and waits for that event.In console application i am opening the same event (problem starts here) and calling *SetEvent* function. I can not open the event (getting error 5,Access is denied) in the console application.I searched in the net and saw something about integrity level (I am not sure that the problem is related to integrity level).Its telling that service and applicaation got differnt integrity levels.
here is the part of the code,where IPC occures
**service**
```
DWORD
WINAPI IpcThread(LPVOID lpParam)
{
HANDLE ghRequestEvent = NULL ;
ghRequestEvent = CreateEvent(NULL, FALSE,
FALSE, "Global\\Event1") ; //creating the event
if(NULL == ghRequestEvent)
{
//error
}
while(1)
{
WaitForSingleObject(ghRequestEvent, INFINITE) //waiting for the event
//here some action related to event
}
}
```
**Console Application**
Here in application ,opening the event and seting the event
```
unsigned int
event_notification()
{
HANDLE ghRequestEvent = NULL ;
ghRequestEvent = OpenEvent(SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, "Global\\Event1") ;
if(NULL == ghRequestEvent)
{
//error
}
SetEvent(ghRequestEvent) ;
}
```
I am running both application (serivce and console application) with administrative privilege (i logged in as Administraor and running the console application by right clicking and using the option "run as administrator") .
The error i am getting in console application (where i am opening the event) is error no 5(Access is denied. ) .
So it will be very helpfull if you tell how to do the IPC between a service and an application in Vista
Thanks in advance
Navaneeth | Are the service and the application running as the same user with different integrity levels, or are they running as different users?
If it is the former, then this article from MSDN [which talks about integrity levels might help](http://msdn.microsoft.com/en-us/library/bb250462.aspx). They have some sample code for lowering the integrity level of a file. I'm not sure that this could be relevant for an event though.
```
#include <sddl.h>
#include <AccCtrl.h>
#include <Aclapi.h>
void SetLowLabelToFile()
{
// The LABEL_SECURITY_INFORMATION SDDL SACL to be set for low integrity
#define LOW_INTEGRITY_SDDL_SACL_W L"S:(ML;;NW;;;LW)"
DWORD dwErr = ERROR_SUCCESS;
PSECURITY_DESCRIPTOR pSD = NULL;
PACL pSacl = NULL; // not allocated
BOOL fSaclPresent = FALSE;
BOOL fSaclDefaulted = FALSE;
LPCWSTR pwszFileName = L"Sample.txt";
if (ConvertStringSecurityDescriptorToSecurityDescriptorW(
LOW_INTEGRITY_SDDL_SACL_W, SDDL_REVISION_1, &pSD;, NULL))
{
if (GetSecurityDescriptorSacl(pSD, &fSaclPresent;, &pSacl;,
&fSaclDefaulted;))
{
// Note that psidOwner, psidGroup, and pDacl are
// all NULL and set the new LABEL_SECURITY_INFORMATION
dwErr = SetNamedSecurityInfoW((LPWSTR) pwszFileName,
SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION,
NULL, NULL, NULL, pSacl);
}
LocalFree(pSD);
}
}
```
If it is the latter you might look at this link which [suggests creating a NULL ACL](http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2007-04/msg00086.html) and associating it with the object (in the example it is a named pipe, but the approach is similar for an event I'm sure:
```
BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = &sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, (PACL) 0, FALSE);
CreateNamedPipe(..., &sa);
``` |
113,989 | <p>Is there an easy way (in .Net) to test if a Font is installed on the current machine?</p>
| [
{
"answer_id": 113998,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/89886/how-do-you-get-a-list-of-all-the-installed-fonts#89895\">How do you get a list of all the installed fonts?</a></p>\n\n<pre><code>var fontsCollection = new InstalledFontCollection();\nforeach (var fontFamily in fontsCollection.Families)\n{\n if (fontFamily.Name == fontName) {...} \\\\ check if font is installed\n}\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.text.installedfontcollection.aspx\" rel=\"noreferrer\">InstalledFontCollection class</a> for details.</p>\n\n<p>MSDN:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/0yf5t4e8(VS.71).aspx\" rel=\"noreferrer\">Enumerating Installed Fonts</a></p>\n"
},
{
"answer_id": 114003,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 6,
"selected": true,
"text": "<pre><code>string fontName = \"Consolas\";\nfloat fontSize = 12;\n\nusing (Font fontTester = new Font( \n fontName, \n fontSize, \n FontStyle.Regular, \n GraphicsUnit.Pixel)) \n{\n if (fontTester.Name == fontName)\n {\n // Font exists\n }\n else\n {\n // Font doesn't exist\n }\n}\n</code></pre>\n"
},
{
"answer_id": 114066,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks to Jeff, I have better read the documentation of the Font class:</p>\n\n<blockquote>\n <p>If the familyName parameter\n specifies a font that is not installed\n on the machine running the application\n or is not supported, Microsoft Sans\n Serif will be substituted.</p>\n</blockquote>\n\n<p>The result of this knowledge:</p>\n\n<pre><code> private bool IsFontInstalled(string fontName) {\n using (var testFont = new Font(fontName, 8)) {\n return 0 == string.Compare(\n fontName,\n testFont.Name,\n StringComparison.InvariantCultureIgnoreCase);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 14653702,
"author": "Hans",
"author_id": 472522,
"author_profile": "https://Stackoverflow.com/users/472522",
"pm_score": 2,
"selected": false,
"text": "<p>Going off of GvS' answer:</p>\n\n<pre><code> private static bool IsFontInstalled(string fontName)\n {\n using (var testFont = new Font(fontName, 8))\n return fontName.Equals(testFont.Name, StringComparison.InvariantCultureIgnoreCase);\n }\n</code></pre>\n"
},
{
"answer_id": 17596784,
"author": "jltrem",
"author_id": 571637,
"author_profile": "https://Stackoverflow.com/users/571637",
"pm_score": 3,
"selected": false,
"text": "<p>Other answers proposed using <code>Font</code> creation only work if the <code>FontStyle.Regular</code> is available. Some fonts, for example Verlag Bold, do not have a regular style. Creation would fail with exception <em>Font 'Verlag Bold' does not support style 'Regular'</em>. You'll need to check for styles that your application will require. A solution follows:</p>\n\n<pre><code> public static bool IsFontInstalled(string fontName)\n {\n bool installed = IsFontInstalled(fontName, FontStyle.Regular);\n if (!installed) { installed = IsFontInstalled(fontName, FontStyle.Bold); }\n if (!installed) { installed = IsFontInstalled(fontName, FontStyle.Italic); }\n\n return installed;\n }\n\n public static bool IsFontInstalled(string fontName, FontStyle style)\n {\n bool installed = false;\n const float emSize = 8.0f;\n\n try\n {\n using (var testFont = new Font(fontName, emSize, style))\n {\n installed = (0 == string.Compare(fontName, testFont.Name, StringComparison.InvariantCultureIgnoreCase));\n }\n }\n catch\n {\n }\n\n return installed;\n }\n</code></pre>\n"
},
{
"answer_id": 23280503,
"author": "nateirvin",
"author_id": 1687106,
"author_profile": "https://Stackoverflow.com/users/1687106",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how I would do it:</p>\n\n<pre><code>private static bool IsFontInstalled(string name)\n{\n using (InstalledFontCollection fontsCollection = new InstalledFontCollection())\n {\n return fontsCollection.Families\n .Any(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));\n }\n}\n</code></pre>\n\n<p>One thing to note with this is that the <code>Name</code> property is not always what you would expect from looking in C:\\WINDOWS\\Fonts. For example, I have a font installed called \"Arabic Typsetting Regular\". <code>IsFontInstalled(\"Arabic Typesetting Regular\")</code> will return false, but <code>IsFontInstalled(\"Arabic Typesetting\")</code> will return true. (\"Arabic Typesetting\" is the name of the font in Windows' font preview tool.)</p>\n\n<p>As far as resources go, I ran a test where I called this method several times, and the test finished in only a few milliseconds every time. My machine's a bit overpowered, but unless you'd need to run this query very frequently it seems the performance is very good (and even if you did, that's what caching is for).</p>\n"
},
{
"answer_id": 61184284,
"author": "Sourcephy",
"author_id": 8196012,
"author_profile": "https://Stackoverflow.com/users/8196012",
"pm_score": 0,
"selected": false,
"text": "<p>In my case I need to check font filename with extension</p>\n\n<p>ex: verdana.ttf = Verdana Regular, verdanai.ttf = Verdana Italic</p>\n\n<pre><code>using System.IO;\n\nIsFontInstalled(\"verdana.ttf\")\n\npublic bool IsFontInstalled(string ContentFontName)\n{\n return File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), ContentFontName.ToUpper()));\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11492/"
]
| Is there an easy way (in .Net) to test if a Font is installed on the current machine? | ```
string fontName = "Consolas";
float fontSize = 12;
using (Font fontTester = new Font(
fontName,
fontSize,
FontStyle.Regular,
GraphicsUnit.Pixel))
{
if (fontTester.Name == fontName)
{
// Font exists
}
else
{
// Font doesn't exist
}
}
``` |
113,991 | <p>A heap is a list where the following applies:</p>
<pre><code>l[i] <= l[2*i] && l[i] <= [2*i+1]
</code></pre>
<p>for <code>0 <= i < len(list)</code></p>
<p>I'm looking for in-place sorting.</p>
| [
{
"answer_id": 114020,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": -1,
"selected": false,
"text": "<p>Read the items off the top of the heap one by one. Basically what you have then is heap sort.</p>\n"
},
{
"answer_id": 114023,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": true,
"text": "<p>Well you are half way through a Heap Sort already, by having your data in a heap. You just need to implement the second part of the heap sort algorithm. This should be faster than using quicksort on the heap array.</p>\n\n<p>If you are feeling brave you could have a go at implementing <a href=\"http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD796a.PDF\" rel=\"nofollow noreferrer\">smoothsort</a>, which is faster than heapsort for nearly-sorted data.</p>\n"
},
{
"answer_id": 114057,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 0,
"selected": false,
"text": "<p>Sorting a heap in-place kind of sounds like a job for <a href=\"http://en.wikipedia.org/wiki/Heapsort\" rel=\"nofollow noreferrer\">Heap Sort</a>.</p>\n\n<p>I assume memory is constrained, an embedded app, perhaps?</p>\n"
},
{
"answer_id": 114061,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": "<p>Just use heap-sort. It is in-place. That would be the most natural choice.</p>\n\n<p>You can as well just use your heap as it and sort it with some other algorithm. Afterwards you re-build your heap from the sorted list. Quicksort is a good candidate because you can be sure it won't run in the worst-case O(n²) order simply because your heap is already pre-sorted.</p>\n\n<p>That may be faster if your compare-function is expensive. Heap-sort tend to evaluate the compare-function quite often.</p>\n"
},
{
"answer_id": 114064,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>Since you already have a heap, couldn't you just use the second phase of the <a href=\"http://en.wikipedia.org/wiki/Heapsort\" rel=\"nofollow noreferrer\">heap sort</a>? It works in place and should be nice and efficient.</p>\n"
},
{
"answer_id": 114071,
"author": "HenryR",
"author_id": 2827,
"author_profile": "https://Stackoverflow.com/users/2827",
"pm_score": 0,
"selected": false,
"text": "<p>For in-place sorting, the fastest way follows. Beware of off-by-one errors in my code. Note that this method gives a reversed sorted list which needs to be unreversed in the final step. If you use a max-heap, this problem goes away. </p>\n\n<p>The general idea is a neat one: swap the smallest element (at index 0) with the last element in the heap, bubble that element down until the heap property is restored, shrink the size of the heap by one and repeat. </p>\n\n<p>This isn't the absolute fastest way for non-in-place sorting as David Mackay demonstrates <a href=\"http://http://users.aims.ac.za/~mackay/sorting/sorting.html\" rel=\"nofollow noreferrer\">here</a> - you can do better by putting an element more likely to be the smallest at the top of the heap instead of one from the bottom row.</p>\n\n<p>Time complexity is T(n.log n) worst case - n iterations with possibly log n (the height of the heap) goes through the while loop.</p>\n\n<pre><code>for (int k=len(l)-1;k>0;k--){\nswap( l, 0, k );\nwhile (i*2 < k)\n {\nint left = i*2;\nint right = l*2 + 1;\nint swapidx = i;\nif ( l[left] < l[right] )\n {\n if (l[i] > l[left])\n {\n swapidx = left;\n }\n }\nelse\n {\n if (l[i] > l[right])\n {\n swapidx = right;\n }\n }\n\nif (swapidx == i)\n {\n // Found right place in the heap, break.\n break;\n }\nswap( l, i, swapidx );\ni = swapidx;\n }}\n\n// Now reverse the list in linear time:\nint s = 0; \nint e = len(l)-1;\nwhile (e > s)\n {\n swap( l, s, e );\n s++; e--:\n }\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899/"
]
| A heap is a list where the following applies:
```
l[i] <= l[2*i] && l[i] <= [2*i+1]
```
for `0 <= i < len(list)`
I'm looking for in-place sorting. | Well you are half way through a Heap Sort already, by having your data in a heap. You just need to implement the second part of the heap sort algorithm. This should be faster than using quicksort on the heap array.
If you are feeling brave you could have a go at implementing [smoothsort](http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD796a.PDF), which is faster than heapsort for nearly-sorted data. |
113,992 | <p>In what order are the following parameters tested (in C++)?</p>
<pre><code>if (a || b && c)
{
}
</code></pre>
<p>I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.</p>
<p><strong><em>Edit: Accepted Answer & Follow Up</em></strong></p>
<p>This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/126fe14k.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/126fe14k.aspx</a></p>
| [
{
"answer_id": 113995,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": true,
"text": "<p>From <a href=\"http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>a || (b && c)\n</code></pre>\n\n<p>This is the default precedence.</p>\n"
},
{
"answer_id": 113999,
"author": "Einar",
"author_id": 2964,
"author_profile": "https://Stackoverflow.com/users/2964",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not sure but it should be easy for you to find out.</p>\n\n<p>Just create a small program with a statement that prints out the truth value of:\n(true || false && true)</p>\n\n<p>If the result is true, then the || has higher precedence than &&, if it is falase, it's the other way around.</p>\n"
},
{
"answer_id": 114016,
"author": "Rodrigo Queiro",
"author_id": 20330,
"author_profile": "https://Stackoverflow.com/users/20330",
"pm_score": 3,
"selected": false,
"text": "<p>[<a href=\"http://www.cppreference.com/wiki/operator_precedence]\" rel=\"noreferrer\">http://www.cppreference.com/wiki/operator_precedence]</a> (Found by googling \"C++ operator precedence\")</p>\n\n<p>That page tells us that &&, in group 13, has higher precedence than || in group 14, so the expression is equivalent to a || (b && c).</p>\n\n<p>Unfortunately, the wikipedia article [<a href=\"http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence]\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence]</a> disagrees with this, but since I have the C89 standard on my desk and it agrees with the first site, I'm going to revise the wikipedia article.</p>\n"
},
{
"answer_id": 114166,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>To answer the follow-up: obviously the table at MSDN is botched, perhaps by somebody unable to do a decent HTML table (or using a Microsoft tool to generate it!).<br>\nI suppose it should look more like the Wikipedia table referenced by Rodrigo, where we have clear sub-sections.<br>\nBut clearly the accepted answer is right, somehow we have same priority with && and || than with * and +, for example.<br>\nThe snippet you gave is clear and unambiguous for me, but I suppose adding parentheses wouldn't hurt either.</p>\n"
},
{
"answer_id": 114185,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 2,
"selected": false,
"text": "<p>&& (boolean AND) has higher precedence than || (boolean OR). Therefore the following are identical:</p>\n\n<pre><code>a || b && c\na || (b && c)\n</code></pre>\n\n<p>A good mnemonic rule is to remember that AND is like multiplication and OR is like addition. If we replace AND with * and OR with +, we get a more familiar equivalent:</p>\n\n<pre><code>a + b * c\na + (b * c)\n</code></pre>\n\n<p>Actually, in Boolean logic, AND and OR act similar to these arithmetic operators:</p>\n\n<pre>\na b a AND b a * b a OR b a + b\n---------------------------------------\n0 0 0 0 0 0\n0 1 0 0 1 1\n1 0 0 0 1 1\n1 1 1 1 1 1 (2 really, but we pretend it's 1)\n</pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/113992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
]
| In what order are the following parameters tested (in C++)?
```
if (a || b && c)
{
}
```
I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.
***Edit: Accepted Answer & Follow Up***
This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right.
<http://msdn.microsoft.com/en-us/library/126fe14k.aspx> | From [here](http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm):
```
a || (b && c)
```
This is the default precedence. |
114,010 | <p>Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.</p>
<p><em>edited later to clarify the use case</em></p>
<p>An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.</p>
| [
{
"answer_id": 114022,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 1,
"selected": false,
"text": "<p>Use reflection to get the Type, use GetConstructor on the type, use Invoke on the constructor.</p>\n\n<p>Edit: Thanks to Sklivvz for pointing out that I answered a question that wasn't asked ;)</p>\n\n<p>The answer to the actual question: I've found that generating C# code and then using CodeDomProvider (but not CodeDOM itself -- terrible) and then compiling that down and reflecting types out of that is the easiest way of doing 'anonymous' objects at runtime.</p>\n"
},
{
"answer_id": 114080,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to look into the DLR. I havn't done so myself (yet) but the use-case for the DLR (dynamic languages) sounds a lot like what you're trying to do.</p>\n\n<p>Depending on what you want to do the Castle-framework's dynamic proxy object might be a good fit too.</p>\n"
},
{
"answer_id": 114101,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, there is.\nFrom memory:</p>\n\n<pre><code>public static T create<T>(T t)\n{\n return Activator.CreateInstance<T>();\n}\n\nobject anon = create(existingAnonymousType);\n</code></pre>\n"
},
{
"answer_id": 114346,
"author": "Chris Ballard",
"author_id": 18782,
"author_profile": "https://Stackoverflow.com/users/18782",
"pm_score": 1,
"selected": false,
"text": "<p>You can use Reflection.Emit to generate the required classes dynamically, although it's pretty nasty to code up.</p>\n\n<p>If you decide upon this route, I would suggest downloading the <a href=\"http://www.codeplex.com/reflectoraddins\" rel=\"nofollow noreferrer\">Reflection Emit Language Addin</a> for <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">.NET Reflector</a>, as this allows you to see how existing classes would be built using Reflection.Emit, hence a good method for learning this corner of the framework.</p>\n"
},
{
"answer_id": 117669,
"author": "SteinNorheim",
"author_id": 19220,
"author_profile": "https://Stackoverflow.com/users/19220",
"pm_score": 1,
"selected": false,
"text": "<p>You might also want to have a look into the FormatterServices class: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatterservices\" rel=\"nofollow noreferrer\">MSDN entry on FormatterServices</a></p>\n\n<p>It contains GetSafeUninitializedObject that will create an empty instance of the class, and several other handy methods when doing serialization.</p>\n\n<p><em>In reply to comment from Michael:\nIf you don't have the Type instance for type T, you can always get it from typeof(T). If you have an object of an unknown type, you can invoke GetType() on it in order to get the Type instance.</em></p>\n"
},
{
"answer_id": 132589,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 3,
"selected": true,
"text": "<p>Here is another way, seems more direct.</p>\n\n<pre><code>object anon = Activator.CreateInstance(existingObject.GetType());\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9777/"
]
| Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.
*edited later to clarify the use case*
An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work. | Here is another way, seems more direct.
```
object anon = Activator.CreateInstance(existingObject.GetType());
``` |
114,054 | <p>Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction.</p>
<p>I am trying to develop an automation framework using <a href="http://en.wikipedia.org/wiki/HP_QuickTest_Professional" rel="nofollow noreferrer">QuickTest Professional</a>, a testing tool.</p>
<ul>
<li>There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets).</li>
<li>I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop.</li>
<li>I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.</li>
</ul>
| [
{
"answer_id": 114133,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there..</p>\n\n<p>Now, I have not done VBScript for a LONG time so, to pseudo it:</p>\n\n<pre><code>While Not EndOfExcelSheet\n ReadDataFromExcel();\n If errOccurred Then TakeScreenPrint();\n 'NOTE: We have caught the error and requested the screen print\n 'is taken, but we have NOT bubbled the exception up!\nEnd While\n</code></pre>\n"
},
{
"answer_id": 114162,
"author": "Attila",
"author_id": 20322,
"author_profile": "https://Stackoverflow.com/users/20322",
"pm_score": 0,
"selected": false,
"text": "<p>It's hard to answer your question based on what you wrote, but the first thing that comes to my mind is to add a boolean parameter to your exception-handling function (let's call it ExceptionHandler). Say, if the parameter (let's call it ExitLoop) is true, you wll exit from the \"entire loop\", otherwise, continue. Now, it might be too tedius to change that for old calls to the function (calls without the new parameter) -- I'm not sure if VB supports function overloading. If this is the case, you can rename your ExceptionHandler to ExceptionHandler2, add the new parameter (ExitLoop) and logic to it and create a (now new) function ExceptionHandler that calls ExceptionHandler2 with its parameters plus true for ExitLoop.</p>\n\n<p>Hope it helps.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction.
I am trying to develop an automation framework using [QuickTest Professional](http://en.wikipedia.org/wiki/HP_QuickTest_Professional), a testing tool.
* There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets).
* I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop.
* I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call. | Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there..
Now, I have not done VBScript for a LONG time so, to pseudo it:
```
While Not EndOfExcelSheet
ReadDataFromExcel();
If errOccurred Then TakeScreenPrint();
'NOTE: We have caught the error and requested the screen print
'is taken, but we have NOT bubbled the exception up!
End While
``` |
114,149 | <p>The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends? </p>
<p>I'm aware of immutability, but that doesn't really carry over to container objects to name but one example.</p>
| [
{
"answer_id": 114155,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>C# doesn't have such feature. You can pass argument by value or by reference. Reference itself is immutable unless you specify <em><a href=\"http://msdn.microsoft.com/en-us/library/14akc2c7(VS.71).aspx\" rel=\"nofollow noreferrer\">ref</a></em> modifier. But referenced data isn't immutable. So you need to be careful if you want to avoid side effects.</p>\n\n<p>MSDN:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/0f66670z(VS.71).aspx\" rel=\"nofollow noreferrer\">Passing Parameters</a></p>\n"
},
{
"answer_id": 114202,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 5,
"selected": false,
"text": "<p>To get the benefit of const-craziness (or pureness in functional programming terms), you will need to design your classes in a way so they are immutable, just like the String class of c# is.</p>\n\n<p>This approach is way better than just marking an object as readonly, since with immutable classes you can pass data around easily in multi-tasking environments.</p>\n"
},
{
"answer_id": 114571,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>The <strong>const</strong> keyword can be used for compile time constants such as primitive types and strings</li>\n<li>The <strong>readonly</strong> keyword can be used for run-time constants such as reference types</li>\n</ul>\n\n<p>The problem with <strong>readonly</strong> is that it only allows the reference (pointer) to be constant. The thing referenced (pointed to) can still be modified. This is the tricky part but there is no way around it. To implement constant objects means making them not expose any mutable methods or properties but this is awkward.</p>\n\n<p>See also <a href=\"http://www.amazon.co.uk/gp/product/toc/0321245660\" rel=\"nofollow noreferrer\">Effective C#: 50 Specific Ways to Improve Your C#</a> (Item 2 - Prefer readonly to const.)</p>\n"
},
{
"answer_id": 114809,
"author": "Trap",
"author_id": 7839,
"author_profile": "https://Stackoverflow.com/users/7839",
"pm_score": 7,
"selected": true,
"text": "<p>I've come across this issue a lot of times too and ended up using interfaces.</p>\n\n<p>I think it's important to drop the idea that C# is any form, or even an evolution of C++. They're two different languages that share almost the same syntax.</p>\n\n<p>I usually express 'const correctness' in C# by defining a read-only view of a class:</p>\n\n<pre><code>public interface IReadOnlyCustomer\n{\n String Name { get; }\n int Age { get; }\n}\n\npublic class Customer : IReadOnlyCustomer\n{\n private string m_name;\n private int m_age;\n\n public string Name\n {\n get { return m_name; }\n set { m_name = value; }\n }\n\n public int Age\n {\n get { return m_age; }\n set { m_age = value; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 116282,
"author": "munificent",
"author_id": 9457,
"author_profile": "https://Stackoverflow.com/users/9457",
"pm_score": 2,
"selected": false,
"text": "<p>Interfaces are the answer, and are actually more powerful than \"const\" in C++. const is a one-size-fits-all solution to the problem where \"const\" is defined as \"doesn't set members or call something that sets members\". That's a good shorthand for const-ness in many scenarios, but not all of them. For example, consider a function that calculates a value based on some members but also caches the results. In C++, that's considered non-const, although from the user's perspective it is essentially const.</p>\n\n<p>Interfaces give you more flexibility in defining the specific subset of capabilities you want to provide from your class. Want const-ness? Just provide an interface with no mutating methods. Want to allow setting some things but not others? Provide an interface with just those methods.</p>\n"
},
{
"answer_id": 121064,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 5,
"selected": false,
"text": "<p>I just wanted to note for you that many of the System.Collections.Generics containers have an AsReadOnly method which will give you back an immutable collection.</p>\n"
},
{
"answer_id": 132718,
"author": "Stuart McConnell",
"author_id": 22111,
"author_profile": "https://Stackoverflow.com/users/22111",
"pm_score": 2,
"selected": false,
"text": "<p>Agree with some of the others look at using readonly fields that you initialize in the constructor, to create immutable objects.</p>\n\n<pre><code> public class Customer\n {\n private readonly string m_name;\n private readonly int m_age;\n\n public Customer(string name, int age)\n {\n m_name = name;\n m_age = age;\n }\n\n public string Name\n {\n get { return m_name; }\n }\n\n public int Age\n {\n get { return m_age; }\n }\n }\n</code></pre>\n\n<p>Alternatively you could also add access scope on the properties, i.e. public get and protected set?</p>\n\n<pre><code> public class Customer\n {\n private string m_name;\n private int m_age;\n\n protected Customer() \n {}\n\n public Customer(string name, int age)\n {\n m_name = name;\n m_age = age;\n }\n\n public string Name\n {\n get { return m_name; }\n protected set { m_name = value; }\n }\n\n public int Age\n {\n get { return m_age; }\n protected set { m_age = value; }\n }\n }\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11801/"
]
| The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends?
I'm aware of immutability, but that doesn't really carry over to container objects to name but one example. | I've come across this issue a lot of times too and ended up using interfaces.
I think it's important to drop the idea that C# is any form, or even an evolution of C++. They're two different languages that share almost the same syntax.
I usually express 'const correctness' in C# by defining a read-only view of a class:
```
public interface IReadOnlyCustomer
{
String Name { get; }
int Age { get; }
}
public class Customer : IReadOnlyCustomer
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
``` |
114,154 | <p>XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a <em>Binding</em> instance and assigns it to the <em>Text</em> property of the <em>TextBox</em> element.</p>
<pre><code><TextBox Text="{Binding ElementName=Foo, Path=Bar}"/>
</code></pre>
<p>I want to extend XAML so that the developer could enter this as valid...</p>
<pre><code><TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/>
</code></pre>
<p>This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it?</p>
<p>If this is possible I have a followup question. Can I take a string <em>"{Binding ElementName=Foo, Path=Bar}"</em> and ask the framework to process it and return the <em>Binding</em> instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed.</p>
| [
{
"answer_id": 114175,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>take a look at markupextensions\n<a href=\"http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx</a></p>\n"
},
{
"answer_id": 114195,
"author": "Brownie",
"author_id": 6600,
"author_profile": "https://Stackoverflow.com/users/6600",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>Binding</code> class is a <a href=\"http://msdn.microsoft.com/en-us/library/ms747254.aspx\" rel=\"nofollow noreferrer\">Markup Extension</a>. You can write your own by deriving from <code>System.Windows.Markup.MarkupExtension</code>.</p>\n\n<p><code>ElementName</code> and <code>Path</code> are simply properties on the <code>Binding</code> object.</p>\n\n<p>As for the followup you can create a new <code>Binding</code> in code by instantiating the <code>Binding</code> object. I do not know of a way to process a string through.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
]
| XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a *Binding* instance and assigns it to the *Text* property of the *TextBox* element.
```
<TextBox Text="{Binding ElementName=Foo, Path=Bar}"/>
```
I want to extend XAML so that the developer could enter this as valid...
```
<TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/>
```
This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it?
If this is possible I have a followup question. Can I take a string *"{Binding ElementName=Foo, Path=Bar}"* and ask the framework to process it and return the *Binding* instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed. | take a look at markupextensions
<http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx> |
114,165 | <p>At work we use <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine.</p>
<p>I've read on several places on the Internet about a major upgrade but couldn't get it to work.
Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX?</p>
| [
{
"answer_id": 114736,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 8,
"selected": false,
"text": "<p>Finally I found a solution - I'm posting it here for other people who might have the same problem (all 5 of you):</p>\n\n<ul>\n<li>Change the product ID to *</li>\n<li><p>Under product add The following:</p>\n\n<pre><code><Property Id=\"PREVIOUSVERSIONSINSTALLED\" Secure=\"yes\" />\n<Upgrade Id=\"YOUR_GUID\"> \n <UpgradeVersion\n Minimum=\"1.0.0.0\" Maximum=\"99.0.0.0\"\n Property=\"PREVIOUSVERSIONSINSTALLED\"\n IncludeMinimum=\"yes\" IncludeMaximum=\"no\" />\n</Upgrade> \n</code></pre></li>\n<li><p>Under InstallExecuteSequence add:</p>\n\n<pre><code><RemoveExistingProducts Before=\"InstallInitialize\" /> \n</code></pre></li>\n</ul>\n\n<p>From now on whenever I install the product it removed previous installed versions.</p>\n\n<p><strong>Note:</strong> replace upgrade Id with your own GUID</p>\n"
},
{
"answer_id": 114786,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 4,
"selected": false,
"text": "<p>You might be better asking this on the <a href=\"https://wixtoolset.org/documentation/mailinglist/\" rel=\"nofollow noreferrer\">WiX-users mailing list</a>.</p>\n\n<p>WiX is best used with a firm understanding of what Windows Installer is doing. You might consider getting \"<a href=\"https://rads.stackoverflow.com/amzn/click/1590592972\" rel=\"nofollow noreferrer\">The Definitive Guide to Windows Installer</a>\".</p>\n\n<p>The action that removes an existing product is the <a href=\"https://learn.microsoft.com/en-us/windows/desktop/Msi/removeexistingproducts-action\" rel=\"nofollow noreferrer\">RemoveExistingProducts action</a>. Because the consequences of what it does depends on where it's scheduled - namely, whether a failure causes the old product to be reinstalled, and whether unchanged files are copied again - you have to schedule it yourself.</p>\n\n<p><code>RemoveExistingProducts</code> processes <code><Upgrade></code> elements in the current installation, matching the <code>@Id</code> attribute to the <code>UpgradeCode</code> (specified in the <code><Product></code> element) of all the installed products on the system. The <code>UpgradeCode</code> defines a family of related products. Any products which have this UpgradeCode, whose versions fall into the range specified, and where the <code>UpgradeVersion/@OnlyDetect</code> attribute is <code>no</code> (or is omitted), will be removed.</p>\n\n<p>The documentation for <code>RemoveExistingProducts</code> mentions setting the <code>UPGRADINGPRODUCTCODE</code> property. It means that the uninstall process <em>for the product being removed</em> receives that property, whose value is the <code>Product/@Id</code> for the product being installed.</p>\n\n<p>If your original installation did not include an <code>UpgradeCode</code>, you will not be able to use this feature.</p>\n"
},
{
"answer_id": 128021,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 4,
"selected": false,
"text": "<p>I used this site to help me understand the basics about WiX Upgrade:</p>\n\n<p><a href=\"http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization\" rel=\"nofollow noreferrer\">http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization</a></p>\n\n<p>Afterwards I created a sample Installer, (installed a test file), then created the Upgrade installer (installed 2 sample test files). This will give you a basic understanding of how the mechanism works.</p>\n\n<p>And as Mike said in the book from Apress, \"The Definitive Guide to Windows Installer\", it will help you out to understand, but it is not written using WiX.</p>\n\n<p>Another site that was pretty helpful was this one:</p>\n\n<p><a href=\"http://web.archive.org/web/20110209022712/http://wixwiki.com/index.php?title=Main_Page\" rel=\"nofollow noreferrer\">http://www.wixwiki.com/index.php?title=Main_Page</a></p>\n"
},
{
"answer_id": 214650,
"author": "Brian Gillespie",
"author_id": 6151,
"author_profile": "https://Stackoverflow.com/users/6151",
"pm_score": 5,
"selected": false,
"text": "<p>The Upgrade element inside the Product element, combined with proper scheduling of the action will perform the uninstall you're after. Be sure to list the upgrade codes of all the products you want to remove.</p>\n\n<pre><code><Property Id=\"PREVIOUSVERSIONSINSTALLED\" Secure=\"yes\" />\n<Upgrade Id=\"00000000-0000-0000-0000-000000000000\">\n <UpgradeVersion Minimum=\"1.0.0.0\" Maximum=\"1.0.5.0\" Property=\"PREVIOUSVERSIONSINSTALLED\" IncludeMinimum=\"yes\" IncludeMaximum=\"no\" />\n</Upgrade>\n</code></pre>\n\n<p>Note that, if you're careful with your builds, you can prevent people from accidentally installing an older version of your product over a newer one. That's what the Maximum field is for. When we build installers, we set UpgradeVersion Maximum to the version being built, but IncludeMaximum=\"no\" to prevent this scenario.</p>\n\n<p>You have choices regarding the scheduling of RemoveExistingProducts. I prefer scheduling it after InstallFinalize (rather than after InstallInitialize as others have recommended):</p>\n\n<pre><code><InstallExecuteSequence>\n <RemoveExistingProducts After=\"InstallFinalize\"></RemoveExistingProducts>\n</InstallExecuteSequence>\n</code></pre>\n\n<p>This leaves the previous version of the product installed until after the new files and registry keys are copied. This lets me migrate data from the old version to the new (for example, you've switched storage of user preferences from the registry to an XML file, but you want to be polite and migrate their settings). This migration is done in a deferred custom action just before InstallFinalize.</p>\n\n<p>Another benefit is efficiency: if there are unchanged files, Windows Installer doesn't bother copying them again when you schedule after InstallFinalize. If you schedule after InstallInitialize, the previous version is completely removed first, and then the new version is installed. This results in unnecessary deletion and recopying of files.</p>\n\n<p>For other scheduling options, see the RemoveExistingProducts help topic in MSDN. This week, the link is: <a href=\"http://msdn.microsoft.com/en-us/library/aa371197.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa371197.aspx</a></p>\n"
},
{
"answer_id": 724098,
"author": "Rob Mensching",
"author_id": 23852,
"author_profile": "https://Stackoverflow.com/users/23852",
"pm_score": 7,
"selected": false,
"text": "<p>The following is the sort of syntax I use for major upgrades:</p>\n\n<pre><code><Product Id=\"*\" UpgradeCode=\"PUT-GUID-HERE\" Version=\"$(var.ProductVersion)\">\n <Upgrade Id=\"PUT-GUID-HERE\">\n <UpgradeVersion OnlyDetect=\"yes\" Minimum=\"$(var.ProductVersion)\" Property=\"NEWERVERSIONDETECTED\" IncludeMinimum=\"no\" />\n <UpgradeVersion OnlyDetect=\"no\" Maximum=\"$(var.ProductVersion)\" Property=\"OLDERVERSIONBEINGUPGRADED\" IncludeMaximum=\"no\" />\n</Upgrade>\n\n<InstallExecuteSequence>\n <RemoveExistingProducts After=\"InstallInitialize\" />\n</InstallExecuteSequence>\n</code></pre>\n\n<p>As @Brian Gillespie noted there are other places to schedule the RemoveExistingProducts depending on desired optimizations. Note the PUT-GUID-HERE must be identical.</p>\n"
},
{
"answer_id": 1042474,
"author": "Faraz",
"author_id": 2423,
"author_profile": "https://Stackoverflow.com/users/2423",
"pm_score": 3,
"selected": false,
"text": "<p>I would suggest having a look at Alex Shevchuk's tutorial. He explains \"major upgrade\" through WiX with a good hands-on example at <a href=\"http://blogs.technet.com/alexshev/archive/2008/02/15/from-msi-to-wix-part-8-major-upgrade.aspx\" rel=\"noreferrer\">From MSI to WiX, Part 8 - Major Upgrade</a>.</p>\n"
},
{
"answer_id": 2407440,
"author": "Merill Fernando",
"author_id": 241338,
"author_profile": "https://Stackoverflow.com/users/241338",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using the latest version of WiX (3.0) and couldn't get the above working. But this did work:</p>\n\n<pre><code><Product Id=\"*\" UpgradeCode=\"PUT-GUID-HERE\" ... >\n\n<Upgrade Id=\"PUT-GUID-HERE\">\n <UpgradeVersion OnlyDetect=\"no\" Property=\"PREVIOUSFOUND\"\n Minimum=\"1.0.0.0\" IncludeMinimum=\"yes\"\n Maximum=\"99.0.0.0\" IncludeMaximum=\"no\" />\n</Upgrade>\n</code></pre>\n\n<p>Note that PUT-GUID-HERE should be the same as the GUID that you have defined in the UpgradeCode property of the Product. </p>\n"
},
{
"answer_id": 3575801,
"author": "Ant",
"author_id": 11529,
"author_profile": "https://Stackoverflow.com/users/11529",
"pm_score": 9,
"selected": true,
"text": "<p>In the newest versions (from the 3.5.1315.0 beta), you can use the <a href=\"http://wixtoolset.org/documentation/manual/v3/xsd/wix/majorupgrade.html\" rel=\"noreferrer\" title=\"Major upgrade\">MajorUpgrade element</a> instead of using your own.</p>\n\n<p>For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded):</p>\n\n<pre><code><MajorUpgrade\n AllowDowngrades=\"no\" DowngradeErrorMessage=\"!(loc.NewerVersionInstalled)\"\n AllowSameVersionUpgrades=\"no\"\n />\n</code></pre>\n"
},
{
"answer_id": 4525879,
"author": "Daniel Morritt",
"author_id": 505667,
"author_profile": "https://Stackoverflow.com/users/505667",
"pm_score": 3,
"selected": false,
"text": "<p>One important thing I missed from the tutorials for a while (stolen from <a href=\"http://www.tramontana.co.hu/wix/lesson4.php\">http://www.tramontana.co.hu/wix/lesson4.php</a>) which resulted in the \"Another version of this product is already installed\" errors:</p>\n\n<p>*<strong>Small updates</strong> <em>mean small changes to one or a few files where the change doesn't warrant changing the product version (major.minor.build). You don't have to change the Product GUID, either. Note that you always have to change the Package GUID when you create a new .msi file that is different from the previous ones in any respect. The Installer keeps track of your installed programs and finds them when the user wants to change or remove the installation using these GUIDs. Using the same GUID for different packages will confuse the Installer.</em> </p>\n\n<p><strong>Minor upgrades</strong> <em>denote changes where the product version will already change. Modify the Version attribute of the Product tag. The product will remain the same, so you don't need to change the Product GUID but, of course, get a new Package GUID.</em> </p>\n\n<p><strong>Major upgrades</strong> <em>denote significant changes like going from one full version to another. Change everything: Version attribute, Product and Package GUIDs.</em></p>\n"
},
{
"answer_id": 8534048,
"author": "Sasha",
"author_id": 543591,
"author_profile": "https://Stackoverflow.com/users/543591",
"pm_score": 4,
"selected": false,
"text": "<p>I read the <a href=\"http://en.wikipedia.org/wiki/WiX\" rel=\"nofollow noreferrer\">WiX</a> documentation, downloaded examples, but I still had plenty of problems with upgrades. Minor upgrades don't execute uninstall of the previous products despite of possibility to specify those uninstall. I spent more that a day for investigations and found that WiX 3.5 intoduced a new tag for upgrades. Here is the usage:</p>\n\n<pre><code><MajorUpgrade Schedule=\"afterInstallInitialize\"\n DowngradeErrorMessage=\"A later version of [ProductName] is already installed. Setup will now exit.\" \n AllowDowngrades=\"no\" />\n</code></pre>\n\n<p>But the <strong>main reason</strong> of problems was that documentation says to use the \"<strong>REINSTALL=ALL REINSTALLMODE=vomus</strong>\" parameters for minor and small upgrades, but it doesn't say that those parameters are <strong>FORBIDDEN for major upgrades</strong> - they simply stop working. So you shouldn't use them with major upgrades.</p>\n"
},
{
"answer_id": 22619073,
"author": "Gian Marco",
"author_id": 66629,
"author_profile": "https://Stackoverflow.com/users/66629",
"pm_score": 1,
"selected": false,
"text": "<p>This is what worked for me, even with major <strong>DOWN</strong> grade:</p>\n\n<pre><code><Wix ...>\n <Product ...>\n <Property Id=\"REINSTALLMODE\" Value=\"amus\" />\n <MajorUpgrade AllowDowngrades=\"yes\" />\n</code></pre>\n"
},
{
"answer_id": 34098823,
"author": "NishantJ",
"author_id": 1244334,
"author_profile": "https://Stackoverflow.com/users/1244334",
"pm_score": 2,
"selected": false,
"text": "<p>Below worked for me. </p>\n\n<pre><code><Product Id=\"*\" Name=\"XXXInstaller\" Language=\"1033\" Version=\"1.0.0.0\" \n Manufacturer=\"XXXX\" UpgradeCode=\"YOUR_GUID_HERE\">\n<Package InstallerVersion=\"xxx\" Compressed=\"yes\"/>\n<Upgrade Id=\"YOUR_GUID_HERE\">\n <UpgradeVersion Property=\"REMOVINGTHEOLDVERSION\" Minimum=\"1.0.0.0\" \n RemoveFeatures=\"ALL\" />\n</Upgrade>\n<InstallExecuteSequence>\n <RemoveExistingProducts After=\"InstallInitialize\" />\n</InstallExecuteSequence>\n</code></pre>\n\n<p>Please make sure that the UpgradeCode in Product is matching to Id in Upgrade. </p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361/"
]
| At work we use [WiX](http://en.wikipedia.org/wiki/WiX) for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine.
I've read on several places on the Internet about a major upgrade but couldn't get it to work.
Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX? | In the newest versions (from the 3.5.1315.0 beta), you can use the [MajorUpgrade element](http://wixtoolset.org/documentation/manual/v3/xsd/wix/majorupgrade.html "Major upgrade") instead of using your own.
For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded):
```
<MajorUpgrade
AllowDowngrades="no" DowngradeErrorMessage="!(loc.NewerVersionInstalled)"
AllowSameVersionUpgrades="no"
/>
``` |
114,172 | <p>I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails.</p>
<p>Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process?</p>
<p>Say the command is used like this:
'whoami.exe /all'</p>
<p>I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process.</p>
| [
{
"answer_id": 114199,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "<p>You didn't note which programming language. It is not doable from a .bat file if that's what you wanted, but you can do it in any programming language. Example in C:</p>\n\n<pre><code>int main(int argc, void **argv)\n{\n // dump contents of argv to some log file\n int i=0;\n for (i=0; i<argc; i++)\n printf(\"Argument #%d: %s\\n\", argv[i]);\n // run the 'real' program, giving it the rest of argv vector (1+)\n // for example spawn, exec or system() functions can do it\n return 0; // or you can do a blocking call, and pick the return value from the program\n}\n</code></pre>\n"
},
{
"answer_id": 114203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Look for whoami.exe, BACK IT UP, replace it with your own executable and see do whatever you like with it's parameters (maybe save them in a text file).</p>\n"
},
{
"answer_id": 114209,
"author": "Allan Mertner",
"author_id": 13394,
"author_profile": "https://Stackoverflow.com/users/13394",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think using a \"script\" will work, since the intermediate should have a .exe extension for your ploy to work.</p>\n\n<p>I would write a very small command line program to do this; something like the following (written in Delphi/Virtual Pascal so it will result in a Win32 executable, but any compiled language should do):</p>\n\n<pre><code>program PassThrough;\n\nuses\n Dos; // Imports the Exec routine\n\nconst\n PassTo = 'Original.exe'; // The program you really want to call\n\nvar \n CommandLine: String;\n i: Integer;\n f: Text;\n\nbegin\n CommandLine := '';\n for i := 1 to ParamCount do\n CommandLine := CommandLine + ParamStr(i) + ' ';\n\n Assign(f,'Passthrough.log');\n Append(f);\n Writeln(f, CommandLine); // Write a line in the log\n Close(f);\n\n\n Exec(PassTo, CommandLine); // Run the intended program\nend.\n</code></pre>\n"
},
{
"answer_id": 114219,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": false,
"text": "<p>Can't you just change the calling program to log the parameters it used to call the process, and the exit code?\nThis would be way easier than trying to dig into whoami.exe</p>\n"
},
{
"answer_id": 114235,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 2,
"selected": true,
"text": "<p>From a batch file:</p>\n\n<pre><code>echo Parameters: %* >> logfile.txt\nwhoami.exe %*\n</code></pre>\n\n<p>With the caveat that you can have problems if the parameters contain spaces (and you passed the in escaping with \"), because the command-line parser basically de-escapes them and they should be re-escaped before passed to an other executable.</p>\n"
},
{
"answer_id": 114356,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "<p>If you can reproduce the crash, use Process Explorer before crashed process is terminated to see its command line.</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx</a></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257098/"
]
| I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails.
Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process?
Say the command is used like this:
'whoami.exe /all'
I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process. | From a batch file:
```
echo Parameters: %* >> logfile.txt
whoami.exe %*
```
With the caveat that you can have problems if the parameters contain spaces (and you passed the in escaping with "), because the command-line parser basically de-escapes them and they should be re-escaped before passed to an other executable. |
114,179 | <p>I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable.</p>
<p>I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object).</p>
<p>Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable.</p>
<p>I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well?</p>
<p>Here is the class stripped down:</p>
<pre><code>internal sealed class SektionCache : CacheBase
{
public static readonly SektionCache Instance = new SektionCache();
private static readonly object lockObject = new object();
private static bool isUpdating;
private IEnumerable<Sektion> sektioner;
static SektionCache()
{
UpdateCache();
}
public IEnumerable<Sektion> Sektioner
{
get { return sektioner; }
}
public static void UpdateCache()
{
// SNIP - getting data, locking etc.
Instance.sektioner = newSektioner;
// SNIP
}
}
</code></pre>
| [
{
"answer_id": 114193,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "<p>Since the getter <code>{ return sektioner; }</code> is called before the new value is put in the field, the old value is returned. Then, the loop <code>foreach (Sektion s in cache.Sektioner)</code> uses the value that was received when the getter was called, i.e. the old value. That value will be used throughout the foreach loop. </p>\n"
},
{
"answer_id": 114201,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>First of all I can't see object locking, unused lockObject variable makes me sad. IEnumerable is not special. Each thread will have it's own copy of reference to some instance of sektioner object. You can't affect other threads that way. What would happen with old version of data pointed by sektioner field largely depends on calling party.</p>\n"
},
{
"answer_id": 114206,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": true,
"text": "<p>The thread which is currently enumerating sektioner will continue to enumerate it even when you update the reference within the singleton. There is nothing special about objects which implement IEnumerable.</p>\n\n<p>You should perhaps add the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile\" rel=\"nofollow noreferrer\">volatile</a> keyword to the sektioner field as you are not providing read-locking and multiple threads are reading/writing it.</p>\n"
},
{
"answer_id": 114462,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>I think, if you want a thread safety, you should use this way:</p>\n\n<pre><code>internal sealed class SektionCache : CacheBase\n{\n //public static readonly SektionCache Instance = new SektionCache();\n\n // this template is better ( safer ) than the previous one, for thread-safe singleton patter >>>\n private static SektionCache defaultInstance;\n private static object readonly lockObject = new object();\n public static SektionCach Default {\n get {\n SektionCach result = defaultInstance;\n if ( null == result ) {\n lock( lockObject ) {\n if ( null == result ) {\n defaultInstance = result = new SektionCache();\n }\n }\n }\n\n return result;\n }\n }\n // <<< this template is better ( safer ) than the previous one\n\n //private static readonly object lockObject = new object();\n //private static bool isUpdating;\n //private IEnumerable<Sektion> sektioner;\n\n // this declaration is enough\n private volatile IEnumerable<Sektion> sektioner;\n\n // no static constructor is required >>>\n //static SektionCache()\n //{\n // UpdateCache();\n //}\n // <<< no static constructor is required\n\n // I think, you can use getter and setter for reading & changing a collection\n public IEnumerable<Sektion> Sektioner {\n get {\n IEnumerable<Sektion> result = this.sektioner;\n // i don't know, if you need this functionality >>>\n // if ( null == result ) { result = new Sektion[0]; }\n // <<< i don't know, if you need this functionality\n return result;\n }\n set { this.sektion = value; }\n }\n\n //public static void UpdateCache()\n //{\n //// SNIP - getting data, locking etc.\n //Instance.sektioner = newSektioner;\n //// SNIP\n //}\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
]
| I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable.
I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object).
Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable.
I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well?
Here is the class stripped down:
```
internal sealed class SektionCache : CacheBase
{
public static readonly SektionCache Instance = new SektionCache();
private static readonly object lockObject = new object();
private static bool isUpdating;
private IEnumerable<Sektion> sektioner;
static SektionCache()
{
UpdateCache();
}
public IEnumerable<Sektion> Sektioner
{
get { return sektioner; }
}
public static void UpdateCache()
{
// SNIP - getting data, locking etc.
Instance.sektioner = newSektioner;
// SNIP
}
}
``` | The thread which is currently enumerating sektioner will continue to enumerate it even when you update the reference within the singleton. There is nothing special about objects which implement IEnumerable.
You should perhaps add the [volatile](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile) keyword to the sektioner field as you are not providing read-locking and multiple threads are reading/writing it. |
114,180 | <p>What would be better practice when giving a function the original variable to work with:</p>
<pre><code>unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
</code></pre>
<p>or:</p>
<pre><code>void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
</code></pre>
<p>IOW: Is there any reason to pick one over another?</p>
| [
{
"answer_id": 114189,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 9,
"selected": true,
"text": "<p>My rule of thumb is:</p>\n\n<p>Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.</p>\n\n<p>Use references otherwise.</p>\n"
},
{
"answer_id": 114351,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 6,
"selected": false,
"text": "<p>I really think you will benefit from establishing the following function calling coding guidelines:</p>\n\n<ol>\n<li><p>As in all other places, always be <code>const</code>-correct.</p>\n\n<ul>\n<li>Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the <code>const</code> specifier.</li>\n</ul></li>\n<li><p>Only pass a value by pointer if the value 0/NULL is a valid input in the current context.</p>\n\n<ul>\n<li><p>Rationale 1: As <strong>a caller</strong>, you see that whatever you pass in <em>must be</em> in a usable state.</p></li>\n<li><p>Rationale 2: As <strong>called</strong>, you know that whatever comes in <em>is</em> in a usable state. Hence, no NULL-check or error handling needs to be done for that value.</p></li>\n<li><p>Rationale 3: Rationales 1 and 2 will be <em>compiler enforced</em>. Always catch errors at compile time if you can.</p></li>\n</ul></li>\n<li><p>If a function argument is an out-value, then pass it by reference.</p>\n\n<ul>\n<li>Rationale: We don't want to break item 2...</li>\n</ul></li>\n<li><p>Choose \"pass by value\" over \"pass by const reference\" only if the value is a POD (<a href=\"https://stackoverflow.com/questions/146452/what-are-pod-types-in-c\">Plain old Datastructure</a>) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.</p>\n\n<ul>\n<li>Rationale: Avoid unnecessary copies.</li>\n<li>Note: <em>small enough</em> and <em>cheap enough</em> are not absolute measurables.</li>\n</ul></li>\n</ol>\n"
},
{
"answer_id": 114380,
"author": "NotJarvis",
"author_id": 16268,
"author_profile": "https://Stackoverflow.com/users/16268",
"pm_score": 2,
"selected": false,
"text": "<p>Pass by const reference unless there is a reason you wish to change/keep the contents you are passing in.</p>\n\n<p>This will be the most efficient method in most cases.</p>\n\n<p>Make sure you use const on each parameter you do not wish to change, as this not only protects you from doing something stupid in the function, it gives a good indication to other users what the function does to the passed in values. This includes making a pointer const when you only want to change whats pointed to...</p>\n"
},
{
"answer_id": 114769,
"author": "Aaron N. Tubbs",
"author_id": 4810,
"author_profile": "https://Stackoverflow.com/users/4810",
"pm_score": 5,
"selected": false,
"text": "<p>This ultimately ends up being subjective. The discussion thus far is useful, but I don't think there is a correct or decisive answer to this. A lot will depend on style guidelines and your needs at the time.</p>\n\n<p>While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (<a href=\"https://google.github.io/styleguide/cppguide.html#Reference_Arguments\" rel=\"noreferrer\">https://google.github.io/styleguide/cppguide.html#Reference_Arguments</a>), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.</p>\n"
},
{
"answer_id": 115486,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A reference is an implicit pointer. Basically you can change the value the reference points to but you can't change the reference to point to something else. So my 2 cents is that if you only want to change the value of a parameter pass it as a reference but if you need to change the parameter to point to a different object pass it using a pointer.</p>\n"
},
{
"answer_id": 115518,
"author": "Max Caceres",
"author_id": 4842,
"author_profile": "https://Stackoverflow.com/users/4842",
"pm_score": 3,
"selected": false,
"text": "<p>You should pass a pointer if you are going to modify the value of the variable.\nEven though technically passing a reference or a pointer are the same, passing a pointer in your use case is more readable as it \"advertises\" the fact that the value will be changed by the function.</p>\n"
},
{
"answer_id": 213963,
"author": "Kiley Hykawy",
"author_id": 22727,
"author_profile": "https://Stackoverflow.com/users/22727",
"pm_score": 3,
"selected": false,
"text": "<p>If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.</p>\n\n<p>A better solution in most cases (from a safety perspective) is to use <a href=\"http://www.boost.org/doc/libs/1_35_0/libs/optional/doc/html/index.html\" rel=\"noreferrer\">boost::optional</a>. This allows you to pass in optional values by reference and also as a return value.</p>\n\n<pre><code>// Sample method using optional as input parameter\nvoid PrintOptional(const boost::optional<std::string>& optional_str)\n{\n if (optional_str)\n {\n cout << *optional_str << std::endl;\n }\n else\n {\n cout << \"(no string)\" << std::endl;\n }\n}\n\n// Sample method using optional as return value\nboost::optional<int> ReturnOptional(bool return_nothing)\n{\n if (return_nothing)\n {\n return boost::optional<int>();\n }\n\n return boost::optional<int>(42);\n}\n</code></pre>\n"
},
{
"answer_id": 214034,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "<p>Consider C#'s out keyword. The compiler requires the caller of a method to apply the out keyword to any out args, even though it knows already if they are. This is intended to enhance readability. Although with modern IDEs I'm inclined to think that this is a job for syntax (or semantic) highlighting.</p>\n"
},
{
"answer_id": 5159043,
"author": "RezaPlusPlus",
"author_id": 505589,
"author_profile": "https://Stackoverflow.com/users/505589",
"pm_score": 3,
"selected": false,
"text": "<p>Use a reference when you can, use a pointer when you have to.\nFrom <a href=\"https://isocpp.org/wiki/faq/references#pointers-and-references\" rel=\"nofollow\">C++ FAQ: \"When should I use references, and when should I use pointers?\"</a></p>\n"
},
{
"answer_id": 19659142,
"author": "Germán Diago",
"author_id": 429879,
"author_profile": "https://Stackoverflow.com/users/429879",
"pm_score": 2,
"selected": false,
"text": "<p>Pointers:</p>\n\n<ul>\n<li>Can be assigned <code>nullptr</code> (or <code>NULL</code>).</li>\n<li>At the call site, you must use <code>&</code> if your type is not a pointer itself,\nmaking explicitly you are modifying your object.</li>\n<li>Pointers can be rebound.</li>\n</ul>\n\n<p>References:</p>\n\n<ul>\n<li>Cannot be null.</li>\n<li>Once bound, cannot change.</li>\n<li>Callers don't need to explicitly use <code>&</code>. This is considered sometimes\nbad because you must go to the implementation of the function to see if\nyour parameter is modified. </li>\n</ul>\n"
},
{
"answer_id": 49256541,
"author": "Saurabh Raoot",
"author_id": 2519258,
"author_profile": "https://Stackoverflow.com/users/2519258",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Pointers</strong></p>\n\n<ul>\n<li>A pointer is a variable that holds a memory address. </li>\n<li>A pointer declaration consists of a base type, an *, and the variable name.</li>\n<li>A pointer can point to any number of variables in lifetime</li>\n<li><p>A pointer that does not currently point to a valid memory location is given the value null (Which is zero)</p>\n\n<pre><code>BaseType* ptrBaseType;\nBaseType objBaseType;\nptrBaseType = &objBaseType;\n</code></pre></li>\n<li><p>The & is a unary operator that returns the memory address of its operand.</p></li>\n<li><p>Dereferencing operator (*) is used to access the value stored in the variable which pointer points to.</p>\n\n<pre><code> int nVar = 7;\n int* ptrVar = &nVar;\n int nVar2 = *ptrVar;\n</code></pre></li>\n</ul>\n\n<p><strong>Reference</strong></p>\n\n<ul>\n<li><p>A reference (&) is like an alias to an existing variable. </p></li>\n<li><p>A reference (&) is like a constant pointer that is automatically dereferenced.</p></li>\n<li><p>It is usually used for function argument lists and function return values.</p></li>\n<li><p>A reference must be initialized when it is created.</p></li>\n<li><p>Once a reference is initialized to an object, it cannot be changed to refer to another object.</p></li>\n<li><p>You cannot have NULL references.</p></li>\n<li><p>A const reference can refer to a const int. It is done with a temporary variable with value of the const</p>\n\n<pre><code>int i = 3; //integer declaration\nint * pi = &i; //pi points to the integer i\nint& ri = i; //ri is refers to integer i – creation of reference and initialization\n</code></pre></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/eWoBz.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eWoBz.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/nhMdc.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nhMdc.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 55869842,
"author": "amirfg",
"author_id": 9087376,
"author_profile": "https://Stackoverflow.com/users/9087376",
"pm_score": 0,
"selected": false,
"text": "<p>A reference is similar to a pointer, except that you don’t need to use a prefix ∗ to access the value referred to by the reference. Also, a reference cannot be made to refer to a different object after its initialization.</p>\n\n<p>References are particularly useful for specifying function arguments.</p>\n\n<p>for more information see \"A Tour of C++\" by \"Bjarne Stroustrup\" (2014) Pages 11-12</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20349/"
]
| What would be better practice when giving a function the original variable to work with:
```
unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
```
or:
```
void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
```
IOW: Is there any reason to pick one over another? | My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise. |
114,204 | <p>I've set up DAV in apache2, which works great. The thing is, all read/write operations are done with the apache user's credentials. Instead I want to use the HTTP authenticated user's credentials. If I authenticate as "john", all read and write operations should use the system user john's credentials (from /etc/passwd). <a href="http://httpd.apache.org/docs/2.2/suexec.html" rel="nofollow noreferrer">suEXEC</a> seems like overkill since I am not executing anything, but I might be wrong...</p>
<p>Here's the current configuration:</p>
<pre><code><VirtualHost *:80>
DocumentRoot /var/www/webdav
ServerName webdav.mydomain.com
ServerAdmin [email protected]
<Location "/">
DAV On
AuthType Basic
AuthName "WebDAV Restricted"
AuthUserFile /etc/apache2/extra/webdav-passwords
require valid-user
Options +Indexes
</Location>
DAVLockDB /var/lib/dav/lockdb
ErrorLog /var/log/apache2/webdav-error.log
TransferLog /var/log/apache2/webdav-access.log
</VirtualHost>
</code></pre>
| [
{
"answer_id": 114275,
"author": "niXar",
"author_id": 19979,
"author_profile": "https://Stackoverflow.com/users/19979",
"pm_score": 2,
"selected": false,
"text": "<p>Shot answer, and as far as I know: you don't.</p>\n<p>Long answer: it is possible to implement such a feature with an appropriate mpm, and there were <a href=\"http://httpd.apache.org/docs/2.0/mod/perchild.html\" rel=\"nofollow noreferrer\">various</a> <a href=\"http://www.telana.com/peruser.php\" rel=\"nofollow noreferrer\">attempts</a> to do so, but they don't seem to be very actively supported, and are at least not in the mainline Apache codebase.</p>\n<p>peruser:</p>\n<blockquote>\n<p>Q. Is peruser ready for production use?</p>\n<p>A. In general, no.</p>\n</blockquote>\n<p>perchild:</p>\n<blockquote>\n<p>This module is not functional. Development of this module is not complete and is not currently active. Do not use perchild unless you are a programmer willing to help fix it.</p>\n</blockquote>\n<p>That's too bad, really; most uses of WebDav I've seen store ownership information at the application layer, in the database, anyway. The consensus for doing file sharing is to use Samba instead; and that's not really a solution, I admit.</p>\n"
},
{
"answer_id": 1111598,
"author": "Mark Porter",
"author_id": 29462,
"author_profile": "https://Stackoverflow.com/users/29462",
"pm_score": 2,
"selected": true,
"text": "<p>We have been using davenport (<a href=\"http://davenport.sourceforge.net/\" rel=\"nofollow noreferrer\">http://davenport.sourceforge.net/</a>) for years to provide access to Windows/samba shares over webdav. Samba/Windows gives a lot of control over this sort of thing, and the Davenport just makes it usable over the web over SSL without a VPN</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13365/"
]
| I've set up DAV in apache2, which works great. The thing is, all read/write operations are done with the apache user's credentials. Instead I want to use the HTTP authenticated user's credentials. If I authenticate as "john", all read and write operations should use the system user john's credentials (from /etc/passwd). [suEXEC](http://httpd.apache.org/docs/2.2/suexec.html) seems like overkill since I am not executing anything, but I might be wrong...
Here's the current configuration:
```
<VirtualHost *:80>
DocumentRoot /var/www/webdav
ServerName webdav.mydomain.com
ServerAdmin [email protected]
<Location "/">
DAV On
AuthType Basic
AuthName "WebDAV Restricted"
AuthUserFile /etc/apache2/extra/webdav-passwords
require valid-user
Options +Indexes
</Location>
DAVLockDB /var/lib/dav/lockdb
ErrorLog /var/log/apache2/webdav-error.log
TransferLog /var/log/apache2/webdav-access.log
</VirtualHost>
``` | We have been using davenport (<http://davenport.sourceforge.net/>) for years to provide access to Windows/samba shares over webdav. Samba/Windows gives a lot of control over this sort of thing, and the Davenport just makes it usable over the web over SSL without a VPN |
114,208 | <p>Let me explain:
this is path to this folder: > <code>www.my_site.com/images</code></p>
<p>And images are created by <code>user_id</code>, and for example, images of <code>user_id = 27</code> are,
<code>27_1.jpg</code>, <code>27_2.jpg</code>, <code>27_3.jpg</code>!
How to list and print images which start with <code>27_%.jpg</code>?
I hope You have understood me!
PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information</p>
<p>Here starts my loop</p>
<pre><code>while dbread.Read()
'and then id user_id
dbread('user_id')
</code></pre>
<p>NEXT???</p>
<hr>
<p>I nedd to create XML, till now I created like this:</p>
<p>act.WriteLine("")
act.WriteLine("<a href="http://www.my_site.com/images/" rel="nofollow noreferrer">http://www.my_site.com/images/</a>"&dbread("user_id")&"_1.jpg")
act.WriteLine("")</p>
<p>But this is not answer because I need to create this nodes how many images of this user exist?</p>
<p>In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site)</p>
<p>Do you understand me?</p>
| [
{
"answer_id": 114231,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": true,
"text": "<p>Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment. </p>\n\n<p>Possible Fixes:</p>\n\n<ul>\n<li>log out/log in, then start apache</li>\n<li>source the file: <code># . /etc/profile.d/foo.sh</code>, then restart apache</li>\n<li>source the file in the apache init script</li>\n</ul>\n\n<p>You also need to make sure that <code>/etc/profile.d/</code> is sourced when Apache is started by <code>init</code> rather than yourself. </p>\n\n<p>The best fix might also depend on the distribution you are using, because they use different schemes for configuration.</p>\n"
},
{
"answer_id": 115760,
"author": "niXar",
"author_id": 19979,
"author_profile": "https://Stackoverflow.com/users/19979",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_env.html#setenv\" rel=\"nofollow noreferrer\">SetEnv</a> in your config files (/etc/httpd/conf.d/*.conf, .htaccess ...). Additionally you should be able to define them in /etc/sysconfig/httpd (on RPM-based distribs) and <em>export</em> them (note: not tested).</p>\n\n<p>Note: it wouldn't surprise me if some distributions tried quite hard to hide as much as possible, as far as system config is concerned, from a publically accessible service such as Apache. And if they don't, they might start doing this in a future version. Hence I advise you to do this explicitly. If you need to share such a setting between Apache and your shells, you could try sourcing <em>/etc/profile.d/yourprofile.sh</em> from <em>/etc/sysconfig/httpd</em></p>\n"
},
{
"answer_id": 128897,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "<p>Apache config files allow you to set environment variables on a per site basis.<br></p>\n\n<p>So if your web server is serving pages from two logical sites you can have the same environment variable set differently for each site and thus get your PHP to react differently.</p>\n\n<p>See the <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_env.html\" rel=\"nofollow noreferrer\">Apache mod_env</a> for details:</p>\n"
},
{
"answer_id": 26251452,
"author": "Don Grem",
"author_id": 468282,
"author_profile": "https://Stackoverflow.com/users/468282",
"pm_score": 0,
"selected": false,
"text": "<p>If you need env vars for Apache only, what worked for me was editing the <code>/etc/apache2/envvars</code> and restart of Apache. I added these settings:</p>\n\n<pre><code>export LANG='en_US.UTF-8'\nexport LC_ALL='en_US.UTF-8'\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205368/"
]
| Let me explain:
this is path to this folder: > `www.my_site.com/images`
And images are created by `user_id`, and for example, images of `user_id = 27` are,
`27_1.jpg`, `27_2.jpg`, `27_3.jpg`!
How to list and print images which start with `27_%.jpg`?
I hope You have understood me!
PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information
Here starts my loop
```
while dbread.Read()
'and then id user_id
dbread('user_id')
```
NEXT???
---
I nedd to create XML, till now I created like this:
act.WriteLine("")
act.WriteLine("<http://www.my_site.com/images/>"&dbread("user\_id")&"\_1.jpg")
act.WriteLine("")
But this is not answer because I need to create this nodes how many images of this user exist?
In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site)
Do you understand me? | Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment.
Possible Fixes:
* log out/log in, then start apache
* source the file: `# . /etc/profile.d/foo.sh`, then restart apache
* source the file in the apache init script
You also need to make sure that `/etc/profile.d/` is sourced when Apache is started by `init` rather than yourself.
The best fix might also depend on the distribution you are using, because they use different schemes for configuration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.