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
|
---|---|---|---|---|---|---|
104,952 | <p>I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests:</p>
<ol>
<li>See how much of my referenced code under test is getting executed</li>
<li>See how many methods of my code under test (if any) are not unit tested at all</li>
</ol>
<p>Setting up the VSTS code coverage tool (see the <a href="https://blogs.msdn.com/ms_joc/articles/406608.aspx" rel="nofollow noreferrer" title="MSDN Code Coverage Blog">link text</a>) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. </p>
<pre><code>class CodeCoverageTarget
{
public:
std::string ThisMethodRuns() {
return "Running";
}
std::string ThisMethodDoesNotRun() {
return "Not Running";
}
};
#include <iostream>
#include "CodeCoverageTarget.h"
using namespace std;
int main()
{
CodeCoverageTarget cct;
cout<<cct.ThisMethodRuns()<<endl;
}
</code></pre>
<p>When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? </p>
<p>Thanks in advance,
KGB</p>
| [
{
"answer_id": 104974,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>Turn off inlining of functions. The easiest way to do this is to just compile in Debug mode.</p>\n\n<p><strong>Edit:</strong> after seeing your clarification, I find my answer is in error. Perhaps if you moved the body of the function into another section of the .h file, using the \"inline\" keyword?</p>\n"
},
{
"answer_id": 105070,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry I should have clarified that I am building debug mode with inlining and all optimization off. Besides, the code is getting removed before inlining even occurs since it's never referenced to even be considered for inlining.</p>\n"
},
{
"answer_id": 105238,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>You could try adding a line of code to call the function only if some condition is true, and guarantee that that condition will never be true. Just make sure the compiler can't figure that out. For example,</p>\n\n<pre><code>\nint main(int argc, char **argv)\n{\n if(argv == NULL) // C runtime says this won't happen\n someMethodWhichIsntReallyEverCalled();\n}\n</code></pre>\n"
},
{
"answer_id": 105458,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to switch between inline and non inline functions based on your build, using .inl files, like this:</p>\n\n<p>in foo.inl file:</p>\n\n<pre><code>inline std::string Foo::ThisMethodDoesNotRun()\n{\n return \"Not Running\";\n}\n</code></pre>\n\n<p>in foo.h:</p>\n\n<pre><code>#if !COVERAGE_BUILD\n#include \"foo.inl\"\n#endif\n</code></pre>\n\n<p>in foo.cpp:</p>\n\n<pre><code>#if COVERAGE_BUILD\n#define inline\n#include \"foo.inl\"\n#endif\n</code></pre>\n"
},
{
"answer_id": 107444,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "<p>One way to ensure your functions are not discarded is to export them. You can do this by adding <a href=\"http://msdn.microsoft.com/en-us/library/3y1sfaz2(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>__declspec(dllexport)</code></a> to your function declarations. It is best to wrap this in a C preprocessor macro so that you can turn it off, since it is compiler-specific and you might not want all of your builds to export symbols. Another way to export functions is to create a <a href=\"http://msdn.microsoft.com/en-us/library/d91k01sh(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>.DEF</code> file</a>.</p>\n\n<p>If inlining is the problem, you might also have success with <a href=\"http://msdn.microsoft.com/en-us/library/kxybs02x(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>__declspec(noinline)</code></a>.</p>\n\n<p>Is your code in a static library which is then compiled into a test EXE/DLL? The linker will automatically discard unreferenced object files that are in static libraries. Example: if the static library contains <code>a.obj</code> and <code>b.obj</code> and the EXE/DLL that you're linking it into references symbols from <code>b.obj</code> but not <code>a.obj</code>, then the contents of <code>a.obj</code> will not be linked into the executable or DLL. However, after re-reading your description it doesn't sound like that's what's happening here.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests:
1. See how much of my referenced code under test is getting executed
2. See how many methods of my code under test (if any) are not unit tested at all
Setting up the VSTS code coverage tool (see the [link text](https://blogs.msdn.com/ms_joc/articles/406608.aspx "MSDN Code Coverage Blog")) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code.
```
class CodeCoverageTarget
{
public:
std::string ThisMethodRuns() {
return "Running";
}
std::string ThisMethodDoesNotRun() {
return "Not Running";
}
};
#include <iostream>
#include "CodeCoverageTarget.h"
using namespace std;
int main()
{
CodeCoverageTarget cct;
cout<<cct.ThisMethodRuns()<<endl;
}
```
When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool?
Thanks in advance,
KGB | You could try adding a line of code to call the function only if some condition is true, and guarantee that that condition will never be true. Just make sure the compiler can't figure that out. For example,
```
int main(int argc, char **argv)
{
if(argv == NULL) // C runtime says this won't happen
someMethodWhichIsntReallyEverCalled();
}
``` |
104,953 | <p>I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using <code>DIVs</code> with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph.</p>
<p>In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property <code>float: left</code>. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated.</p>
<p>I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's:</p>
<ol>
<li>Cross-browser (ideally without too many browser hacks)</li>
<li>Runs in Quirks mode</li>
<li>As clear/clean as possible, to facilitate customizations</li>
<li>Done without JavaScript if possible.</li>
</ol>
| [
{
"answer_id": 104965,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 4,
"selected": false,
"text": "<p>You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div.parent{\n position: relative;\n left: 0px; /* stick it wherever it was positioned by default */\n top: 0px;\n}\n\ndiv.child{\n position: absolute;\n left: 10px;\n top: 10px;\n}\n</code></pre>\n"
},
{
"answer_id": 104981,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>Absolute positioning positions an element relative to its nearest positioned ancestor. So put <code>position: relative</code> on the container, then for child elements, <code>top</code> and <code>left</code> will be relative to the top-left of the container so long as the child elements have <code>position: absolute</code>. More information is available in <a href=\"http://www.w3.org/TR/CSS21/visuren.html#comp-abspos\" rel=\"nofollow noreferrer\">the CSS 2.1 specification</a>.</p>\n"
},
{
"answer_id": 105035,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 10,
"selected": true,
"text": "<p>You are right that CSS positioning is the way to go. Here's a quick run down:</p>\n\n<p><code>position: relative</code> will layout an element relative to <em>itself.</em> In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).</p>\n\n<p>However, you're most likely interested in <code>position: absolute</code> which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has <code>position: relative</code> or <code>position: absolute</code> set on it, then it will act as the parent for positioning coordinates for its children.</p>\n\n<p>To demonstrate:</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>#container {\r\n position: relative;\r\n border: 1px solid red;\r\n height: 100px;\r\n}\r\n\r\n#box {\r\n position: absolute;\r\n top: 50px;\r\n left: 20px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"container\">\r\n <div id=\"box\">absolute</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In that example, the top left corner of <code>#box</code> would be 100px down and 50px left of the top left corner of <code>#container</code>. If <code>#container</code> did not have <code>position: relative</code> set, the coordinates of <code>#box</code> would be relative to the top left corner of the browser view port.</p>\n"
},
{
"answer_id": 44819597,
"author": "yusufshakeel",
"author_id": 4441708,
"author_profile": "https://Stackoverflow.com/users/4441708",
"pm_score": 4,
"selected": false,
"text": "<p>I know I am late but hope this helps.</p>\n\n<p>Following are the values for the position property.</p>\n\n<ul>\n<li>static</li>\n<li>fixed</li>\n<li>relative</li>\n<li>absolute</li>\n</ul>\n\n<p><strong>position : static</strong></p>\n\n<p>This is default. It means the element will occur at a position that it normally would.</p>\n\n<pre><code>#myelem {\n position : static;\n}\n</code></pre>\n\n<p><strong>position : fixed</strong></p>\n\n<p>This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls.</p>\n\n<p>(Ideal if you want scroll-to-top button at the bottom right corner of the page).</p>\n\n<pre><code>#myelem {\n position : fixed;\n bottom : 30px;\n right : 30px;\n}\n</code></pre>\n\n<p><strong>position : relative</strong></p>\n\n<p>To place an element at a new location relative to its original position.</p>\n\n<pre><code>#myelem {\n position : relative;\n left : 30px;\n top : 30px;\n}\n</code></pre>\n\n<p>The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location.</p>\n\n<p><strong>position : absolute</strong></p>\n\n<p>If we want an element to be placed at an exact position in the page.</p>\n\n<pre><code>#myelem {\n position : absolute;\n top : 30px;\n left : 300px;\n}\n</code></pre>\n\n<p>The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page.</p>\n\n<p>And finally...</p>\n\n<p><strong>position relative + absolute</strong></p>\n\n<p>We can set the position property of a parent element to <em>relative</em> and then set the position property of the child element to <em>absolute</em>. This way we can position the child relative to the parent at an absolute position.</p>\n\n<pre><code>#container {\n position : relative;\n}\n\n#div-2 {\n position : absolute;\n top : 0;\n right : 0;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/NgOYQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NgOYQ.png\" alt=\"Absolute position of a child element w.r.t. a Relative positioned parent element.\"></a></p>\n\n<p>We can see in the above image the <strong>#div-2</strong> element is positioned at the top-right corner inside the <strong>#container</strong> element.</p>\n\n<p>GitHub: You can find the HTML of the above image <a href=\"https://github.com/yusufshakeel/css-project/blob/master/position.html\" rel=\"noreferrer\">here</a> and CSS <a href=\"https://github.com/yusufshakeel/css-project/blob/master/css/position.css\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Hope this <a href=\"https://www.dyclassroom.com/css/css-position\" rel=\"noreferrer\">tutorial</a> helps.</p>\n"
},
{
"answer_id": 50373390,
"author": "Nesha Zoric",
"author_id": 1660318,
"author_profile": "https://Stackoverflow.com/users/1660318",
"pm_score": 1,
"selected": false,
"text": "<p>If you need to position an element relative to its containing element first you need to add <code>position: relative</code> <strong>to the container element</strong>. The child element you want to position relatively to the parent <strong>has to have</strong> <code>position: absolute</code>. The way that absolute positioning works is that <strong>it is done relative to the first relatively (or absolutely) positioned parent element</strong>. In case there is <strong>no relatively</strong> positioned parent, the element will be positioned relative to the <strong>root element</strong> (directly to the HTML element).</p>\n\n<p>So if you want to position your child element to the top left of the parent container, you should do this:</p>\n\n<pre><code>.parent {\n position: relative;\n} \n\n.child {\n position: absolute;\n top: 0;\n left: 0; \n}\n</code></pre>\n\n<p>You will benefit greatly from reading <a href=\"https://kolosek.com/css-position-relative-vs-position-absolute/\" rel=\"nofollow noreferrer\">this article</a>. Hope this helps!</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
]
| I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using `DIVs` with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph.
In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property `float: left`. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated.
I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's:
1. Cross-browser (ideally without too many browser hacks)
2. Runs in Quirks mode
3. As clear/clean as possible, to facilitate customizations
4. Done without JavaScript if possible. | You are right that CSS positioning is the way to go. Here's a quick run down:
`position: relative` will layout an element relative to *itself.* In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).
However, you're most likely interested in `position: absolute` which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has `position: relative` or `position: absolute` set on it, then it will act as the parent for positioning coordinates for its children.
To demonstrate:
```css
#container {
position: relative;
border: 1px solid red;
height: 100px;
}
#box {
position: absolute;
top: 50px;
left: 20px;
}
```
```html
<div id="container">
<div id="box">absolute</div>
</div>
```
In that example, the top left corner of `#box` would be 100px down and 50px left of the top left corner of `#container`. If `#container` did not have `position: relative` set, the coordinates of `#box` would be relative to the top left corner of the browser view port. |
104,967 | <p>As a pet-project, I'd like to attempt to implement a basic language of my own design that can be used as a web-scripting language. It's trivial to run a C++ program as an Apache CGI, so the real work lies in how to parse an input file containing non-code (HTML/CSS markup) and server-side code.</p>
<p>In my undergrad compiler course, we used <a href="http://www.gnu.org/software/flex/" rel="nofollow noreferrer">Flex</a> and <a href="http://www.gnu.org/software/bison/" rel="nofollow noreferrer">Bison</a> to generate a scanner and a parser for a simple language. We were given a copy of the grammar and wrote a parser that translated the simple language to a simple assembly for a virtual machine. The flex scanner tokenizes the input, and passes the tokens to the Bison parser.</p>
<p>The difference between that and what I'd like to do is that like PHP, this language could have plain HTML markup and the scripting language interspersed like the following:</p>
<pre><code><p>Hello,
<? echo "World ?>
</p>
</code></pre>
<p>Am I incorrect in assuming that it would be efficient to parse the input file as follows:</p>
<ol>
<li>Scan input until a script start tag is found ('
<li>Second scanner tokenizes the server-side script section of the input file (from the open tag: '') and passes the token to the parser, which has no need to know about the markup in the file.</li>
<li>Control is returned to the first scanner that continues this general pattern.</li>
</ol>
<p>Basically, the first scanner only differentiates between Markup (which is returned directly to the browser unmodified) and code, which is passed to the second scanner, which in turn tokenizes the code and passes the tokens to the parser. </p>
<p>If this is <em>not</em> a solid design pattern, how do languages such as PHP handle scanning input and parsing code efficiently?</p>
| [
{
"answer_id": 105082,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 2,
"selected": false,
"text": "<p>PHP doesn't differentiate between the scanning and the Markup. It simply outputs to buffer when in Markup mode, and then switches to parsing when in code mode. You don't need a two pass scanner, and you can do this with just a single flex lexer. </p>\n\n<p>If you are interested in how PHP itself works, download the source (try the PHP4 source it is a lot easier to understand). What you want to look at is in the Zend Directory, <code>zend_language_scanner.l</code>. </p>\n\n<p>Having written something similar myself, I would really recommend rethinking going the Flex and Bison route, and go with something modern like <a href=\"http://www.antlr.org/\" rel=\"nofollow noreferrer\">Antlr</a>. It is a lot easier, easier to understand (the macros employed in a lex grammar get very confusing and hard to read) and it has a built in debugger (<a href=\"http://www.antlr.org/works/index.html\" rel=\"nofollow noreferrer\">AntlrWorks</a>) so you don't have to spend hours looking at 3 Meg debug files. It also supports many languages (Java, c#, C, Python, Actionscript) and has an excellent book and a very good website that should be able to get you up and running in no time.</p>\n"
},
{
"answer_id": 111218,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 4,
"selected": true,
"text": "<p>You want to look at start conditions. For example:</p>\n\n<pre><code>\"<?\" { BEGIN (PHP); }\n<PHP>[a-zA-Z]* { return PHP_TOKEN; }\n<PHP>\">?\" { BEGIN (0); }\n[a-zA-Z]* { return HTML_TOKEN; }\n</code></pre>\n\n<p>You start off in state 0, use the BEGIN macro to change states.\nTo match a RE only while in a particular state, prefix the RE with the state name surrounded by angle-brackets.</p>\n\n<p>In the example above, \"PHP\" is state. \"PHP_TOKEN\" and \"HTML_TOKEN\" are _%token_s defined by your yacc file.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8636/"
]
| As a pet-project, I'd like to attempt to implement a basic language of my own design that can be used as a web-scripting language. It's trivial to run a C++ program as an Apache CGI, so the real work lies in how to parse an input file containing non-code (HTML/CSS markup) and server-side code.
In my undergrad compiler course, we used [Flex](http://www.gnu.org/software/flex/) and [Bison](http://www.gnu.org/software/bison/) to generate a scanner and a parser for a simple language. We were given a copy of the grammar and wrote a parser that translated the simple language to a simple assembly for a virtual machine. The flex scanner tokenizes the input, and passes the tokens to the Bison parser.
The difference between that and what I'd like to do is that like PHP, this language could have plain HTML markup and the scripting language interspersed like the following:
```
<p>Hello,
<? echo "World ?>
</p>
```
Am I incorrect in assuming that it would be efficient to parse the input file as follows:
1. Scan input until a script start tag is found ('
- Second scanner tokenizes the server-side script section of the input file (from the open tag: '') and passes the token to the parser, which has no need to know about the markup in the file.
- Control is returned to the first scanner that continues this general pattern.
Basically, the first scanner only differentiates between Markup (which is returned directly to the browser unmodified) and code, which is passed to the second scanner, which in turn tokenizes the code and passes the tokens to the parser.
If this is *not* a solid design pattern, how do languages such as PHP handle scanning input and parsing code efficiently? | You want to look at start conditions. For example:
```
"<?" { BEGIN (PHP); }
<PHP>[a-zA-Z]* { return PHP_TOKEN; }
<PHP>">?" { BEGIN (0); }
[a-zA-Z]* { return HTML_TOKEN; }
```
You start off in state 0, use the BEGIN macro to change states.
To match a RE only while in a particular state, prefix the RE with the state name surrounded by angle-brackets.
In the example above, "PHP" is state. "PHP\_TOKEN" and "HTML\_TOKEN" are \_%token\_s defined by your yacc file. |
104,971 | <p>I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?</p>
| [
{
"answer_id": 104984,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT * FROM [MyTable] WHERE [Date] IN\n(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n HAVING COUNT(*) < @Max\n)\n</code></pre>\n\n<p>See @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot.</p>\n"
},
{
"answer_id": 104991,
"author": "Ihar Bury",
"author_id": 18001,
"author_profile": "https://Stackoverflow.com/users/18001",
"pm_score": 2,
"selected": false,
"text": "<p>Use the COUNT aggregate:</p>\n\n<pre><code>SELECT Date\nFROM SomeTable\nGROUP BY Date\nHAVING COUNT(*) < @k\n</code></pre>\n"
},
{
"answer_id": 104992,
"author": "Das",
"author_id": 17585,
"author_profile": "https://Stackoverflow.com/users/17585",
"pm_score": 2,
"selected": false,
"text": "<p>For \"appears x times\" queries it is best to use HAVING clause. In your case, query can be like:</p>\n\n<pre><code>SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k\n</code></pre>\n\n<p>or, in you need to select other columns except Date:</p>\n\n<pre><code>SELECT * FROM Table WHERE Date IN (\nSELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k)\n</code></pre>\n\n<p>You can also rewrite the IN to INNER JOIN, however this won't give performance gain, as, in fact, query optimizer will do this for you in most RDBMS. Having index on Date will certainly improve performance for this query.</p>\n"
},
{
"answer_id": 104994,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT date, COUNT(date)\nFROM table\nGROUP BY date\nHAVING COUNT(date) < k\n</code></pre>\n\n<p>And then to get the original data back:</p>\n\n<pre><code>SELECT table.*\nFROM table\nINNER JOIN (\n SELECT date, COUNT(date) \n FROM table\n GROUP BY date\n HAVING COUNT(date) < k) dates ON table.date = dates.date\n</code></pre>\n"
},
{
"answer_id": 104997,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming you are using Oracle, and k = 5:-</p>\n\n<pre><code>select date_col,count(*)\nfrom your_table\ngroup by date_col\nhaving count(*) < 5;\n</code></pre>\n\n<p>If your date column has time filled out as well, and you want to ignore it, modify the query so it looks as follows:-</p>\n\n<pre><code>select trunc(date_col) as date_col,count(*)\nfrom your_table\ngroup by trunc(date_col)\nhaving count(*) < 5;\n</code></pre>\n"
},
{
"answer_id": 104999,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 4,
"selected": true,
"text": "<pre><code>select dates \n from table t \n group by dates having count(dates) < k ;\n</code></pre>\n\n<p>Hopefully, it works for ORACLE.\nHTH</p>\n"
},
{
"answer_id": 105006,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>example</p>\n\n<pre><code>DECLARE @Max int\nSELECT @Max = 5\n\nSELECT t1.* \nFROM [MyTable] t1 \nJOIN(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n HAVING COUNT(*) < @Max\n) t2 on t1.[Date] = t2.[Date] \n</code></pre>\n"
},
{
"answer_id": 115362,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 0,
"selected": false,
"text": "<p>You may not be able to count directly on the datefield if your dates include times. You may need to convert to just the year/month/day format first and then do the count on that.</p>\n\n<p>Otherwise your counts will be off as usually there are very few records withthe exact same time.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
]
| I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times? | ```
select dates
from table t
group by dates having count(dates) < k ;
```
Hopefully, it works for ORACLE.
HTH |
105,014 | <p>A while ago I came across some code that marked a member variable of a class with the <code>mutable</code> keyword. As far as I can see it simply allows you to modify a variable in a <code>const</code> method:</p>
<pre><code>class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; }
};
</code></pre>
<p>Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a <code>boost::mutex</code> as mutable allowing <code>const</code> functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.</p>
| [
{
"answer_id": 105038,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 6,
"selected": false,
"text": "<p>Your use with boost::mutex is exactly what this keyword is intended for. Another use is for internal result caching to speed access.</p>\n\n<p>Basically, 'mutable' applies to any class attribute that does not affect the externally visible state of the object.</p>\n\n<p>In the sample code in your question, mutable might be inappropriate if the value of done_ affects external state, it depends on what is in the ...; part.</p>\n"
},
{
"answer_id": 105052,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>Mutable is for marking specific attribute as modifiable from within <code>const</code> methods. That is its only purpose. Think carefully before using it, because your code will probably be cleaner and more readable if you change the design rather than use <code>mutable</code>.</p>\n\n<p><a href=\"http://www.highprogrammer.com/alan/rants/mutable.html\" rel=\"noreferrer\">http://www.highprogrammer.com/alan/rants/mutable.html</a></p>\n\n<blockquote>\n <p>So if the above madness isn't what\n mutable is for, what is it for? Here's\n the subtle case: mutable is for the\n case where an object is logically\n constant, but in practice needs to\n change. These cases are few and far\n between, but they exist.</p>\n</blockquote>\n\n<p>Examples the author gives include caching and temporary debugging variables.</p>\n"
},
{
"answer_id": 105054,
"author": "Joe Schneider",
"author_id": 1541,
"author_profile": "https://Stackoverflow.com/users/1541",
"pm_score": 1,
"selected": false,
"text": "<p>In some cases (like poorly designed iterators), the class needs to keep a count or some other incidental value, that doesn't really affect the major \"state\" of the class. This is most often where I see mutable used. Without mutable, you'd be forced to sacrifice the entire const-ness of your design.</p>\n\n<p>It feels like a hack most of the time to me as well. Useful in a very very few situations.</p>\n"
},
{
"answer_id": 105056,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "<p>It's useful in situations where you have hidden internal state such as a cache. For example:</p>\n\n<pre>\nclass HashTable\n{\n...\npublic:\n string lookup(string key) const\n {\n if(key == lastKey)\n return lastValue;\n\n string value = lookupInternal(key);\n\n lastKey = key;\n lastValue = value;\n\n return value;\n }\n\nprivate:\n mutable string lastKey, lastValue;\n};</pre>\n\n<p>And then you can have a <code>const HashTable</code> object still use its <code>lookup()</code> method, which modifies the internal cache.</p>\n"
},
{
"answer_id": 105061,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 10,
"selected": true,
"text": "<p>It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result. </p>\n\n<p>Since c++11 <code>mutable</code> can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):</p>\n\n<pre><code>int x = 0;\nauto f1 = [=]() mutable {x = 42;}; // OK\nauto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda\n</code></pre>\n"
},
{
"answer_id": 105072,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": false,
"text": "<p>mutable is mainly used on an implementation detail of the class. The user of the class doesn't need to know about it, therefore method's he thinks \"should\" be const can be. Your example of having a mutex be mutable is a good canonical example.</p>\n"
},
{
"answer_id": 105086,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "<p>Well, yeah, that's what it does. I use it for members that are modified by methods that do not <em>logically</em> change the state of a class - for instance, to speed up lookups by implementing a cache:</p>\n\n<pre><code>class CIniWrapper\n{\npublic:\n CIniWrapper(LPCTSTR szIniFile);\n\n // non-const: logically modifies the state of the object\n void SetValue(LPCTSTR szName, LPCTSTR szValue);\n\n // const: does not logically change the object\n LPCTSTR GetValue(LPCTSTR szName, LPCTSTR szDefaultValue) const;\n\n // ...\n\nprivate:\n // cache, avoids going to disk when a named value is retrieved multiple times\n // does not logically change the public interface, so declared mutable\n // so that it can be used by the const GetValue() method\n mutable std::map<string, string> m_mapNameToValue;\n};\n</code></pre>\n\n<p>Now, you must use this with care - concurrency issues are a big concern, as a caller might assume that they are thread safe if only using <code>const</code> methods. And of course, modifying <code>mutable</code> data shouldn't change the behavior of the object in any significant fashion, something that could be violated by the example i gave if, for instance, it was expected that changes written to disk would be immediately visible to the app. </p>\n"
},
{
"answer_id": 105216,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 3,
"selected": false,
"text": "<p>Your use of it isn't a hack, though like many things in C++, mutable <em>can</em> be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.</p>\n"
},
{
"answer_id": 105276,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 4,
"selected": false,
"text": "<p><code>mutable</code> does exist as you infer to allow one to modify data in an otherwise constant function.</p>\n\n<p>The intent is that you might have a function that \"does nothing\" to the internal state of the object, and so you mark the function <code>const</code>, but you might really need to modify some of the objects state in ways that don't affect its correct functionality.</p>\n\n<p>The keyword may act as a hint to the compiler -- a theoretical compiler could place a constant object (such as a global) in memory that was marked read-only. The presence of <code>mutable</code> hints that this should not be done.</p>\n\n<p>Here are some valid reasons to declare and use mutable data:</p>\n\n<ul>\n<li>Thread safety. Declaring a <code>mutable boost::mutex</code> is perfectly reasonable.</li>\n<li>Statistics. Counting the number of calls to a function, given some or all of its arguments.</li>\n<li>Memoization. Computing some expensive answer, and then storing it for future reference rather than recomputing it again.</li>\n</ul>\n"
},
{
"answer_id": 2384201,
"author": "Dan L",
"author_id": 286776,
"author_profile": "https://Stackoverflow.com/users/286776",
"pm_score": 7,
"selected": false,
"text": "<p>The <code>mutable</code> keyword is a way to pierce the <code>const</code> veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way <strong>except</strong> when and how it is marked <code>mutable</code>.</p>\n\n<p>With your <code>const</code> reference or pointer you are constrained to:</p>\n\n<ul>\n<li>only read access for any visible data members</li>\n<li>permission to call only methods that are marked as <code>const</code>. </li>\n</ul>\n\n<p>The <code>mutable</code> exception makes it so you can now write or set data members that are marked <code>mutable</code>. That's the only externally visible difference.</p>\n\n<p>Internally those <code>const</code> methods that are visible to you can also write to data members that are marked <code>mutable</code>. Essentially the const veil is pierced comprehensively. It is completely up to the API designer to ensure that <code>mutable</code> doesn't destroy the <code>const</code> concept and is only used in useful special cases. The <code>mutable</code> keyword helps because it clearly marks data members that are subject to these special cases.</p>\n\n<p>In practice you can use <code>const</code> obsessively throughout your codebase (you essentially want to \"infect\" your codebase with the <code>const</code> \"disease\"). In this world pointers and references are <code>const</code> with very few exceptions, yielding code that is easier to reason about and understand. For a interesting digression look up \"referential transparency\". </p>\n\n<p>Without the <code>mutable</code> keyword you will eventually be forced to use <code>const_cast</code> to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately <code>const_cast</code> is significantly more destructive than <code>mutable</code> because it forces the API <strong>client</strong> to destroy the <code>const</code> protection of the objects (s)he is using. Additionally it causes widespread <code>const</code> destruction: <code>const_cast</code>ing a const pointer or reference allows unfettered write and method calling access to visible members. In contrast <code>mutable</code> requires the API designer to exercise fine grained control over the <code>const</code> exceptions, and usually these exceptions are hidden in <code>const</code> methods operating on private data.</p>\n\n<p>(N.B. I refer to to data and method <em>visibility</em> a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed <a href=\"https://stackoverflow.com/questions/224966/private-and-protected-members-c\">here</a>.)</p>\n"
},
{
"answer_id": 6017425,
"author": "Daniel Hershcovich",
"author_id": 223267,
"author_profile": "https://Stackoverflow.com/users/223267",
"pm_score": 1,
"selected": false,
"text": "<p>The classic example (as mentioned in other answers) and the only situation I have seen the <code>mutable</code> keyword used in so far, is for caching the result of a complicated <code>Get</code> method, where the cache is implemented as a data member of the class and not as a static variable in the method (for reasons of sharing between several functions or plain cleanliness).</p>\n\n<p>In general, the alternatives to using the <code>mutable</code> keyword are usually a static variable in the method or the <code>const_cast</code> trick.</p>\n\n<p>Another detailed explanation is in <a href=\"http://www.possibility.com/Cpp/const.html\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 17364794,
"author": "mkschreder",
"author_id": 1953157,
"author_profile": "https://Stackoverflow.com/users/1953157",
"pm_score": 3,
"selected": false,
"text": "<p>Mutable is used when you have a variable inside the class that is only used within that class to signal things like for example a mutex or a lock. This variable does not change the behaviour of the class, but is necessary in order to implement thread safety of the class itself. Thus if without \"mutable\", you would not be able to have \"const\" functions because this variable will need to be changed in all functions that are available to the outside world. Therefore, mutable was introduced in order to make a member variable writable even by a const function. </p>\n\n<blockquote>\n <p>The mutable specified informs both the compiler and the reader that it\n is safe and expected that a member variable may be modified within a const\n member function.</p>\n</blockquote>\n"
},
{
"answer_id": 21105132,
"author": "Zack Yezek",
"author_id": 1937375,
"author_profile": "https://Stackoverflow.com/users/1937375",
"pm_score": 3,
"selected": false,
"text": "<p>Use \"mutable\" when for things that are LOGICALLY stateless to the user (and thus should have \"const\" getters in the public class' APIs) but are NOT stateless in the underlying IMPLEMENTATION (the code in your .cpp).</p>\n\n<p>The cases I use it most frequently are lazy initialization of state-less \"plain old data\" members. Namely, it is ideal in the narrow cases when such members are expensive to either build (processor) or carry around (memory) and many users of the object will never ask for them. In that situation you want lazy construction on the back end for performance, since 90% of the objects built will never need to build them at all, yet you still need to present the correct stateless API for public consumption. </p>\n"
},
{
"answer_id": 21499101,
"author": "Saurabh",
"author_id": 3201489,
"author_profile": "https://Stackoverflow.com/users/3201489",
"pm_score": 2,
"selected": false,
"text": "<p>The mutable can be handy when you are overriding a const virtual function and want to modify your child class member variable in that function. In most of the cases you would not want to alter the interface of the base class, so you have to use mutable member variable of your own.</p>\n"
},
{
"answer_id": 21949205,
"author": "Rajdeep Rathore",
"author_id": 3339634,
"author_profile": "https://Stackoverflow.com/users/3339634",
"pm_score": -1,
"selected": false,
"text": "<p>The very keyword 'mutable' is actually a reserved keyword.often it is used to vary the value of constant variable.If you want to have multiple values of a constsnt,use the keyword mutable.</p>\n\n<pre><code>//Prototype \nclass tag_name{\n :\n :\n mutable var_name;\n :\n :\n }; \n</code></pre>\n"
},
{
"answer_id": 23884114,
"author": "Martin G",
"author_id": 3545094,
"author_profile": "https://Stackoverflow.com/users/3545094",
"pm_score": 2,
"selected": false,
"text": "<p>The mutable keyword is very useful when creating stubs for class test purposes. You can stub a const function and still be able to increase (mutable) counters or whatever test functionality you have added to your stub. This keeps the interface of the stubbed class intact.</p>\n"
},
{
"answer_id": 24942741,
"author": "Kevin Cox",
"author_id": 1166181,
"author_profile": "https://Stackoverflow.com/users/1166181",
"pm_score": 2,
"selected": false,
"text": "<p>Mutable changes the meaning of <code>const</code> from bitwise const to logical const for the class.</p>\n\n<p>This means that classes with mutable members are longer be bitwise const and will no longer appear in read-only sections of the executable.</p>\n\n<p>Furthermore, it modifies type-checking by allowing <code>const</code> member functions to change mutable members without using <code>const_cast</code>.</p>\n\n<pre><code>class Logical {\n mutable int var;\n\npublic:\n Logical(): var(0) {}\n void set(int x) const { var = x; }\n};\n\nclass Bitwise {\n int var;\n\npublic:\n Bitwise(): var(0) {}\n void set(int x) const {\n const_cast<Bitwise*>(this)->var = x;\n }\n};\n\nconst Logical logical; // Not put in read-only.\nconst Bitwise bitwise; // Likely put in read-only.\n\nint main(void)\n{\n logical.set(5); // Well defined.\n bitwise.set(5); // Undefined.\n}\n</code></pre>\n\n<p>See the other answers for more details but I wanted to highlight that it isn't merely for type-saftey and that it affects the compiled result.</p>\n"
},
{
"answer_id": 28139786,
"author": "Venkatakrishna Kalepalli",
"author_id": 4184683,
"author_profile": "https://Stackoverflow.com/users/4184683",
"pm_score": 0,
"selected": false,
"text": "<p>One of the best example where we use mutable is, in deep copy. in copy constructor we send <code>const &obj</code> as argument. So the new object created will be of constant type. If we want to change (mostly we won't change, in rare case we may change) the members in this newly created const object we need to declare it as <code>mutable</code>. </p>\n\n<p><code>mutable</code> storage class can be used only on non static non const data member of a class. Mutable data member of a class can be modified even if it's part of an object which is declared as const.</p>\n\n<pre><code>class Test\n{\npublic:\n Test(): x(1), y(1) {};\n mutable int x;\n int y;\n};\n\nint main()\n{\n const Test object;\n object.x = 123;\n //object.y = 123;\n /* \n * The above line if uncommented, will create compilation error.\n */ \n\n cout<< \"X:\"<< object.x << \", Y:\" << object.y;\n return 0;\n}\n\nOutput:-\nX:123, Y:1\n</code></pre>\n\n<p>In the above example, we are able to change the value of member variable <code>x</code> though it's part of an object which is declared as const. This is because the variable <code>x</code> is declared as mutable. But if you try to modify the value of member variable <code>y</code>, compiler will throw an error.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| A while ago I came across some code that marked a member variable of a class with the `mutable` keyword. As far as I can see it simply allows you to modify a variable in a `const` method:
```
class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; }
};
```
Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a `boost::mutex` as mutable allowing `const` functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack. | It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11 `mutable` can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):
```
int x = 0;
auto f1 = [=]() mutable {x = 42;}; // OK
auto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda
``` |
105,031 | <p>Using C#, I want to get the total amount of RAM that my computer has.
With the PerformanceCounter I can get the amount of Available ram, by setting:</p>
<pre><code>counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
</code></pre>
<p>But I can't seem to find a way to get the total amount of memory. How would I go about doing this?</p>
<p><strong>Update:</strong></p>
<p>MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.</p>
| [
{
"answer_id": 105053,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>.NET has a memory amount limit that it can access.\nIn Windows XP 2GB was the "hard ceiling".\nFor instance: You could have 4 GB in it, and it would kill the app when it hit 2GB.</p>\n<p>Also in 64 bit mode, there is a percentage of memory you can use out of the system, so I'm not sure if you can ask for the whole thing or if this is specifically guarded against.</p>\n"
},
{
"answer_id": 105084,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 8,
"selected": false,
"text": "<p>Add a reference to <code>Microsoft.VisualBasic</code> and a <code>using Microsoft.VisualBasic.Devices;</code>.</p>\n\n<p>The <code>ComputerInfo</code> class has all the information that you need. </p>\n"
},
{
"answer_id": 105099,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 3,
"selected": false,
"text": "<p>You could use 'WMI'.</p>\n<p>I found a 'snippet'.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Set objWMIService = GetObject("winmgmts:" _\n& "{impersonationLevel=impersonate}!\\\\" _ \n& strComputer & "\\root\\cimv2") \nSet colComputer = objWMIService.ExecQuery _\n("Select * from Win32_ComputerSystem")\n\nFor Each objComputer in colComputer \n strMemory = objComputer.TotalPhysicalMemory\nNext\n</code></pre>\n"
},
{
"answer_id": 105109,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 7,
"selected": true,
"text": "<p>The Windows API function <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex\" rel=\"noreferrer\"><code>GlobalMemoryStatusEx</code></a> can be called with p/invoke:</p>\n<pre><code> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\n private class MEMORYSTATUSEX\n {\n public uint dwLength;\n public uint dwMemoryLoad;\n public ulong ullTotalPhys;\n public ulong ullAvailPhys;\n public ulong ullTotalPageFile;\n public ulong ullAvailPageFile;\n public ulong ullTotalVirtual;\n public ulong ullAvailVirtual;\n public ulong ullAvailExtendedVirtual;\n public MEMORYSTATUSEX()\n {\n this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));\n }\n }\n\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]\n static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);\n</code></pre>\n<p>Then use like:</p>\n<pre><code>ulong installedMemory;\nMEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();\nif( GlobalMemoryStatusEx( memStatus))\n{ \n installedMemory = memStatus.ullTotalPhys;\n}\n</code></pre>\n<p>Or you can use WMI (managed but slower) to query <code>TotalPhysicalMemory</code> in the <code>Win32_ComputerSystem</code> class.</p>\n"
},
{
"answer_id": 105890,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 6,
"selected": false,
"text": "<p>Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):</p>\n\n<pre><code>static ulong GetTotalMemoryInBytes()\n{\n return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;\n}\n</code></pre>\n"
},
{
"answer_id": 2655015,
"author": "grendel",
"author_id": 171396,
"author_profile": "https://Stackoverflow.com/users/171396",
"pm_score": 5,
"selected": false,
"text": "<p>If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\nclass app\n{\n static void Main ()\n {\n var pc = new PerformanceCounter (\"Mono Memory\", \"Total Physical Memory\");\n Console.WriteLine (\"Physical RAM (bytes): {0}\", pc.RawValue);\n }\n}\n</code></pre>\n\n<p>If you are interested in C code which provides the performance counter, it can be found <a href=\"http://anonsvn.mono-project.com/viewvc/trunk/mono/mono/metadata/mono-perfcounters.c?r1=154243&r2=155566&pathrev=155566\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 10462545,
"author": "SuMeeT ShaHaPeTi",
"author_id": 1376882,
"author_profile": "https://Stackoverflow.com/users/1376882",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/*The simplest way to get/display total physical memory in VB.net (Tested)\n\npublic sub get_total_physical_mem()\n\n dim total_physical_memory as integer\n\n total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))\n MsgBox(\"Total Physical Memory\" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + \"Mb\" )\nend sub\n*/\n\n\n//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)\n\npublic void get_total_physical_mem()\n{\n int total_physical_memory = 0;\n\n total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024));\n Interaction.MsgBox(\"Total Physical Memory\" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + \"Mb\");\n}\n</code></pre>\n"
},
{
"answer_id": 22753830,
"author": "Nilan Niyomal",
"author_id": 2219885,
"author_profile": "https://Stackoverflow.com/users/2219885",
"pm_score": 3,
"selected": false,
"text": "<p>you can simply use this code to get those information, just add the reference </p>\n\n<pre><code>using Microsoft.VisualBasic.Devices;\n</code></pre>\n\n<p>and the simply use the following code </p>\n\n<pre><code> private void button1_Click(object sender, EventArgs e)\n {\n getAvailableRAM();\n }\n\n public void getAvailableRAM()\n {\n ComputerInfo CI = new ComputerInfo();\n ulong mem = ulong.Parse(CI.TotalPhysicalMemory.ToString());\n richTextBox1.Text = (mem / (1024*1024) + \" MB\").ToString();\n }\n</code></pre>\n"
},
{
"answer_id": 24395572,
"author": "zgerd",
"author_id": 2496267,
"author_profile": "https://Stackoverflow.com/users/2496267",
"pm_score": 4,
"selected": false,
"text": "<p>Another way to do this, is by using the .NET System.Management querying facilities:</p>\n\n<pre><code>string Query = \"SELECT Capacity FROM Win32_PhysicalMemory\";\nManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);\n\nUInt64 Capacity = 0;\nforeach (ManagementObject WniPART in searcher.Get())\n{\n Capacity += Convert.ToUInt64(WniPART.Properties[\"Capacity\"].Value);\n}\n\nreturn Capacity;\n</code></pre>\n"
},
{
"answer_id": 26514915,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 0,
"selected": false,
"text": "<p>Nobody has mentioned <a href=\"http://msdn.microsoft.com/en-gb/library/windows/desktop/ms683210%28v=vs.85%29.aspx\" rel=\"nofollow\">GetPerformanceInfo</a> yet. <a href=\"http://www.pinvoke.net/default.aspx/psapi/GetPerformanceInfo.html\" rel=\"nofollow\">PInvoke signatures</a> are available.</p>\n\n<p>This function makes the following system-wide information available:</p>\n\n<ul>\n<li>CommitTotal</li>\n<li>CommitLimit</li>\n<li>CommitPeak</li>\n<li>PhysicalTotal</li>\n<li>PhysicalAvailable</li>\n<li>SystemCache</li>\n<li>KernelTotal</li>\n<li>KernelPaged</li>\n<li>KernelNonpaged</li>\n<li>PageSize</li>\n<li>HandleCount</li>\n<li>ProcessCount</li>\n<li>ThreadCount</li>\n</ul>\n\n<p><code>PhysicalTotal</code> is what the OP is looking for, although the value is the number of pages, so to convert to bytes, multiply by the <code>PageSize</code> value returned.</p>\n"
},
{
"answer_id": 33413251,
"author": "Lance",
"author_id": 4767537,
"author_profile": "https://Stackoverflow.com/users/4767537",
"pm_score": 2,
"selected": false,
"text": "<p>This function (<code>ManagementQuery</code>) works on Windows XP and later:</p>\n\n<pre><code>private static string ManagementQuery(string query, string parameter, string scope = null) {\n string result = string.Empty;\n var searcher = string.IsNullOrEmpty(scope) ? new ManagementObjectSearcher(query) : new ManagementObjectSearcher(scope, query);\n foreach (var os in searcher.Get()) {\n try {\n result = os[parameter].ToString();\n }\n catch {\n //ignore\n }\n\n if (!string.IsNullOrEmpty(result)) {\n break;\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Console.WriteLine(BytesToMb(Convert.ToInt64(ManagementQuery(\"SELECT TotalPhysicalMemory FROM Win32_ComputerSystem\", \"TotalPhysicalMemory\", \"root\\\\CIMV2\"))));\n</code></pre>\n"
},
{
"answer_id": 34100935,
"author": "sstan",
"author_id": 4955425,
"author_profile": "https://Stackoverflow.com/users/4955425",
"pm_score": 5,
"selected": false,
"text": "<p>All the answers here, including the accepted one, will give you the total amount of RAM <strong><em>available</em></strong> for use. And that may have been what OP wanted.</p>\n\n<p>But if you are interested in getting the amount of <strong><em>installed</em></strong> RAM, then you'll want to make a call to the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/cc300158(v=vs.85).aspx\">GetPhysicallyInstalledSystemMemory</a> function.</p>\n\n<p>From the link, in the Remarks section:</p>\n\n<blockquote>\n <p>The <strong>GetPhysicallyInstalledSystemMemory</strong> function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the <strong>GlobalMemoryStatusEx</strong> function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. <strong><em>The amount of memory available to the operating system can be less than the amount of memory physically installed in the computer</em></strong> because the BIOS and some drivers may reserve memory as I/O regions for memory-mapped devices, making the memory unavailable to the operating system and applications.</p>\n</blockquote>\n\n<p><strong>Sample code:</strong></p>\n\n<pre><code>[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);\n\nstatic void Main()\n{\n long memKb;\n GetPhysicallyInstalledSystemMemory(out memKb);\n Console.WriteLine((memKb / 1024 / 1024) + \" GB of RAM installed.\");\n}\n</code></pre>\n"
},
{
"answer_id": 34900103,
"author": "Mehul Sant",
"author_id": 5815839,
"author_profile": "https://Stackoverflow.com/users/5815839",
"pm_score": 3,
"selected": false,
"text": "<pre><code>// use `/ 1048576` to get ram in MB\n// and `/ (1048576 * 1024)` or `/ 1048576 / 1024` to get ram in GB\nprivate static String getRAMsize()\n{\n ManagementClass mc = new ManagementClass(\"Win32_ComputerSystem\");\n ManagementObjectCollection moc = mc.GetInstances();\n foreach (ManagementObject item in moc)\n {\n return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties[\"TotalPhysicalMemory\"].Value) / 1048576, 0)) + \" MB\";\n }\n\n return \"RAMsize\";\n}\n</code></pre>\n"
},
{
"answer_id": 53017759,
"author": "Soroush Falahati",
"author_id": 1913051,
"author_profile": "https://Stackoverflow.com/users/1913051",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Compatible with .Net and Mono (tested with Win10/FreeBSD/CentOS)</strong></p>\n\n<p>Using <code>ComputerInfo</code> source code and <code>PerformanceCounter</code>s for Mono and as backup for .Net:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Security;\n\npublic class SystemMemoryInfo\n{\n private readonly PerformanceCounter _monoAvailableMemoryCounter;\n private readonly PerformanceCounter _monoTotalMemoryCounter;\n private readonly PerformanceCounter _netAvailableMemoryCounter;\n\n private ulong _availablePhysicalMemory;\n private ulong _totalPhysicalMemory;\n\n public SystemMemoryInfo()\n {\n try\n {\n if (PerformanceCounterCategory.Exists(\"Mono Memory\"))\n {\n _monoAvailableMemoryCounter = new PerformanceCounter(\"Mono Memory\", \"Available Physical Memory\");\n _monoTotalMemoryCounter = new PerformanceCounter(\"Mono Memory\", \"Total Physical Memory\");\n }\n else if (PerformanceCounterCategory.Exists(\"Memory\"))\n {\n _netAvailableMemoryCounter = new PerformanceCounter(\"Memory\", \"Available Bytes\");\n }\n }\n catch\n {\n // ignored\n }\n }\n\n public ulong AvailablePhysicalMemory\n {\n [SecurityCritical]\n get\n {\n Refresh();\n\n return _availablePhysicalMemory;\n }\n }\n\n public ulong TotalPhysicalMemory\n {\n [SecurityCritical]\n get\n {\n Refresh();\n\n return _totalPhysicalMemory;\n }\n }\n\n [SecurityCritical]\n [DllImport(\"Kernel32\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);\n\n [SecurityCritical]\n [DllImport(\"Kernel32\", CharSet = CharSet.Auto, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);\n\n [SecurityCritical]\n private void Refresh()\n {\n try\n {\n if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)\n {\n _totalPhysicalMemory = (ulong) _monoTotalMemoryCounter.NextValue();\n _availablePhysicalMemory = (ulong) _monoAvailableMemoryCounter.NextValue();\n }\n else if (Environment.OSVersion.Version.Major < 5)\n {\n var memoryStatus = MEMORYSTATUS.Init();\n GlobalMemoryStatus(ref memoryStatus);\n\n if (memoryStatus.dwTotalPhys > 0)\n {\n _availablePhysicalMemory = memoryStatus.dwAvailPhys;\n _totalPhysicalMemory = memoryStatus.dwTotalPhys;\n }\n else if (_netAvailableMemoryCounter != null)\n {\n _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();\n }\n }\n else\n {\n var memoryStatusEx = MEMORYSTATUSEX.Init();\n\n if (GlobalMemoryStatusEx(ref memoryStatusEx))\n {\n _availablePhysicalMemory = memoryStatusEx.ullAvailPhys;\n _totalPhysicalMemory = memoryStatusEx.ullTotalPhys;\n }\n else if (_netAvailableMemoryCounter != null)\n {\n _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();\n }\n }\n }\n catch\n {\n // ignored\n }\n }\n\n private struct MEMORYSTATUS\n {\n private uint dwLength;\n internal uint dwMemoryLoad;\n internal uint dwTotalPhys;\n internal uint dwAvailPhys;\n internal uint dwTotalPageFile;\n internal uint dwAvailPageFile;\n internal uint dwTotalVirtual;\n internal uint dwAvailVirtual;\n\n public static MEMORYSTATUS Init()\n {\n return new MEMORYSTATUS\n {\n dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUS)))\n };\n }\n }\n\n private struct MEMORYSTATUSEX\n {\n private uint dwLength;\n internal uint dwMemoryLoad;\n internal ulong ullTotalPhys;\n internal ulong ullAvailPhys;\n internal ulong ullTotalPageFile;\n internal ulong ullAvailPageFile;\n internal ulong ullTotalVirtual;\n internal ulong ullAvailVirtual;\n internal ulong ullAvailExtendedVirtual;\n\n public static MEMORYSTATUSEX Init()\n {\n return new MEMORYSTATUSEX\n {\n dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUSEX)))\n };\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59073095,
"author": "BRAHIM Kamel",
"author_id": 2597372,
"author_profile": "https://Stackoverflow.com/users/2597372",
"pm_score": 5,
"selected": false,
"text": "<p>For those who are using <code>.net Core 3.0</code> there is no need to use <code>PInvoke</code> platform in order to get the available physical memory. The <code>GC</code> class has added a new method <code>GC.GetGCMemoryInfo</code> that returns a <code>GCMemoryInfo Struct</code> with <code>TotalAvailableMemoryBytes</code> as a property. This property returns the total available memory for the garbage collector.(same value as MEMORYSTATUSEX)</p>\n\n<pre><code>var gcMemoryInfo = GC.GetGCMemoryInfo();\ninstalledMemory = gcMemoryInfo.TotalAvailableMemoryBytes;\n// it will give the size of memory in MB\nvar physicalMemory = (double) installedMemory / 1048576.0;\n</code></pre>\n"
},
{
"answer_id": 66804236,
"author": "Alberico Francesco",
"author_id": 15469158,
"author_profile": "https://Stackoverflow.com/users/15469158",
"pm_score": -1,
"selected": false,
"text": "<p><code>var ram = new ManagementObjectSearcher("select * from Win32_PhysicalMemory") .Get().Cast<ManagementObject>().First();</code></p>\n<p>|</p>\n<p><code>var a = Convert.ToInt64(ram["Capacity"]) / 1024 / 1024 / 1024;</code></p>\n<p>(richiede System.Managment.dll come riferimento, testato su C# con Framework 4.7.2)</p>\n<p>questa procedura salva in "a" la ram totale presente in GB</p>\n<hr />\n<p><code>ulong memory() { return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; }</code></p>\n<p>|</p>\n<p><code>var b = Convert.ToDecimal(memory()) / 1024 / 1024 / 1024;</code></p>\n<p>(richiede Microsoft.VisualBasics.dll come riferimento, testato su C# Framework 4.7.2)</p>\n<p>questa procedura salva in "b" il valore della ram in GB effettivamente disponibile</p>\n<hr />\n"
},
{
"answer_id": 74258606,
"author": "Rob",
"author_id": 18735,
"author_profile": "https://Stackoverflow.com/users/18735",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another, much more simply way, using .net:</p>\n<pre><code>// total memory\nlong totalPhysicalMemory = My.Computer.Info.TotalPhysicalMemory;\n\n// unused memory\nlong availablePhysicalMemory = My.Computer.Info.AvailablePhysicalMemory;\n\n// used memory\nlong usedMemory = totalPhysicalMemory - availablePhysicalMemory;\n</code></pre>\n"
},
{
"answer_id": 74472605,
"author": "frakon",
"author_id": 2094687,
"author_profile": "https://Stackoverflow.com/users/2094687",
"pm_score": 0,
"selected": false,
"text": "<p>Solution working on <strong>Linux (.Net Core)</strong>.\nInspired by <a href=\"https://github.com/Jinjinov/Hardware.Info\" rel=\"nofollow noreferrer\">GitHub/Hardware.Info</a>.\nOptimized to have minimal memory allocation and avg retrieval takes 0.020 ms.</p>\n<pre><code>private static readonly object _linuxMemoryLock = new();\nprivate static readonly char[] _arrayForMemInfoRead = new char[200];\n\npublic static void GetBytesCountOnLinux(out ulong availableBytes, out ulong totalBytes)\n{\n lock (_linuxMemoryLock) // lock because of reusing static fields due to optimization\n {\n totalBytes = GetBytesCountFromLinuxMemInfo(token: "MemTotal:", refreshFromFile: true);\n availableBytes = GetBytesCountFromLinuxMemInfo(token: "MemAvailable:", refreshFromFile: false);\n }\n}\n\nprivate static ulong GetBytesCountFromLinuxMemInfo(string token, bool refreshFromFile)\n{\n // NOTE: Using the linux file /proc/meminfo which is refreshed frequently and starts with:\n //MemTotal: 7837208 kB\n //MemFree: 190612 kB\n //MemAvailable: 5657580 kB\n\n var readSpan = _arrayForMemInfoRead.AsSpan();\n\n if (refreshFromFile)\n {\n using var fileStream = new FileStream("/proc/meminfo", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n\n using var reader = new StreamReader(fileStream, Encoding.UTF8, leaveOpen: true);\n\n reader.ReadBlock(readSpan);\n }\n\n var tokenIndex = readSpan.IndexOf(token);\n\n var fromTokenSpan = readSpan.Slice(tokenIndex + token.Length);\n\n var kbIndex = fromTokenSpan.IndexOf("kB");\n\n var notTrimmedSpan = fromTokenSpan.Slice(0, kbIndex);\n\n var trimmedSpan = notTrimmedSpan.Trim(' ');\n\n var kBytesCount = ulong.Parse(trimmedSpan);\n\n var bytesCount = kBytesCount * 1024;\n\n return bytesCount;\n}\n</code></pre>\n<hr />\n<p><strong>Linux and Windows together</strong> - for easy copy paste. Windows code taken from the <a href=\"https://stackoverflow.com/a/105109/2094687\">accepted answer</a>.</p>\n<pre><code>public static void GetRamBytes(out ulong availableBytes, out ulong totalBytes)\n{\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n GetBytesCountOnLinux(out availableBytes, out totalBytes);\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n GetBytesCountOnWindows(out availableBytes, out totalBytes);\n }\n else\n {\n throw new NotImplementedException("Not implemented for OS: " + Environment.OSVersion);\n }\n}\n\nprivate static readonly object _winMemoryLock = new();\nprivate static readonly MEMORYSTATUSEX _memStatus = new();\n\nprivate static void GetBytesCountOnWindows(out ulong availableBytes, out ulong totalBytes)\n{\n lock (_winMemoryLock) // lock because of reusing the static class _memStatus\n {\n GlobalMemoryStatusEx(_memStatus);\n\n availableBytes = _memStatus.ullAvailPhys;\n totalBytes = _memStatus.ullTotalPhys;\n }\n}\n\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\nprivate class MEMORYSTATUSEX\n{\n public uint dwLength;\n public uint dwMemoryLoad;\n public ulong ullTotalPhys;\n public ulong ullAvailPhys;\n public ulong ullTotalPageFile;\n public ulong ullAvailPageFile;\n public ulong ullTotalVirtual;\n public ulong ullAvailVirtual;\n public ulong ullAvailExtendedVirtual;\n\n public MEMORYSTATUSEX()\n {\n this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));\n }\n}\n\n[return: MarshalAs(UnmanagedType.Bool)]\n[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]\nprivate static extern bool GlobalMemoryStatusEx([In] [Out] MEMORYSTATUSEX lpBuffer);\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13713/"
]
| Using C#, I want to get the total amount of RAM that my computer has.
With the PerformanceCounter I can get the amount of Available ram, by setting:
```
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
```
But I can't seem to find a way to get the total amount of memory. How would I go about doing this?
**Update:**
MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there. | The Windows API function [`GlobalMemoryStatusEx`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex) can be called with p/invoke:
```
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
}
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
```
Then use like:
```
ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{
installedMemory = memStatus.ullTotalPhys;
}
```
Or you can use WMI (managed but slower) to query `TotalPhysicalMemory` in the `Win32_ComputerSystem` class. |
105,095 | <p>If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?</p>
<p>If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?</p>
<p>sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines. </p>
<p>same thing would apply to any other language implementation that has a GIL.</p>
| [
{
"answer_id": 105127,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 1,
"selected": false,
"text": "<p>You still need to use locks (your code could be interrupted at any time to execute another thread and this can cause data inconsistencies). The problem with GIL is that it prevents Python code from using more cores at the same time (or multiple processors if they are available).</p>\n"
},
{
"answer_id": 105145,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": false,
"text": "<p>No - the GIL just protects python internals from multiple threads altering their state. This is a very low-level of locking, sufficient only to keep python's own structures in a consistent state. It doesn't cover the <em>application</em> level locking you'll need to do to cover thread safety in your own code.</p>\n\n<p>The essence of locking is to ensure that a particular <em>block</em> of code is only executed by one thread. The GIL enforces this for blocks the size of a single bytecode, but usually you want the lock to span a larger block of code than this.</p>\n"
},
{
"answer_id": 105175,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 3,
"selected": false,
"text": "<p>This post describes the GIL at a fairly high-level:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/20080516010343/http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html\" rel=\"noreferrer\">https://web.archive.org/web/20080516010343/http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html</a></li>\n</ul>\n\n<p>Of particular interest are these quotes:</p>\n\n<blockquote>\n <p>Every ten instructions (this default\n can be changed), the core releases the\n GIL for the current thread. At that\n point, the OS chooses a thread from\n all the threads competing for the lock\n (possibly choosing the same thread\n that just released the GIL – you don't\n have any control over which thread\n gets chosen); that thread acquires the\n GIL and then runs for another ten\n bytecodes.</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p>Note carefully that the GIL only\n restricts pure Python code. Extensions\n (external Python libraries usually\n written in C) can be written that\n release the lock, which then allows\n the Python interpreter to run\n separately from the extension until\n the extension reacquires the lock.</p>\n</blockquote>\n\n<p>It sounds like the GIL just provides fewer possible instances for a context switch, and makes multi-core/processor systems behave as a single core, with respect to each python interpreter instance, so yes, you still need to use synchronization mechanisms.</p>\n"
},
{
"answer_id": 105272,
"author": "David Eyk",
"author_id": 18950,
"author_profile": "https://Stackoverflow.com/users/18950",
"pm_score": 3,
"selected": false,
"text": "<p>The Global Interpreter Lock prevents threads from accessing the <em>interpreter</em> simultaneously (thus CPython only ever uses one core). However, as I understand it, the threads are still interrupted and scheduled <em>preemptively</em>, which means you still need locks on shared data structures, lest your threads stomp on each other's toes.</p>\n\n<p>The answer I've encountered time and time again is that multithreading in Python is rarely worth the overhead, because of this. I've heard good things about the <a href=\"http://pyprocessing.berlios.de/\" rel=\"noreferrer\">PyProcessing</a> project, which makes running multiple processes as \"simple\" as multithreading, with shared data structures, queues, etc. (PyProcessing will be introduced into the standard library of the upcoming Python 2.6 as the <a href=\"http://www.python.org/dev/peps/pep-0371/\" rel=\"noreferrer\">multiprocessing</a> module.) This gets you around the GIL, as each process has its own interpreter.</p>\n"
},
{
"answer_id": 105369,
"author": "Will Harris",
"author_id": 4702,
"author_profile": "https://Stackoverflow.com/users/4702",
"pm_score": 7,
"selected": true,
"text": "<p>You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code.</p>\n\n<p>For example:</p>\n\n<pre><code>#!/usr/bin/env python\nimport threading\n\nshared_balance = 0\n\nclass Deposit(threading.Thread):\n def run(self):\n for _ in xrange(1000000):\n global shared_balance\n balance = shared_balance\n balance += 100\n shared_balance = balance\n\nclass Withdraw(threading.Thread):\n def run(self):\n for _ in xrange(1000000):\n global shared_balance\n balance = shared_balance\n balance -= 100\n shared_balance = balance\n\nthreads = [Deposit(), Withdraw()]\n\nfor thread in threads:\n thread.start()\n\nfor thread in threads:\n thread.join()\n\nprint shared_balance\n</code></pre>\n\n<p>Here, your code can be interrupted between reading the shared state (<code>balance = shared_balance</code>) and writing the changed result back (<code>shared_balance = balance</code>), causing a lost update. The result is a random value for the shared state.</p>\n\n<p>To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have <a href=\"http://en.wikipedia.org/wiki/Software_transactional_memory\" rel=\"noreferrer\">some way to detect when the shared state had changed since it was read</a>.</p>\n"
},
{
"answer_id": 241814,
"author": "Bruno Gomes",
"author_id": 8669,
"author_profile": "https://Stackoverflow.com/users/8669",
"pm_score": 4,
"selected": false,
"text": "<p>Adding to the discussion:</p>\n\n<p>Because the GIL exists, some operations are atomic in Python and do not need a lock. </p>\n\n<p><a href=\"http://www.python.org/doc/faq/library/#what-kinds-of-global-value-mutation-are-thread-safe\" rel=\"noreferrer\">http://www.python.org/doc/faq/library/#what-kinds-of-global-value-mutation-are-thread-safe</a></p>\n\n<p>As stated by the other answers, however, you <em>still</em> need to use locks whenever the application logic requires them (such as in a Producer/Consumer problem).</p>\n"
},
{
"answer_id": 385446,
"author": "jimx",
"author_id": 47606,
"author_profile": "https://Stackoverflow.com/users/47606",
"pm_score": 0,
"selected": false,
"text": "<p>A little bit of update from Will Harris's example:</p>\n\n<pre><code>class Withdraw(threading.Thread): \ndef run(self): \n for _ in xrange(1000000): \n global shared_balance \n if shared_balance >= 100:\n balance = shared_balance\n balance -= 100 \n shared_balance = balance\n</code></pre>\n\n<p>Put a value check statement in the withdraw and I don't see negative anymore and updates seems consistent. My question is:</p>\n\n<p>If GIL prevents only one thread can be executed at any atomic time, then where would be the stale value? If no stale value, why we need lock? (Assuming we only talk about pure python code)</p>\n\n<p>If I understand correctly, the above condition check wouldn't work in a <em>real</em> threading environment. When more than one threads are executing concurrently, stale value can be created hence the inconsistency of the share state, then you really need a lock. But if python really only allows just one thread at any time (time slicing threading), then there shouldn't be possible for stale value to exist, right?</p>\n"
},
{
"answer_id": 385887,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Think of it this way:</p>\n\n<p>On a single processor computer, multithreading happens by suspending one thread and starting another fast enough to make it appear to be running at the same time. This is like Python with the GIL: only one thread is ever actually running.</p>\n\n<p>The problem is that the thread can be suspended anywhere, for example, if I want to compute b = (a + b) * 3, this might produce instructions something like this:</p>\n\n<pre><code>1 a += b\n2 a *= 3\n3 b = a\n</code></pre>\n\n<p>Now, lets say that is running in a thread and that thread is suspended after either line 1 or 2 and then another thread kicks in and runs:</p>\n\n<pre><code>b = 5\n</code></pre>\n\n<p>Then when the other thread resumes, b is overwritten by the old computed values, which is probably not what was expected.</p>\n\n<p>So you can see that even though they're not ACTUALLY running at the same time, you still need locking.</p>\n"
},
{
"answer_id": 20408373,
"author": "Akshar Raaj",
"author_id": 839549,
"author_profile": "https://Stackoverflow.com/users/839549",
"pm_score": 2,
"selected": false,
"text": "<p>Locks are still needed. I will try explaining why they are needed.</p>\n\n<p>Any operation/instruction is executed in the interpreter. GIL ensures that interpreter is held by a single thread at <strong>a particular instant of time</strong>. And your program with multiple threads works in a single interpreter. At any particular instant of time, this interpreter is held by a single thread. It means that only thread which is holding the interpreter is <strong>running</strong> at any instant of time.</p>\n\n<p>Suppose there are two threads,say t1 and t2, and both want to execute two instructions which is reading the value of a global variable and incrementing it.</p>\n\n<pre><code>#increment value\nglobal var\nread_var = var\nvar = read_var + 1\n</code></pre>\n\n<p>As put above, GIL only ensures that two threads can't execute an instruction simultaneously, which means both threads can't execute <code>read_var = var</code> at any particular instant of time. But they can execute instruction one after another and you can still have problem. Consider this situation:</p>\n\n<ul>\n<li>Suppose read_var is 0.</li>\n<li>GIL is held by thread t1.</li>\n<li>t1 executes <code>read_var = var</code>. So, read_var in t1 is 0. GIL will only ensure that this read operation will not be executed for any other thread at this instant.</li>\n<li>GIL is given to thread t2.</li>\n<li>t2 executes <code>read_var = var</code>. But read_var is still 0. So, read_var in t2 is 0.</li>\n<li>GIL is given to t1.</li>\n<li>t1 executes <code>var = read_var+1</code> and var becomes 1.</li>\n<li>GIL is given to t2.</li>\n<li>t2 thinks read_var=0, because that's what it read.</li>\n<li>t2 executes <code>var = read_var+1</code> and var becomes 1.</li>\n<li>Our expectation was that <code>var</code> should become 2.</li>\n<li>So, a lock must be used to keep both reading and incrementing as an atomic operation.</li>\n<li>Will Harris' answer explains it through a code example.</li>\n</ul>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
]
| If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?
If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?
sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines.
same thing would apply to any other language implementation that has a GIL. | You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code.
For example:
```
#!/usr/bin/env python
import threading
shared_balance = 0
class Deposit(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
balance = shared_balance
balance += 100
shared_balance = balance
class Withdraw(threading.Thread):
def run(self):
for _ in xrange(1000000):
global shared_balance
balance = shared_balance
balance -= 100
shared_balance = balance
threads = [Deposit(), Withdraw()]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print shared_balance
```
Here, your code can be interrupted between reading the shared state (`balance = shared_balance`) and writing the changed result back (`shared_balance = balance`), causing a lost update. The result is a random value for the shared state.
To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have [some way to detect when the shared state had changed since it was read](http://en.wikipedia.org/wiki/Software_transactional_memory). |
105,125 | <p>Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file. Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment. We would really like to do this auto-magically, much like the build itself. Is there an easy way to do this?</p>
<p>Side note: both machines are running Windows (XP or server, I think).</p>
<p>Side note 2: Performance doesn't really matter. This is an integration box.</p>
| [
{
"answer_id": 105289,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 1,
"selected": false,
"text": "<p>if you have regularly scheduled builds you could easily put something in the cron like this</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>then stop tomcat at say 1:30 am</p>\n\n<pre><code>30 1 * * * ./path_to_tamcat/bin/catalina.sh stop\n</code></pre>\n\n<p>then start it up again 2 mins later</p>\n\n<pre><code>32 1 * * * ./path_to_tamcat/bin/catalina.sh start\n</code></pre>\n\n<p>granted this isn't the best for irregular deployment, but you could easily have regular deployment with scheduled restart. </p>\n"
},
{
"answer_id": 105394,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds a bit to me like you are using the little Tomcat deployment manager thing. I basically have no experience with that, just so you know. That said, where I work we use two settings.</p>\n\n<p>In the server.xml file, the context has the attribute <em>reloadable=\"true\"</em>.</p>\n\n<p>All we have to do is place the WAR file in the right spot and Tomcat unpacks it and reloads it, no problem.</p>\n\n<p>Now when I looked it up, the <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/config/context.html\" rel=\"nofollow noreferrer\">official configuration reference</a> says:</p>\n\n<blockquote>\n <p>\"This feature is very useful during application development, but it requires significant runtime overhead and is not recommended for use on deployed production applications.\"</p>\n</blockquote>\n\n<p>Like I said, we've never had problems. Our systems process a large number of requests and we don't seem to have a problem. We've never benchmarked the two configurations against each other though.</p>\n\n<p>You might want to give it a try. At least you would learn if it is happy enough to reload things when done that way. You can check the performance as well to see if it's a problem for you.</p>\n\n<p>I should note that every once in a while things just don't go right and we have to restart Tomcat anyway, but that's relatively rare.</p>\n\n<p>If this works, all you need to do is have a script copy the WAR in the right spot and monitor to make sure things work. After enough deploys Tomcat will run out of permgen space, so you have to be aware that you might need to restart Tomcat by hand anyway.</p>\n\n<p>Other random guesses:</p>\n\n<ol>\n<li>Are you FTPing directly into the final WAR location? Maybe Tomcat is just trying to open it too early?</li>\n<li>Are you getting any kind of error message? Maybe that could help you track the problem down?</li>\n<li>Have you tried other versions of Tomcat (if available to you)? Maybe 5.5 doesn't have the problem (or 5.0 if you're on 5.5)? Maybe just a newer point release?</li>\n</ol>\n"
},
{
"answer_id": 106061,
"author": "Martin OConnor",
"author_id": 18233,
"author_profile": "https://Stackoverflow.com/users/18233",
"pm_score": 1,
"selected": false,
"text": "<p>If you look at the tomcat startup and shutdown .bat (or .sh) scripts in the bin directory, you will see that they actually run a java process to start tomcat or in the case of shutting down, connects to tomcats shutdown port - see server.xml in the conf directory.\nYou could configure your build ant task to invoke the tomcat jars in the same way as the scripts do.</p>\n"
},
{
"answer_id": 106288,
"author": "user17978",
"author_id": 17978,
"author_profile": "https://Stackoverflow.com/users/17978",
"pm_score": 0,
"selected": false,
"text": "<p>What version of tomcat are you using?\nWhat exactly happens to make it appear as if a \"hot\" deploy doesn't work?</p>\n"
},
{
"answer_id": 106746,
"author": "shsteimer",
"author_id": 292,
"author_profile": "https://Stackoverflow.com/users/292",
"pm_score": 1,
"selected": false,
"text": "<p>Is tomcat registered as a windows service?</p>\n\n<p>If so, just write a .bat script using netstart and netstop and have the called as the last step of your deployment process.</p>\n"
},
{
"answer_id": 343607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>reloadable=\"true\"</p>\n\n<p>does not enable re-deployment of war-files (this will work automatically), it enables monitoring of changes of files in WEB-INF/classes and WEB-INF/lib, which is probably not what you want.</p>\n\n<p>Most of the time when re-deployement of war-files in Tomcat freezes, I was able to trace it back to classloader leaks, see see <a href=\"http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java\" rel=\"nofollow noreferrer\">Classloader leaks: the dreaded \"java.lang.OutOfMemoryError: PermGen space\" exception</a></p>\n"
},
{
"answer_id": 2110708,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 0,
"selected": false,
"text": "<p>You didn't give much detail why your hot deploys \"doesn't work properly\", but if it's actually been caused by a resource in <code>/WEB-INF/lib</code> been locked (which is not an uncommon cause; you see this often with the <code>mail.jar</code> of the JavaMail API), then just set the <code>Context</code>'s <code>antiResourceLocking</code> attribute to <code>true</code>. Here's an example how the webapp's <code>/META-INF/context.xml</code> would look like:</p>\n\n<pre><code><Context antiResourceLocking=\"true\">\n <!-- Your stuff here. -->\n</Context>\n</code></pre>\n"
},
{
"answer_id": 64460421,
"author": "Sobhan",
"author_id": 7189597,
"author_profile": "https://Stackoverflow.com/users/7189597",
"pm_score": 0,
"selected": false,
"text": "<p>One way to start the tomcat on the startup is to run it using cron using the @reboot attribute:</p>\n<p>open up a terminal and type :</p>\n<pre><code>sudo crontab -e\n</code></pre>\n<p>at the end of the file enter the command:</p>\n<pre><code>@reboot /`PATH_TO_WHERE_TOMCAT_INSTALLED`/bin/startup.sh\n</code></pre>\n<p>save the file and exit.</p>\n<p>The above command will run the command once everytime computer boots up.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7357/"
]
| Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file. Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment. We would really like to do this auto-magically, much like the build itself. Is there an easy way to do this?
Side note: both machines are running Windows (XP or server, I think).
Side note 2: Performance doesn't really matter. This is an integration box. | if you have regularly scheduled builds you could easily put something in the cron like this
```
crontab -e
```
then stop tomcat at say 1:30 am
```
30 1 * * * ./path_to_tamcat/bin/catalina.sh stop
```
then start it up again 2 mins later
```
32 1 * * * ./path_to_tamcat/bin/catalina.sh start
```
granted this isn't the best for irregular deployment, but you could easily have regular deployment with scheduled restart. |
105,198 | <p>I'm still a little unclear and when to wrap a <em>lock</em> around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge:</p>
<pre><code>class Foo
{
private static readonly string bar = "O_o";
private bool TrySomething()
{
string bar;
lock(Foo.objectToLockOn)
{
bar = Foo.bar;
}
// Do something with bar
}
}
</code></pre>
<p>That just doesn't make sense to me--why would there by concurrency issues with READING a register?</p>
<p>Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL...</p>
<pre><code>class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
lock(Foo.objectToLockOn)
{
return Foo.joke;
}
}
}
</code></pre>
<p>vs.</p>
<pre><code>class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
string joke;
lock(Foo.objectToLockOn)
{
joke = Foo.joke;
}
return joke;
}
}
</code></pre>
| [
{
"answer_id": 105218,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 1,
"selected": false,
"text": "<p>If you're just writing a value to a pointer, you don't need to lock, since that action is atomic. Generally, you should lock any time you need to do a transaction involving at least two atomic actions (reads or writes) that depend on the state not changing between the beginning and end.</p>\n\n<p>That said – I come from Java land, where all reads and writes of variables are atomic actions. Other answers here suggest that .NET is different.</p>\n"
},
{
"answer_id": 105237,
"author": "Brian",
"author_id": 2831,
"author_profile": "https://Stackoverflow.com/users/2831",
"pm_score": 1,
"selected": false,
"text": "<p>Dirty reads?</p>\n"
},
{
"answer_id": 105274,
"author": "Mark Bessey",
"author_id": 17826,
"author_profile": "https://Stackoverflow.com/users/17826",
"pm_score": 3,
"selected": false,
"text": "<p>Reading or writing a 32-bit or smaller field is an atomic operation in C#. There's no need for a lock in the code you presented, as far as I can see.</p>\n"
},
{
"answer_id": 105275,
"author": "Rob",
"author_id": 18505,
"author_profile": "https://Stackoverflow.com/users/18505",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion, you should try very hard to not put static variables in a position where they need to be read/written to from different threads. They are essentially free-for-all global variables in that case, and globals are almost always a Bad Thing.</p>\n\n<p>That being said, if you do put a static variable in such a position, you may want to lock during a read, just in case - remember, another thread may have swooped in and changed the value <em>during</em> the read, and if it does, you may end up with corrupt data. Reads are not necessarily atomic operations unless you ensure they are by locking. Same with writes - they are not always atomic operations either.</p>\n\n<p>Edit:\nAs Mark pointed out, for certain primitives in C# reads are always atomic. But be careful with other data types.</p>\n"
},
{
"answer_id": 105278,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 0,
"selected": false,
"text": "<p>As for your \"which is better\" question, they're the same since the function scope isn't used for anything else.</p>\n"
},
{
"answer_id": 105296,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<p>It looks to me that the lock is unnecessary in your first case. Using the static initializer to initialize bar is guaranteed to be thread safe. Since you only ever read the value, there's no need to lock it. If the value's never going to change, there will never be any contention, why lock at all?</p>\n"
},
{
"answer_id": 105650,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 6,
"selected": true,
"text": "<p>Since none of the code you've written modifies the static field after initialization, there is no need for any locking. Just replacing the string with a new value won't need synchronization either, unless the new value depends on the results of a read of the old value.</p>\n<p>Static fields aren't the only things that need synchronization, any shared reference which could be modified is vulnerable to synchronization issues.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>class Foo\n{\n private int count = 0;\n public void TrySomething() \n {\n count++;\n }\n}\n</code></pre>\n<p>You might suppose that two threads executing the TrySomething method would be fine. But its not.</p>\n<ol>\n<li>Thread A reads the value of count (0) into a register so it can be incremented.</li>\n<li>Context switch! The thread scheduler decides thread A has had enough execution time. Next in line is Thread B.</li>\n<li>Thread B reads the value of count (0) into a register.</li>\n<li>Thread B increments the register.</li>\n<li>Thread B saves the result (1) to count.</li>\n<li>Context switch back to A.</li>\n<li>Thread A reloads the register with the value of count (0) saved on its stack.</li>\n<li>Thread A increments the register.</li>\n<li>Thread A saves the result (1) to count.</li>\n</ol>\n<p>So, even though we called count++ twice, the value of count has just gone from 0 to 1. Lets make the code thread-safe:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>class Foo\n{\n private int count = 0;\n private readonly object sync = new object();\n public void TrySomething() \n {\n lock(sync)\n count++;\n }\n}\n</code></pre>\n<p>Now when Thread A gets interrupted Thread B cannot mess with count because it will hit the lock statement and then block until Thread A has released sync.</p>\n<p>By the way, there is an alternative way to make incrementing Int32s and Int64s thread-safe:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>class Foo\n{\n private int count = 0;\n public void TrySomething() \n {\n System.Threading.Interlocked.Increment(ref count);\n }\n}\n</code></pre>\n<p>Regarding the second part of your question, I think I would just go with whichever is easier to read, any performance difference there will be negligible. Early optimisation is the root of all evil, etc.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/archive/blogs/jmstall/why-threading-is-hard\" rel=\"nofollow noreferrer\">Why threading is hard</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
]
| I'm still a little unclear and when to wrap a *lock* around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge:
```
class Foo
{
private static readonly string bar = "O_o";
private bool TrySomething()
{
string bar;
lock(Foo.objectToLockOn)
{
bar = Foo.bar;
}
// Do something with bar
}
}
```
That just doesn't make sense to me--why would there by concurrency issues with READING a register?
Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL...
```
class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
lock(Foo.objectToLockOn)
{
return Foo.joke;
}
}
}
```
vs.
```
class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
string joke;
lock(Foo.objectToLockOn)
{
joke = Foo.joke;
}
return joke;
}
}
``` | Since none of the code you've written modifies the static field after initialization, there is no need for any locking. Just replacing the string with a new value won't need synchronization either, unless the new value depends on the results of a read of the old value.
Static fields aren't the only things that need synchronization, any shared reference which could be modified is vulnerable to synchronization issues.
```csharp
class Foo
{
private int count = 0;
public void TrySomething()
{
count++;
}
}
```
You might suppose that two threads executing the TrySomething method would be fine. But its not.
1. Thread A reads the value of count (0) into a register so it can be incremented.
2. Context switch! The thread scheduler decides thread A has had enough execution time. Next in line is Thread B.
3. Thread B reads the value of count (0) into a register.
4. Thread B increments the register.
5. Thread B saves the result (1) to count.
6. Context switch back to A.
7. Thread A reloads the register with the value of count (0) saved on its stack.
8. Thread A increments the register.
9. Thread A saves the result (1) to count.
So, even though we called count++ twice, the value of count has just gone from 0 to 1. Lets make the code thread-safe:
```csharp
class Foo
{
private int count = 0;
private readonly object sync = new object();
public void TrySomething()
{
lock(sync)
count++;
}
}
```
Now when Thread A gets interrupted Thread B cannot mess with count because it will hit the lock statement and then block until Thread A has released sync.
By the way, there is an alternative way to make incrementing Int32s and Int64s thread-safe:
```csharp
class Foo
{
private int count = 0;
public void TrySomething()
{
System.Threading.Interlocked.Increment(ref count);
}
}
```
Regarding the second part of your question, I think I would just go with whichever is easier to read, any performance difference there will be negligible. Early optimisation is the root of all evil, etc.
[Why threading is hard](https://learn.microsoft.com/en-us/archive/blogs/jmstall/why-threading-is-hard) |
105,212 | <p>Suppose I have a directory <code>/dir</code> inside which there are 3 symlinks to other directories
<code>/dir/dir11</code>, <code>/dir/dir12</code>, and <code>/dir/dir13</code>. I want to list all the files in <code>dir</code> including the ones in <code>dir11</code>, <code>dir12</code> and <code>dir13</code>.</p>
<p>To be more generic, I want to list all files including the ones in the directories which are symlinks. <code>find .</code>, <code>ls -R</code>, etc stop at the symlink without navigating into them to list further.</p>
| [
{
"answer_id": 105249,
"author": "Michael Ridley",
"author_id": 4838,
"author_profile": "https://Stackoverflow.com/users/4838",
"pm_score": 9,
"selected": true,
"text": "<p>The <code>-L</code> option to <code>ls</code> will accomplish what you want. It dereferences symbolic links.</p>\n\n<p>So your command would be:</p>\n\n<pre><code>ls -LR\n</code></pre>\n\n<p>You can also accomplish this with</p>\n\n<pre><code>find -follow\n</code></pre>\n\n<p>The <code>-follow</code> option directs find to follow symbolic links to directories.</p>\n\n<p>On Mac OS X use</p>\n\n<pre><code>find -L\n</code></pre>\n\n<p>as <code>-follow</code> has been deprecated.</p>\n"
},
{
"answer_id": 105251,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 4,
"selected": false,
"text": "<p>Using ls:</p>\n\n<pre><code> ls -LR\n</code></pre>\n\n<p>from 'man ls':</p>\n\n<pre><code> -L, --dereference\n when showing file information for a symbolic link, show informa‐\n tion for the file the link references rather than for the link\n itself\n</code></pre>\n\n<p>Or, using find:</p>\n\n<pre><code>find -L .\n</code></pre>\n\n<p>From the find manpage:</p>\n\n<pre><code>-L Follow symbolic links.\n</code></pre>\n\n<p>If you find you want to only follow a <em>few</em> symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.</p>\n"
},
{
"answer_id": 105256,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 6,
"selected": false,
"text": "<pre><code>find /dir -type f -follow -print\n</code></pre>\n\n<p><code>-type f</code> means it will display real files (not symlinks)</p>\n\n<p><code>-follow</code> means it will follow your directory symlinks</p>\n\n<p><code>-print</code> will cause it to display the filenames.</p>\n\n<p>If you want a ls type display, you can do the following</p>\n\n<pre><code>find /dir -type f -follow -print|xargs ls -l\n</code></pre>\n"
},
{
"answer_id": 105258,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ls -R -L\n</code></pre>\n\n<p><code>-L</code> dereferences symbolic links. This will also make it impossible to see any symlinks to files, though - they'll look like the pointed-to file.</p>\n"
},
{
"answer_id": 105365,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 7,
"selected": false,
"text": "<p>How about <a href=\"http://mama.indstate.edu/users/ice/tree\" rel=\"noreferrer\">tree</a>? <code>tree -l</code> will follow symlinks.</p>\n\n<p><strong>Disclaimer</strong>: I wrote this package.</p>\n"
},
{
"answer_id": 11785629,
"author": "Ashwin Muni",
"author_id": 1092329,
"author_profile": "https://Stackoverflow.com/users/1092329",
"pm_score": 3,
"selected": false,
"text": "<pre><code>find -L /var/www/ -type l\n\n# man find\n</code></pre>\n\n<blockquote>\n<pre><code>-L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the\n</code></pre>\n \n <p>properties of\n the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to\n examine the file to\n which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is\n in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the\n symbolic link will\n be searched.</p>\n</blockquote>\n"
},
{
"answer_id": 25059432,
"author": "divinedragon",
"author_id": 979772,
"author_profile": "https://Stackoverflow.com/users/979772",
"pm_score": 3,
"selected": false,
"text": "<p>I knew <code>tree</code> was an appropriate, but I didn't have tree installed. So, I got a pretty close alternate <a href=\"http://systembash.com/content/one-line-linux-command-to-print-out-directory-tree-listing/\" rel=\"noreferrer\">here</a> </p>\n\n<pre><code>find ./ | sed -e 's/[^-][^\\/]*\\//--/g;s/--/ |-/'\n</code></pre>\n"
},
{
"answer_id": 51562111,
"author": "qrtLs",
"author_id": 4933053,
"author_profile": "https://Stackoverflow.com/users/4933053",
"pm_score": -1,
"selected": false,
"text": "<p>in case you would like to print all file <strong>contents</strong>:\n<code>find . -type f -exec cat {} +</code></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18072/"
]
| Suppose I have a directory `/dir` inside which there are 3 symlinks to other directories
`/dir/dir11`, `/dir/dir12`, and `/dir/dir13`. I want to list all the files in `dir` including the ones in `dir11`, `dir12` and `dir13`.
To be more generic, I want to list all files including the ones in the directories which are symlinks. `find .`, `ls -R`, etc stop at the symlink without navigating into them to list further. | The `-L` option to `ls` will accomplish what you want. It dereferences symbolic links.
So your command would be:
```
ls -LR
```
You can also accomplish this with
```
find -follow
```
The `-follow` option directs find to follow symbolic links to directories.
On Mac OS X use
```
find -L
```
as `-follow` has been deprecated. |
105,252 | <p>How do I convert between big-endian and little-endian values in C++?</p>
<p>For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.</p>
<hr />
<p>Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.</p>
| [
{
"answer_id": 105297,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "<p>If you're doing this to transfer data between different platforms look at the ntoh and hton functions.</p>\n"
},
{
"answer_id": 105319,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 4,
"selected": false,
"text": "<p>We've done this with templates. You could do something like this:</p>\n\n<pre><code>// Specialization for 2-byte types.\ntemplate<>\ninline void endian_byte_swapper< 2 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n ushort* p_dest = reinterpret_cast< ushort* >(dest);\n ushort const* const p_src = reinterpret_cast< ushort const* >(src);\n *p_dest = (*p_src >> 8) | (*p_src << 8);\n}\n\n// Specialization for 4-byte types.\ntemplate<>\ninline void endian_byte_swapper< 4 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n uint* p_dest = reinterpret_cast< uint* >(dest);\n uint const* const p_src = reinterpret_cast< uint const* >(src);\n *p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);\n}\n</code></pre>\n"
},
{
"answer_id": 105323,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 3,
"selected": false,
"text": "<p>The same way you do in C:</p>\n\n<pre><code>short big = 0xdead;\nshort little = (((big & 0xff)<<8) | ((big & 0xff00)>>8));\n</code></pre>\n\n<p>You could also declare a vector of unsigned chars, memcpy the input value into it, reverse the bytes into another vector and memcpy the bytes out, but that'll take orders of magnitude longer than bit-twiddling, especially with 64-bit values.</p>\n"
},
{
"answer_id": 105328,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": -1,
"selected": false,
"text": "<p>Look up bit shifting, as this is basically all you need to do to swap from little -> big endian. Then depending on the bit size, you change how you do the bit shifting.</p>\n"
},
{
"answer_id": 105339,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using <strong>Visual C++</strong> do the following: You include intrin.h and call the following functions:</p>\n\n<p>For 16 bit numbers:</p>\n\n<pre><code>unsigned short _byteswap_ushort(unsigned short value);\n</code></pre>\n\n<p>For 32 bit numbers:</p>\n\n<pre><code>unsigned long _byteswap_ulong(unsigned long value);\n</code></pre>\n\n<p>For 64 bit numbers:</p>\n\n<pre><code>unsigned __int64 _byteswap_uint64(unsigned __int64 value);\n</code></pre>\n\n<p>8 bit numbers (chars) don't need to be converted.</p>\n\n<p>Also these are only defined for unsigned values they work for signed integers as well.</p>\n\n<p>For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.</p>\n\n<p>Other compilers have similar intrinsics as well. </p>\n\n<p>In <strong>GCC</strong> for example you can directly call <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\" rel=\"noreferrer\">some builtins as documented here</a>:</p>\n\n<pre><code>uint32_t __builtin_bswap32 (uint32_t x)\nuint64_t __builtin_bswap64 (uint64_t x)\n</code></pre>\n\n<p>(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.</p>\n\n<p>16 bit swap it's just a bit-rotate.</p>\n\n<p>Calling the intrinsics instead of rolling your own gives you the best performance and code density btw.. </p>\n"
},
{
"answer_id": 105342,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 4,
"selected": false,
"text": "<p>The procedure for going from big-endian to little-endian is the same as going from little-endian to big-endian.</p>\n\n<p>Here's some example code:</p>\n\n<pre><code>void swapByteOrder(unsigned short& us)\n{\n us = (us >> 8) |\n (us << 8);\n}\n\nvoid swapByteOrder(unsigned int& ui)\n{\n ui = (ui >> 24) |\n ((ui<<8) & 0x00FF0000) |\n ((ui>>8) & 0x0000FF00) |\n (ui << 24);\n}\n\nvoid swapByteOrder(unsigned long long& ull)\n{\n ull = (ull >> 56) |\n ((ull<<40) & 0x00FF000000000000) |\n ((ull<<24) & 0x0000FF0000000000) |\n ((ull<<8) & 0x000000FF00000000) |\n ((ull>>8) & 0x00000000FF000000) |\n ((ull>>24) & 0x0000000000FF0000) |\n ((ull>>40) & 0x000000000000FF00) |\n (ull << 56);\n}\n</code></pre>\n"
},
{
"answer_id": 105354,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": false,
"text": "<p>On most POSIX systems (through it's not in the POSIX standard) there is the endian.h, which can be used to determine what encoding your system uses. From there it's something like this:</p>\n\n<pre><code>unsigned int change_endian(unsigned int x)\n{\n unsigned char *ptr = (unsigned char *)&x;\n return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];\n}\n</code></pre>\n\n<p>This swaps the order (from big endian to little endian):</p>\n\n<p>If you have the number 0xDEADBEEF (on a little endian system stored as 0xEFBEADDE), ptr[0] will be 0xEF, ptr[1] is 0xBE, etc.</p>\n\n<p>But if you want to use it for networking, then htons, htonl and htonll (and their inverses ntohs, ntohl and ntohll) will be helpful for converting from host order to network order.</p>\n"
},
{
"answer_id": 105371,
"author": "anon6439",
"author_id": 15477,
"author_profile": "https://Stackoverflow.com/users/15477",
"pm_score": 4,
"selected": false,
"text": "<p>There is an assembly instruction called BSWAP that will do the swap for you, <em>extremely fast</em>.\nYou can read about it <a href=\"http://oopweb.com/Assembly/Documents/ArtOfAssembly/Volume/Chapter_6/CH06-1.html#HEADING1-291\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Visual Studio, or more precisely the Visual C++ runtime library, has platform intrinsics for this, called <code>_byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64()</code>. Similar should exist for other platforms, but I'm not aware of what they would be called.</p>\n"
},
{
"answer_id": 105410,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 6,
"selected": false,
"text": "<p>If you are doing this for purposes of network/host compatability you should use:</p>\n\n<pre><code>ntohl() //Network to Host byte order (Long)\nhtonl() //Host to Network byte order (Long)\n\nntohs() //Network to Host byte order (Short)\nhtons() //Host to Network byte order (Short)\n</code></pre>\n\n<p>If you are doing this for some other reason one of the byte_swap solutions presented here would work just fine.</p>\n"
},
{
"answer_id": 105632,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a generalized version I came up with off the top of my head, for swapping a value in place. The other suggestions would be better if performance is a problem.</p>\n\n<pre><code> template<typename T>\n void ByteSwap(T * p)\n {\n for (int i = 0; i < sizeof(T)/2; ++i)\n std::swap(((char *)p)[i], ((char *)p)[sizeof(T)-1-i]);\n }\n</code></pre>\n\n<p><strong>Disclaimer:</strong> I haven't tried to compile this or test it yet.</p>\n"
},
{
"answer_id": 107099,
"author": "Mathieu Pagé",
"author_id": 5861,
"author_profile": "https://Stackoverflow.com/users/5861",
"pm_score": 2,
"selected": false,
"text": "<p>I have this code that allow me to convert from HOST_ENDIAN_ORDER (whatever it is) to LITTLE_ENDIAN_ORDER or BIG_ENDIAN_ORDER. I use a template, so if I try to convert from HOST_ENDIAN_ORDER to LITTLE_ENDIAN_ORDER and they happen to be the same for the machine for wich I compile, no code will be generated.</p>\n\n<p>Here is the code with some comments:</p>\n\n<pre><code>// We define some constant for little, big and host endianess. Here I use \n// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you\n// don't want to use boost you will have to modify this part a bit.\nenum EEndian\n{\n LITTLE_ENDIAN_ORDER,\n BIG_ENDIAN_ORDER,\n#if defined(BOOST_LITTLE_ENDIAN)\n HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER\n#elif defined(BOOST_BIG_ENDIAN)\n HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER\n#else\n#error \"Impossible de determiner l'indianness du systeme cible.\"\n#endif\n};\n\n// this function swap the bytes of values given it's size as a template\n// parameter (could sizeof be used?).\ntemplate <class T, unsigned int size>\ninline T SwapBytes(T value)\n{\n union\n {\n T value;\n char bytes[size];\n } in, out;\n\n in.value = value;\n\n for (unsigned int i = 0; i < size / 2; ++i)\n {\n out.bytes[i] = in.bytes[size - 1 - i];\n out.bytes[size - 1 - i] = in.bytes[i];\n }\n\n return out.value;\n}\n\n// Here is the function you will use. Again there is two compile-time assertion\n// that use the boost librarie. You could probably comment them out, but if you\n// do be cautious not to use this function for anything else than integers\n// types. This function need to be calles like this :\n//\n// int x = someValue;\n// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);\n//\ntemplate<EEndian from, EEndian to, class T>\ninline T EndianSwapBytes(T value)\n{\n // A : La donnée à swapper à une taille de 2, 4 ou 8 octets\n BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n\n // A : La donnée à swapper est d'un type arithmetic\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n // Si from et to sont du même type on ne swap pas.\n if (from == to)\n return value;\n\n return SwapBytes<T, sizeof(T)>(value);\n}\n</code></pre>\n"
},
{
"answer_id": 3522853,
"author": "Steve Lorimer",
"author_id": 955273,
"author_profile": "https://Stackoverflow.com/users/955273",
"pm_score": 5,
"selected": false,
"text": "<p>I took a few suggestions from this post and put them together to form this:</p>\n<pre><code>#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/detail/endian.hpp>\n#include <stdexcept>\n#include <cstdint>\n\nenum endianness\n{\n little_endian,\n big_endian,\n network_endian = big_endian,\n \n #if defined(BOOST_LITTLE_ENDIAN)\n host_endian = little_endian\n #elif defined(BOOST_BIG_ENDIAN)\n host_endian = big_endian\n #else\n #error "unable to determine system endianness"\n #endif\n};\n\nnamespace detail {\n\ntemplate<typename T, size_t sz>\nstruct swap_bytes\n{\n inline T operator()(T val)\n {\n throw std::out_of_range("data size");\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 1>\n{\n inline T operator()(T val)\n {\n return val;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 2>\n{\n inline T operator()(T val)\n {\n return ((((val) >> 8) & 0xff) | (((val) & 0xff) << 8));\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 4>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff000000) >> 24) |\n (((val) & 0x00ff0000) >> 8) |\n (((val) & 0x0000ff00) << 8) |\n (((val) & 0x000000ff) << 24));\n }\n};\n\ntemplate<>\nstruct swap_bytes<float, 4>\n{\n inline float operator()(float val)\n {\n uint32_t mem =swap_bytes<uint32_t, sizeof(uint32_t)>()(*(uint32_t*)&val);\n return *(float*)&mem;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 8>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff00000000000000ull) >> 56) |\n (((val) & 0x00ff000000000000ull) >> 40) |\n (((val) & 0x0000ff0000000000ull) >> 24) |\n (((val) & 0x000000ff00000000ull) >> 8 ) |\n (((val) & 0x00000000ff000000ull) << 8 ) |\n (((val) & 0x0000000000ff0000ull) << 24) |\n (((val) & 0x000000000000ff00ull) << 40) |\n (((val) & 0x00000000000000ffull) << 56));\n }\n};\n\ntemplate<>\nstruct swap_bytes<double, 8>\n{\n inline double operator()(double val)\n {\n uint64_t mem =swap_bytes<uint64_t, sizeof(uint64_t)>()(*(uint64_t*)&val);\n return *(double*)&mem;\n }\n};\n\ntemplate<endianness from, endianness to, class T>\nstruct do_byte_swap\n{\n inline T operator()(T value)\n {\n return swap_bytes<T, sizeof(T)>()(value);\n }\n};\n// specialisations when attempting to swap to the same endianess\ntemplate<class T> struct do_byte_swap<little_endian, little_endian, T> { inline T operator()(T value) { return value; } };\ntemplate<class T> struct do_byte_swap<big_endian, big_endian, T> { inline T operator()(T value) { return value; } };\n\n} // namespace detail\n\ntemplate<endianness from, endianness to, class T>\ninline T byte_swap(T value)\n{\n // ensure the data is only 1, 2, 4 or 8 bytes\n BOOST_STATIC_ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n // ensure we're only swapping arithmetic types\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n return detail::do_byte_swap<from, to, T>()(value);\n}\n</code></pre>\n<p>You would then use it as follows:</p>\n<pre><code>// swaps val from host-byte-order to network-byte-order\nauto swapped = byte_swap<host_endian, network_endian>(val);\n</code></pre>\n<p>and vice-versa</p>\n<pre><code>// swap a value received from the network into host-byte-order\nauto val = byte_swap<network_endian, host_endian>(val_from_network);\n</code></pre>\n"
},
{
"answer_id": 4956493,
"author": "Alexandre C.",
"author_id": 373025,
"author_profile": "https://Stackoverflow.com/users/373025",
"pm_score": 7,
"selected": false,
"text": "<p>Simply put:</p>\n\n<pre><code>#include <climits>\n\ntemplate <typename T>\nT swap_endian(T u)\n{\n static_assert (CHAR_BIT == 8, \"CHAR_BIT != 8\");\n\n union\n {\n T u;\n unsigned char u8[sizeof(T)];\n } source, dest;\n\n source.u = u;\n\n for (size_t k = 0; k < sizeof(T); k++)\n dest.u8[k] = source.u8[sizeof(T) - k - 1];\n\n return dest.u;\n}\n</code></pre>\n\n<p>usage: <code>swap_endian<uint32_t>(42)</code>.</p>\n"
},
{
"answer_id": 4956807,
"author": "Maxim Egorushkin",
"author_id": 412080,
"author_profile": "https://Stackoverflow.com/users/412080",
"pm_score": 3,
"selected": false,
"text": "<p>Most platforms have a system header file that provides efficient byteswap functions. On Linux it is in <code><endian.h></code>. You can wrap it nicely in C++:</p>\n\n<pre><code>#include <iostream>\n\n#include <endian.h>\n\ntemplate<size_t N> struct SizeT {};\n\n#define BYTESWAPS(bits) \\\ntemplate<class T> inline T htobe(T t, SizeT<bits / 8>) { return htobe ## bits(t); } \\\ntemplate<class T> inline T htole(T t, SizeT<bits / 8>) { return htole ## bits(t); } \\\ntemplate<class T> inline T betoh(T t, SizeT<bits / 8>) { return be ## bits ## toh(t); } \\\ntemplate<class T> inline T letoh(T t, SizeT<bits / 8>) { return le ## bits ## toh(t); }\n\nBYTESWAPS(16)\nBYTESWAPS(32)\nBYTESWAPS(64)\n\n#undef BYTESWAPS\n\ntemplate<class T> inline T htobe(T t) { return htobe(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T htole(T t) { return htole(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T betoh(T t) { return betoh(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T letoh(T t) { return letoh(t, SizeT<sizeof t>()); }\n\nint main()\n{\n std::cout << std::hex;\n std::cout << htobe(static_cast<unsigned short>(0xfeca)) << '\\n';\n std::cout << htobe(0xafbeadde) << '\\n';\n\n // Use ULL suffix to specify integer constant as unsigned long long \n std::cout << htobe(0xfecaefbeafdeedfeULL) << '\\n';\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>cafe\ndeadbeaf\nfeeddeafbeefcafe\n</code></pre>\n"
},
{
"answer_id": 6487066,
"author": "friedemann",
"author_id": 815363,
"author_profile": "https://Stackoverflow.com/users/815363",
"pm_score": 2,
"selected": false,
"text": "<p>i like this one, just for style :-)</p>\n\n<pre><code>long swap(long i) {\n char *c = (char *) &i;\n return * (long *) (char[]) {c[3], c[2], c[1], c[0] };\n}\n</code></pre>\n"
},
{
"answer_id": 10346064,
"author": "Matthieu M.",
"author_id": 147192,
"author_profile": "https://Stackoverflow.com/users/147192",
"pm_score": 6,
"selected": false,
"text": "<p>From <strong><a href=\"http://commandcenter.blogspot.fr/2012/04/byte-order-fallacy.html\" rel=\"nofollow noreferrer\">The Byte Order Fallacy</a></strong> by Rob Pike:</p>\n<blockquote>\n<p>Let's say your data stream has a little-endian-encoded 32-bit integer. Here's how to extract it (assuming unsigned bytes):</p>\n</blockquote>\n<pre><code>i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | ((unsigned)data[3]<<24);\n</code></pre>\n<blockquote>\n<p>If it's big-endian, here's how to extract it:</p>\n</blockquote>\n<pre><code>i = (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | ((unsigned)data[0]<<24);\n</code></pre>\n<p><strong>TL;DR:</strong> don't worry about your platform native order, all that counts is the byte order of the stream your are reading from, and you better hope it's well defined.</p>\n<p><em>Note 1: It is expected that <code>int</code> and <code>unsigned int</code> be 32 bits here, types may require adjustment otherwise.</em></p>\n<p><em>Note 2: The last byte must be explicitly cast to <code>unsigned</code> before shifting, as by default it's promoted to <code>int</code>, and a shift by 24 bits means manipulating the sign bit which is Undefined Behavior.</em></p>\n"
},
{
"answer_id": 18333053,
"author": "user2699548",
"author_id": 2699548,
"author_profile": "https://Stackoverflow.com/users/2699548",
"pm_score": 3,
"selected": false,
"text": "<p>Note that, at least for Windows, htonl() is much slower than their intrinsic counterpart _byteswap_ulong(). The former is a DLL library call into ws2_32.dll, the latter is one BSWAP assembly instruction. Therefore, if you are writing some platform-dependent code, prefer using the intrinsics for speed:</p>\n\n<pre><code>#define htonl(x) _byteswap_ulong(x)\n</code></pre>\n\n<p>This may be especially important for .PNG image processing where all integers are saved in Big Endian with explanation \"One can use htonl()...\" {to slow down typical Windows programs, if you are not prepared}.</p>\n"
},
{
"answer_id": 18334154,
"author": "sh1",
"author_id": 2417578,
"author_profile": "https://Stackoverflow.com/users/2417578",
"pm_score": 2,
"selected": false,
"text": "<p>If you take the common pattern for reversing the order of bits in a word, and cull the part that reverses bits within each byte, then you're left with something which only reverses the bytes within a word. For 64-bits:</p>\n\n<pre><code>x = ((x & 0x00000000ffffffff) << 32) ^ ((x >> 32) & 0x00000000ffffffff);\nx = ((x & 0x0000ffff0000ffff) << 16) ^ ((x >> 16) & 0x0000ffff0000ffff);\nx = ((x & 0x00ff00ff00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff00ff00ff);\n</code></pre>\n\n<p>The compiler <em>should</em> clean out the superfluous bit-masking operations (I left them in to highlight the pattern), but if it doesn't you can rewrite the first line this way:</p>\n\n<pre><code>x = ( x << 32) ^ (x >> 32);\n</code></pre>\n\n<p>That should normally simplify down to a single rotate instruction on most architectures (ignoring that the whole operation is probably one instruction).</p>\n\n<p>On a RISC processor the large, complicated constants may cause the compiler difficulties. You can trivially calculate each of the constants from the previous one, though. Like so:</p>\n\n<pre><code>uint64_t k = 0x00000000ffffffff; /* compiler should know a trick for this */\nx = ((x & k) << 32) ^ ((x >> 32) & k);\nk ^= k << 16;\nx = ((x & k) << 16) ^ ((x >> 16) & k);\nk ^= k << 8;\nx = ((x & k) << 8) ^ ((x >> 8) & k);\n</code></pre>\n\n<p>If you like, you can write that as a loop. It won't be efficient, but just for fun:</p>\n\n<pre><code>int i = sizeof(x) * CHAR_BIT / 2;\nuintmax_t k = (1 << i) - 1;\nwhile (i >= 8)\n{\n x = ((x & k) << i) ^ ((x >> i) & k);\n i >>= 1;\n k ^= k << i;\n}\n</code></pre>\n\n<p>And for completeness, here's the simplified 32-bit version of the first form:</p>\n\n<pre><code>x = ( x << 16) ^ (x >> 16);\nx = ((x & 0x00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff);\n</code></pre>\n"
},
{
"answer_id": 25177297,
"author": "The Quantum Physicist",
"author_id": 1317944,
"author_profile": "https://Stackoverflow.com/users/1317944",
"pm_score": 3,
"selected": false,
"text": "<p>Seriously... I don't understand why all solutions are that <strong><em>complicated</em></strong>! <strong>How about the simplest, most general template function that swaps any type of any size under any circumstances in any operating system????</strong></p>\n\n<pre><code>template <typename T>\nvoid SwapEnd(T& var)\n{\n static_assert(std::is_pod<T>::value, \"Type must be POD type for safety\");\n std::array<char, sizeof(T)> varArray;\n std::memcpy(varArray.data(), &var, sizeof(T));\n for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)\n std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);\n std::memcpy(&var, varArray.data(), sizeof(T));\n}\n</code></pre>\n\n<p>It's the magic power of C and C++ together! Simply swap the original variable character by character.</p>\n\n<p><strong>Point 1</strong>: No operators: Remember that I didn't use the simple assignment operator \"=\" because some objects will be messed up when the endianness is flipped and the copy constructor (or assignment operator) won't work. Therefore, it's more reliable to copy them char by char.</p>\n\n<p><strong>Point 2</strong>: Be aware of alignment issues: Notice that we're copying to and from an array, which is the right thing to do because the C++ compiler doesn't guarantee that we can access unaligned memory (this answer was updated from its original form for this). For example, if you allocate <code>uint64_t</code>, your compiler cannot guarantee that you can access the 3rd byte of that as a <code>uint8_t</code>. Therefore, the right thing to do is to copy this to a char array, swap it, then copy it back (so no <code>reinterpret_cast</code>). Notice that compilers are mostly smart enough to convert what you did back to a <code>reinterpret_cast</code> if they're capable of accessing individual bytes regardless of alignment.</p>\n\n<p><strong>To use this function</strong>:</p>\n\n<pre><code>double x = 5;\nSwapEnd(x);\n</code></pre>\n\n<p>and now <code>x</code> is different in endianness.</p>\n"
},
{
"answer_id": 25704741,
"author": "Adam Freeman",
"author_id": 538458,
"author_profile": "https://Stackoverflow.com/users/538458",
"pm_score": 2,
"selected": false,
"text": "<p>If a big-endian 32-bit unsigned integer looks like 0xAABBCCDD which is equal to 2864434397, then that same 32-bit unsigned integer looks like 0xDDCCBBAA on a little-endian processor which is also equal to 2864434397.</p>\n\n<p>If a big-endian 16-bit unsigned short looks like 0xAABB which is equal to 43707, then that same 16-bit unsigned short looks like 0xBBAA on a little-endian processor which is also equal to 43707.</p>\n\n<p>Here are a couple of handy #define functions to swap bytes from little-endian to big-endian and vice-versa --></p>\n\n<pre><code>// can be used for short, unsigned short, word, unsigned word (2-byte types)\n#define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))\n\n// can be used for int or unsigned int or float (4-byte types)\n#define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))\n\n// can be used for unsigned long long or double (8-byte types)\n#define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))\n</code></pre>\n"
},
{
"answer_id": 26007257,
"author": "The Welder",
"author_id": 2086872,
"author_profile": "https://Stackoverflow.com/users/2086872",
"pm_score": 0,
"selected": false,
"text": "<p>Wow, I couldn't believe some of the answers I've read here. There's actually an instruction in assembly which does this faster than anything else. bswap. You could simply write a function like this...</p>\n<pre><code>__declspec(naked) uint32_t EndianSwap(uint32 value)\n{\n __asm\n {\n mov eax, dword ptr[esp + 4]\n bswap eax\n ret\n }\n}\n</code></pre>\n<p>It is <em>MUCH</em> faster than the intrinsics that have been suggested. I've disassembled them and looked. The above function has no prologue/epilogue so virtually has no overhead at all.</p>\n<pre><code>unsigned long _byteswap_ulong(unsigned long value);\n</code></pre>\n<p>Doing 16 bit is just as easy, with the exception that you'd use xchg al, ah. bswap only works on 32-bit registers.</p>\n<p>64-bit is a little more tricky, but not overly so. Much better than all of the above examples with loops and templates etc.</p>\n<p>There are some caveats here... Firstly bswap is only available on 80x486 CPU's and above. Is anyone planning on running it on a 386?!? If so, you can still replace bswap with...</p>\n<pre><code>mov ebx, eax\nshr ebx, 16\nxchg al, ah\nxchg bl, bh\nshl eax, 16\nor eax, ebx\n</code></pre>\n<p>Also inline assembly is only available in x86 code in Visual Studio. A naked function cannot be lined and also isn't available in x64 builds. I that instance, you're going to have to use the compiler intrinsics.</p>\n"
},
{
"answer_id": 35092546,
"author": "Joao",
"author_id": 1604608,
"author_profile": "https://Stackoverflow.com/users/1604608",
"pm_score": 2,
"selected": false,
"text": "<p>Just thought I added my own solution here since I haven't seen it anywhere. It's a small and portable C++ templated function and portable that only uses bit operations.</p>\n\n<pre><code>template<typename T> inline static T swapByteOrder(const T& val) {\n int totalBytes = sizeof(val);\n T swapped = (T) 0;\n for (int i = 0; i < totalBytes; ++i) {\n swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);\n }\n return swapped;\n}\n</code></pre>\n"
},
{
"answer_id": 37386513,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 0,
"selected": false,
"text": "<p>Portable technique for implementing optimizer-friendly unaligned non-inplace endian accessors. They work on every compiler, every boundary alignment and every byte ordering. These unaligned routines are supplemented, or mooted, depending on native endian and alignment. Partial listing but you get the idea. BO* are constant values based on native byte ordering.</p>\n\n<pre><code>uint32_t sw_get_uint32_1234(pu32)\nuint32_1234 *pu32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32_1234[0] = (*pu32)[BO32_0];\n bou32.u32_1234[1] = (*pu32)[BO32_1];\n bou32.u32_1234[2] = (*pu32)[BO32_2];\n bou32.u32_1234[3] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_1234(pu32, u32)\nuint32_1234 *pu32;\nuint32_t u32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_1234[0];\n (*pu32)[BO32_1] = bou32.u32_1234[1];\n (*pu32)[BO32_2] = bou32.u32_1234[2];\n (*pu32)[BO32_3] = bou32.u32_1234[3];\n}\n\n#if HAS_SW_INT64\nint64 sw_get_int64_12345678(pi64)\nint64_12345678 *pi64;\n{\n union {\n int64_12345678 i64_12345678;\n int64 i64;\n } boi64;\n boi64.i64_12345678[0] = (*pi64)[BO64_0];\n boi64.i64_12345678[1] = (*pi64)[BO64_1];\n boi64.i64_12345678[2] = (*pi64)[BO64_2];\n boi64.i64_12345678[3] = (*pi64)[BO64_3];\n boi64.i64_12345678[4] = (*pi64)[BO64_4];\n boi64.i64_12345678[5] = (*pi64)[BO64_5];\n boi64.i64_12345678[6] = (*pi64)[BO64_6];\n boi64.i64_12345678[7] = (*pi64)[BO64_7];\n return(boi64.i64);\n}\n#endif\n\nint32_t sw_get_int32_3412(pi32)\nint32_3412 *pi32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32_3412[2] = (*pi32)[BO32_0];\n boi32.i32_3412[3] = (*pi32)[BO32_1];\n boi32.i32_3412[0] = (*pi32)[BO32_2];\n boi32.i32_3412[1] = (*pi32)[BO32_3];\n return(boi32.i32);\n}\n\nvoid sw_set_int32_3412(pi32, i32)\nint32_3412 *pi32;\nint32_t i32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32 = i32;\n (*pi32)[BO32_0] = boi32.i32_3412[2];\n (*pi32)[BO32_1] = boi32.i32_3412[3];\n (*pi32)[BO32_2] = boi32.i32_3412[0];\n (*pi32)[BO32_3] = boi32.i32_3412[1];\n}\n\nuint32_t sw_get_uint32_3412(pu32)\nuint32_3412 *pu32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32_3412[2] = (*pu32)[BO32_0];\n bou32.u32_3412[3] = (*pu32)[BO32_1];\n bou32.u32_3412[0] = (*pu32)[BO32_2];\n bou32.u32_3412[1] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_3412(pu32, u32)\nuint32_3412 *pu32;\nuint32_t u32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_3412[2];\n (*pu32)[BO32_1] = bou32.u32_3412[3];\n (*pu32)[BO32_2] = bou32.u32_3412[0];\n (*pu32)[BO32_3] = bou32.u32_3412[1];\n}\n\nfloat sw_get_float_1234(pf)\nfloat_1234 *pf;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f_1234[0] = (*pf)[BO32_0];\n bof.f_1234[1] = (*pf)[BO32_1];\n bof.f_1234[2] = (*pf)[BO32_2];\n bof.f_1234[3] = (*pf)[BO32_3];\n return(bof.f);\n}\n\nvoid sw_set_float_1234(pf, f)\nfloat_1234 *pf;\nfloat f;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f = (float)f;\n (*pf)[BO32_0] = bof.f_1234[0];\n (*pf)[BO32_1] = bof.f_1234[1];\n (*pf)[BO32_2] = bof.f_1234[2];\n (*pf)[BO32_3] = bof.f_1234[3];\n}\n\ndouble sw_get_double_12345678(pd)\ndouble_12345678 *pd;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d_12345678[0] = (*pd)[BO64_0];\n bod.d_12345678[1] = (*pd)[BO64_1];\n bod.d_12345678[2] = (*pd)[BO64_2];\n bod.d_12345678[3] = (*pd)[BO64_3];\n bod.d_12345678[4] = (*pd)[BO64_4];\n bod.d_12345678[5] = (*pd)[BO64_5];\n bod.d_12345678[6] = (*pd)[BO64_6];\n bod.d_12345678[7] = (*pd)[BO64_7];\n return(bod.d);\n}\n\nvoid sw_set_double_12345678(pd, d)\ndouble_12345678 *pd;\ndouble d;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d = d;\n (*pd)[BO64_0] = bod.d_12345678[0];\n (*pd)[BO64_1] = bod.d_12345678[1];\n (*pd)[BO64_2] = bod.d_12345678[2];\n (*pd)[BO64_3] = bod.d_12345678[3];\n (*pd)[BO64_4] = bod.d_12345678[4];\n (*pd)[BO64_5] = bod.d_12345678[5];\n (*pd)[BO64_6] = bod.d_12345678[6];\n (*pd)[BO64_7] = bod.d_12345678[7];\n}\n</code></pre>\n\n<p>These typedefs have the benefit of raising compiler errors if not used with accessors, thus mitigating forgotten accessor bugs.</p>\n\n<pre><code>typedef char int8_1[1], uint8_1[1];\n\ntypedef char int16_12[2], uint16_12[2]; /* little endian */\ntypedef char int16_21[2], uint16_21[2]; /* big endian */\n\ntypedef char int24_321[3], uint24_321[3]; /* Alpha Micro, PDP-11 */\n\ntypedef char int32_1234[4], uint32_1234[4]; /* little endian */\ntypedef char int32_3412[4], uint32_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char int32_4321[4], uint32_4321[4]; /* big endian */\n\ntypedef char int64_12345678[8], uint64_12345678[8]; /* little endian */\ntypedef char int64_34128756[8], uint64_34128756[8]; /* Alpha Micro, PDP-11 */\ntypedef char int64_87654321[8], uint64_87654321[8]; /* big endian */\n\ntypedef char float_1234[4]; /* little endian */\ntypedef char float_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char float_4321[4]; /* big endian */\n\ntypedef char double_12345678[8]; /* little endian */\ntypedef char double_78563412[8]; /* Alpha Micro? */\ntypedef char double_87654321[8]; /* big endian */\n</code></pre>\n"
},
{
"answer_id": 39548833,
"author": "pz64_",
"author_id": 6737471,
"author_profile": "https://Stackoverflow.com/users/6737471",
"pm_score": 2,
"selected": false,
"text": "<p>Using the codes below, you can swap between BigEndian and LittleEndian easily </p>\n\n<pre><code>#define uint32_t unsigned \n#define uint16_t unsigned short\n\n#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \\\n(((uint16_t)(x) & 0xff00)>>8))\n\n#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \\\n(((uint32_t)(x) & 0x0000ff00)<<8)| \\\n(((uint32_t)(x) & 0x00ff0000)>>8)| \\\n(((uint32_t)(x) & 0xff000000)>>24))\n</code></pre>\n"
},
{
"answer_id": 41196306,
"author": "Ryan Hilbert",
"author_id": 2884225,
"author_profile": "https://Stackoverflow.com/users/2884225",
"pm_score": 1,
"selected": false,
"text": "<p>I recently wrote a macro to do this in C, but it's equally valid in C++:</p>\n<pre><code>#define REVERSE_BYTES(...) do for(size_t REVERSE_BYTES=0; REVERSE_BYTES<sizeof(__VA_ARGS__)>>1; ++REVERSE_BYTES)\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES];\\\nwhile(0)\n</code></pre>\n<p>It accepts any type and reverses the bytes in the passed argument.\nExample usages:</p>\n<pre><code>int main(){\n unsigned long long x = 0xABCDEF0123456789;\n printf("Before: %llX\\n",x);\n REVERSE_BYTES(x);\n printf("After : %llX\\n",x);\n\n char c[7]="nametag";\n printf("Before: %c%c%c%c%c%c%c\\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n REVERSE_BYTES(c);\n printf("After : %c%c%c%c%c%c%c\\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n}\n</code></pre>\n<p>Which prints:</p>\n<pre><code>Before: ABCDEF0123456789\nAfter : 8967452301EFCDAB\nBefore: nametag\nAfter : gateman\n</code></pre>\n<p>The above is perfectly copy/paste-able, but there's a lot going on here, so I'll break down how it works piece by piece:</p>\n<p>The first notable thing is that the entire macro is encased in a <code>do while(0)</code> block. This is a <a href=\"https://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html\" rel=\"nofollow noreferrer\">common idiom</a> to allow normal semicolon use after the macro.</p>\n<p>Next up is the use of a variable named <code>REVERSE_BYTES</code> as the <code>for</code> loop's counter. The name of the macro itself is used as a variable name to ensure that it doesn't clash with any other symbols that may be in scope wherever the macro is used. Since the name is being used within the macro's expansion, it won't be expanded again when used as a variable name here.</p>\n<p>Within the <code>for</code> loop, there are two bytes being referenced and <a href=\"https://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"nofollow noreferrer\">XOR swapped</a> (so a temporary variable name is not required):</p>\n<pre><code>((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES]\n((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES]\n</code></pre>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html\" rel=\"nofollow noreferrer\"><code>__VA_ARGS__</code></a> represents whatever was given to the macro, and is used to increase the flexibility of what may be passed in (albeit not by much). The address of this argument is then taken and cast to an <code>unsigned char</code> pointer to permit the swapping of its bytes via array <code>[]</code> subscripting.</p>\n<p>The final peculiar point is the lack of <code>{}</code> braces. They aren't necessary because all of the steps in each swap are joined with the <a href=\"https://en.wikipedia.org/wiki/Comma_operator\" rel=\"nofollow noreferrer\">comma operator</a>, making them one statement.</p>\n<p>Finally, it's worth noting that this is not the ideal approach if speed is a top priority. If this is an important factor, some of the type-specific macros or platform-specific directives referenced in other answers are likely a better option. This approach, however, is portable to all types, all major platforms, and both the C and C++ languages.</p>\n"
},
{
"answer_id": 43923866,
"author": "Nick",
"author_id": 964080,
"author_profile": "https://Stackoverflow.com/users/964080",
"pm_score": 2,
"selected": false,
"text": "<p>I am really surprised no one mentioned htobeXX and betohXX functions. They are defined in endian.h and are very similar to network functions htonXX.</p>\n"
},
{
"answer_id": 44123161,
"author": "Malcolm McLean",
"author_id": 3310281,
"author_profile": "https://Stackoverflow.com/users/3310281",
"pm_score": -1,
"selected": false,
"text": "<p>Here's how to read a double stored in IEEE 754 64 bit format, even if your host computer uses a different system.</p>\n\n<pre><code>/*\n* read a double from a stream in ieee754 format regardless of host\n* encoding.\n* fp - the stream\n* bigendian - set to if big bytes first, clear for little bytes\n* first\n*\n*/\ndouble freadieee754(FILE *fp, int bigendian)\n{\n unsigned char buff[8];\n int i;\n double fnorm = 0.0;\n unsigned char temp;\n int sign;\n int exponent;\n double bitval;\n int maski, mask;\n int expbits = 11;\n int significandbits = 52;\n int shift;\n double answer;\n\n /* read the data */\n for (i = 0; i < 8; i++)\n buff[i] = fgetc(fp);\n /* just reverse if not big-endian*/\n if (!bigendian)\n {\n for (i = 0; i < 4; i++)\n {\n temp = buff[i];\n buff[i] = buff[8 - i - 1];\n buff[8 - i - 1] = temp;\n }\n }\n sign = buff[0] & 0x80 ? -1 : 1;\n /* exponet in raw format*/\n exponent = ((buff[0] & 0x7F) << 4) | ((buff[1] & 0xF0) >> 4);\n\n /* read inthe mantissa. Top bit is 0.5, the successive bits half*/\n bitval = 0.5;\n maski = 1;\n mask = 0x08;\n for (i = 0; i < significandbits; i++)\n {\n if (buff[maski] & mask)\n fnorm += bitval;\n\n bitval /= 2.0;\n mask >>= 1;\n if (mask == 0)\n {\n mask = 0x80;\n maski++;\n }\n }\n /* handle zero specially */\n if (exponent == 0 && fnorm == 0)\n return 0.0;\n\n shift = exponent - ((1 << (expbits - 1)) - 1); /* exponent = shift + bias */\n /* nans have exp 1024 and non-zero mantissa */\n if (shift == 1024 && fnorm != 0)\n return sqrt(-1.0);\n /*infinity*/\n if (shift == 1024 && fnorm == 0)\n {\n\n#ifdef INFINITY\n return sign == 1 ? INFINITY : -INFINITY;\n#endif\n return (sign * 1.0) / 0.0;\n }\n if (shift > -1023)\n {\n answer = ldexp(fnorm + 1.0, shift);\n return answer * sign;\n }\n else\n {\n /* denormalised numbers */\n if (fnorm == 0.0)\n return 0.0;\n shift = -1022;\n while (fnorm < 1.0)\n {\n fnorm *= 2;\n shift--;\n }\n answer = ldexp(fnorm, shift);\n return answer * sign;\n }\n}\n</code></pre>\n\n<p>For the rest of the suite of functions, including the write and the integer routines see my github project</p>\n\n<p><a href=\"https://github.com/MalcolmMcLean/ieee754\" rel=\"nofollow noreferrer\">https://github.com/MalcolmMcLean/ieee754</a></p>\n"
},
{
"answer_id": 55634732,
"author": "Quinn Carver",
"author_id": 2953356,
"author_profile": "https://Stackoverflow.com/users/2953356",
"pm_score": 0,
"selected": false,
"text": "<p>Byte swapping with ye olde 3-step-xor trick around a pivot in a template function gives a flexible, quick O(ln2) solution that does not require a library, the style here also rejects 1 byte types:</p>\n\n<pre><code>template<typename T>void swap(T &t){\n for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n *((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55756299,
"author": "cycollins",
"author_id": 8611540,
"author_profile": "https://Stackoverflow.com/users/8611540",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like the safe way would be to use htons on each word. So, if you have...</p>\n\n<pre><code>std::vector<uint16_t> storage(n); // where n is the number to be converted\n\n// the following would do the trick\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n</code></pre>\n\n<p>The above would be a no-op if you were on a big-endian system, so I would look for whatever your platform uses as a compile-time condition to decide whether htons is a no-op. It is O(n) after all. On a Mac, it would be something like ...</p>\n\n<pre><code>#if (__DARWIN_BYTE_ORDER != __DARWIN_BIG_ENDIAN)\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n#endif\n</code></pre>\n"
},
{
"answer_id": 61146679,
"author": "Thinkal VB",
"author_id": 7057208,
"author_profile": "https://Stackoverflow.com/users/7057208",
"pm_score": 1,
"selected": false,
"text": "<p>If you have C++ 17 then add this header</p>\n\n<pre><code>#include <algorithm>\n</code></pre>\n\n<p>Use this template function to swap the bytes:</p>\n\n<pre><code>template <typename T>\nvoid swapEndian(T& buffer)\n{\n static_assert(std::is_pod<T>::value, \"swapEndian support POD type only\");\n char* startIndex = static_cast<char*>((void*)buffer.data());\n char* endIndex = startIndex + sizeof(buffer);\n std::reverse(startIndex, endIndex);\n}\n</code></pre>\n\n<p>call it like:</p>\n\n<pre><code>swapEndian (stlContainer);\n</code></pre>\n"
},
{
"answer_id": 63106400,
"author": "Mrocco",
"author_id": 12178397,
"author_profile": "https://Stackoverflow.com/users/12178397",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a basic function to swap to/from little and big endian. It's basic but it doesn't require supplementary libraries.</p>\n<pre><code>void endianness_swap(uint32_t& val) {\n uint8_t a, b, c;\n a = (val & 0xFF000000) >> 24;\n b = (val & 0x00FF0000) >> 16;\n c = (val & 0x0000FF00) >> 8;\n val=(val & 0x000000FF) << 24;\n val = val + (c << 16) + (b << 8) + (a);\n}\n</code></pre>\n"
},
{
"answer_id": 67458876,
"author": "Sunny127",
"author_id": 1925162,
"author_profile": "https://Stackoverflow.com/users/1925162",
"pm_score": -1,
"selected": false,
"text": "<pre><code>void writeLittleEndianToBigEndian(void* ptrLittleEndian, void* ptrBigEndian , size_t bufLen )\n{\n char *pchLittleEndian = (char*)ptrLittleEndian;\n\n char *pchBigEndian = (char*)ptrBigEndian;\n\n for ( size_t i = 0 ; i < bufLen ; i++ ) \n pchBigEndian[bufLen-1-i] = pchLittleEndian[i];\n}\n\nstd::uint32_t row = 0x12345678;\n\nchar buf[4]; \n\nwriteLittleEndianToBigEndian( &row, &buf, sizeof(row) );\n</code></pre>\n"
},
{
"answer_id": 67681004,
"author": "natersoz",
"author_id": 138264,
"author_profile": "https://Stackoverflow.com/users/138264",
"pm_score": 0,
"selected": false,
"text": "<p>Not as efficient as using an intrinsic function, but certainly portable. My answer:</p>\n<pre><code>#include <cstdint>\n#include <type_traits>\n\n/**\n * Perform an endian swap of bytes against a templatized unsigned word.\n *\n * @tparam value_type The data type to perform the endian swap against.\n * @param value The data value to swap.\n *\n * @return value_type The resulting swapped word.\n */\ntemplate <typename value_type>\nconstexpr inline auto endian_swap(value_type value) -> value_type\n{\n using half_type = typename std::conditional<\n sizeof(value_type) == 8u,\n uint32_t,\n typename std::conditional<sizeof(value_type) == 4u, uint16_t, uint8_t>::\n type>::type;\n\n size_t const half_bits = sizeof(value_type) * 8u / 2u;\n half_type const upper_half = static_cast<half_type>(value >> half_bits);\n half_type const lower_half = static_cast<half_type>(value);\n\n if (sizeof(value_type) == 2u)\n {\n return (static_cast<value_type>(lower_half) << half_bits) | upper_half;\n }\n\n return ((static_cast<value_type>(endian_swap(lower_half)) << half_bits) |\n endian_swap(upper_half));\n}\n</code></pre>\n"
},
{
"answer_id": 69500743,
"author": "Glenn Teitelbaum",
"author_id": 2963099,
"author_profile": "https://Stackoverflow.com/users/2963099",
"pm_score": 0,
"selected": false,
"text": "<p>A c++20 branchless version now that std::endian exists but before c++23 adds std::byteswap</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <bit>\n#include <type_traits>\n#include <concepts>\n#include <array>\n#include <cstring>\n#include <iostream>\n#include <bitset>\n\ntemplate <int LEN, int OFF=LEN/2>\nclass do_swap\n{\n // FOR 8 bytes:\n // LEN=8 (LEN/2==4) <H><G><F><E><D><C><B><A>\n // OFF=4: FROM=0, TO=7 => [A]<G><F><E><D><C><B>[H]\n // OFF=3: FROM=1, TO=6 => [A][B]<F><E><D><C>[G][H]\n // OFF=2: FROM=2, TO=5 => [A][B][C]<E><D>[F][G][H]\n // OFF=1: FROM=3, TO=4 => [A][B][C][D][E][F][G][H]\n // OFF=0: FROM=4, TO=3 => DONE\npublic:\n enum consts {FROM=LEN/2-OFF, TO=(LEN-1)-FROM};\n using NXT=do_swap<LEN, OFF-1>;\n// flip the first and last for the current iteration's range\n static void flip(std::array<std::byte, LEN>& b)\n {\n std::byte tmp=b[FROM];\n b[FROM]=b[TO];\n b[TO]=tmp;\n NXT::flip(b);\n }\n};\ntemplate <int LEN>\nclass do_swap<LEN, 0> // STOP the template recursion\n{\npublic:\n static void flip(std::array<std::byte, LEN>&)\n {\n }\n};\n\ntemplate<std::integral T, std::endian TO, std::endian FROM=std::endian::native>\n requires ((TO==std::endian::big) || (TO==std::endian::little))\n && ((FROM==std::endian::big) || (FROM==std::endian::little))\nclass endian_swap\n{\npublic:\n enum consts {BYTE_COUNT=sizeof(T)};\n static T cvt(const T integral)\n {\n // if FROM and TO are the same -- nothing to do\n if (TO==FROM)\n {\n return integral;\n }\n\n // endian::big --> endian::little is the same as endian::little --> endian::big\n // the bytes have to be reversed\n // memcpy seems to be the most supported way to do byte swaps in a defined way\n std::array<std::byte, BYTE_COUNT> bytes;\n std::memcpy(&bytes, &integral, BYTE_COUNT);\n do_swap<BYTE_COUNT>::flip(bytes);\n T ret;\n std::memcpy(&ret, &bytes, BYTE_COUNT);\n return ret;\n }\n};\n\nstd::endian big()\n{\n return std::endian::big;\n}\n\nstd::endian little()\n{\n return std::endian::little;\n}\n\nstd::endian native()\n{\n return std::endian::native;\n}\n\nlong long swap_to_big(long long x)\n{\n return endian_swap<long long, std::endian::big>::cvt(x);\n}\n\nlong long swap_to_little(long long x)\n{\n return endian_swap<long long, std::endian::little>::cvt(x);\n}\n\nvoid show(std::string label, long long x)\n{\n std::cout << label << "\\t: " << std::bitset<64>(x) << " (" << x << ")" << std::endl;\n}\n\nint main(int argv, char ** argc)\n{\n long long init=0xF8FCFEFF7F3F1F0;\n long long to_big=swap_to_big(init);\n long long to_little=swap_to_little(init);\n show("Init", init);\n show(">big", to_big);\n show(">little", to_little);\n}\n</code></pre>\n"
},
{
"answer_id": 74330996,
"author": "yano",
"author_id": 3476780,
"author_profile": "https://Stackoverflow.com/users/3476780",
"pm_score": 0,
"selected": false,
"text": "<p>Came here looking for a Boost solution and left disappointed, but finally found it elsewhere. You can use <a href=\"https://www.boost.org/doc/libs/1_68_0/libs/endian/doc/conversion.html\" rel=\"nofollow noreferrer\"><code>boost::endian::endian_reverse</code></a>. It's templated/overloaded for all the primitive types:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <iomanip>\n#include "boost/endian/conversion.hpp"\n\nint main()\n{\n uint32_t word = 0x01;\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word << std::endl;\n // outputs 00000001;\n\n uint32_t word2 = boost::endian::endian_reverse(word);\n // there's also a `void ::endian_reverse_inplace(...) function\n // that reverses the value passed to it in place and returns nothing\n\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word2 << std::endl;\n // outputs 01000000\n\n return 0;\n}\n</code></pre>\n<p><a href=\"https://godbolt.org/z/543WaY4sq\" rel=\"nofollow noreferrer\">Demonstration</a></p>\n<p>Although, it looks like c++23 finally put this to bed with <a href=\"https://en.cppreference.com/w/cpp/numeric/byteswap\" rel=\"nofollow noreferrer\"><code>std::byteswap</code></a>. (I'm using c++17, so this was not an option.)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19129/"
]
| How do I convert between big-endian and little-endian values in C++?
For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.
---
Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here. | If you're using **Visual C++** do the following: You include intrin.h and call the following functions:
For 16 bit numbers:
```
unsigned short _byteswap_ushort(unsigned short value);
```
For 32 bit numbers:
```
unsigned long _byteswap_ulong(unsigned long value);
```
For 64 bit numbers:
```
unsigned __int64 _byteswap_uint64(unsigned __int64 value);
```
8 bit numbers (chars) don't need to be converted.
Also these are only defined for unsigned values they work for signed integers as well.
For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.
Other compilers have similar intrinsics as well.
In **GCC** for example you can directly call [some builtins as documented here](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html):
```
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)
```
(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.
16 bit swap it's just a bit-rotate.
Calling the intrinsics instead of rolling your own gives you the best performance and code density btw.. |
105,264 | <p>I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ...</p>
<p>Can anyone point me in the right direction?</p>
| [
{
"answer_id": 105297,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "<p>If you're doing this to transfer data between different platforms look at the ntoh and hton functions.</p>\n"
},
{
"answer_id": 105319,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 4,
"selected": false,
"text": "<p>We've done this with templates. You could do something like this:</p>\n\n<pre><code>// Specialization for 2-byte types.\ntemplate<>\ninline void endian_byte_swapper< 2 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n ushort* p_dest = reinterpret_cast< ushort* >(dest);\n ushort const* const p_src = reinterpret_cast< ushort const* >(src);\n *p_dest = (*p_src >> 8) | (*p_src << 8);\n}\n\n// Specialization for 4-byte types.\ntemplate<>\ninline void endian_byte_swapper< 4 >(char* dest, char const* src)\n{\n // Use bit manipulations instead of accessing individual bytes from memory, much faster.\n uint* p_dest = reinterpret_cast< uint* >(dest);\n uint const* const p_src = reinterpret_cast< uint const* >(src);\n *p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);\n}\n</code></pre>\n"
},
{
"answer_id": 105323,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 3,
"selected": false,
"text": "<p>The same way you do in C:</p>\n\n<pre><code>short big = 0xdead;\nshort little = (((big & 0xff)<<8) | ((big & 0xff00)>>8));\n</code></pre>\n\n<p>You could also declare a vector of unsigned chars, memcpy the input value into it, reverse the bytes into another vector and memcpy the bytes out, but that'll take orders of magnitude longer than bit-twiddling, especially with 64-bit values.</p>\n"
},
{
"answer_id": 105328,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": -1,
"selected": false,
"text": "<p>Look up bit shifting, as this is basically all you need to do to swap from little -> big endian. Then depending on the bit size, you change how you do the bit shifting.</p>\n"
},
{
"answer_id": 105339,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using <strong>Visual C++</strong> do the following: You include intrin.h and call the following functions:</p>\n\n<p>For 16 bit numbers:</p>\n\n<pre><code>unsigned short _byteswap_ushort(unsigned short value);\n</code></pre>\n\n<p>For 32 bit numbers:</p>\n\n<pre><code>unsigned long _byteswap_ulong(unsigned long value);\n</code></pre>\n\n<p>For 64 bit numbers:</p>\n\n<pre><code>unsigned __int64 _byteswap_uint64(unsigned __int64 value);\n</code></pre>\n\n<p>8 bit numbers (chars) don't need to be converted.</p>\n\n<p>Also these are only defined for unsigned values they work for signed integers as well.</p>\n\n<p>For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.</p>\n\n<p>Other compilers have similar intrinsics as well. </p>\n\n<p>In <strong>GCC</strong> for example you can directly call <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\" rel=\"noreferrer\">some builtins as documented here</a>:</p>\n\n<pre><code>uint32_t __builtin_bswap32 (uint32_t x)\nuint64_t __builtin_bswap64 (uint64_t x)\n</code></pre>\n\n<p>(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.</p>\n\n<p>16 bit swap it's just a bit-rotate.</p>\n\n<p>Calling the intrinsics instead of rolling your own gives you the best performance and code density btw.. </p>\n"
},
{
"answer_id": 105342,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 4,
"selected": false,
"text": "<p>The procedure for going from big-endian to little-endian is the same as going from little-endian to big-endian.</p>\n\n<p>Here's some example code:</p>\n\n<pre><code>void swapByteOrder(unsigned short& us)\n{\n us = (us >> 8) |\n (us << 8);\n}\n\nvoid swapByteOrder(unsigned int& ui)\n{\n ui = (ui >> 24) |\n ((ui<<8) & 0x00FF0000) |\n ((ui>>8) & 0x0000FF00) |\n (ui << 24);\n}\n\nvoid swapByteOrder(unsigned long long& ull)\n{\n ull = (ull >> 56) |\n ((ull<<40) & 0x00FF000000000000) |\n ((ull<<24) & 0x0000FF0000000000) |\n ((ull<<8) & 0x000000FF00000000) |\n ((ull>>8) & 0x00000000FF000000) |\n ((ull>>24) & 0x0000000000FF0000) |\n ((ull>>40) & 0x000000000000FF00) |\n (ull << 56);\n}\n</code></pre>\n"
},
{
"answer_id": 105354,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": false,
"text": "<p>On most POSIX systems (through it's not in the POSIX standard) there is the endian.h, which can be used to determine what encoding your system uses. From there it's something like this:</p>\n\n<pre><code>unsigned int change_endian(unsigned int x)\n{\n unsigned char *ptr = (unsigned char *)&x;\n return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];\n}\n</code></pre>\n\n<p>This swaps the order (from big endian to little endian):</p>\n\n<p>If you have the number 0xDEADBEEF (on a little endian system stored as 0xEFBEADDE), ptr[0] will be 0xEF, ptr[1] is 0xBE, etc.</p>\n\n<p>But if you want to use it for networking, then htons, htonl and htonll (and their inverses ntohs, ntohl and ntohll) will be helpful for converting from host order to network order.</p>\n"
},
{
"answer_id": 105371,
"author": "anon6439",
"author_id": 15477,
"author_profile": "https://Stackoverflow.com/users/15477",
"pm_score": 4,
"selected": false,
"text": "<p>There is an assembly instruction called BSWAP that will do the swap for you, <em>extremely fast</em>.\nYou can read about it <a href=\"http://oopweb.com/Assembly/Documents/ArtOfAssembly/Volume/Chapter_6/CH06-1.html#HEADING1-291\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Visual Studio, or more precisely the Visual C++ runtime library, has platform intrinsics for this, called <code>_byteswap_ushort(), _byteswap_ulong(), and _byteswap_int64()</code>. Similar should exist for other platforms, but I'm not aware of what they would be called.</p>\n"
},
{
"answer_id": 105410,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 6,
"selected": false,
"text": "<p>If you are doing this for purposes of network/host compatability you should use:</p>\n\n<pre><code>ntohl() //Network to Host byte order (Long)\nhtonl() //Host to Network byte order (Long)\n\nntohs() //Network to Host byte order (Short)\nhtons() //Host to Network byte order (Short)\n</code></pre>\n\n<p>If you are doing this for some other reason one of the byte_swap solutions presented here would work just fine.</p>\n"
},
{
"answer_id": 105632,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a generalized version I came up with off the top of my head, for swapping a value in place. The other suggestions would be better if performance is a problem.</p>\n\n<pre><code> template<typename T>\n void ByteSwap(T * p)\n {\n for (int i = 0; i < sizeof(T)/2; ++i)\n std::swap(((char *)p)[i], ((char *)p)[sizeof(T)-1-i]);\n }\n</code></pre>\n\n<p><strong>Disclaimer:</strong> I haven't tried to compile this or test it yet.</p>\n"
},
{
"answer_id": 107099,
"author": "Mathieu Pagé",
"author_id": 5861,
"author_profile": "https://Stackoverflow.com/users/5861",
"pm_score": 2,
"selected": false,
"text": "<p>I have this code that allow me to convert from HOST_ENDIAN_ORDER (whatever it is) to LITTLE_ENDIAN_ORDER or BIG_ENDIAN_ORDER. I use a template, so if I try to convert from HOST_ENDIAN_ORDER to LITTLE_ENDIAN_ORDER and they happen to be the same for the machine for wich I compile, no code will be generated.</p>\n\n<p>Here is the code with some comments:</p>\n\n<pre><code>// We define some constant for little, big and host endianess. Here I use \n// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you\n// don't want to use boost you will have to modify this part a bit.\nenum EEndian\n{\n LITTLE_ENDIAN_ORDER,\n BIG_ENDIAN_ORDER,\n#if defined(BOOST_LITTLE_ENDIAN)\n HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER\n#elif defined(BOOST_BIG_ENDIAN)\n HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER\n#else\n#error \"Impossible de determiner l'indianness du systeme cible.\"\n#endif\n};\n\n// this function swap the bytes of values given it's size as a template\n// parameter (could sizeof be used?).\ntemplate <class T, unsigned int size>\ninline T SwapBytes(T value)\n{\n union\n {\n T value;\n char bytes[size];\n } in, out;\n\n in.value = value;\n\n for (unsigned int i = 0; i < size / 2; ++i)\n {\n out.bytes[i] = in.bytes[size - 1 - i];\n out.bytes[size - 1 - i] = in.bytes[i];\n }\n\n return out.value;\n}\n\n// Here is the function you will use. Again there is two compile-time assertion\n// that use the boost librarie. You could probably comment them out, but if you\n// do be cautious not to use this function for anything else than integers\n// types. This function need to be calles like this :\n//\n// int x = someValue;\n// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);\n//\ntemplate<EEndian from, EEndian to, class T>\ninline T EndianSwapBytes(T value)\n{\n // A : La donnée à swapper à une taille de 2, 4 ou 8 octets\n BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n\n // A : La donnée à swapper est d'un type arithmetic\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n // Si from et to sont du même type on ne swap pas.\n if (from == to)\n return value;\n\n return SwapBytes<T, sizeof(T)>(value);\n}\n</code></pre>\n"
},
{
"answer_id": 3522853,
"author": "Steve Lorimer",
"author_id": 955273,
"author_profile": "https://Stackoverflow.com/users/955273",
"pm_score": 5,
"selected": false,
"text": "<p>I took a few suggestions from this post and put them together to form this:</p>\n<pre><code>#include <boost/type_traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/detail/endian.hpp>\n#include <stdexcept>\n#include <cstdint>\n\nenum endianness\n{\n little_endian,\n big_endian,\n network_endian = big_endian,\n \n #if defined(BOOST_LITTLE_ENDIAN)\n host_endian = little_endian\n #elif defined(BOOST_BIG_ENDIAN)\n host_endian = big_endian\n #else\n #error "unable to determine system endianness"\n #endif\n};\n\nnamespace detail {\n\ntemplate<typename T, size_t sz>\nstruct swap_bytes\n{\n inline T operator()(T val)\n {\n throw std::out_of_range("data size");\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 1>\n{\n inline T operator()(T val)\n {\n return val;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 2>\n{\n inline T operator()(T val)\n {\n return ((((val) >> 8) & 0xff) | (((val) & 0xff) << 8));\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 4>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff000000) >> 24) |\n (((val) & 0x00ff0000) >> 8) |\n (((val) & 0x0000ff00) << 8) |\n (((val) & 0x000000ff) << 24));\n }\n};\n\ntemplate<>\nstruct swap_bytes<float, 4>\n{\n inline float operator()(float val)\n {\n uint32_t mem =swap_bytes<uint32_t, sizeof(uint32_t)>()(*(uint32_t*)&val);\n return *(float*)&mem;\n }\n};\n\ntemplate<typename T>\nstruct swap_bytes<T, 8>\n{\n inline T operator()(T val)\n {\n return ((((val) & 0xff00000000000000ull) >> 56) |\n (((val) & 0x00ff000000000000ull) >> 40) |\n (((val) & 0x0000ff0000000000ull) >> 24) |\n (((val) & 0x000000ff00000000ull) >> 8 ) |\n (((val) & 0x00000000ff000000ull) << 8 ) |\n (((val) & 0x0000000000ff0000ull) << 24) |\n (((val) & 0x000000000000ff00ull) << 40) |\n (((val) & 0x00000000000000ffull) << 56));\n }\n};\n\ntemplate<>\nstruct swap_bytes<double, 8>\n{\n inline double operator()(double val)\n {\n uint64_t mem =swap_bytes<uint64_t, sizeof(uint64_t)>()(*(uint64_t*)&val);\n return *(double*)&mem;\n }\n};\n\ntemplate<endianness from, endianness to, class T>\nstruct do_byte_swap\n{\n inline T operator()(T value)\n {\n return swap_bytes<T, sizeof(T)>()(value);\n }\n};\n// specialisations when attempting to swap to the same endianess\ntemplate<class T> struct do_byte_swap<little_endian, little_endian, T> { inline T operator()(T value) { return value; } };\ntemplate<class T> struct do_byte_swap<big_endian, big_endian, T> { inline T operator()(T value) { return value; } };\n\n} // namespace detail\n\ntemplate<endianness from, endianness to, class T>\ninline T byte_swap(T value)\n{\n // ensure the data is only 1, 2, 4 or 8 bytes\n BOOST_STATIC_ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);\n // ensure we're only swapping arithmetic types\n BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);\n\n return detail::do_byte_swap<from, to, T>()(value);\n}\n</code></pre>\n<p>You would then use it as follows:</p>\n<pre><code>// swaps val from host-byte-order to network-byte-order\nauto swapped = byte_swap<host_endian, network_endian>(val);\n</code></pre>\n<p>and vice-versa</p>\n<pre><code>// swap a value received from the network into host-byte-order\nauto val = byte_swap<network_endian, host_endian>(val_from_network);\n</code></pre>\n"
},
{
"answer_id": 4956493,
"author": "Alexandre C.",
"author_id": 373025,
"author_profile": "https://Stackoverflow.com/users/373025",
"pm_score": 7,
"selected": false,
"text": "<p>Simply put:</p>\n\n<pre><code>#include <climits>\n\ntemplate <typename T>\nT swap_endian(T u)\n{\n static_assert (CHAR_BIT == 8, \"CHAR_BIT != 8\");\n\n union\n {\n T u;\n unsigned char u8[sizeof(T)];\n } source, dest;\n\n source.u = u;\n\n for (size_t k = 0; k < sizeof(T); k++)\n dest.u8[k] = source.u8[sizeof(T) - k - 1];\n\n return dest.u;\n}\n</code></pre>\n\n<p>usage: <code>swap_endian<uint32_t>(42)</code>.</p>\n"
},
{
"answer_id": 4956807,
"author": "Maxim Egorushkin",
"author_id": 412080,
"author_profile": "https://Stackoverflow.com/users/412080",
"pm_score": 3,
"selected": false,
"text": "<p>Most platforms have a system header file that provides efficient byteswap functions. On Linux it is in <code><endian.h></code>. You can wrap it nicely in C++:</p>\n\n<pre><code>#include <iostream>\n\n#include <endian.h>\n\ntemplate<size_t N> struct SizeT {};\n\n#define BYTESWAPS(bits) \\\ntemplate<class T> inline T htobe(T t, SizeT<bits / 8>) { return htobe ## bits(t); } \\\ntemplate<class T> inline T htole(T t, SizeT<bits / 8>) { return htole ## bits(t); } \\\ntemplate<class T> inline T betoh(T t, SizeT<bits / 8>) { return be ## bits ## toh(t); } \\\ntemplate<class T> inline T letoh(T t, SizeT<bits / 8>) { return le ## bits ## toh(t); }\n\nBYTESWAPS(16)\nBYTESWAPS(32)\nBYTESWAPS(64)\n\n#undef BYTESWAPS\n\ntemplate<class T> inline T htobe(T t) { return htobe(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T htole(T t) { return htole(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T betoh(T t) { return betoh(t, SizeT<sizeof t>()); }\ntemplate<class T> inline T letoh(T t) { return letoh(t, SizeT<sizeof t>()); }\n\nint main()\n{\n std::cout << std::hex;\n std::cout << htobe(static_cast<unsigned short>(0xfeca)) << '\\n';\n std::cout << htobe(0xafbeadde) << '\\n';\n\n // Use ULL suffix to specify integer constant as unsigned long long \n std::cout << htobe(0xfecaefbeafdeedfeULL) << '\\n';\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>cafe\ndeadbeaf\nfeeddeafbeefcafe\n</code></pre>\n"
},
{
"answer_id": 6487066,
"author": "friedemann",
"author_id": 815363,
"author_profile": "https://Stackoverflow.com/users/815363",
"pm_score": 2,
"selected": false,
"text": "<p>i like this one, just for style :-)</p>\n\n<pre><code>long swap(long i) {\n char *c = (char *) &i;\n return * (long *) (char[]) {c[3], c[2], c[1], c[0] };\n}\n</code></pre>\n"
},
{
"answer_id": 10346064,
"author": "Matthieu M.",
"author_id": 147192,
"author_profile": "https://Stackoverflow.com/users/147192",
"pm_score": 6,
"selected": false,
"text": "<p>From <strong><a href=\"http://commandcenter.blogspot.fr/2012/04/byte-order-fallacy.html\" rel=\"nofollow noreferrer\">The Byte Order Fallacy</a></strong> by Rob Pike:</p>\n<blockquote>\n<p>Let's say your data stream has a little-endian-encoded 32-bit integer. Here's how to extract it (assuming unsigned bytes):</p>\n</blockquote>\n<pre><code>i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | ((unsigned)data[3]<<24);\n</code></pre>\n<blockquote>\n<p>If it's big-endian, here's how to extract it:</p>\n</blockquote>\n<pre><code>i = (data[3]<<0) | (data[2]<<8) | (data[1]<<16) | ((unsigned)data[0]<<24);\n</code></pre>\n<p><strong>TL;DR:</strong> don't worry about your platform native order, all that counts is the byte order of the stream your are reading from, and you better hope it's well defined.</p>\n<p><em>Note 1: It is expected that <code>int</code> and <code>unsigned int</code> be 32 bits here, types may require adjustment otherwise.</em></p>\n<p><em>Note 2: The last byte must be explicitly cast to <code>unsigned</code> before shifting, as by default it's promoted to <code>int</code>, and a shift by 24 bits means manipulating the sign bit which is Undefined Behavior.</em></p>\n"
},
{
"answer_id": 18333053,
"author": "user2699548",
"author_id": 2699548,
"author_profile": "https://Stackoverflow.com/users/2699548",
"pm_score": 3,
"selected": false,
"text": "<p>Note that, at least for Windows, htonl() is much slower than their intrinsic counterpart _byteswap_ulong(). The former is a DLL library call into ws2_32.dll, the latter is one BSWAP assembly instruction. Therefore, if you are writing some platform-dependent code, prefer using the intrinsics for speed:</p>\n\n<pre><code>#define htonl(x) _byteswap_ulong(x)\n</code></pre>\n\n<p>This may be especially important for .PNG image processing where all integers are saved in Big Endian with explanation \"One can use htonl()...\" {to slow down typical Windows programs, if you are not prepared}.</p>\n"
},
{
"answer_id": 18334154,
"author": "sh1",
"author_id": 2417578,
"author_profile": "https://Stackoverflow.com/users/2417578",
"pm_score": 2,
"selected": false,
"text": "<p>If you take the common pattern for reversing the order of bits in a word, and cull the part that reverses bits within each byte, then you're left with something which only reverses the bytes within a word. For 64-bits:</p>\n\n<pre><code>x = ((x & 0x00000000ffffffff) << 32) ^ ((x >> 32) & 0x00000000ffffffff);\nx = ((x & 0x0000ffff0000ffff) << 16) ^ ((x >> 16) & 0x0000ffff0000ffff);\nx = ((x & 0x00ff00ff00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff00ff00ff);\n</code></pre>\n\n<p>The compiler <em>should</em> clean out the superfluous bit-masking operations (I left them in to highlight the pattern), but if it doesn't you can rewrite the first line this way:</p>\n\n<pre><code>x = ( x << 32) ^ (x >> 32);\n</code></pre>\n\n<p>That should normally simplify down to a single rotate instruction on most architectures (ignoring that the whole operation is probably one instruction).</p>\n\n<p>On a RISC processor the large, complicated constants may cause the compiler difficulties. You can trivially calculate each of the constants from the previous one, though. Like so:</p>\n\n<pre><code>uint64_t k = 0x00000000ffffffff; /* compiler should know a trick for this */\nx = ((x & k) << 32) ^ ((x >> 32) & k);\nk ^= k << 16;\nx = ((x & k) << 16) ^ ((x >> 16) & k);\nk ^= k << 8;\nx = ((x & k) << 8) ^ ((x >> 8) & k);\n</code></pre>\n\n<p>If you like, you can write that as a loop. It won't be efficient, but just for fun:</p>\n\n<pre><code>int i = sizeof(x) * CHAR_BIT / 2;\nuintmax_t k = (1 << i) - 1;\nwhile (i >= 8)\n{\n x = ((x & k) << i) ^ ((x >> i) & k);\n i >>= 1;\n k ^= k << i;\n}\n</code></pre>\n\n<p>And for completeness, here's the simplified 32-bit version of the first form:</p>\n\n<pre><code>x = ( x << 16) ^ (x >> 16);\nx = ((x & 0x00ff00ff) << 8) ^ ((x >> 8) & 0x00ff00ff);\n</code></pre>\n"
},
{
"answer_id": 25177297,
"author": "The Quantum Physicist",
"author_id": 1317944,
"author_profile": "https://Stackoverflow.com/users/1317944",
"pm_score": 3,
"selected": false,
"text": "<p>Seriously... I don't understand why all solutions are that <strong><em>complicated</em></strong>! <strong>How about the simplest, most general template function that swaps any type of any size under any circumstances in any operating system????</strong></p>\n\n<pre><code>template <typename T>\nvoid SwapEnd(T& var)\n{\n static_assert(std::is_pod<T>::value, \"Type must be POD type for safety\");\n std::array<char, sizeof(T)> varArray;\n std::memcpy(varArray.data(), &var, sizeof(T));\n for(int i = 0; i < static_cast<int>(sizeof(var)/2); i++)\n std::swap(varArray[sizeof(var) - 1 - i],varArray[i]);\n std::memcpy(&var, varArray.data(), sizeof(T));\n}\n</code></pre>\n\n<p>It's the magic power of C and C++ together! Simply swap the original variable character by character.</p>\n\n<p><strong>Point 1</strong>: No operators: Remember that I didn't use the simple assignment operator \"=\" because some objects will be messed up when the endianness is flipped and the copy constructor (or assignment operator) won't work. Therefore, it's more reliable to copy them char by char.</p>\n\n<p><strong>Point 2</strong>: Be aware of alignment issues: Notice that we're copying to and from an array, which is the right thing to do because the C++ compiler doesn't guarantee that we can access unaligned memory (this answer was updated from its original form for this). For example, if you allocate <code>uint64_t</code>, your compiler cannot guarantee that you can access the 3rd byte of that as a <code>uint8_t</code>. Therefore, the right thing to do is to copy this to a char array, swap it, then copy it back (so no <code>reinterpret_cast</code>). Notice that compilers are mostly smart enough to convert what you did back to a <code>reinterpret_cast</code> if they're capable of accessing individual bytes regardless of alignment.</p>\n\n<p><strong>To use this function</strong>:</p>\n\n<pre><code>double x = 5;\nSwapEnd(x);\n</code></pre>\n\n<p>and now <code>x</code> is different in endianness.</p>\n"
},
{
"answer_id": 25704741,
"author": "Adam Freeman",
"author_id": 538458,
"author_profile": "https://Stackoverflow.com/users/538458",
"pm_score": 2,
"selected": false,
"text": "<p>If a big-endian 32-bit unsigned integer looks like 0xAABBCCDD which is equal to 2864434397, then that same 32-bit unsigned integer looks like 0xDDCCBBAA on a little-endian processor which is also equal to 2864434397.</p>\n\n<p>If a big-endian 16-bit unsigned short looks like 0xAABB which is equal to 43707, then that same 16-bit unsigned short looks like 0xBBAA on a little-endian processor which is also equal to 43707.</p>\n\n<p>Here are a couple of handy #define functions to swap bytes from little-endian to big-endian and vice-versa --></p>\n\n<pre><code>// can be used for short, unsigned short, word, unsigned word (2-byte types)\n#define BYTESWAP16(n) (((n&0xFF00)>>8)|((n&0x00FF)<<8))\n\n// can be used for int or unsigned int or float (4-byte types)\n#define BYTESWAP32(n) ((BYTESWAP16((n&0xFFFF0000)>>16))|((BYTESWAP16(n&0x0000FFFF))<<16))\n\n// can be used for unsigned long long or double (8-byte types)\n#define BYTESWAP64(n) ((BYTESWAP32((n&0xFFFFFFFF00000000)>>32))|((BYTESWAP32(n&0x00000000FFFFFFFF))<<32))\n</code></pre>\n"
},
{
"answer_id": 26007257,
"author": "The Welder",
"author_id": 2086872,
"author_profile": "https://Stackoverflow.com/users/2086872",
"pm_score": 0,
"selected": false,
"text": "<p>Wow, I couldn't believe some of the answers I've read here. There's actually an instruction in assembly which does this faster than anything else. bswap. You could simply write a function like this...</p>\n<pre><code>__declspec(naked) uint32_t EndianSwap(uint32 value)\n{\n __asm\n {\n mov eax, dword ptr[esp + 4]\n bswap eax\n ret\n }\n}\n</code></pre>\n<p>It is <em>MUCH</em> faster than the intrinsics that have been suggested. I've disassembled them and looked. The above function has no prologue/epilogue so virtually has no overhead at all.</p>\n<pre><code>unsigned long _byteswap_ulong(unsigned long value);\n</code></pre>\n<p>Doing 16 bit is just as easy, with the exception that you'd use xchg al, ah. bswap only works on 32-bit registers.</p>\n<p>64-bit is a little more tricky, but not overly so. Much better than all of the above examples with loops and templates etc.</p>\n<p>There are some caveats here... Firstly bswap is only available on 80x486 CPU's and above. Is anyone planning on running it on a 386?!? If so, you can still replace bswap with...</p>\n<pre><code>mov ebx, eax\nshr ebx, 16\nxchg al, ah\nxchg bl, bh\nshl eax, 16\nor eax, ebx\n</code></pre>\n<p>Also inline assembly is only available in x86 code in Visual Studio. A naked function cannot be lined and also isn't available in x64 builds. I that instance, you're going to have to use the compiler intrinsics.</p>\n"
},
{
"answer_id": 35092546,
"author": "Joao",
"author_id": 1604608,
"author_profile": "https://Stackoverflow.com/users/1604608",
"pm_score": 2,
"selected": false,
"text": "<p>Just thought I added my own solution here since I haven't seen it anywhere. It's a small and portable C++ templated function and portable that only uses bit operations.</p>\n\n<pre><code>template<typename T> inline static T swapByteOrder(const T& val) {\n int totalBytes = sizeof(val);\n T swapped = (T) 0;\n for (int i = 0; i < totalBytes; ++i) {\n swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);\n }\n return swapped;\n}\n</code></pre>\n"
},
{
"answer_id": 37386513,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 0,
"selected": false,
"text": "<p>Portable technique for implementing optimizer-friendly unaligned non-inplace endian accessors. They work on every compiler, every boundary alignment and every byte ordering. These unaligned routines are supplemented, or mooted, depending on native endian and alignment. Partial listing but you get the idea. BO* are constant values based on native byte ordering.</p>\n\n<pre><code>uint32_t sw_get_uint32_1234(pu32)\nuint32_1234 *pu32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32_1234[0] = (*pu32)[BO32_0];\n bou32.u32_1234[1] = (*pu32)[BO32_1];\n bou32.u32_1234[2] = (*pu32)[BO32_2];\n bou32.u32_1234[3] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_1234(pu32, u32)\nuint32_1234 *pu32;\nuint32_t u32;\n{\n union {\n uint32_1234 u32_1234;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_1234[0];\n (*pu32)[BO32_1] = bou32.u32_1234[1];\n (*pu32)[BO32_2] = bou32.u32_1234[2];\n (*pu32)[BO32_3] = bou32.u32_1234[3];\n}\n\n#if HAS_SW_INT64\nint64 sw_get_int64_12345678(pi64)\nint64_12345678 *pi64;\n{\n union {\n int64_12345678 i64_12345678;\n int64 i64;\n } boi64;\n boi64.i64_12345678[0] = (*pi64)[BO64_0];\n boi64.i64_12345678[1] = (*pi64)[BO64_1];\n boi64.i64_12345678[2] = (*pi64)[BO64_2];\n boi64.i64_12345678[3] = (*pi64)[BO64_3];\n boi64.i64_12345678[4] = (*pi64)[BO64_4];\n boi64.i64_12345678[5] = (*pi64)[BO64_5];\n boi64.i64_12345678[6] = (*pi64)[BO64_6];\n boi64.i64_12345678[7] = (*pi64)[BO64_7];\n return(boi64.i64);\n}\n#endif\n\nint32_t sw_get_int32_3412(pi32)\nint32_3412 *pi32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32_3412[2] = (*pi32)[BO32_0];\n boi32.i32_3412[3] = (*pi32)[BO32_1];\n boi32.i32_3412[0] = (*pi32)[BO32_2];\n boi32.i32_3412[1] = (*pi32)[BO32_3];\n return(boi32.i32);\n}\n\nvoid sw_set_int32_3412(pi32, i32)\nint32_3412 *pi32;\nint32_t i32;\n{\n union {\n int32_3412 i32_3412;\n int32_t i32;\n } boi32;\n boi32.i32 = i32;\n (*pi32)[BO32_0] = boi32.i32_3412[2];\n (*pi32)[BO32_1] = boi32.i32_3412[3];\n (*pi32)[BO32_2] = boi32.i32_3412[0];\n (*pi32)[BO32_3] = boi32.i32_3412[1];\n}\n\nuint32_t sw_get_uint32_3412(pu32)\nuint32_3412 *pu32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32_3412[2] = (*pu32)[BO32_0];\n bou32.u32_3412[3] = (*pu32)[BO32_1];\n bou32.u32_3412[0] = (*pu32)[BO32_2];\n bou32.u32_3412[1] = (*pu32)[BO32_3];\n return(bou32.u32);\n}\n\nvoid sw_set_uint32_3412(pu32, u32)\nuint32_3412 *pu32;\nuint32_t u32;\n{\n union {\n uint32_3412 u32_3412;\n uint32_t u32;\n } bou32;\n bou32.u32 = u32;\n (*pu32)[BO32_0] = bou32.u32_3412[2];\n (*pu32)[BO32_1] = bou32.u32_3412[3];\n (*pu32)[BO32_2] = bou32.u32_3412[0];\n (*pu32)[BO32_3] = bou32.u32_3412[1];\n}\n\nfloat sw_get_float_1234(pf)\nfloat_1234 *pf;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f_1234[0] = (*pf)[BO32_0];\n bof.f_1234[1] = (*pf)[BO32_1];\n bof.f_1234[2] = (*pf)[BO32_2];\n bof.f_1234[3] = (*pf)[BO32_3];\n return(bof.f);\n}\n\nvoid sw_set_float_1234(pf, f)\nfloat_1234 *pf;\nfloat f;\n{\n union {\n float_1234 f_1234;\n float f;\n } bof;\n bof.f = (float)f;\n (*pf)[BO32_0] = bof.f_1234[0];\n (*pf)[BO32_1] = bof.f_1234[1];\n (*pf)[BO32_2] = bof.f_1234[2];\n (*pf)[BO32_3] = bof.f_1234[3];\n}\n\ndouble sw_get_double_12345678(pd)\ndouble_12345678 *pd;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d_12345678[0] = (*pd)[BO64_0];\n bod.d_12345678[1] = (*pd)[BO64_1];\n bod.d_12345678[2] = (*pd)[BO64_2];\n bod.d_12345678[3] = (*pd)[BO64_3];\n bod.d_12345678[4] = (*pd)[BO64_4];\n bod.d_12345678[5] = (*pd)[BO64_5];\n bod.d_12345678[6] = (*pd)[BO64_6];\n bod.d_12345678[7] = (*pd)[BO64_7];\n return(bod.d);\n}\n\nvoid sw_set_double_12345678(pd, d)\ndouble_12345678 *pd;\ndouble d;\n{\n union {\n double_12345678 d_12345678;\n double d;\n } bod;\n bod.d = d;\n (*pd)[BO64_0] = bod.d_12345678[0];\n (*pd)[BO64_1] = bod.d_12345678[1];\n (*pd)[BO64_2] = bod.d_12345678[2];\n (*pd)[BO64_3] = bod.d_12345678[3];\n (*pd)[BO64_4] = bod.d_12345678[4];\n (*pd)[BO64_5] = bod.d_12345678[5];\n (*pd)[BO64_6] = bod.d_12345678[6];\n (*pd)[BO64_7] = bod.d_12345678[7];\n}\n</code></pre>\n\n<p>These typedefs have the benefit of raising compiler errors if not used with accessors, thus mitigating forgotten accessor bugs.</p>\n\n<pre><code>typedef char int8_1[1], uint8_1[1];\n\ntypedef char int16_12[2], uint16_12[2]; /* little endian */\ntypedef char int16_21[2], uint16_21[2]; /* big endian */\n\ntypedef char int24_321[3], uint24_321[3]; /* Alpha Micro, PDP-11 */\n\ntypedef char int32_1234[4], uint32_1234[4]; /* little endian */\ntypedef char int32_3412[4], uint32_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char int32_4321[4], uint32_4321[4]; /* big endian */\n\ntypedef char int64_12345678[8], uint64_12345678[8]; /* little endian */\ntypedef char int64_34128756[8], uint64_34128756[8]; /* Alpha Micro, PDP-11 */\ntypedef char int64_87654321[8], uint64_87654321[8]; /* big endian */\n\ntypedef char float_1234[4]; /* little endian */\ntypedef char float_3412[4]; /* Alpha Micro, PDP-11 */\ntypedef char float_4321[4]; /* big endian */\n\ntypedef char double_12345678[8]; /* little endian */\ntypedef char double_78563412[8]; /* Alpha Micro? */\ntypedef char double_87654321[8]; /* big endian */\n</code></pre>\n"
},
{
"answer_id": 39548833,
"author": "pz64_",
"author_id": 6737471,
"author_profile": "https://Stackoverflow.com/users/6737471",
"pm_score": 2,
"selected": false,
"text": "<p>Using the codes below, you can swap between BigEndian and LittleEndian easily </p>\n\n<pre><code>#define uint32_t unsigned \n#define uint16_t unsigned short\n\n#define swap16(x) ((((uint16_t)(x) & 0x00ff)<<8)| \\\n(((uint16_t)(x) & 0xff00)>>8))\n\n#define swap32(x) ((((uint32_t)(x) & 0x000000ff)<<24)| \\\n(((uint32_t)(x) & 0x0000ff00)<<8)| \\\n(((uint32_t)(x) & 0x00ff0000)>>8)| \\\n(((uint32_t)(x) & 0xff000000)>>24))\n</code></pre>\n"
},
{
"answer_id": 41196306,
"author": "Ryan Hilbert",
"author_id": 2884225,
"author_profile": "https://Stackoverflow.com/users/2884225",
"pm_score": 1,
"selected": false,
"text": "<p>I recently wrote a macro to do this in C, but it's equally valid in C++:</p>\n<pre><code>#define REVERSE_BYTES(...) do for(size_t REVERSE_BYTES=0; REVERSE_BYTES<sizeof(__VA_ARGS__)>>1; ++REVERSE_BYTES)\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES],\\\n ((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES] ^= ((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES];\\\nwhile(0)\n</code></pre>\n<p>It accepts any type and reverses the bytes in the passed argument.\nExample usages:</p>\n<pre><code>int main(){\n unsigned long long x = 0xABCDEF0123456789;\n printf("Before: %llX\\n",x);\n REVERSE_BYTES(x);\n printf("After : %llX\\n",x);\n\n char c[7]="nametag";\n printf("Before: %c%c%c%c%c%c%c\\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n REVERSE_BYTES(c);\n printf("After : %c%c%c%c%c%c%c\\n",c[0],c[1],c[2],c[3],c[4],c[5],c[6]);\n}\n</code></pre>\n<p>Which prints:</p>\n<pre><code>Before: ABCDEF0123456789\nAfter : 8967452301EFCDAB\nBefore: nametag\nAfter : gateman\n</code></pre>\n<p>The above is perfectly copy/paste-able, but there's a lot going on here, so I'll break down how it works piece by piece:</p>\n<p>The first notable thing is that the entire macro is encased in a <code>do while(0)</code> block. This is a <a href=\"https://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html\" rel=\"nofollow noreferrer\">common idiom</a> to allow normal semicolon use after the macro.</p>\n<p>Next up is the use of a variable named <code>REVERSE_BYTES</code> as the <code>for</code> loop's counter. The name of the macro itself is used as a variable name to ensure that it doesn't clash with any other symbols that may be in scope wherever the macro is used. Since the name is being used within the macro's expansion, it won't be expanded again when used as a variable name here.</p>\n<p>Within the <code>for</code> loop, there are two bytes being referenced and <a href=\"https://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"nofollow noreferrer\">XOR swapped</a> (so a temporary variable name is not required):</p>\n<pre><code>((unsigned char*)&(__VA_ARGS__))[REVERSE_BYTES]\n((unsigned char*)&(__VA_ARGS__))[sizeof(__VA_ARGS__)-1-REVERSE_BYTES]\n</code></pre>\n<p><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html\" rel=\"nofollow noreferrer\"><code>__VA_ARGS__</code></a> represents whatever was given to the macro, and is used to increase the flexibility of what may be passed in (albeit not by much). The address of this argument is then taken and cast to an <code>unsigned char</code> pointer to permit the swapping of its bytes via array <code>[]</code> subscripting.</p>\n<p>The final peculiar point is the lack of <code>{}</code> braces. They aren't necessary because all of the steps in each swap are joined with the <a href=\"https://en.wikipedia.org/wiki/Comma_operator\" rel=\"nofollow noreferrer\">comma operator</a>, making them one statement.</p>\n<p>Finally, it's worth noting that this is not the ideal approach if speed is a top priority. If this is an important factor, some of the type-specific macros or platform-specific directives referenced in other answers are likely a better option. This approach, however, is portable to all types, all major platforms, and both the C and C++ languages.</p>\n"
},
{
"answer_id": 43923866,
"author": "Nick",
"author_id": 964080,
"author_profile": "https://Stackoverflow.com/users/964080",
"pm_score": 2,
"selected": false,
"text": "<p>I am really surprised no one mentioned htobeXX and betohXX functions. They are defined in endian.h and are very similar to network functions htonXX.</p>\n"
},
{
"answer_id": 44123161,
"author": "Malcolm McLean",
"author_id": 3310281,
"author_profile": "https://Stackoverflow.com/users/3310281",
"pm_score": -1,
"selected": false,
"text": "<p>Here's how to read a double stored in IEEE 754 64 bit format, even if your host computer uses a different system.</p>\n\n<pre><code>/*\n* read a double from a stream in ieee754 format regardless of host\n* encoding.\n* fp - the stream\n* bigendian - set to if big bytes first, clear for little bytes\n* first\n*\n*/\ndouble freadieee754(FILE *fp, int bigendian)\n{\n unsigned char buff[8];\n int i;\n double fnorm = 0.0;\n unsigned char temp;\n int sign;\n int exponent;\n double bitval;\n int maski, mask;\n int expbits = 11;\n int significandbits = 52;\n int shift;\n double answer;\n\n /* read the data */\n for (i = 0; i < 8; i++)\n buff[i] = fgetc(fp);\n /* just reverse if not big-endian*/\n if (!bigendian)\n {\n for (i = 0; i < 4; i++)\n {\n temp = buff[i];\n buff[i] = buff[8 - i - 1];\n buff[8 - i - 1] = temp;\n }\n }\n sign = buff[0] & 0x80 ? -1 : 1;\n /* exponet in raw format*/\n exponent = ((buff[0] & 0x7F) << 4) | ((buff[1] & 0xF0) >> 4);\n\n /* read inthe mantissa. Top bit is 0.5, the successive bits half*/\n bitval = 0.5;\n maski = 1;\n mask = 0x08;\n for (i = 0; i < significandbits; i++)\n {\n if (buff[maski] & mask)\n fnorm += bitval;\n\n bitval /= 2.0;\n mask >>= 1;\n if (mask == 0)\n {\n mask = 0x80;\n maski++;\n }\n }\n /* handle zero specially */\n if (exponent == 0 && fnorm == 0)\n return 0.0;\n\n shift = exponent - ((1 << (expbits - 1)) - 1); /* exponent = shift + bias */\n /* nans have exp 1024 and non-zero mantissa */\n if (shift == 1024 && fnorm != 0)\n return sqrt(-1.0);\n /*infinity*/\n if (shift == 1024 && fnorm == 0)\n {\n\n#ifdef INFINITY\n return sign == 1 ? INFINITY : -INFINITY;\n#endif\n return (sign * 1.0) / 0.0;\n }\n if (shift > -1023)\n {\n answer = ldexp(fnorm + 1.0, shift);\n return answer * sign;\n }\n else\n {\n /* denormalised numbers */\n if (fnorm == 0.0)\n return 0.0;\n shift = -1022;\n while (fnorm < 1.0)\n {\n fnorm *= 2;\n shift--;\n }\n answer = ldexp(fnorm, shift);\n return answer * sign;\n }\n}\n</code></pre>\n\n<p>For the rest of the suite of functions, including the write and the integer routines see my github project</p>\n\n<p><a href=\"https://github.com/MalcolmMcLean/ieee754\" rel=\"nofollow noreferrer\">https://github.com/MalcolmMcLean/ieee754</a></p>\n"
},
{
"answer_id": 55634732,
"author": "Quinn Carver",
"author_id": 2953356,
"author_profile": "https://Stackoverflow.com/users/2953356",
"pm_score": 0,
"selected": false,
"text": "<p>Byte swapping with ye olde 3-step-xor trick around a pivot in a template function gives a flexible, quick O(ln2) solution that does not require a library, the style here also rejects 1 byte types:</p>\n\n<pre><code>template<typename T>void swap(T &t){\n for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n *((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);\n *((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55756299,
"author": "cycollins",
"author_id": 8611540,
"author_profile": "https://Stackoverflow.com/users/8611540",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like the safe way would be to use htons on each word. So, if you have...</p>\n\n<pre><code>std::vector<uint16_t> storage(n); // where n is the number to be converted\n\n// the following would do the trick\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n</code></pre>\n\n<p>The above would be a no-op if you were on a big-endian system, so I would look for whatever your platform uses as a compile-time condition to decide whether htons is a no-op. It is O(n) after all. On a Mac, it would be something like ...</p>\n\n<pre><code>#if (__DARWIN_BYTE_ORDER != __DARWIN_BIG_ENDIAN)\nstd::transform(word_storage.cbegin(), word_storage.cend()\n , word_storage.begin(), [](const uint16_t input)->uint16_t {\n return htons(input); });\n#endif\n</code></pre>\n"
},
{
"answer_id": 61146679,
"author": "Thinkal VB",
"author_id": 7057208,
"author_profile": "https://Stackoverflow.com/users/7057208",
"pm_score": 1,
"selected": false,
"text": "<p>If you have C++ 17 then add this header</p>\n\n<pre><code>#include <algorithm>\n</code></pre>\n\n<p>Use this template function to swap the bytes:</p>\n\n<pre><code>template <typename T>\nvoid swapEndian(T& buffer)\n{\n static_assert(std::is_pod<T>::value, \"swapEndian support POD type only\");\n char* startIndex = static_cast<char*>((void*)buffer.data());\n char* endIndex = startIndex + sizeof(buffer);\n std::reverse(startIndex, endIndex);\n}\n</code></pre>\n\n<p>call it like:</p>\n\n<pre><code>swapEndian (stlContainer);\n</code></pre>\n"
},
{
"answer_id": 63106400,
"author": "Mrocco",
"author_id": 12178397,
"author_profile": "https://Stackoverflow.com/users/12178397",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a basic function to swap to/from little and big endian. It's basic but it doesn't require supplementary libraries.</p>\n<pre><code>void endianness_swap(uint32_t& val) {\n uint8_t a, b, c;\n a = (val & 0xFF000000) >> 24;\n b = (val & 0x00FF0000) >> 16;\n c = (val & 0x0000FF00) >> 8;\n val=(val & 0x000000FF) << 24;\n val = val + (c << 16) + (b << 8) + (a);\n}\n</code></pre>\n"
},
{
"answer_id": 67458876,
"author": "Sunny127",
"author_id": 1925162,
"author_profile": "https://Stackoverflow.com/users/1925162",
"pm_score": -1,
"selected": false,
"text": "<pre><code>void writeLittleEndianToBigEndian(void* ptrLittleEndian, void* ptrBigEndian , size_t bufLen )\n{\n char *pchLittleEndian = (char*)ptrLittleEndian;\n\n char *pchBigEndian = (char*)ptrBigEndian;\n\n for ( size_t i = 0 ; i < bufLen ; i++ ) \n pchBigEndian[bufLen-1-i] = pchLittleEndian[i];\n}\n\nstd::uint32_t row = 0x12345678;\n\nchar buf[4]; \n\nwriteLittleEndianToBigEndian( &row, &buf, sizeof(row) );\n</code></pre>\n"
},
{
"answer_id": 67681004,
"author": "natersoz",
"author_id": 138264,
"author_profile": "https://Stackoverflow.com/users/138264",
"pm_score": 0,
"selected": false,
"text": "<p>Not as efficient as using an intrinsic function, but certainly portable. My answer:</p>\n<pre><code>#include <cstdint>\n#include <type_traits>\n\n/**\n * Perform an endian swap of bytes against a templatized unsigned word.\n *\n * @tparam value_type The data type to perform the endian swap against.\n * @param value The data value to swap.\n *\n * @return value_type The resulting swapped word.\n */\ntemplate <typename value_type>\nconstexpr inline auto endian_swap(value_type value) -> value_type\n{\n using half_type = typename std::conditional<\n sizeof(value_type) == 8u,\n uint32_t,\n typename std::conditional<sizeof(value_type) == 4u, uint16_t, uint8_t>::\n type>::type;\n\n size_t const half_bits = sizeof(value_type) * 8u / 2u;\n half_type const upper_half = static_cast<half_type>(value >> half_bits);\n half_type const lower_half = static_cast<half_type>(value);\n\n if (sizeof(value_type) == 2u)\n {\n return (static_cast<value_type>(lower_half) << half_bits) | upper_half;\n }\n\n return ((static_cast<value_type>(endian_swap(lower_half)) << half_bits) |\n endian_swap(upper_half));\n}\n</code></pre>\n"
},
{
"answer_id": 69500743,
"author": "Glenn Teitelbaum",
"author_id": 2963099,
"author_profile": "https://Stackoverflow.com/users/2963099",
"pm_score": 0,
"selected": false,
"text": "<p>A c++20 branchless version now that std::endian exists but before c++23 adds std::byteswap</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <bit>\n#include <type_traits>\n#include <concepts>\n#include <array>\n#include <cstring>\n#include <iostream>\n#include <bitset>\n\ntemplate <int LEN, int OFF=LEN/2>\nclass do_swap\n{\n // FOR 8 bytes:\n // LEN=8 (LEN/2==4) <H><G><F><E><D><C><B><A>\n // OFF=4: FROM=0, TO=7 => [A]<G><F><E><D><C><B>[H]\n // OFF=3: FROM=1, TO=6 => [A][B]<F><E><D><C>[G][H]\n // OFF=2: FROM=2, TO=5 => [A][B][C]<E><D>[F][G][H]\n // OFF=1: FROM=3, TO=4 => [A][B][C][D][E][F][G][H]\n // OFF=0: FROM=4, TO=3 => DONE\npublic:\n enum consts {FROM=LEN/2-OFF, TO=(LEN-1)-FROM};\n using NXT=do_swap<LEN, OFF-1>;\n// flip the first and last for the current iteration's range\n static void flip(std::array<std::byte, LEN>& b)\n {\n std::byte tmp=b[FROM];\n b[FROM]=b[TO];\n b[TO]=tmp;\n NXT::flip(b);\n }\n};\ntemplate <int LEN>\nclass do_swap<LEN, 0> // STOP the template recursion\n{\npublic:\n static void flip(std::array<std::byte, LEN>&)\n {\n }\n};\n\ntemplate<std::integral T, std::endian TO, std::endian FROM=std::endian::native>\n requires ((TO==std::endian::big) || (TO==std::endian::little))\n && ((FROM==std::endian::big) || (FROM==std::endian::little))\nclass endian_swap\n{\npublic:\n enum consts {BYTE_COUNT=sizeof(T)};\n static T cvt(const T integral)\n {\n // if FROM and TO are the same -- nothing to do\n if (TO==FROM)\n {\n return integral;\n }\n\n // endian::big --> endian::little is the same as endian::little --> endian::big\n // the bytes have to be reversed\n // memcpy seems to be the most supported way to do byte swaps in a defined way\n std::array<std::byte, BYTE_COUNT> bytes;\n std::memcpy(&bytes, &integral, BYTE_COUNT);\n do_swap<BYTE_COUNT>::flip(bytes);\n T ret;\n std::memcpy(&ret, &bytes, BYTE_COUNT);\n return ret;\n }\n};\n\nstd::endian big()\n{\n return std::endian::big;\n}\n\nstd::endian little()\n{\n return std::endian::little;\n}\n\nstd::endian native()\n{\n return std::endian::native;\n}\n\nlong long swap_to_big(long long x)\n{\n return endian_swap<long long, std::endian::big>::cvt(x);\n}\n\nlong long swap_to_little(long long x)\n{\n return endian_swap<long long, std::endian::little>::cvt(x);\n}\n\nvoid show(std::string label, long long x)\n{\n std::cout << label << "\\t: " << std::bitset<64>(x) << " (" << x << ")" << std::endl;\n}\n\nint main(int argv, char ** argc)\n{\n long long init=0xF8FCFEFF7F3F1F0;\n long long to_big=swap_to_big(init);\n long long to_little=swap_to_little(init);\n show("Init", init);\n show(">big", to_big);\n show(">little", to_little);\n}\n</code></pre>\n"
},
{
"answer_id": 74330996,
"author": "yano",
"author_id": 3476780,
"author_profile": "https://Stackoverflow.com/users/3476780",
"pm_score": 0,
"selected": false,
"text": "<p>Came here looking for a Boost solution and left disappointed, but finally found it elsewhere. You can use <a href=\"https://www.boost.org/doc/libs/1_68_0/libs/endian/doc/conversion.html\" rel=\"nofollow noreferrer\"><code>boost::endian::endian_reverse</code></a>. It's templated/overloaded for all the primitive types:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <iomanip>\n#include "boost/endian/conversion.hpp"\n\nint main()\n{\n uint32_t word = 0x01;\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word << std::endl;\n // outputs 00000001;\n\n uint32_t word2 = boost::endian::endian_reverse(word);\n // there's also a `void ::endian_reverse_inplace(...) function\n // that reverses the value passed to it in place and returns nothing\n\n std::cout << std::hex << std::setfill('0') << std::setw(8) << word2 << std::endl;\n // outputs 01000000\n\n return 0;\n}\n</code></pre>\n<p><a href=\"https://godbolt.org/z/543WaY4sq\" rel=\"nofollow noreferrer\">Demonstration</a></p>\n<p>Although, it looks like c++23 finally put this to bed with <a href=\"https://en.cppreference.com/w/cpp/numeric/byteswap\" rel=\"nofollow noreferrer\"><code>std::byteswap</code></a>. (I'm using c++17, so this was not an option.)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
]
| I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ...
Can anyone point me in the right direction? | If you're using **Visual C++** do the following: You include intrin.h and call the following functions:
For 16 bit numbers:
```
unsigned short _byteswap_ushort(unsigned short value);
```
For 32 bit numbers:
```
unsigned long _byteswap_ulong(unsigned long value);
```
For 64 bit numbers:
```
unsigned __int64 _byteswap_uint64(unsigned __int64 value);
```
8 bit numbers (chars) don't need to be converted.
Also these are only defined for unsigned values they work for signed integers as well.
For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.
Other compilers have similar intrinsics as well.
In **GCC** for example you can directly call [some builtins as documented here](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html):
```
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)
```
(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.
16 bit swap it's just a bit-rotate.
Calling the intrinsics instead of rolling your own gives you the best performance and code density btw.. |
105,308 | <p>I want to take the url:
<a href="http://www.mydomain.com/signup-12345" rel="nofollow noreferrer">http://www.mydomain.com/signup-12345</a></p>
<p>And actually give them:
<a href="http://www.mydomain.com/signup/?aff=12345" rel="nofollow noreferrer">http://www.mydomain.com/signup/?aff=12345</a></p>
<p>I have NO history with mod_rewrite, HELP!</p>
| [
{
"answer_id": 105336,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 3,
"selected": false,
"text": "<p>Try this : </p>\n\n<p>RewriteRule ^/signup-(\\d+)/$ /signup/?aff=$1 [I]</p>\n"
},
{
"answer_id": 111010,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Something that I found relatively hard to find out was how to do the reverse of what you are doing, whereby you need to find out the value of part of the query string. </p>\n\n<p>So for example:</p>\n\n<p>If you wanted to rewrite the Url:\n<a href=\"http://www.example.com/signup-\" rel=\"nofollow noreferrer\">http://www.example.com/signup-</a><strong>old</strong>-script.<strong>asp</strong>?<strong>aff</strong>=12345</p>\n\n<p>to:\n<a href=\"http://www.example.com/signup-\" rel=\"nofollow noreferrer\">http://www.example.com/signup-</a><strong>new</strong>-script.<strong>php</strong>?<strong>affID</strong>=12345</p>\n\n<p>you could use:</p>\n\n<pre><code>RewriteCond %{query_string}& ^aff=((.+&)|&)$ \nRewriteRule ^/signup-old-script.asp$ /signup-new-script.php?affID=%2 [L,R]\n</code></pre>\n\n<p>Notice the <strong>%</strong> sign in the rewrite rule instead of the <strong>$</strong> sign.</p>\n\n<p>I had to do this so I could support old flash maps in a new site that had links to \".cfm\" files with an ID in the query string. </p>\n"
},
{
"answer_id": 5170559,
"author": "Ship",
"author_id": 641583,
"author_profile": "https://Stackoverflow.com/users/641583",
"pm_score": 1,
"selected": false,
"text": "<p>As far i know, </p>\n\n<p><em>flag causes the RewriteCond to be ignored.</em> - for \"Ignore case\" - from <code>IsapiRewrite</code> version 2</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13704/"
]
| I want to take the url:
<http://www.mydomain.com/signup-12345>
And actually give them:
<http://www.mydomain.com/signup/?aff=12345>
I have NO history with mod\_rewrite, HELP! | Something that I found relatively hard to find out was how to do the reverse of what you are doing, whereby you need to find out the value of part of the query string.
So for example:
If you wanted to rewrite the Url:
<http://www.example.com/signup->**old**-script.**asp**?**aff**=12345
to:
<http://www.example.com/signup->**new**-script.**php**?**affID**=12345
you could use:
```
RewriteCond %{query_string}& ^aff=((.+&)|&)$
RewriteRule ^/signup-old-script.asp$ /signup-new-script.php?affID=%2 [L,R]
```
Notice the **%** sign in the rewrite rule instead of the **$** sign.
I had to do this so I could support old flash maps in a new site that had links to ".cfm" files with an ID in the query string. |
105,349 | <p>I am using bash in os X Terminal app, and my custom $PS1 breaks when I scroll through my history.</p>
<pre><code>PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n\[${red}\$${NC}\]"
</code></pre>
<p>also tried
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\r\n[${red}\$${NC}]" </p>
<p>The problem seems to be in the newline. I have used this bash prompt on Slackware no prob.</p>
| [
{
"answer_id": 105363,
"author": "apandit",
"author_id": 6128,
"author_profile": "https://Stackoverflow.com/users/6128",
"pm_score": 0,
"selected": false,
"text": "<p>If the problem seems to be with the newline, try putting \\r\\n instead of just \\n and see if it makes a difference.</p>\n"
},
{
"answer_id": 105658,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 0,
"selected": false,
"text": "<p>I get the same problem (on OS X) with your PS1.\nIf I remove the <code>\\[</code> and <code>\\]</code></p>\n\n<pre><code>PS1=\"${BLUE}\\u${CYAN}@${RED}\\h${BLUE}\\w\\n${red}\\$${NC}\"\n</code></pre>\n\n<p>this works fine. Are the sqare brackets needed? I've never used them, but from <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Printing-a-Prompt\" rel=\"nofollow noreferrer\">the docs</a>:</p>\n\n<blockquote>\n <p><code>\\[</code>\n Begin a sequence of non-printing characters. This could be used to\n embed a terminal control sequence into\n the prompt. </p>\n \n <p><code>\\]</code>\n End a sequence of non-printing characters.</p>\n</blockquote>\n"
},
{
"answer_id": 105922,
"author": "Milhous",
"author_id": 17712,
"author_profile": "https://Stackoverflow.com/users/17712",
"pm_score": 0,
"selected": false,
"text": "<p>I have now tried</p>\n\n<pre><code>PS1=\"${BLUE}\\u${CYAN}@${RED}\\h${BLUE}\\w${RED}\\r\\n\\$\\[${blue}\\]\"\n</code></pre>\n\n<p>Which seems to work \nThe brackets needed to make previous commands work.</p>\n"
},
{
"answer_id": 105926,
"author": "Ben Stiglitz",
"author_id": 6298,
"author_profile": "https://Stackoverflow.com/users/6298",
"pm_score": 4,
"selected": true,
"text": "<p>You need the [ and ] arond every escape sequence; do $BLUE and the like include these? If not, they need to be bracketed with these calls.</p>\n"
},
{
"answer_id": 1911711,
"author": "Hedgehog",
"author_id": 152860,
"author_profile": "https://Stackoverflow.com/users/152860",
"pm_score": 2,
"selected": false,
"text": "<p>To avoid such 'escaping' difficulties as you prompt needs evole to be more complex, this should be a skeleton to start growing on:</p>\n\n<pre><code>function _my_prompt ()\n{ \n # magic goes here\n my_prmpt=.... \n}\nPROMPT_COMMAND='_my_prompt'\nPS1=\"[\\$my_prmpt] \\$\"\n</code></pre>\n"
},
{
"answer_id": 2038892,
"author": "user247669",
"author_id": 247669,
"author_profile": "https://Stackoverflow.com/users/247669",
"pm_score": 2,
"selected": false,
"text": "<p>I was having the same problem when logging on remote (debian) systems. As the escaped values in .bashrc all were nicely bracketed, I did some googling and discovered that the cause might be differences in window size on the local and the remote system. Adding </p>\n\n<p>shopt -s checkwinsize</p>\n\n<p>to .bashrc on the remote systems has fixed the problem for me.</p>\n\n<p>Source: <a href=\"http://forums.macosxhints.com/showthread.php?t=17068\" rel=\"nofollow noreferrer\">http://forums.macosxhints.com/showthread.php?t=17068</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
]
| I am using bash in os X Terminal app, and my custom $PS1 breaks when I scroll through my history.
```
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n\[${red}\$${NC}\]"
```
also tried
PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\r\n[${red}\$${NC}]"
The problem seems to be in the newline. I have used this bash prompt on Slackware no prob. | You need the [ and ] arond every escape sequence; do $BLUE and the like include these? If not, they need to be bracketed with these calls. |
105,372 | <p>How can you enumerate an <code>enum</code> in C#?</p>
<p>E.g. the following code does not compile:</p>
<pre class="lang-cs prettyprint-override"><code>public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
</code></pre>
<p>And it gives the following compile-time error:</p>
<blockquote>
<p>'Suit' is a 'type' but is used like a 'variable'</p>
</blockquote>
<p>It fails on the <code>Suit</code> keyword, the second one.</p>
| [
{
"answer_id": 105401,
"author": "Tom Carr",
"author_id": 14954,
"author_profile": "https://Stackoverflow.com/users/14954",
"pm_score": 6,
"selected": false,
"text": "<p>I think you can use</p>\n\n<pre><code>Enum.GetNames(Suit)\n</code></pre>\n"
},
{
"answer_id": 105402,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 13,
"selected": true,
"text": "<pre><code>foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))\n{\n}\n</code></pre>\n\n<p><strong>Note</strong>: The cast to <code>(Suit[])</code> is not strictly necessary, <a href=\"https://gist.github.com/bartoszkp/9e059c3edccc07a5e588#gistcomment-2625454\" rel=\"noreferrer\">but it does make the code 0.5 ns faster</a>.</p>\n"
},
{
"answer_id": 105421,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 10,
"selected": false,
"text": "<p>It looks to me like you really want to print out the names of each enum, rather than the values. In which case <code>Enum.GetNames()</code> seems to be the right approach.</p>\n\n<pre><code>public enum Suits\n{\n Spades,\n Hearts,\n Clubs,\n Diamonds,\n NumSuits\n}\n\npublic void PrintAllSuits()\n{\n foreach (string name in Enum.GetNames(typeof(Suits)))\n {\n System.Console.WriteLine(name);\n }\n}\n</code></pre>\n\n<p>By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.</p>\n\n<p>I would use <code>Enum.GetValues(typeof(Suit))</code> instead.</p>\n\n<pre><code>public enum Suits\n{\n Spades,\n Hearts,\n Clubs,\n Diamonds,\n NumSuits\n}\n\npublic void PrintAllSuits()\n{\n foreach (var suit in Enum.GetValues(typeof(Suits)))\n {\n System.Console.WriteLine(suit.ToString());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 105617,
"author": "Joshua Drake",
"author_id": 19308,
"author_profile": "https://Stackoverflow.com/users/19308",
"pm_score": 6,
"selected": false,
"text": "<pre><code>public void PrintAllSuits()\n{\n foreach(string suit in Enum.GetNames(typeof(Suits)))\n {\n Console.WriteLine(suit);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 944352,
"author": "bob",
"author_id": 23805,
"author_profile": "https://Stackoverflow.com/users/23805",
"pm_score": 9,
"selected": false,
"text": "<p>I made some extensions for easy enum usage. Maybe someone can use it...</p>\n\n<pre><code>public static class EnumExtensions\n{\n /// <summary>\n /// Gets all items for an enum value.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n public static IEnumerable<T> GetAllItems<T>(this Enum value)\n {\n foreach (object item in Enum.GetValues(typeof(T)))\n {\n yield return (T)item;\n }\n }\n\n /// <summary>\n /// Gets all items for an enum type.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n public static IEnumerable<T> GetAllItems<T>() where T : struct\n {\n foreach (object item in Enum.GetValues(typeof(T)))\n {\n yield return (T)item;\n }\n }\n\n /// <summary>\n /// Gets all combined items from an enum value.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n /// <example>\n /// Displays ValueA and ValueB.\n /// <code>\n /// EnumExample dummy = EnumExample.Combi;\n /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())\n /// {\n /// Console.WriteLine(item);\n /// }\n /// </code>\n /// </example>\n public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)\n {\n int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);\n\n foreach (object item in Enum.GetValues(typeof(T)))\n {\n int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);\n\n if (itemAsInt == (valueAsInt & itemAsInt))\n {\n yield return (T)item;\n }\n }\n }\n\n /// <summary>\n /// Determines whether the enum value contains a specific value.\n /// </summary>\n /// <param name=\"value\">The value.</param>\n /// <param name=\"request\">The request.</param>\n /// <returns>\n /// <c>true</c> if value contains the specified value; otherwise, <c>false</c>.\n /// </returns>\n /// <example>\n /// <code>\n /// EnumExample dummy = EnumExample.Combi;\n /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))\n /// {\n /// Console.WriteLine(\"dummy contains EnumExample.ValueA\");\n /// }\n /// </code>\n /// </example>\n public static bool Contains<T>(this Enum value, T request)\n {\n int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);\n int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);\n\n if (requestAsInt == (valueAsInt & requestAsInt))\n {\n return true;\n }\n\n return false;\n }\n}\n</code></pre>\n\n<p>The enum itself must be decorated with the <a href=\"http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx\" rel=\"noreferrer\">FlagsAttribute</a>:</p>\n\n<pre><code>[Flags]\npublic enum EnumExample\n{\n ValueA = 1,\n ValueB = 2,\n ValueC = 4,\n ValueD = 8,\n Combi = ValueA | ValueB\n}\n</code></pre>\n"
},
{
"answer_id": 1375234,
"author": "Ekevoo",
"author_id": 98029,
"author_profile": "https://Stackoverflow.com/users/98029",
"pm_score": 8,
"selected": false,
"text": "<p>Some versions of the .NET framework do not support <code>Enum.GetValues</code>. Here's a good workaround from <a href=\"https://web.archive.org/web/20100530072822/http://ideas.dalezak.ca/2008/11/enumgetvalues-in-compact-framework.html\" rel=\"noreferrer\">Ideas 2.0: Enum.GetValues in Compact Framework</a>:</p>\n\n<pre><code>public Enum[] GetValues(Enum enumeration)\n{\n FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);\n Enum[] enumerations = new Enum[fields.Length];\n\n for (var i = 0; i < fields.Length; i++)\n enumerations[i] = (Enum) fields[i].GetValue(enumeration);\n\n return enumerations;\n}\n</code></pre>\n\n<p>As with any code that involves <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection\" rel=\"noreferrer\">reflection</a>, you should take steps to ensure it runs only once and results are cached.</p>\n"
},
{
"answer_id": 1743591,
"author": "lmat - Reinstate Monica",
"author_id": 200985,
"author_profile": "https://Stackoverflow.com/users/200985",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n<pre><code>foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }\n</code></pre>\n \n <p>I've heard vague rumours that this is\n terifically slow. Anyone know? – Orion\n Edwards Oct 15 '08 at 1:31 7 </p>\n</blockquote>\n\n<p>I think caching the array would speed it up considerably. It looks like you're getting a new array (through reflection) every time. Rather:</p>\n\n<pre><code>Array enums = Enum.GetValues(typeof(Suit));\nforeach (Suit suitEnum in enums) \n{\n DoSomething(suitEnum);\n}\n</code></pre>\n\n<p>That's at least a little faster, ja?</p>\n"
},
{
"answer_id": 3195229,
"author": "Mallox",
"author_id": 81112,
"author_profile": "https://Stackoverflow.com/users/81112",
"pm_score": 6,
"selected": false,
"text": "<p>My solution works in <a href=\"https://en.wikipedia.org/wiki/.NET_Compact_Framework\" rel=\"noreferrer\">.NET Compact Framework</a> (3.5) and supports type checking <strong>at compile time</strong>:</p>\n\n<pre><code>public static List<T> GetEnumValues<T>() where T : new() {\n T valueType = new T();\n return typeof(T).GetFields()\n .Select(fieldInfo => (T)fieldInfo.GetValue(valueType))\n .Distinct()\n .ToList();\n}\n\npublic static List<String> GetEnumNames<T>() {\n return typeof (T).GetFields()\n .Select(info => info.Name)\n .Distinct()\n .ToList();\n}\n</code></pre>\n\n<ul>\n<li>If anyone knows how to get rid of the <code>T valueType = new T()</code>, I'd be happy to see a solution.</li>\n</ul>\n\n<p>A call would look like this:</p>\n\n<pre><code>List<MyEnum> result = Utils.GetEnumValues<MyEnum>();\n</code></pre>\n"
},
{
"answer_id": 4200724,
"author": "Aubrey Taylor",
"author_id": 510266,
"author_profile": "https://Stackoverflow.com/users/510266",
"pm_score": 6,
"selected": false,
"text": "<p>You won't get <code>Enum.GetValues()</code> in <a href=\"http://en.wikipedia.org/wiki/Microsoft_Silverlight\" rel=\"noreferrer\">Silverlight</a>.</p>\n\n<p><a href=\"http://web.archive.org/web/20101105013136/http://www.dolittle.no/blogs/einar/archive/2008/01/13/missing-enum-getvalues-when-doing-silverlight-for-instance.aspx\" rel=\"noreferrer\">Original Blog Post by Einar Ingebrigtsen</a>:</p>\n\n<pre><code>public class EnumHelper\n{\n public static T[] GetValues<T>()\n {\n Type enumType = typeof(T);\n\n if (!enumType.IsEnum)\n {\n throw new ArgumentException(\"Type '\" + enumType.Name + \"' is not an enum\");\n }\n\n List<T> values = new List<T>();\n\n var fields = from field in enumType.GetFields()\n where field.IsLiteral\n select field;\n\n foreach (FieldInfo field in fields)\n {\n object value = field.GetValue(enumType);\n values.Add((T)value);\n }\n\n return values.ToArray();\n }\n\n public static object[] GetValues(Type enumType)\n {\n if (!enumType.IsEnum)\n {\n throw new ArgumentException(\"Type '\" + enumType.Name + \"' is not an enum\");\n }\n\n List<object> values = new List<object>();\n\n var fields = from field in enumType.GetFields()\n where field.IsLiteral\n select field;\n\n foreach (FieldInfo field in fields)\n {\n object value = field.GetValue(enumType);\n values.Add(value);\n }\n\n return values.ToArray();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9113274,
"author": "James",
"author_id": 1185191,
"author_profile": "https://Stackoverflow.com/users/1185191",
"pm_score": 7,
"selected": false,
"text": "<p>I think this is more efficient than other suggestions because <code>GetValues()</code> is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if <code>Suit</code> is not an <code>enum</code>.</p>\n\n<pre><code>EnumLoop<Suit>.ForEach((suit) => {\n DoSomethingWith(suit);\n});\n</code></pre>\n\n<p><code>EnumLoop</code> has this completely generic definition:</p>\n\n<pre><code>class EnumLoop<Key> where Key : struct, IConvertible {\n static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));\n static internal void ForEach(Action<Key> act) {\n for (int i = 0; i < arr.Length; i++) {\n act(arr[i]);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11666195,
"author": "Mickey Perlstein",
"author_id": 1125913,
"author_profile": "https://Stackoverflow.com/users/1125913",
"pm_score": 5,
"selected": false,
"text": "<p>I use ToString() then split and parse the spit array in flags.</p>\n\n<pre><code>[Flags]\npublic enum ABC {\n a = 1,\n b = 2,\n c = 4\n};\n\npublic IEnumerable<ABC> Getselected (ABC flags)\n{\n var values = flags.ToString().Split(',');\n var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));\n return enums;\n}\n\nABC temp= ABC.a | ABC.b;\nvar list = getSelected (temp);\nforeach (var item in list)\n{\n Console.WriteLine(item.ToString() + \" ID=\" + (int)item);\n}\n</code></pre>\n"
},
{
"answer_id": 13077473,
"author": "jhilden",
"author_id": 1173800,
"author_profile": "https://Stackoverflow.com/users/1173800",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a working example of creating select options for a <a href=\"https://en.wikipedia.org/wiki/Data_definition_language\" rel=\"noreferrer\">DDL</a>:</p>\n\n<pre><code>var resman = ViewModelResources.TimeFrame.ResourceManager;\n\nViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame\n in Enum.GetValues(typeof(MapOverlayTimeFrames))\n select new SelectListItem\n {\n Value = timeFrame.ToString(),\n Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()\n };\n</code></pre>\n"
},
{
"answer_id": 14513140,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 4,
"selected": false,
"text": "<h3>I do not hold the opinion this is better, or even good. I am just stating yet another solution.</h3>\n<p>If enum values range strictly from 0 to n - 1, a generic alternative is:</p>\n<pre><code>public void EnumerateEnum<T>()\n{\n int length = Enum.GetValues(typeof(T)).Length;\n for (var i = 0; i < length; i++)\n {\n var @enum = (T)(object)i;\n }\n}\n</code></pre>\n<p>If enum values are contiguous and you can provide the first and last element of the enum, then:</p>\n<pre><code>public void EnumerateEnum()\n{\n for (var i = Suit.Spade; i <= Suit.Diamond; i++)\n {\n var @enum = i;\n }\n}\n</code></pre>\n<p>But that's not strictly enumerating, just looping. The second method is much faster than any other approach though...</p>\n"
},
{
"answer_id": 15457453,
"author": "sircodesalot",
"author_id": 2043536,
"author_profile": "https://Stackoverflow.com/users/2043536",
"pm_score": 7,
"selected": false,
"text": "<p>Use <code>Cast<T></code>:</p>\n\n<pre><code>var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();\n</code></pre>\n\n<p>There you go, <code>IEnumerable<Suit></code>.</p>\n"
},
{
"answer_id": 17121612,
"author": "Darkside",
"author_id": 606847,
"author_profile": "https://Stackoverflow.com/users/606847",
"pm_score": 5,
"selected": false,
"text": "<p>Just by combining the top answers, I threw together a very simple extension:</p>\n\n<pre><code>public static class EnumExtensions\n{\n /// <summary>\n /// Gets all items for an enum value.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\">The value.</param>\n /// <returns></returns>\n public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum\n {\n return (T[])Enum.GetValues(typeof (T));\n }\n}\n</code></pre>\n\n<p>It is clean, simple, and, by @Jeppe-Stig-Nielsen's comment, fast.</p>\n"
},
{
"answer_id": 18191073,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 5,
"selected": false,
"text": "<p>Three ways:</p>\n\n<ol>\n<li><code>Enum.GetValues(type)</code> // Since .NET 1.1, not in Silverlight or .NET Compact Framework</li>\n<li><code>type.GetEnumValues()</code> // Only on .NET 4 and above</li>\n<li><code>type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null))</code> // Works everywhere</li>\n</ol>\n\n<p><em>I am not sure why <code>GetEnumValues</code> was introduced on type instances. It isn't very readable at all for me.</em></p>\n\n<hr>\n\n<p>Having a helper class like <code>Enum<T></code> is what is most readable and memorable for me:</p>\n\n<pre><code>public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible\n{\n public static IEnumerable<T> GetValues()\n {\n return (T[])Enum.GetValues(typeof(T));\n }\n\n public static IEnumerable<string> GetNames()\n {\n return Enum.GetNames(typeof(T));\n }\n}\n</code></pre>\n\n<p>Now you call:</p>\n\n<pre><code>Enum<Suit>.GetValues();\n\n// Or\nEnum.GetValues(typeof(Suit)); // Pretty consistent style\n</code></pre>\n\n<p>One can also use some sort of caching if performance matters, but I don't expect this to be an issue at all.</p>\n\n<pre><code>public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible\n{\n // Lazily loaded\n static T[] values;\n static string[] names;\n\n public static IEnumerable<T> GetValues()\n {\n return values ?? (values = (T[])Enum.GetValues(typeof(T)));\n }\n\n public static IEnumerable<string> GetNames()\n {\n return names ?? (names = Enum.GetNames(typeof(T)));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20009790,
"author": "dmihailescu",
"author_id": 376495,
"author_profile": "https://Stackoverflow.com/users/376495",
"pm_score": 4,
"selected": false,
"text": "<p>If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:</p>\n\n<pre><code>public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible\n{\n if (typeof(T).BaseType != typeof(Enum))\n {\n throw new ArgumentException(string.Format(\"{0} is not of type System.Enum\", typeof(T)));\n }\n return Enum.GetValues(typeof(T)) as T[];\n}\n</code></pre>\n\n<p>And you can use it like below:</p>\n\n<pre><code>static readonly YourEnum[] _values = GetEnumValues<YourEnum>();\n</code></pre>\n\n<p>Of course you can return <code>IEnumerable<T></code>, but that buys you nothing here.</p>\n"
},
{
"answer_id": 21231697,
"author": "matt burns",
"author_id": 276093,
"author_profile": "https://Stackoverflow.com/users/276093",
"pm_score": 4,
"selected": false,
"text": "<pre><code>foreach (Suit suit in Enum.GetValues(typeof(Suit)))\n{\n}\n</code></pre>\n\n<p>(The current accepted answer has a cast that I don't think \nis needed (although I may be wrong).)</p>\n"
},
{
"answer_id": 22941865,
"author": "anar khalilov",
"author_id": 437979,
"author_profile": "https://Stackoverflow.com/users/437979",
"pm_score": 4,
"selected": false,
"text": "<p>I know it is a bit messy, but if you are fan of one-liners, here is one:</p>\n\n<pre><code>((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));\n</code></pre>\n"
},
{
"answer_id": 25814247,
"author": "Gabriel",
"author_id": 632986,
"author_profile": "https://Stackoverflow.com/users/632986",
"pm_score": 4,
"selected": false,
"text": "<p>A simple and generic way to convert an enum to something you can interact:</p>\n\n<pre><code>public static Dictionary<int, string> ToList<T>() where T : struct\n{\n return ((IEnumerable<T>)Enum\n .GetValues(typeof(T)))\n .ToDictionary(\n item => Convert.ToInt32(item),\n item => item.ToString());\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>var enums = EnumHelper.ToList<MyEnum>();\n</code></pre>\n"
},
{
"answer_id": 31096712,
"author": "Ross Gatih",
"author_id": 1747521,
"author_profile": "https://Stackoverflow.com/users/1747521",
"pm_score": 4,
"selected": false,
"text": "<p>This question appears in Chapter 10 of \"<a href=\"http://www.amazon.ca/Microsoft-Visual-2013-Step/dp/073568183X\" rel=\"noreferrer\">C# Step by Step 2013</a>\"</p>\n\n<p>The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):</p>\n\n<pre><code>class Pack\n{\n public const int NumSuits = 4;\n public const int CardsPerSuit = 13;\n private PlayingCard[,] cardPack;\n\n public Pack()\n {\n this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];\n for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)\n {\n for (Value value = Value.Two; value <= Value.Ace; value++)\n {\n cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);\n }\n }\n }\n}\n</code></pre>\n\n<p>In this case, <code>Suit</code> and <code>Value</code> are both enumerations:</p>\n\n<pre><code>enum Suit { Clubs, Diamonds, Hearts, Spades }\nenum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}\n</code></pre>\n\n<p>and <code>PlayingCard</code> is a card object with a defined <code>Suit</code> and <code>Value</code>:</p>\n\n<pre><code>class PlayingCard\n{\n private readonly Suit suit;\n private readonly Value value;\n\n public PlayingCard(Suit s, Value v)\n {\n this.suit = s;\n this.value = v;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32884992,
"author": "Slappywag",
"author_id": 4218542,
"author_profile": "https://Stackoverflow.com/users/4218542",
"pm_score": 3,
"selected": false,
"text": "<p>What if you know the type will be an <code>enum</code>, but you don't know what the exact type is at compile time?</p>\n\n<pre><code>public class EnumHelper\n{\n public static IEnumerable<T> GetValues<T>()\n {\n return Enum.GetValues(typeof(T)).Cast<T>();\n }\n\n public static IEnumerable getListOfEnum(Type type)\n {\n MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod(\"GetValues\").MakeGenericMethod(type);\n return (IEnumerable)getValuesMethod.Invoke(null, null);\n }\n}\n</code></pre>\n\n<p>The method <code>getListOfEnum</code> uses reflection to take any enum type and returns an <code>IEnumerable</code> of all enum values.</p>\n\n<p>Usage:</p>\n\n<pre><code>Type myType = someEnumValue.GetType();\n\nIEnumerable resultEnumerable = getListOfEnum(myType);\n\nforeach (var item in resultEnumerable)\n{\n Console.WriteLine(String.Format(\"Item: {0} Value: {1}\",item.ToString(),(int)item));\n}\n</code></pre>\n"
},
{
"answer_id": 34953875,
"author": "Kylo Ren",
"author_id": 4576125,
"author_profile": "https://Stackoverflow.com/users/4576125",
"pm_score": 5,
"selected": false,
"text": "<p>There are two ways to iterate an <code>Enum</code>:</p>\n\n<pre><code>1. var values = Enum.GetValues(typeof(myenum))\n2. var values = Enum.GetNames(typeof(myenum))\n</code></pre>\n\n<p>The first will give you values in form on an array of **<code>object</code>**s, and the second will give you values in form of an array of **<code>String</code>**s.</p>\n\n<p>Use it in a <code>foreach</code> loop as below:</p>\n\n<pre><code>foreach(var value in values)\n{\n // Do operations here\n}\n</code></pre>\n"
},
{
"answer_id": 41558833,
"author": "Termininja",
"author_id": 3618581,
"author_profile": "https://Stackoverflow.com/users/3618581",
"pm_score": 2,
"selected": false,
"text": "<p>Also you can bind to the public static members of the enum directly by using reflection:</p>\n\n<pre><code>typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)\n .ToList().ForEach(x => DoSomething(x.Name));\n</code></pre>\n"
},
{
"answer_id": 43134553,
"author": "MUT",
"author_id": 5863303,
"author_profile": "https://Stackoverflow.com/users/5863303",
"pm_score": 4,
"selected": false,
"text": "<p>Add method <code>public static IEnumerable<T> GetValues<T>()</code> to your class, like:</p>\n\n<pre><code>public static IEnumerable<T> GetValues<T>()\n{\n return Enum.GetValues(typeof(T)).Cast<T>();\n}\n</code></pre>\n\n<p>Call and pass your enum. Now you can iterate through it using <code>foreach</code>:</p>\n\n<pre><code> public static void EnumerateAllSuitsDemoMethod()\n {\n // Custom method\n var foos = GetValues<Suit>();\n foreach (var foo in foos)\n {\n // Do something\n }\n }\n</code></pre>\n"
},
{
"answer_id": 46680065,
"author": "Emily Chen",
"author_id": 4549031,
"author_profile": "https://Stackoverflow.com/users/4549031",
"pm_score": 3,
"selected": false,
"text": "<p><code>enum</code> types are called \"enumeration types\" not because they are containers that \"enumerate\" values (which they aren't), but because they are defined by <em>enumerating</em> the possible values for a variable of that type. </p>\n\n<p>(Actually, that's a bit more complicated than that - enum types are considered to have an \"underlying\" integer type, which means each enum value corresponds to an integer value (this is typically implicit, but can be manually specified). C# was designed in a way so that you could stuff <em>any</em> integer of that type into the enum variable, even if it isn't a \"named\" value.)</p>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/system.enum.getnames(v=vs.110).aspx\" rel=\"noreferrer\">System.Enum.GetNames method</a> can be used to retrieve an array of strings which are the names of the enum values, as the name suggests.</p>\n\n<p>EDIT: Should have suggested the <a href=\"https://msdn.microsoft.com/en-us/library/system.enum.getvalues(v=vs.110).aspx\" rel=\"noreferrer\">System.Enum.GetValues</a> method instead. Oops.</p>\n"
},
{
"answer_id": 58249447,
"author": "R.Akhlaghi",
"author_id": 2830315,
"author_profile": "https://Stackoverflow.com/users/2830315",
"pm_score": 3,
"selected": false,
"text": "<p>For getting a list of int from an enum, use the following. It works!</p>\n<pre><code>List<int> listEnumValues = new List<int>();\nYourEnumType[] myEnumMembers = (YourEnumType[])Enum.GetValues(typeof(YourEnumType));\nforeach ( YourEnumType enumMember in myEnumMembers)\n{\n listEnumValues.Add(enumMember.GetHashCode());\n}\n</code></pre>\n"
},
{
"answer_id": 58974242,
"author": "rlv-dan",
"author_id": 1087811,
"author_profile": "https://Stackoverflow.com/users/1087811",
"pm_score": 1,
"selected": false,
"text": "<p>If you have:</p>\n\n<pre><code>enum Suit\n{\n Spades,\n Hearts,\n Clubs,\n Diamonds\n}\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>foreach (var e in Enum.GetValues(typeof(Suit)))\n{\n Console.WriteLine(e.ToString() + \" = \" + (int)e);\n}\n</code></pre>\n\n<p>Will output:</p>\n\n<pre><code>Spades = 0\nHearts = 1\nClubs = 2\nDiamonds = 3\n</code></pre>\n"
},
{
"answer_id": 58975533,
"author": "Erçin Dedeoğlu",
"author_id": 2426367,
"author_profile": "https://Stackoverflow.com/users/2426367",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query\" rel=\"nofollow noreferrer\">LINQ</a> Generic Way:</p>\n\n<pre><code> public static Dictionary<int, string> ToList<T>() where T : struct =>\n ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> var enums = ToList<Enum>();\n</code></pre>\n"
},
{
"answer_id": 65103244,
"author": "Arad",
"author_id": 7734384,
"author_profile": "https://Stackoverflow.com/users/7734384",
"pm_score": 7,
"selected": false,
"text": "<h1>New .NET 5 Solution:</h1>\n<p>.NET 5 has introduced a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-5.0#System_Enum_GetValues__1\" rel=\"noreferrer\">new generic version for the <code>GetValues</code></a> method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Suit[] suitValues = Enum.GetValues<Suit>();\n</code></pre>\n<p>Which is now by far the most convenient way of doing this.</p>\n<p>Usage in a foreach loop:</p>\n<pre><code>foreach (Suit suit in Enum.GetValues<Suit>())\n{\n\n}\n</code></pre>\n<p>And if you just need the enum names as strings, you can use the generic <code>GetNames</code> method:</p>\n<pre><code>string[] suitNames = Enum.GetNames<Suit>();\n</code></pre>\n"
},
{
"answer_id": 66007982,
"author": "Inam Abbas",
"author_id": 7258037,
"author_profile": "https://Stackoverflow.com/users/7258037",
"pm_score": 0,
"selected": false,
"text": "<p>I think its help you try it.</p>\n<pre><code>public class Program\n{\n\n public static List<T> GetEnamList<T>()\n {\n var enums = Enum.GetValues(typeof(T)).Cast<T>().Select(v => v).ToList();\n return enums;\n }\n private void LoadEnumList()\n {\n List<DayofWeek> dayofweeks = GetEnamList<DayofWeek>();\n\n foreach (var item in dayofweeks)\n {\n dayofweeks.Add(item);\n }\n }\n}\n\n public enum DayofWeek\n {\n Monday,\n Tuesday,\n Wensday,\n Thursday,\n Friday,\n Sturday,\n Sunday\n }\n</code></pre>\n"
},
{
"answer_id": 66110060,
"author": "marsh-wiggle",
"author_id": 1574221,
"author_profile": "https://Stackoverflow.com/users/1574221",
"pm_score": 2,
"selected": false,
"text": "<p>When you have a bit enum like this</p>\n<pre><code>enum DemoFlags\n{\n DemoFlag = 1,\n OtherFlag = 2,\n TestFlag = 4,\n LastFlag = 8,\n}\n</code></pre>\n<p>With this assignement</p>\n<pre><code>DemoFlags demoFlags = DemoFlags.DemoFlag | DemoFlags.TestFlag;\n</code></pre>\n<p>and need a result like this</p>\n<pre><code>"DemoFlag | TestFlag"\n</code></pre>\n<p>this method helps:</p>\n<pre><code>public static string ConvertToEnumString<T>(T enumToConvert, string separator = " | ") where T : Enum\n{\n StringBuilder convertedEnums = new StringBuilder();\n\n foreach (T enumValue in Enum.GetValues(typeof(T)))\n {\n if (enumToConvert.HasFlag(enumValue)) convertedEnums.Append($"{ enumValue }{separator}");\n }\n\n if (convertedEnums.Length > 0) convertedEnums.Length -= separator.Length;\n\n return convertedEnums.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 71026767,
"author": "code4fun",
"author_id": 18145484,
"author_profile": "https://Stackoverflow.com/users/18145484",
"pm_score": 2,
"selected": false,
"text": "<p>A simple Enum.GetNames(<em>EnumType</em>) should work</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
]
| How can you enumerate an `enum` in C#?
E.g. the following code does not compile:
```cs
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
```
And it gives the following compile-time error:
>
> 'Suit' is a 'type' but is used like a 'variable'
>
>
>
It fails on the `Suit` keyword, the second one. | ```
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
```
**Note**: The cast to `(Suit[])` is not strictly necessary, [but it does make the code 0.5 ns faster](https://gist.github.com/bartoszkp/9e059c3edccc07a5e588#gistcomment-2625454). |
105,477 | <p>I think I've got it down to the most basic case:</p>
<pre><code>int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * arr) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
</code></pre>
<p>The output is this:</p>
<pre class="lang-none prettyprint-override"><code>> ./a.out
car[3]=-1869558540
a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer
being freed
*** set a breakpoint in malloc_error_break to debug
>
</code></pre>
<p>If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.</p>
| [
{
"answer_id": 105507,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": false,
"text": "<p>You've allocated arr in foo, but that pointers value is stored in the call stack. If you want to do this, do it like this:</p>\n\n<pre><code>void foo( int ** arr) {\n *arr = (int *)malloc( sizeof(int) * 25 );\n (*arr)[3] = 69;\n}\n</code></pre>\n\n<p>And in main, simply pass a pointer to foo (like foo(&arr))</p>\n"
},
{
"answer_id": 105508,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 7,
"selected": true,
"text": "<p>You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function. \nAs m_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about references):</p>\n\n<pre><code>int main(int argc, char ** argv) {\n int * arr;\n\n foo(arr);\n printf(\"car[3]=%d\\n\",arr[3]);\n free (arr);\n return 1;\n}\n\nvoid foo(int * &arr ) {\n arr = (int*) malloc( sizeof(int)*25 );\n arr[3] = 69;\n}\n</code></pre>\n\n<p>Another (better imho) way is to not pass the pointer as an argument but to return a pointer:</p>\n\n<pre><code>int main(int argc, char ** argv) {\n int * arr;\n\n arr = foo();\n printf(\"car[3]=%d\\n\",arr[3]);\n free (arr);\n return 1;\n}\n\nint * foo(void ) {\n int * arr;\n arr = (int*) malloc( sizeof(int)*25 );\n arr[3] = 69;\n return arr;\n}\n</code></pre>\n\n<p>And you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - that's how C is...</p>\n\n<pre><code>int main(int argc, char ** argv) {\n int * arr;\n\n foo(&arr);\n printf(\"car[3]=%d\\n\",arr[3]);\n free (arr);\n return 1;\n}\n\nvoid foo(int ** arr ) {\n (*arr) = (int*) malloc( sizeof(int)*25 );\n (*arr)[3] = 69;\n}\n</code></pre>\n"
},
{
"answer_id": 105521,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "<p>You cannot change the value of your argument (arr) if it's not passed in by reference (&). In general, you would want to return the pointer, so your method should be:</p>\n\n<p>arr=foo();</p>\n\n<p>It's bad juju to try to reassign arguments; I don't recommend the (&) solution.</p>\n"
},
{
"answer_id": 105539,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 2,
"selected": false,
"text": "<p>foo receives a local copy of the int pointer, alloactes memory to it and leaks that memory when it goes out of scope.</p>\n\n<p>One way to fix this to get foo to return the pointer:</p>\n\n<pre><code>int * foo() {\n return (int*) malloc( sizeof(int)*25 );\n}\n\nint main() {\n int* arr = foo();\n}\n</code></pre>\n\n<p>Another is to pass foo a pointer to a pointer</p>\n\n<pre><code>void foo(int ** arr) {\n *arr = malloc(...);\n}\n\nint main() {\n foo(&arr);\n}\n</code></pre>\n\n<p>In C++ it is simpler to modify foo to accept a reference to a pointer. The only change you need in C++ is to change foo to</p>\n\n<pre><code>void foo(int * & arr)\n</code></pre>\n"
},
{
"answer_id": 105590,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 1,
"selected": false,
"text": "<p>Since your are passing the pointer by value, the arr pointer inside main isn't pointing to the allocated memory. This means two thing: you've got yourself a memory leak (NO, the memory isn't freed after the function foo completes), and when you access the arr pointer inside main you are accessing some arbitrary range of memory, hence you don't get 3 printed out and hence free() refuses to work. You're lucky you didn't get a segmentation fault when accessing arr[3] inside main.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I think I've got it down to the most basic case:
```
int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * arr) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
```
The output is this:
```none
> ./a.out
car[3]=-1869558540
a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer
being freed
*** set a breakpoint in malloc_error_break to debug
>
```
If anyone can shed light on where my understanding is failing, it'd be greatly appreciated. | You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function.
As m\_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about references):
```
int main(int argc, char ** argv) {
int * arr;
foo(arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int * &arr ) {
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
}
```
Another (better imho) way is to not pass the pointer as an argument but to return a pointer:
```
int main(int argc, char ** argv) {
int * arr;
arr = foo();
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
int * foo(void ) {
int * arr;
arr = (int*) malloc( sizeof(int)*25 );
arr[3] = 69;
return arr;
}
```
And you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - that's how C is...
```
int main(int argc, char ** argv) {
int * arr;
foo(&arr);
printf("car[3]=%d\n",arr[3]);
free (arr);
return 1;
}
void foo(int ** arr ) {
(*arr) = (int*) malloc( sizeof(int)*25 );
(*arr)[3] = 69;
}
``` |
105,499 | <p>I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy. </p>
<p>If I use the web service, then it is possible to set proxy. </p>
| [
{
"answer_id": 108530,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this is what you are looking for but the below is a working code sample to authenticate using the client credentials.</p>\n\n<pre><code> Dim client As ProductServiceClient = New ProductServiceClient(\"wsHttpProductService\")\n client.ClientCredentials.UserName.UserName = \"username\"\n client.ClientCredentials.UserName.Password = \"password\"\n Dim ProductList As List(Of Product) = client.GetProducts()\n mView.Products = ProductList\n client.Close()\n</code></pre>\n"
},
{
"answer_id": 108532,
"author": "Pawel Pabich",
"author_id": 3323,
"author_profile": "https://Stackoverflow.com/users/3323",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not entirely sure if this is what you are looking for but here you go.</p>\n\n<pre><code> MyClient client = new MyClient();\n client.ClientCredentials.UserName.UserName = \"u\";\n client.ClientCredentials.UserName.Password = \"p\";\n</code></pre>\n"
},
{
"answer_id": 6354185,
"author": "Diganta Kumar",
"author_id": 798727,
"author_profile": "https://Stackoverflow.com/users/798727",
"pm_score": 2,
"selected": false,
"text": "<p>I resolved this by adding an Active Directory user to the Application Pool>Identity instead of network services. This user is also in a group who has permission to browse internet through proxy server. Also add this user to the IIS_WPG group on the client host server.</p>\n\n<p>In the code below the first bit authenticate the client with the WCF service. The second bit suppose to pass the crendentials to internal proxy server so that the client call a WCF service on the DMZ server. But I don't think the proxy part is works. I am leaving the code anyway. </p>\n\n<pre><code> // username token credentials\n var clientCredentials = new ClientCredentials();\n clientCredentials.UserName.UserName = ConfigurationManager.AppSettings[\"Client.Mpgs.Username\"];\n clientCredentials.UserName.Password = ConfigurationManager.AppSettings[\"Client.Mpgs.Password\"];\n proxy.ChannelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials));\n proxy.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);\n\n // proxy credentials \n //http://kennyw.com/indigo/143\n //http://blogs.msdn.com/b/stcheng/archive/2008/12/03/wcf-how-to-supply-dedicated-credentials-for-webproxy-authentication.aspx\n proxy.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential\n (\n ConfigurationManager.AppSettings[\"Client.ProxyServer.Username\"]\n , ConfigurationManager.AppSettings[\"Client.ProxyServer.Password\"]\n , ConfigurationManager.AppSettings[\"Client.ProxyServer.DomainName\"]\n );\n</code></pre>\n\n<p>In my web.config I have used the following,</p>\n\n<pre><code><system.net>\n <defaultProxy useDefaultCredentials=\"true\">\n <proxy usesystemdefault=\"True\" proxyaddress=\"http://proxyServer:8080/\" bypassonlocal=\"False\" autoDetect=\"False\" /> </defaultProxy>\n</system.net>\n<system.serviceModel>\n <bindings>\n <wsHttpBinding>\n <binding name=\"WSHttpBinding_ITest\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:01:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"65536\" messageEncoding=\"Text\" textEncoding=\"utf-8\" useDefaultWebProxy=\"true\" allowCookies=\"false\">\n <readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\"/>\n <reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\"/>\n <security mode=\"TransportWithMessageCredential\">\n <transport clientCredentialType=\"None\" proxyCredentialType=\"None\" realm=\"\"/>\n <message clientCredentialType=\"UserName\" negotiateServiceCredential=\"true\" algorithmSuite=\"Default\"/>\n </security>\n </binding>\n </wsHttpBinding>\n </bindings>\n <client>\n <endpoint address=\"https://wcfservice.organisation.com/test/test.svc\" binding=\"wsHttpBinding\" bindingConfiguration=\"WSHttpBinding_ITest\" contract=\"Test.Test\" name=\"WSHttpBinding_ITest\"/>\n </client>\n</system.serviceModel>\n</code></pre>\n\n<p>The above code works from my local machine. When I upload the code to a dev server it does not work. I looked at the proxy server logs and it shows below,</p>\n\n<p>2011-06-14 05:21:10 2 11.11.11.11 - - authentication_failed DENIED \"Organisation/Finance\" - 407 TCP_DENIED CONNECT - tcp wcfservice.organisation.com 443 / - - - 11.11.11.11 612 161 -</p>\n\n<p>2011-06-14 05:21:10 6 11.11.11.152 ServerName$ - policy_denied DENIED \"Organisation/Finance\" - 403 TCP_DENIED CONNECT - tcp wcfservice.organisation.com 443 / - - - 11.11.11.205 185 361 -</p>\n\n<p>Our smart system administrator DF added a Active Directory user to the Application Pool>Identity instead of network services. This user is also in a group who has permission to browse internet through proxy server. Also add this user to the IIS_WPG group on the client host server.</p>\n\n<p>This worked for me.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19146/"
]
| I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy.
If I use the web service, then it is possible to set proxy. | I'm not entirely sure if this is what you are looking for but here you go.
```
MyClient client = new MyClient();
client.ClientCredentials.UserName.UserName = "u";
client.ClientCredentials.UserName.Password = "p";
``` |
105,504 | <p>When retrieving a lookup code value from a table, some folks do this...</p>
<pre><code>Dim dtLookupCode As New LookupCodeDataTable()
Dim taLookupCode AS New LookupCodeTableAdapter()
Dim strDescription As String
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
strDescription = dtLookupCode.Item(0).Meaning
</code></pre>
<p>...however, I've also seen things done "chained" like this...</p>
<pre><code>strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning
</code></pre>
<p>...which bypasses having a lookup code data table in the first place since the table adapter knows what the structure of its result set looks like.</p>
<p>Does using the "chained" method save the overhead of creating the data table object, or does it effectively get created anyway in order to properly handle the .Item(0).Meaning statement?</p>
| [
{
"answer_id": 105520,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 2,
"selected": false,
"text": "<p>Yeah, don't say \"inline\" because that means something specific in other languages. Most likely the performance difference is either zero or so small it doesn't matter, it's just a matter of preference. Do you want to write it out in separate statements to make it more clear, or write it all on one line to type it out quicker?</p>\n"
},
{
"answer_id": 105523,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 3,
"selected": false,
"text": "<p>Those two lines would compile down to the same thing. I would pick whichever one is easier for you read. Inlining normally refers to something <a href=\"http://en.wikipedia.org/wiki/Inline_function\" rel=\"nofollow noreferrer\">a bit different</a>.</p>\n"
},
{
"answer_id": 105527,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>The structure is still created, you just do not have a reference for it.</p>\n"
},
{
"answer_id": 105548,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 2,
"selected": false,
"text": "<p>Usually it just makes the code less readable.</p>\n\n<p>And often, when people use this \"inlining\" (i.e. chaining), they'll re-access a property or field of a class multiple times instead of getting it just once and storing in a local variable. This is generally a bad idea because one doesn't usually know how that field or property is returned. For example, it may be calculated each time, or it may be calculated once and stored privately in the class.</p>\n\n<p>Here are two illustrations. The first snippet is to be avoided:</p>\n\n<pre><code>if (ConfigurationManager.AppSettings(\"ConnectionString\") == null)\n{\n throw new MissingConfigSettingException(\"ConnectionString\");\n}\n\nstring connectionString = ConfigurationManager.AppSettings(\"ConnectionString\");\n</code></pre>\n\n<p>The second is preferable:</p>\n\n<pre><code>string connectionString = ConfigurationManager.AppSettings(\"ConnectionString\")\n\nif (connectionString == null)\n{\n throw new MissingConfigSettingException(\"ConnectionString\");\n}\n</code></pre>\n\n<p>The problem here is that AppSettings() actually has to unbox the AppSettings collection everytime a value is retrieved:</p>\n\n<pre><code>// Disassembled AppSettings member of ConfigurationManager \n\npublic static NameValueCollection AppSettings\n{\n get\n {\n object section = GetSection(\"appSettings\");\n\n if ((section == null) || !(section is NameValueCollection))\n {\n throw new\n ConfigurationErrorsException(SR.GetString(\"Config_appsettings_declaration_invalid\"));\n }\n\n return (NameValueCollection) section;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 105553,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>Debugging the latter is going to be harder if you want to see the intermediate state, and single step through the stages.</p>\n\n<p>I would go for readability over the amount of screen real estate used here since performance is a wash.</p>\n"
},
{
"answer_id": 105573,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 3,
"selected": true,
"text": "<p>Straying from the \"inline\" part of this, actually, the two sets of code won't compile out to the same thing. The issue comes in with: </p>\n\n<pre><code>Dim dtLookupCode As New LookupCodeDataTable()\nDim taLookupCode AS New LookupCodeTableAdapter()\n</code></pre>\n\n<p>In VB, this will create new objects with the appropriately-named references. Followed by:</p>\n\n<pre><code>dtLookupCode = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\n</code></pre>\n\n<p>We immediately replace the original <code>dtLookupCode</code> reference with a new object, which creates garbage to be collected (an unreachable object in RAM).</p>\n\n<p>In the exact, original scenario, therefore, what's referred to as the \"inline\" technique is, <em>technically</em>, more performant. (However, you're unlikely to physically see that difference in this small an example.)</p>\n\n<p>The place where the code would essentially be the same is if the original sample read as follows:</p>\n\n<pre><code>Dim taLookupCode AS New LookupCodeTableAdapter\nDim dtLookupCode As LookupCodeDataTable\nDim strDescription As String\n\ndtLookupCode = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\nstrDescription = dtLookupCode.Item(0).Meaning\n</code></pre>\n\n<p>In this world, we only have the existing references, and are not creating junk objects. I reordered the statements slightly for readability, but the gist is the same. Also, you could easily single-line-initialize the references with something like this, and have the same basic idea:</p>\n\n<pre><code>Dim taLookupCode AS New LookupCodeTableAdapter\nDim dtLookupCode As LookupCodeDataTable = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\nDim strDescription As String = dtLookupCode.Item(0).Meaning\n</code></pre>\n"
},
{
"answer_id": 105574,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>This:</p>\n\n<pre><code>dtLookupCode = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\")\nstrDescription = dtLookupCode.Item(0).Meaning\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>strDescription = taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\").Item(0).Meaning\n</code></pre>\n\n<p>are completely equivalent.</p>\n\n<p>In the first example, you've got an explicit temporary reference (dtLookupTable). In the second example, the temporary reference is implicit. Behind the scenes, the compiler will almost certainly create the same code for both of these. Even if it <em>didn't</em> emit the same code, the extra temporary reference is extremely cheap.</p>\n\n<p>However, I'm not sure if this line:</p>\n\n<pre><code>Dim dtLookupCode As New LookupCodeDataTable()\n</code></pre>\n\n<p>is efficient. It looks to me like this creates a new <code>LookupCodeDataTable</code> which is then discarded when you overwrite the variable in the later statement. I don't program in VB, but I would expect that this line should be:</p>\n\n<pre><code>Dim dtLookupCode As LookupCodeDataTable\n</code></pre>\n\n<p>The reference is cheap (probably free), but constructing an extra lookup table may not be.</p>\n"
},
{
"answer_id": 105643,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 1,
"selected": false,
"text": "<p>I call it chaining.</p>\n\n<p>You are asking the wrong question.</p>\n\n<p>What you need to ask is: Which is more readable?</p>\n\n<p>If chaining makes the code easier to read and understand than go ahead and do it.</p>\n\n<p>If however, it obfuscates, then don't.</p>\n\n<p>Any performance optimizations are non-existant. Don't optimize code, optimize algorithms.</p>\n\n<p>So, if you are going to be calling Item(1) and Item(2), then by chaining, You'll be creating the same object over and over again which is a bad algorithm.</p>\n\n<p>In that case, then the first option is better, as you don't need to recreate the adapter each time.</p>\n"
},
{
"answer_id": 105795,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 1,
"selected": false,
"text": "<p>One reason against 'chaining' is the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a> which would suggest that your code is fragile in the face of changes to LookupCodeDataTable.</p>\n\n<p>You should add a function like this:</p>\n\n<pre><code>function getMeaning( lookupCode as LookupCodeDataTable)\n getMeaning=lookupCode.Item(0).Meaning\nend function\n</code></pre>\n\n<p>and call it like this:</p>\n\n<pre><code>strDescription=getMeaning(taLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\"))\n</code></pre>\n\n<p>Now getMeaning() is available to be called in many other places and if LookupCodeDataTable changes, then you only have to change getMeaning() to fix it.</p>\n"
},
{
"answer_id": 105831,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": 0,
"selected": false,
"text": "<p>It's the same unless you need to refer to the returned objects by \ntaLookupCode.GetDataByCodeAndValue(\"EmpStatus\", \"FULL\") or Item(0)\nmultiple times. Otherwise, you don't know if the runtime for this function is log(n) or n, so for the best bet, I would assign a reference to it. </p>\n"
},
{
"answer_id": 1877058,
"author": "BryCoBat",
"author_id": 35182,
"author_profile": "https://Stackoverflow.com/users/35182",
"pm_score": 0,
"selected": false,
"text": "<p>Besides maintainability, here's another reason to avoid chaining: Error checking.</p>\n\n<p>Yes, you can wrap the whole thing in try/catch, and catch every exception that <em>any part of the chain</em> can throw.</p>\n\n<p>But if you want to validate results in between calls without try/catch, you have to split things apart. For instance:</p>\n\n<ul>\n<li>What happens when GetDataByCodeAndValue returns null? </li>\n<li>What if it returns an empty list?</li>\n</ul>\n\n<p>You can't check for these values without try/catch if you're chaining.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
]
| When retrieving a lookup code value from a table, some folks do this...
```
Dim dtLookupCode As New LookupCodeDataTable()
Dim taLookupCode AS New LookupCodeTableAdapter()
Dim strDescription As String
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
strDescription = dtLookupCode.Item(0).Meaning
```
...however, I've also seen things done "chained" like this...
```
strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning
```
...which bypasses having a lookup code data table in the first place since the table adapter knows what the structure of its result set looks like.
Does using the "chained" method save the overhead of creating the data table object, or does it effectively get created anyway in order to properly handle the .Item(0).Meaning statement? | Straying from the "inline" part of this, actually, the two sets of code won't compile out to the same thing. The issue comes in with:
```
Dim dtLookupCode As New LookupCodeDataTable()
Dim taLookupCode AS New LookupCodeTableAdapter()
```
In VB, this will create new objects with the appropriately-named references. Followed by:
```
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
```
We immediately replace the original `dtLookupCode` reference with a new object, which creates garbage to be collected (an unreachable object in RAM).
In the exact, original scenario, therefore, what's referred to as the "inline" technique is, *technically*, more performant. (However, you're unlikely to physically see that difference in this small an example.)
The place where the code would essentially be the same is if the original sample read as follows:
```
Dim taLookupCode AS New LookupCodeTableAdapter
Dim dtLookupCode As LookupCodeDataTable
Dim strDescription As String
dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
strDescription = dtLookupCode.Item(0).Meaning
```
In this world, we only have the existing references, and are not creating junk objects. I reordered the statements slightly for readability, but the gist is the same. Also, you could easily single-line-initialize the references with something like this, and have the same basic idea:
```
Dim taLookupCode AS New LookupCodeTableAdapter
Dim dtLookupCode As LookupCodeDataTable = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL")
Dim strDescription As String = dtLookupCode.Item(0).Meaning
``` |
105,522 | <p>OK, so things have progressed significantly with my DSL since I asked <a href="https://stackoverflow.com/questions/82776/how-do-i-reference-a-diagram-in-a-dsl-t4-template">this question</a> a few days ago.</p>
<p>As soon as I've refactored my code, I'll post my own answer to that one, but for now, I'm having another problem.</p>
<p>I'm dynamically generating sub-diagrams from a DSL-created model, saving those diagrams as images and then generating a Word document with those images embedded. So far, so good.</p>
<p> But where my shapes have compartments (for examples, Operations on a Service Contract - can you guess what it is, yet?), the compartment header is displayed but <b>none of the items</b>.</p>
<p>If I examine my shape object, it has a single nested child - an ElementListCompartment which in turn, has a number of items that I'm expecting to be displayed. The ElementListCompartment.IsExpanded property is set to true (and the compartment header has a little 'collapse' icon on it) but where, oh where, are my items?</p>
<p>The shape was added to the diagram using</p>
<pre><code>parentShape.FixupChildShapes(modelElement);
</code></pre>
<p>So, can anyone guide me on my merry way?</p>
| [
{
"answer_id": 149768,
"author": "Luis Filipe",
"author_id": 20335,
"author_profile": "https://Stackoverflow.com/users/20335",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe my answer is a little bit too late, but did you confirm using DSL Explorer that your compartments have items?</p>\n"
},
{
"answer_id": 1068424,
"author": "Eugene Burmako",
"author_id": 131615,
"author_profile": "https://Stackoverflow.com/users/131615",
"pm_score": 3,
"selected": true,
"text": "<p>I've recently faced a related problem, and managed to make it work, so here's the story.</p>\n\n<p>The task I was implementing was to load and display a domain model and an associated diagram generated by ActiveWriter's DSL package. </p>\n\n<p>Here's how I've implemented the required functionality (all the methods below belong to the Form1 class I've created to play around):</p>\n\n<pre><code>private Store LoadStore()\n{\n var store = new Store();\n store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));\n return store;\n}\n\nprivate void LoadDiagram(Store store)\n{\n using (var tx = store.TransactionManager.BeginTransaction(\"tx\", true))\n {\n var validator = new ValidationController();\n var deserializer = ActiveWriterSerializationHelper.Instance;\n deserializer.LoadModelAndDiagram(store,\n @\"..\\..\\ActiveWriter1.actiw\", @\"..\\..\\ActiveWriter1.actiw.diagram\", null, validator);\n tx.Commit();\n }\n}\n\nprivate DiagramView CreateDiagramView()\n{\n var store = LoadStore();\n LoadDiagram(store);\n\n using (var tx = store.TransactionManager.BeginTransaction(\"tx2\", true))\n {\n var dir = store.DefaultPartition.ElementDirectory;\n var diag = dir.FindElements<ActiveRecordMapping>().SingleOrDefault();\n var view = new DiagramView(){Diagram = diag};\n diag.Associate(view);\n tx.Commit();\n\n view.Dock = DockStyle.Fill;\n return view;\n }\n}\n\nprotected override void OnLoad(EventArgs e)\n{\n var view = CreateDiagramView();\n this.Controls.Add(view);\n}\n</code></pre>\n\n<p>This stuff worked mostly finely: it correctly loaded the diagram from files created with Visual Studio, drew the diagram within my custom windows form, supported scrolling the canvas and even allowed me to drag shapes here. However, one thing was bugging me - the compartments were empty and had default name, i.e. \"Compartment\".</p>\n\n<p>Google didn't help at all, so I had to dig in by myself. It wasn't very easy but with the help of Reflector and after spending a couple of hours I've managed to make this scenario work as expected!</p>\n\n<p>The problem was as follows. To my surprise DSL libraries do not correctly draw certain diagram elements immediately after they are added to the diagram. Sometimes, only stubs of certain shapes are drawn (as it's displayed in the first picture). Thus, sometimes we need to manually ask the library to redraw diagram shapes.</p>\n\n<p>This functionality can be implemented with so called \"rules\" that in fact are event handlers that get triggered by certain diagram events. Basically what we have to do is attach certain handler to an element-added event of the diagram and ensure shape initialization.</p>\n\n<p>Luckily we don't even have to write any code since DSL designer autogenerates both fixup rules and an utility method that attaches those rules to the diagram (see the EnableDiagramRules below). All we have to do is to call this method right after the store has been created (prior to loading model and diagram).</p>\n\n<pre><code>private Store LoadStore()\n{\n var store = new Store();\n store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));\n ActiveWriterDomainModel.EnableDiagramRules(store);\n return store;\n}\n\n/// <summary>\n/// Enables rules in this domain model related to diagram fixup for the given store.\n/// If diagram data will be loaded into the store, this method should be called first to ensure\n/// that the diagram behaves properly.\n/// </summary>\npublic static void EnableDiagramRules(DslModeling::Store store)\n{\n if(store == null) throw new global::System.ArgumentNullException(\"store\");\n\n DslModeling::RuleManager ruleManager = store.RuleManager;\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.FixUpDiagram));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.ConnectorRolePlayerChanged));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemAddRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemDeleteRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerChangeRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerPositionChangeRule));\n ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemChangeRule));\n}\n</code></pre>\n\n<p>The code above works as follows: </p>\n\n<ol>\n<li><p>Upon new element being added to the diagram (e.g. during deserialization of diagram) the rule \"FixUpDiagram\" gets triggered.</p></li>\n<li><p>The rule then calls <code>Diagram.FixUpDiagram(parentElement, childElement)</code>, where <code>childElement</code> stands for an element being added and <code>parentElement</code> stands for its logical parent (determined using tricky conditional logic, so I didn't try to reproduce it by myself). </p></li>\n<li><p>Down the stack trace FixUpDiagram method calls <code>EnsureCompartments</code> methods of all class shapes in the diagram. </p></li>\n<li><p>The EnsureCompartments method redraws class' compartments turning the stub \"[-] Compartment\" graphic into full-blown \"Properties\" shape as displayed in the picture linked above.</p></li>\n</ol>\n\n<p>P.S. Steve, I've noticed that you did call the fixup but it still didn't work. Well, I'm not a pro in DSL SDK (just started using it a couple of days ago), so cannot explain why you might have troubles. </p>\n\n<p>Maybe, you've called the fixup with wrong arguments. Or maybe Diagram.FixupDiagram(parent, newChild) does something differently from what parent.FixupChildShapes(newChild) does. However here's my variant that just works. Hope this also helps.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5806/"
]
| OK, so things have progressed significantly with my DSL since I asked [this question](https://stackoverflow.com/questions/82776/how-do-i-reference-a-diagram-in-a-dsl-t4-template) a few days ago.
As soon as I've refactored my code, I'll post my own answer to that one, but for now, I'm having another problem.
I'm dynamically generating sub-diagrams from a DSL-created model, saving those diagrams as images and then generating a Word document with those images embedded. So far, so good.
But where my shapes have compartments (for examples, Operations on a Service Contract - can you guess what it is, yet?), the compartment header is displayed but **none of the items**.
If I examine my shape object, it has a single nested child - an ElementListCompartment which in turn, has a number of items that I'm expecting to be displayed. The ElementListCompartment.IsExpanded property is set to true (and the compartment header has a little 'collapse' icon on it) but where, oh where, are my items?
The shape was added to the diagram using
```
parentShape.FixupChildShapes(modelElement);
```
So, can anyone guide me on my merry way? | I've recently faced a related problem, and managed to make it work, so here's the story.
The task I was implementing was to load and display a domain model and an associated diagram generated by ActiveWriter's DSL package.
Here's how I've implemented the required functionality (all the methods below belong to the Form1 class I've created to play around):
```
private Store LoadStore()
{
var store = new Store();
store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));
return store;
}
private void LoadDiagram(Store store)
{
using (var tx = store.TransactionManager.BeginTransaction("tx", true))
{
var validator = new ValidationController();
var deserializer = ActiveWriterSerializationHelper.Instance;
deserializer.LoadModelAndDiagram(store,
@"..\..\ActiveWriter1.actiw", @"..\..\ActiveWriter1.actiw.diagram", null, validator);
tx.Commit();
}
}
private DiagramView CreateDiagramView()
{
var store = LoadStore();
LoadDiagram(store);
using (var tx = store.TransactionManager.BeginTransaction("tx2", true))
{
var dir = store.DefaultPartition.ElementDirectory;
var diag = dir.FindElements<ActiveRecordMapping>().SingleOrDefault();
var view = new DiagramView(){Diagram = diag};
diag.Associate(view);
tx.Commit();
view.Dock = DockStyle.Fill;
return view;
}
}
protected override void OnLoad(EventArgs e)
{
var view = CreateDiagramView();
this.Controls.Add(view);
}
```
This stuff worked mostly finely: it correctly loaded the diagram from files created with Visual Studio, drew the diagram within my custom windows form, supported scrolling the canvas and even allowed me to drag shapes here. However, one thing was bugging me - the compartments were empty and had default name, i.e. "Compartment".
Google didn't help at all, so I had to dig in by myself. It wasn't very easy but with the help of Reflector and after spending a couple of hours I've managed to make this scenario work as expected!
The problem was as follows. To my surprise DSL libraries do not correctly draw certain diagram elements immediately after they are added to the diagram. Sometimes, only stubs of certain shapes are drawn (as it's displayed in the first picture). Thus, sometimes we need to manually ask the library to redraw diagram shapes.
This functionality can be implemented with so called "rules" that in fact are event handlers that get triggered by certain diagram events. Basically what we have to do is attach certain handler to an element-added event of the diagram and ensure shape initialization.
Luckily we don't even have to write any code since DSL designer autogenerates both fixup rules and an utility method that attaches those rules to the diagram (see the EnableDiagramRules below). All we have to do is to call this method right after the store has been created (prior to loading model and diagram).
```
private Store LoadStore()
{
var store = new Store();
store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel));
ActiveWriterDomainModel.EnableDiagramRules(store);
return store;
}
/// <summary>
/// Enables rules in this domain model related to diagram fixup for the given store.
/// If diagram data will be loaded into the store, this method should be called first to ensure
/// that the diagram behaves properly.
/// </summary>
public static void EnableDiagramRules(DslModeling::Store store)
{
if(store == null) throw new global::System.ArgumentNullException("store");
DslModeling::RuleManager ruleManager = store.RuleManager;
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.FixUpDiagram));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.ConnectorRolePlayerChanged));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemAddRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemDeleteRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerChangeRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerPositionChangeRule));
ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemChangeRule));
}
```
The code above works as follows:
1. Upon new element being added to the diagram (e.g. during deserialization of diagram) the rule "FixUpDiagram" gets triggered.
2. The rule then calls `Diagram.FixUpDiagram(parentElement, childElement)`, where `childElement` stands for an element being added and `parentElement` stands for its logical parent (determined using tricky conditional logic, so I didn't try to reproduce it by myself).
3. Down the stack trace FixUpDiagram method calls `EnsureCompartments` methods of all class shapes in the diagram.
4. The EnsureCompartments method redraws class' compartments turning the stub "[-] Compartment" graphic into full-blown "Properties" shape as displayed in the picture linked above.
P.S. Steve, I've noticed that you did call the fixup but it still didn't work. Well, I'm not a pro in DSL SDK (just started using it a couple of days ago), so cannot explain why you might have troubles.
Maybe, you've called the fixup with wrong arguments. Or maybe Diagram.FixupDiagram(parent, newChild) does something differently from what parent.FixupChildShapes(newChild) does. However here's my variant that just works. Hope this also helps. |
105,535 | <p>I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5</p>
| [
{
"answer_id": 105547,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://www.seandeasy.com/expanding-a-drive-within-a-vmware-image/\" rel=\"nofollow noreferrer\">This link</a> gives two approaches that should help.</p>\n\n<p>It looks like this is the most straightforward method:</p>\n\n<pre><code>vmware-vdiskmanager -x 12GB path\\to\\disk.vmdk\n</code></pre>\n\n<p>where 12GB is the desired size of the expanded volume.</p>\n"
},
{
"answer_id": 105561,
"author": "Martin C.",
"author_id": 19246,
"author_profile": "https://Stackoverflow.com/users/19246",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know about 6.0.5, but in former versions there used to be a program called vmware-vdiskmanager in VMWare's program directory. You can use this one to extend the virtual disk container.</p>\n\n<p>After you expanded the container, you need to expand the partitions in the guest, you have to do this from \"the inside\", which depends on the OS you are using on the guest and the filesystem. I often use an Ubuntu Life-CD or a System-Rescue-CD ISO together with qtparted to expand the partitions as needed.n</p>\n"
},
{
"answer_id": 105571,
"author": "Paul Mrozowski",
"author_id": 3656,
"author_profile": "https://Stackoverflow.com/users/3656",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming this is under Windows, there is a program usually in \"C:\\Program Files\\VMWare\\VMware Workstation\\\" called vmware-vdiskmanager.exe that you can use to do this. Open a DOS prompt and CD to that directory. The command to expand the drive is:</p>\n\n<pre><code>vmware-vdiskmanager.exe -x 50Gb NameOfDisk.vmdk\n</code></pre>\n\n<p>Also, this isn't the only thing you can do with this command. If you just type the command w/o any parameters you will see a bunch of the other available options. </p>\n"
},
{
"answer_id": 105663,
"author": "RichS",
"author_id": 6247,
"author_profile": "https://Stackoverflow.com/users/6247",
"pm_score": 0,
"selected": false,
"text": "<p>I've sometimes had problems when using the vmware-vdiskmanager application (it created the extra space, but I couldn't use it). At which point, I used the GParted live CD, which worked perfectly.</p>\n"
},
{
"answer_id": 7494908,
"author": "aznutzokna",
"author_id": 956174,
"author_profile": "https://Stackoverflow.com/users/956174",
"pm_score": 1,
"selected": false,
"text": "<p>Simplest way for me worked yesterday. My colleague advice me. </p>\n\n<ol>\n<li>Turn of your primary virtual machine, where your primary HDD is attached(if it is running).</li>\n<li>Expand your disk in primary virtual machine preferences.\n(Right click Settings, right click your primary hard disk, choose utilities, expand, ...)</li>\n<li>Attach your primary disk to another virtual machine. Boot another virtual machine.\nIf you go to disk manager, you can see, that your disk is bigger then partition, resize it.\nNow it will work, because you are on different other virtual machine and you your expanding disk is not the from which you booted the system, so you can resize the disk in disk manager(win GUI).</li>\n<li>Detach your primary disk from other virtual machine.</li>\n<li>Boot up your primary system, your primary partition is bigger.</li>\n</ol>\n\n<p>Trick is you can not change size of partition, from which Windows booted, so you must attach it to another system, resize it, and it is all.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
]
| I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5 | [This link](http://www.seandeasy.com/expanding-a-drive-within-a-vmware-image/) gives two approaches that should help.
It looks like this is the most straightforward method:
```
vmware-vdiskmanager -x 12GB path\to\disk.vmdk
```
where 12GB is the desired size of the expanded volume. |
105,551 | <p>This exception peppers our production catalina logs on a simple 'getParameter()' call.</p>
<pre>
WARNING: Parameters: Character decoding failed. Parameter skipped.
java.io.CharConversionException: EOF
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:82)
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48)
at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509)
at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266)
at org.apache.catalina.connector.Request.parseParameters(Request.java:2361)
at org.apache.catalina.connector.Request.getParameter(Request.java:1005)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
</pre>
<p>Or Sometimes:</p>
<pre>
java.io.CharConversionException: isHexDigit
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:87)
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48)
at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509)
at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266)
at org.apache.catalina.connector.Request.parseParameters(Request.java:2361)
at org.apache.catalina.connector.Request.getParameter(Request.java:1005)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
</pre>
| [
{
"answer_id": 105968,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 4,
"selected": true,
"text": "<p>Just hypothesizing here. Seems like the URL-decoding of parameters or their values fails (URL-encoding means encoding some characters using the %XX or %XXXX notation where XX or XXXX is the hexadecimal code of the character in ISO-8859-1 or Unicode). In the first case the error might be happening because there aren't enough hexadecimal characters after the % character. In the second case this might be happening because a character after the % character isn't hexadecimal.</p>\n"
},
{
"answer_id": 128256,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>Another thing to investigate is the URIEncoding in your <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/config/http.html\" rel=\"nofollow noreferrer\">Tomcat \"Connector\" configuration.</a> If the link is in a UTF-8 encoded page, it will encode the URL to bytes with UTF-8, then URL encode any of the bytes that need it. However, by default, Tomcat thinks that those bytes are ISO-8859-1, which can lead to problems. </p>\n\n<p>The inverse may also be true: if the page is ISO-8859-1, and Tomcat's URIEncoding has been set to UTF-8, a similar error could result.</p>\n\n<p>Here's a useful discussion about the issues in this area: <a href=\"http://weblogs.java.net/blog/joconner/archive/2005/07/charset_traps.html\" rel=\"nofollow noreferrer\">Charset Pitfalls in JSP/Servlet Containers</a></p>\n"
},
{
"answer_id": 738087,
"author": "Dan W",
"author_id": 89506,
"author_profile": "https://Stackoverflow.com/users/89506",
"pm_score": 1,
"selected": false,
"text": "<p>It could also be this (from Wikipedia):</p>\n\n<p>There exists a non-standard encoding for Unicode characters: %uxxxx, where xxxx is a Unicode value represented as four hexadecimal digits. This behavior is not specified by any RFC and has been rejected by the W3C. The third edition of ECMA-262 still includes an escape(string) function that uses this syntax, but also an encodeURI(uri) function that converts to UTF-8 and percent-encodes each octet.</p>\n\n<p>So you could be using the old escape function in Javascript, but since later versions of Tomcat are stricter about such things (5.5.17 let this encoding slide), only now are you beginning to see exceptions.</p>\n"
},
{
"answer_id": 3473629,
"author": "Peter",
"author_id": 6094,
"author_profile": "https://Stackoverflow.com/users/6094",
"pm_score": 2,
"selected": false,
"text": "<p>I started receiving this error when users were sending '%' over an ajax request. Turns out I wasn't escaping the parameters before making the request. A complete write up of this scenario and fix is covered in this <a href=\"http://ninadgawad.wordpress.com/2008/08/21/character-decoding-error-while-retriving-parameters-in-servlet/\" rel=\"nofollow noreferrer\">blog post</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
]
| This exception peppers our production catalina logs on a simple 'getParameter()' call.
```
WARNING: Parameters: Character decoding failed. Parameter skipped.
java.io.CharConversionException: EOF
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:82)
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48)
at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509)
at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266)
at org.apache.catalina.connector.Request.parseParameters(Request.java:2361)
at org.apache.catalina.connector.Request.getParameter(Request.java:1005)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
```
Or Sometimes:
```
java.io.CharConversionException: isHexDigit
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:87)
at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48)
at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393)
at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509)
at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266)
at org.apache.catalina.connector.Request.parseParameters(Request.java:2361)
at org.apache.catalina.connector.Request.getParameter(Request.java:1005)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
``` | Just hypothesizing here. Seems like the URL-decoding of parameters or their values fails (URL-encoding means encoding some characters using the %XX or %XXXX notation where XX or XXXX is the hexadecimal code of the character in ISO-8859-1 or Unicode). In the first case the error might be happening because there aren't enough hexadecimal characters after the % character. In the second case this might be happening because a character after the % character isn't hexadecimal. |
105,556 | <p>We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?</p>
| [
{
"answer_id": 105591,
"author": "Cyberherbalist",
"author_id": 16964,
"author_profile": "https://Stackoverflow.com/users/16964",
"pm_score": 2,
"selected": true,
"text": "<p>You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter.</p>\n\n<p>Here's what you will see (truncated):</p>\n\n<pre><code>I:\\>xsd\nMicrosoft (R) Xml Schemas/DataTypes support utility\n[Microsoft (R) .NET Framework, Version 1.0.3705.0]\nCopyright (C) Microsoft Corporation 1998-2001. All rights reserved.\n\n\nxsd.exe -\n Utility to generate schema or class files from given source.\n\nxsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:]\nxsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]\nxsd.exe <instance>.xml [/outputdir:]\nxsd.exe <schema>.xdr [/outputdir:]\n</code></pre>\n\n<p>Just follow the instructions.</p>\n"
},
{
"answer_id": 325715,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 1,
"selected": false,
"text": "<p>As XSD in ambiguous in terms of master-detail relations, I doubt an automatic generation is possible.</p>\n\n<p>For example, a declaration such as </p>\n\n<pre><code><xs:element name=\"foo\" type=\"footype\" minOccurs=\"0\" maxOccurs=\"unbounded\" /> \n</code></pre>\n\n<p>can be interpreted as child table \"foo\" (1:n) or as an n:m relation.</p>\n\n<p>minOccurs=\"0\" maxOccurs=\"1\" may be a nullable column, or an optional 1:1 relation.</p>\n\n<p>type=\"xs:string\" maxOccurs=\"1\" is a string ((n)varchar) column, or an optional lookup; but type=\"xs:string\" maxOccurs=\"unbounded\" is a detail table with a (n)varchar column.</p>\n"
},
{
"answer_id": 1851898,
"author": "NA.",
"author_id": 149374,
"author_profile": "https://Stackoverflow.com/users/149374",
"pm_score": 0,
"selected": false,
"text": "<p>There's a tool called <a href=\"http://shrex.sourceforge.net/\" rel=\"nofollow noreferrer\">ShreX</a> that can can makes schemas from xsd and inserts from XML. It tries to do this by itself (you can annotade the xsd to steer it). If you want to decide the structure yourself it might not be what you want.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
]
| We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents? | You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter.
Here's what you will see (truncated):
```
I:\>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 1.0.3705.0]
Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.
xsd.exe -
Utility to generate schema or class files from given source.
xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
```
Just follow the instructions. |
105,564 | <p>The original query looks like this (MySQL):</p>
<pre><code>SELECT *
FROM books
WHERE title LIKE "%text%" OR description LIKE "%text%"
ORDER BY date
</code></pre>
<p>Would it be possible to rewrite it (without unions or procedures), so that result will look like this:</p>
<ul>
<li>list of books where title matches query ordered by date, followed by:</li>
<li>list of books where description matches query ordered by date</li>
</ul>
<p>So basically just give a higher priority to matching titles over descriptions.</p>
| [
{
"answer_id": 105580,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": -1,
"selected": false,
"text": "<p>The union command will help you. Something along these lines:</p>\n\n<pre><code>SELECT *, 1 as order from books where title like '%text%'\nunion\nSELECT *, 2 as order from books where description like '%text%'\nORDER BY order, date\n</code></pre>\n"
},
{
"answer_id": 105588,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 5,
"selected": true,
"text": "<p>In sql server I would do the following:</p>\n\n<pre><code>select * from books \nwhere title like '%text%' or description like '%text%'\norder by case when title like '%text%' then 1 else 2 end, date\n</code></pre>\n\n<p>I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well.</p>\n"
},
{
"answer_id": 105589,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select * from books \nwhere title like \"%text%\" or description like \"%text%\" \norder by date, case when title like \"%text%\" then 0 else 1 end\n</code></pre>\n"
},
{
"answer_id": 105606,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>rjk's suggestion is the right way to go. Bear in mind, though, that this query (with or without a union) can't use indexes, so it's not going to scale well. You might want to check out MySQL's fulltext indexing, which will scale better, allow more sophisticated queries, and even help with result ranking.</p>\n"
},
{
"answer_id": 105622,
"author": "K Richard",
"author_id": 16771,
"author_profile": "https://Stackoverflow.com/users/16771",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a case to sort by:</p>\n\n<pre><code>order by case when title like '%text%' then 0 else 1 end\n</code></pre>\n"
},
{
"answer_id": 105629,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>How about something like this...</p>\n\n<pre><code>select * \nfrom books \nwhere title like \"%text%\" \nor description like \"%text%\" \norder by case when title like \"%text%\" then 1 else 0 end desc, date\n</code></pre>\n"
},
{
"answer_id": 108825,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 0,
"selected": false,
"text": "<pre><code>DECLARE @Books TABLE\n(\n [ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n [Title] NVARCHAR(MAX) NOT NULL,\n [Description] NVARCHAR(MAX) NOT NULL,\n [Date] DATETIME NOT NULL\n)\n\nINSERT INTO @Books\nSELECT 'War and Peace','A Russian Epic','2008-01-01' UNION\nSELECT 'Dogs of War','Mercenary Stories','2006-01-01' UNION\nSELECT 'World At Arms','A Story of World War Two','2007-01-01' UNION\nSELECT 'The B Team','Street Wars','2005-01-01' \n\nSELECT * FROM\n(\n SELECT *, CASE WHEN [Title] LIKE '%war%' THEN 1 WHEN [Description] LIKE '%war%' THEN 2 END AS Ord\n FROM @Books\n WHERE [Title] LIKE '%war%' OR [Description] LIKE '%war%'\n) AS Derived\nORDER BY Ord ASC, [Date] ASC\n</code></pre>\n\n<p>I believe this gives you what you want, but due to the extra workload in the derived CASE statment, it may not have good performance.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
]
| The original query looks like this (MySQL):
```
SELECT *
FROM books
WHERE title LIKE "%text%" OR description LIKE "%text%"
ORDER BY date
```
Would it be possible to rewrite it (without unions or procedures), so that result will look like this:
* list of books where title matches query ordered by date, followed by:
* list of books where description matches query ordered by date
So basically just give a higher priority to matching titles over descriptions. | In sql server I would do the following:
```
select * from books
where title like '%text%' or description like '%text%'
order by case when title like '%text%' then 1 else 2 end, date
```
I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well. |
105,602 | <p>I have inherited a monster.</p>
<p>It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.</p>
<p>To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.</p>
<p>This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.</p>
<p>My question is, what methods would you suggest to refactor or restructure such a thing?</p>
<p>I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.</p>
<p>Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.</p>
<p>Thanks for any and all ideas.</p>
| [
{
"answer_id": 105618,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 2,
"selected": false,
"text": "<p>A <a href=\"http://en.wikipedia.org/wiki/Finite_state_machine\" rel=\"nofollow noreferrer\">state machine</a> seems like the logical place to start, and using WF if you can swing it (sounds like you can't).</p>\n\n<p>You can still implement one without WF, you just have to do it yourself. However, thinking of it like a state machine from the start will probably give you a better implementation then creating a procedural monster that checks internal state on every action.</p>\n\n<p>Diagram out your states, what causes a transition. The actual code to process a record should be factored out, and called when the state executes (if that particular state requires it).</p>\n\n<p>So State1's execute calls your \"read a record\", then based on that record transitions to another state.</p>\n\n<p>The next state may read multiple records and call record processing instructions, then transition back to State1.</p>\n"
},
{
"answer_id": 105634,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 1,
"selected": false,
"text": "<p>Judging by the description, a state machine might be the best way to deal with it. Have an enum variable to store the current state, and implement the processing as a loop over the records, with a switch or if statements to select the action to take based on the current state and the input data. You can also easily dispatch the work to separate functions based on the state using function pointers, too, if it's getting too bulky.</p>\n"
},
{
"answer_id": 105641,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.codinghorror.com/blog/archives/000486.html\" rel=\"nofollow noreferrer\">There was a pretty good blog post about it at Coding Horror</a>. I've only come across this anti-pattern once, and I pretty much just followed his steps.</p>\n"
},
{
"answer_id": 105699,
"author": "SteveDonie",
"author_id": 11051,
"author_profile": "https://Stackoverflow.com/users/11051",
"pm_score": 2,
"selected": false,
"text": "<p>One thing I do in these cases is to use the 'Composed Method' pattern. See <a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2006/12/03/Composed-Method-Pattern.aspx\" rel=\"nofollow noreferrer\">Jeremy Miller's Blog Post</a> on this subject. The basic idea is to use the refactoring tools in your IDE to extract small meaningful methods. Once you've done that, you may be able to further refactor and extract meaningful classes. </p>\n"
},
{
"answer_id": 105840,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes I combine the state pattern with a stack. </p>\n\n<p>It works well for hierarchical structures; a parent element knows what state to push onto the stack to handle a child element, but a child doesn't have to know anything about its parent. In other words, the child doesn't know what the next state is, it simply signals that it is \"complete\" and gets popped off the stack. This helps to decouple the states from each other by keeping dependencies uni-directional.</p>\n\n<p>It works great for processing XML with a SAX parser (the content handler just pushes and pops states to change its behavior as elements are entered and exited). EDI should lend itself to this approach too.</p>\n"
},
{
"answer_id": 106482,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 4,
"selected": false,
"text": "<p>I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.</p>\n\n<p>There is no one thing that will get you out of this. The <a href=\"http://en.wikipedia.org/wiki/Finite_state_machine\" rel=\"noreferrer\">state machine</a> might be the final form your code takes, but thats <em>not</em> going to help you get there, nor should you decide on such a solution before untangling the mess you already have.</p>\n\n<p>First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test. </p>\n\n<p>Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.</p>\n\n<p>Now Refactor!</p>\n\n<p>A couple things I did that i found useful:</p>\n\n<p><strong>Invert <code>if</code> statements</strong> </p>\n\n<p>A huge problem I had was just reading the code when I couldn't find the corresponding <code>else</code> statement, I noticed that a lot of the blocks looked like this</p>\n\n<pre><code>if (someCondition)\n{\n 100+ lines of code\n {\n ...\n }\n}\nelse\n{\n simple statement here\n}\n</code></pre>\n\n<p>By inverting the <code>if</code> I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.</p>\n\n<p><strong>Extract Method</strong></p>\n\n<p>I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.</p>\n\n<p>Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood <em>procedural</em> code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).</p>\n\n<p>Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0321213351\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Refactoring to Patterns</a> is a great book to assist in explainging patterns that are helpful in these situations.</p>\n\n<p>You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.</p>\n"
},
{
"answer_id": 106531,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>I would start with uninhibited use of Extract Method. If you don't have it in your current Visual Studio IDE, you can either get a 3rd-party addin, or load your project in a newer VS. (It'll try to upgrade your project, but you will carefully ignore those changes instead of checking them in.)</p>\n\n<p>You said that you have code indented 15 levels. Start about 1/2-way out, and Extract Method. If you can come up with a good name, use it, but if you can't, extract anyway. Split in half again. You're not going for the ideal structure here; you're trying to break the code in to pieces that will fit in your brain. My brain is not very big, so I'd keep breaking & breaking until it doesn't hurt any more.</p>\n\n<p>As you go, look for any new long methods that seem to be different than the rest; make these in to new classes. Just use a simple class that has only one method for now. Heck, making the method static is fine. Not because you think they're good classes, but because you are so desperate for some organization.</p>\n\n<p>Check in often as you go, so you can checkpoint your work, understand the history later, be ready to do some \"real work\" without needing to merge, and save your teammates the hassle of hard merging.</p>\n\n<p>Eventually you'll need to go back and make sure the method names are good, that the set of methods you've created make sense, clean up the new classes, etc.</p>\n\n<p>If you have a highly reliable Extract Method tool, you can get away without good automated tests. (I'd trust VS in this, for example.) Otherwise, make sure you're not breaking things, or you'll end up worse than you started: with a program that doesn't work at all.</p>\n\n<p>A pairing partner would be helpful here.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19304/"
]
| I have inherited a monster.
It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.
To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.
This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.
My question is, what methods would you suggest to refactor or restructure such a thing?
I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.
Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.
Thanks for any and all ideas. | I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.
There is no one thing that will get you out of this. The [state machine](http://en.wikipedia.org/wiki/Finite_state_machine) might be the final form your code takes, but thats *not* going to help you get there, nor should you decide on such a solution before untangling the mess you already have.
First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test.
Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.
Now Refactor!
A couple things I did that i found useful:
**Invert `if` statements**
A huge problem I had was just reading the code when I couldn't find the corresponding `else` statement, I noticed that a lot of the blocks looked like this
```
if (someCondition)
{
100+ lines of code
{
...
}
}
else
{
simple statement here
}
```
By inverting the `if` I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.
**Extract Method**
I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.
Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood *procedural* code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).
Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.
[Refactoring to Patterns](https://rads.stackoverflow.com/amzn/click/com/0321213351) is a great book to assist in explainging patterns that are helpful in these situations.
You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck. |
105,604 | <p>I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible.</p>
| [
{
"answer_id": 105919,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>Change the user that mediawiki connects as in LocalSettings.php and then using phpMyAdmin, you can edit the privileges of that user (that is, if you aren't comfortable granting and revoking privileges from the mysql console).</p>\n\n<p><a href=\"http://www.phpmyadmin.net/home_page/index.php\" rel=\"nofollow noreferrer\">http://www.phpmyadmin.net/home_page/index.php</a></p>\n"
},
{
"answer_id": 105952,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 3,
"selected": true,
"text": "<p>After the installation, MediaWiki doesn't need to create any more tables. I'd suggest giving the user insert, select, and lock permission.</p>\n\n<pre><code>grant select,lock tables,insert on media_wiki_db.* to 'wiki'@'localhost' identified by 'password';\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12048/"
]
| I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible. | After the installation, MediaWiki doesn't need to create any more tables. I'd suggest giving the user insert, select, and lock permission.
```
grant select,lock tables,insert on media_wiki_db.* to 'wiki'@'localhost' identified by 'password';
``` |
105,609 | <p>I have an enum that looks as follows:</p>
<pre><code>public enum TransactionStatus { Open = 'O', Closed = 'C'};
</code></pre>
<p>and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.</p>
<p>now because the data comes out of the database as an object I am having a heck of a time writing comparison code.</p>
<p>The best I can do is to write:</p>
<pre><code>protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
return ((char)enum_status).ToString() == obj_status.ToString();
}
</code></pre>
<p>However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. <a href="http://blogs.msdn.com/abhinaba/archive/2006/01/14/enumerting-all-values-of-an-enum.aspx" rel="nofollow noreferrer">Supposedly all enums inherit from System.Enum</a> but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.</p>
<p>I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?</p>
| [
{
"answer_id": 105638,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": -1,
"selected": false,
"text": "<p>I would take a look at Enum.Parse. It will let you parse your char back into the proper enum. I believe it works all the way back to C# 1.0. Your code would look a bit like this:</p>\n\n<pre><code>TransactionStatus status = (TransactionStatus)Enum.Parse(typeof(TransactionStatus), obj.ToString());\n</code></pre>\n"
},
{
"answer_id": 105697,
"author": "Chris",
"author_id": 19290,
"author_profile": "https://Stackoverflow.com/users/19290",
"pm_score": 0,
"selected": false,
"text": "<p>Enums are generally messy in C# so when using .NET 2.0 its common to wrap the syntax with generics to avoid having to write such clumsy code.</p>\n\n<p>In .NET 1.1 you can do something like the below, although it's not much tidier than the original snippet:</p>\n\n<pre><code>protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status)\n{\n return (enum_status == Enum.Parse(typeof(TransactionStatus), obj_status.ToString()));\n}\n</code></pre>\n\n<p>This is about the same amount of code but you are now doing enum rather than string comparison.</p>\n\n<p>You could also use the debugger/documentation to see if <code>obj_status</code> really is an object or whether you can safely cast it to a string.</p>\n"
},
{
"answer_id": 105797,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": -1,
"selected": false,
"text": "<p>If you just have to compare values you can use something like:</p>\n\n<pre><code>protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {\n return (char)enum_status == (char)obj_status;\n}\n</code></pre>\n"
},
{
"answer_id": 105963,
"author": "Paul Batum",
"author_id": 48281,
"author_profile": "https://Stackoverflow.com/users/48281",
"pm_score": 3,
"selected": true,
"text": "<pre><code>static void Main(string[] args)\n{\n object val = 'O';\n Console.WriteLine(EnumEqual(TransactionStatus.Open, val));\n\n val = 'R';\n Console.WriteLine(EnumEqual(DirectionStatus.Left, val));\n\n Console.ReadLine();\n}\n\npublic static bool EnumEqual(Enum e, object boxedValue)\n{ \n return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));\n}\n\npublic enum TransactionStatus { Open = 'O', Closed = 'C' };\npublic enum DirectionStatus { Left = 'L', Right = 'R' };\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| I have an enum that looks as follows:
```
public enum TransactionStatus { Open = 'O', Closed = 'C'};
```
and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.
now because the data comes out of the database as an object I am having a heck of a time writing comparison code.
The best I can do is to write:
```
protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
return ((char)enum_status).ToString() == obj_status.ToString();
}
```
However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. [Supposedly all enums inherit from System.Enum](http://blogs.msdn.com/abhinaba/archive/2006/01/14/enumerting-all-values-of-an-enum.aspx) but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.
I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing? | ```
static void Main(string[] args)
{
object val = 'O';
Console.WriteLine(EnumEqual(TransactionStatus.Open, val));
val = 'R';
Console.WriteLine(EnumEqual(DirectionStatus.Left, val));
Console.ReadLine();
}
public static bool EnumEqual(Enum e, object boxedValue)
{
return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));
}
public enum TransactionStatus { Open = 'O', Closed = 'C' };
public enum DirectionStatus { Left = 'L', Right = 'R' };
``` |
105,613 | <p>Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the <code>lizard</code> and <code>pig</code> elements from this example:</p>
<pre><code><pets>
<cat>
<foo>don't care about this</foo>
</cat>
<dog>
<foo>not this one either</foo>
</dog>
<lizard>
<bar>lizard should be returned, because it has a child of bar</bar>
</lizard>
<pig>
<bar>return pig, too</bar>
</pig>
</pets>
</code></pre>
<p>This Xpath gives me all pets: <code>"/pets/*"</code>, but I only want the pets that have a child node of name <code>'bar'</code>.</p>
| [
{
"answer_id": 105628,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 7,
"selected": true,
"text": "<p>Here it is, in all its glory</p>\n\n<pre><code>/pets/*[bar]\n</code></pre>\n\n<p>English: Give me all children of <code>pets</code> that have a child <code>bar</code></p>\n"
},
{
"answer_id": 433246,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>/pets/child::*[child::bar]\n</code></pre>\n\n<p>My pardon, I did not see the comments to the previous reply.</p>\n\n<p>But in this case I'd rather prefer using the <code>descendant::</code> axis, which includes all elements down from specified:</p>\n\n<pre><code>/pets[descendant::bar]\n</code></pre>\n"
},
{
"answer_id": 25768548,
"author": "Hirnhamster",
"author_id": 413531,
"author_profile": "https://Stackoverflow.com/users/413531",
"pm_score": 3,
"selected": false,
"text": "<p>Just in case you wanted to be more specific about the children - you can also use selectors on them.</p>\n\n<p>Example:</p>\n\n<pre><code><pets>\n <cat>\n <foo>don't care about this</foo>\n </cat>\n <dog>\n <foo>not this one either</foo>\n </dog>\n <lizard>\n <bar att=\"baz\">lizard should be returned, because it has a child of bar</bar>\n </lizard>\n <pig>\n <bar>don't return pig - it has no att=bar </bar>\n </pig>\n</pets>\n</code></pre>\n\n<p>Now, you only care about all <code>pets</code> having any child <code>bar</code> <strong>that has an attribute <code>att</code> with value <code>baz</code></strong>. You can use the following xpath expression:</p>\n\n<pre><code>//pets/*[descendant::bar[@att='baz']]\n</code></pre>\n\n<p>Result</p>\n\n<pre><code><lizard>\n <bar att=\"baz\">lizard should be returned, because it has a child of bar</bar>\n</lizard>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10876/"
]
| Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the `lizard` and `pig` elements from this example:
```
<pets>
<cat>
<foo>don't care about this</foo>
</cat>
<dog>
<foo>not this one either</foo>
</dog>
<lizard>
<bar>lizard should be returned, because it has a child of bar</bar>
</lizard>
<pig>
<bar>return pig, too</bar>
</pig>
</pets>
```
This Xpath gives me all pets: `"/pets/*"`, but I only want the pets that have a child node of name `'bar'`. | Here it is, in all its glory
```
/pets/*[bar]
```
English: Give me all children of `pets` that have a child `bar` |
105,642 | <p><strong>Update</strong>: Looks like the query does not throw any timeout. The connection is timing out.</p>
<p>This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.</p>
<p>I <strong>cannot</strong> use any of these techniques:
1) Increase timeout.
2) Run it asynchronously with a callback. This needs to run in a synchronous manner.</p>
<p>please suggest any other techinques to keep the connection alive while executing a time consuming query?</p>
<pre><code>private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
</code></pre>
| [
{
"answer_id": 105655,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 0,
"selected": false,
"text": "<pre><code>command.CommandTimeout *= 2;\n</code></pre>\n\n<p>That will double the default time-out, which is 30 seconds.</p>\n\n<p>Or, put the value for CommandTimeout in a configuration file, so you can adjust it as needed without recompiling.</p>\n"
},
{
"answer_id": 105667,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 0,
"selected": false,
"text": "<p>If you absolutely cannot increase the timeout, your only option is to reduce the time of the query to execute within the default 30 second timeout.</p>\n"
},
{
"answer_id": 105727,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 0,
"selected": false,
"text": "<p>You should break your query up into multiple chunks that each execute within the timeout period.</p>\n"
},
{
"answer_id": 105785,
"author": "Sam Erwin",
"author_id": 18224,
"author_profile": "https://Stackoverflow.com/users/18224",
"pm_score": 1,
"selected": false,
"text": "<p>I have to agree with Terrapin.</p>\n\n<p>You have a few options on how to get your time down. First, if your company employs DBAs, I'd recommend asking them for suggestions.</p>\n\n<p>If that's not an option, or if you want to try some other things first here are your three major options:</p>\n\n<ol>\n<li>Break up the query into components that run under the timeout. This is probably the easiest.</li>\n<li>Change the query to optimize the access path through the database (generally: hitting an index as closely as you can)</li>\n<li>Change or add indices to affect your query's access path.</li>\n</ol>\n"
},
{
"answer_id": 105817,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 2,
"selected": false,
"text": "<p>You should first check your query to see if it's optimized and it isn't somehow running on missing indexes. <strong>30 seconds is allot for most queries</strong>, even on large databases if they are properly tuned. If you have solid proof using the query plan that the query can't be executed any faster than that, then you should increase the timeout, there's no other way to keep the connection, that's the purpose of the timeout to terminate the connection if the query doesn't complete in that time frame.</p>\n"
},
{
"answer_id": 105824,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>If you are constrained from using the default process of changing the timeout value you will most likely have to do a lot more work. The following options come to mind</p>\n\n<ol>\n<li>Validate with your DBA's and another code review that you have truly optimized the query as best as possible</li>\n<li>Work on the underlying DB structure to see if there is any gain you can get on the DB side, creating/modifying an idex(es).</li>\n<li>Divide it into multiple parts, even if this means running procedures with multiple return parameters that simply call another param. (This option is not elegant, and honestly if your code REALLY is going to take this much time I would be going to management and re-discussing the 30 second timeout)</li>\n</ol>\n"
},
{
"answer_id": 106116,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 1,
"selected": false,
"text": "<p>We recently had a similar issue on a SQL Server 2000 database.</p>\n\n<p>During your query, run this query on your master database on the db server and see if there are any locks you should troubleshoot:</p>\n\n<pre><code>select \n spid,\n db_name(sp.dbid) as DBname,\n blocked as BlockedBy,\n waittime as WaitInMs,\n lastwaittype,\n waitresource,\n cpu,\n physical_io,\n memusage,\n loginame,\n login_time,\n last_batch,\n hostname,\n sql_handle\nfrom sysprocesses sp\nwhere (waittype > 0 and spid > 49) or spid in (select blocked from sysprocesses where blocked > 0)\n</code></pre>\n\n<p>SQL Server Management Studio 2008 also contains a very cool activity monitor which lets you see the health of your database during your query.</p>\n\n<p>In our case, it was a networkio lock which kept the database busy. It was some legacy VB code which didn't disconnect its result set quick enough.</p>\n"
},
{
"answer_id": 106123,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to dislike increasing the connection/command timeout since in my mind that would be a matter of taking care of the symptom, not the problem</p>\n"
},
{
"answer_id": 106156,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 5,
"selected": true,
"text": "<p>Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback)\nbut the application will wait (inside a while loop) until the query is complete. From <a href=\"http://msdn.microsoft.com/en-us/library/ca56w9se(VS.80).aspx\" rel=\"noreferrer\">MSDN</a>. This should solve the timeout problem. Please try it out.</p>\n\n<p>But, I agree with others that you should think more about optimizing the query to perform under 30 seconds.</p>\n\n<pre><code> IAsyncResult result = command.BeginExecuteNonQuery();\n\n int count = 0;\n while (!result.IsCompleted)\n {\n Console.WriteLine(\"Waiting ({0})\", count++);\n System.Threading.Thread.Sleep(1000);\n }\n Console.WriteLine(\"Command complete. Affected {0} rows.\",\n command.EndExecuteNonQuery(result));\n</code></pre>\n"
},
{
"answer_id": 827824,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 1,
"selected": false,
"text": "<p>If you are prohibited from using the features of the data access API to allow a query to last more than 30 seconds, then we need to see the SQL. </p>\n\n<p>The performance gains to be made by optimizing the use of ADO.NET are slight in comparison to the gains of optimizing the SQL.</p>\n\n<p>And you already are using the most efficient method of executing SQL. Other techniques would be mind numbingly slower (although, if you did a quick retrieval of your rows and some really slow client side processing using DataSets, you might be able to get the initial retrieval down to less than 30 seconds, but I doubt it.)</p>\n\n<p>If we knew if you were doing inserts, then maybe you should be using bulk insert. But we don't know the content of your sql. </p>\n"
},
{
"answer_id": 831332,
"author": "Vikram Sudhini",
"author_id": 90831,
"author_profile": "https://Stackoverflow.com/users/90831",
"pm_score": 0,
"selected": false,
"text": "<p>just set sqlcommand's CommandTimeout property to 0, this will cause the command to wait until the query finishes...\n eg:</p>\n\n<pre><code>SqlCommand cmd = new SqlCommand(spName,conn);\ncmd.CommandType = CommandType.StoredProcedure;\ncmd.CommandTimeout = 0;\n</code></pre>\n"
},
{
"answer_id": 843398,
"author": "Chad Grant",
"author_id": 1385845,
"author_profile": "https://Stackoverflow.com/users/1385845",
"pm_score": 1,
"selected": false,
"text": "<p>This is an UGLY hack, but might help solve your problem temporarily until you can fix the real problem</p>\n\n<pre><code> private static void CreateCommand(string queryString,string connectionString)\n {\n int maxRetries = 3;\n int retries = 0;\n while(true)\n {\n try\n {\n using (SqlConnection connection = new SqlConnection(connectionString))\n {\n SqlCommand command = new SqlCommand(queryString, connection);\n command.Connection.Open();\n command.ExecuteNonQuery();\n }\n break;\n }\n catch (SqlException se)\n {\n if (se.Message.IndexOf(\"Timeout\", StringComparison.InvariantCultureIgnoreCase) == -1)\n throw; //not a timeout\n\n if (retries >= maxRetries)\n throw new Exception( String.Format(\"Timedout {0} Times\", retries),se);\n\n //or break to throw no error\n\n retries++;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 850816,
"author": "andy",
"author_id": 62653,
"author_profile": "https://Stackoverflow.com/users/62653",
"pm_score": 0,
"selected": false,
"text": "<p>have you thought about breaking the query down into several smaller chunks?</p>\n\n<p>Also, have you ran your query against the Database Engine Tuning Advisor in:</p>\n\n<p>Management Studio > Tools > Database Engine Tuning Advisor</p>\n\n<p>Lastly, could we get a look at the query itself?</p>\n\n<p>cheers</p>\n"
},
{
"answer_id": 851412,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried wrapping your sql inside a stored procedure, they seem to have better memory management. Have seen timeouts like this before in plan sql statement with internal queries using classic ADO. i.e. select * from (select ....) t inner join somthingTable. Where the internal query was returning a very large number of results. </p>\n\n<p>Other tips\n1. Performing reads with the with(nolock) execution hint, it's dirty and I don't recommend it but it will tend to be faster. \n2. Also look at the execution plan of the sql your trying to run and reduce the row scanning, the order in which you join tables. \n3. look at adding some indexes to your tables for faster reads.\n4. I've also found that deleting rows is very expensive, you could try and limit the number of rows per call.\n5. Swap @table variables with #temporary tables has also worked for me in the past.\n6. You may also have saved bad execution plan (heard, never seen).</p>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 853391,
"author": "Frans Bouma",
"author_id": 44991,
"author_profile": "https://Stackoverflow.com/users/44991",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Update: Looks like the query does not\n throw any timeout. The connection is\n timing out.</p>\n</blockquote>\n\n<p>I.o.w., even if you don't execute a query, the connection times out? because there are two time-outs: connection and query. Everybody seems to focus on the query, but if you get connection timeouts, it's a network problem and has nothing to do with the query: the connection first has to be established before a query can be ran, obviously. </p>\n"
},
{
"answer_id": 1651420,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 0,
"selected": false,
"text": "<p>It might be worth trying paging the results back.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19306/"
]
| **Update**: Looks like the query does not throw any timeout. The connection is timing out.
This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.
I **cannot** use any of these techniques:
1) Increase timeout.
2) Run it asynchronously with a callback. This needs to run in a synchronous manner.
please suggest any other techinques to keep the connection alive while executing a time consuming query?
```
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
``` | Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback)
but the application will wait (inside a while loop) until the query is complete. From [MSDN](http://msdn.microsoft.com/en-us/library/ca56w9se(VS.80).aspx). This should solve the timeout problem. Please try it out.
But, I agree with others that you should think more about optimizing the query to perform under 30 seconds.
```
IAsyncResult result = command.BeginExecuteNonQuery();
int count = 0;
while (!result.IsCompleted)
{
Console.WriteLine("Waiting ({0})", count++);
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Command complete. Affected {0} rows.",
command.EndExecuteNonQuery(result));
``` |
105,645 | <p>Tackling a strange scenario here. </p>
<p>We use a proprietary workstation management application which uses mySQL to store its data. Within the application they provide number of reports, such as which user logged into which machine at what time, all the software products installed on the monitored machines, so on and so forth. We are looking to do a different set of reports, however, they do not support custom reports.</p>
<p>Since their data is being stored in mySQL, I gather I can do the reporting manually. I don't have valid credentials to connect to the mySQL server though. <b>Is there anyway for me to create a user account in the mySQL server?</b> I do not want to reset the root password or anything account that might be in there, as it might break the application.</p>
<hr>
<p>I have full access to the Windows 2003 server. I can stop and restart services, including the mySQL server. To the actual mySQL server, I only have basic access through the GUI provided by the software. I can't connect to it directly through CLI or through another tool (due to the lack of credentials). </p>
<hr>
<p>I apologize if it came off as if I'm trying to get unauthorized access to the mySQL server. I have contacted the software company, and as of today it's been two weeks without a response from them. I need to get to the data. I have full access to the physical box, I have admin privileges on it.</p>
| [
{
"answer_id": 105657,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have access to the MySQL server in question?</p>\n\n<p>As in, what access do you have beyond what a regular user would? You should try to go through those routes before you \"hack\" your way in there, since that may or may not be feasible with that software.</p>\n"
},
{
"answer_id": 105674,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 0,
"selected": false,
"text": "<p>I assume I really should not answer this one, but it's just too much fun.</p>\n\n<p>Look at <a href=\"http://en.wikipedia.org/wiki/Sql_injection\" rel=\"nofollow noreferrer\">This</a> page about SQL injections. That should cover your needs. \n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/adding-users.html\" rel=\"nofollow noreferrer\">This</a> page shows how to add user accounts to mySQL</p>\n\n<p>I would try entering the following in random user input fields:</p>\n\n<pre><code>p'; INSERT INTO user VALUES\n</code></pre>\n\n<p>('localhost','myNewAdmin',PASSWORD('some_pass'), \n'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'); </p>\n\n<p>and then</p>\n\n<pre><code>p'; FLUSH PRIVILEGES;\n</code></pre>\n\n<p>p'; is intended to close the regular question. e.g -\nNormal question is: </p>\n\n<pre><code>\"Select Adress from cusomers where custName = ' + $INPUT + ';\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code> Select Adress from cusomers where custName = 'p'; INSERT INTO user \nVALUES('localhost','myNewAdmin',PASSWORD('some_pass'), \n'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'); \n</code></pre>\n"
},
{
"answer_id": 105683,
"author": "Svet",
"author_id": 8934,
"author_profile": "https://Stackoverflow.com/users/8934",
"pm_score": 0,
"selected": false,
"text": "<p>One thing that comes in mind is sniffing the database communication and hope it's not encrypted. If it is encrypted try changing the configuration not to use SSL and restart mysql. A good sniffer that I use is <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a></p>\n\n<p>From <a href=\"http://dev.mysql.com/doc/refman/5.0/en/secure-connections.html\" rel=\"nofollow noreferrer\">mysql 5.0 documentation</a>:</p>\n\n<blockquote>\n <p>MySQL supports secure (encrypted)\n connections between MySQL clients and\n the server using the Secure Sockets\n Layer (SSL) protocol. This section\n discusses how to use SSL connections.\n It also describes a way to set up SSH\n on Windows. For information on how to\n require users to use SSL connections,\n see the discussion of the REQUIRE\n clause of the GRANT statement in\n Section 12.5.1.3, “GRANT Syntax”.</p>\n \n <p>The standard configuration of MySQL is\n intended to be as fast as possible, so\n encrypted connections are not used by\n default. Doing so would make the\n client/server protocol much slower.\n Encrypting data is a CPU-intensive\n operation that requires the computer\n to do additional work and can delay\n other MySQL tasks. For applications\n that require the security provided by\n encrypted connections, the extra\n computation is warranted.</p>\n \n <p>MySQL allows encryption to be enabled\n on a per-connection basis. You can\n choose a normal unencrypted connection\n or a secure encrypted SSL connection\n according the requirements of\n individual applications.</p>\n \n <p>Secure connections are based on the\n OpenSSL API and are available through\n the MySQL C API. Replication uses the\n C API, so secure connections can be\n used between master and slave servers.</p>\n</blockquote>\n\n<p>You've probably already done that but still - try searching through the applications config files. If there's nothing - try searching through the executables/source code - maybe it's in plaintext if you're lucky. </p>\n"
},
{
"answer_id": 105718,
"author": "corymathews",
"author_id": 1925,
"author_profile": "https://Stackoverflow.com/users/1925",
"pm_score": 0,
"selected": false,
"text": "<p>odds are there are triggers on the database side keeping a log so when you hack yourself into the database they will know when and how you did it. Not a good idea.</p>\n"
},
{
"answer_id": 105804,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>You'll want to use the MySQL password recovery process. Follow <a href=\"http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html#resetting-permissions-windows\" rel=\"nofollow noreferrer\">these instructions</a>, except replace the password reset query with a query to <a href=\"http://dev.mysql.com/doc/refman/5.0/en/adding-users.html\" rel=\"nofollow noreferrer\">add a new user</a>. The new user query would be something like:</p>\n\n<pre><code>GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'mypassword' WITH GRANT OPTION;\n</code></pre>\n\n<p>That will create a new user \"myuser\" with the password \"mypassword\", who may log in to MySQL through the local system's CLI. You can then use the MySQL Administrator GUI (<a href=\"http://dev.mysql.com/downloads/gui-tools/5.0.html\" rel=\"nofollow noreferrer\">download here</a>) and update user permissions so you can log in from other systems on the network. Or use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/grant.html\" rel=\"nofollow noreferrer\"><code>GRANT</code> statement</a> from the CLI, if that's more your style.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16522/"
]
| Tackling a strange scenario here.
We use a proprietary workstation management application which uses mySQL to store its data. Within the application they provide number of reports, such as which user logged into which machine at what time, all the software products installed on the monitored machines, so on and so forth. We are looking to do a different set of reports, however, they do not support custom reports.
Since their data is being stored in mySQL, I gather I can do the reporting manually. I don't have valid credentials to connect to the mySQL server though. **Is there anyway for me to create a user account in the mySQL server?** I do not want to reset the root password or anything account that might be in there, as it might break the application.
---
I have full access to the Windows 2003 server. I can stop and restart services, including the mySQL server. To the actual mySQL server, I only have basic access through the GUI provided by the software. I can't connect to it directly through CLI or through another tool (due to the lack of credentials).
---
I apologize if it came off as if I'm trying to get unauthorized access to the mySQL server. I have contacted the software company, and as of today it's been two weeks without a response from them. I need to get to the data. I have full access to the physical box, I have admin privileges on it. | You'll want to use the MySQL password recovery process. Follow [these instructions](http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html#resetting-permissions-windows), except replace the password reset query with a query to [add a new user](http://dev.mysql.com/doc/refman/5.0/en/adding-users.html). The new user query would be something like:
```
GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'mypassword' WITH GRANT OPTION;
```
That will create a new user "myuser" with the password "mypassword", who may log in to MySQL through the local system's CLI. You can then use the MySQL Administrator GUI ([download here](http://dev.mysql.com/downloads/gui-tools/5.0.html)) and update user permissions so you can log in from other systems on the network. Or use the [`GRANT` statement](http://dev.mysql.com/doc/refman/5.0/en/grant.html) from the CLI, if that's more your style. |
105,651 | <p>How can I print wstring in gdb?</p>
| [
{
"answer_id": 105900,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 1,
"selected": false,
"text": "<p>Suppose you've got a <code>std::wstring str</code>. The following should work in gdb:</p>\n\n<pre><code>call printf(\"%ls\", str._M_data())\n</code></pre>\n\n<p>(The -l option in printf makes it a long string, and I believe you need the \"<code>call</code>\" statement because the ordinary gdb printf doesn't like that option.)</p>\n"
},
{
"answer_id": 105904,
"author": "sanxiyn",
"author_id": 18382,
"author_profile": "https://Stackoverflow.com/users/18382",
"pm_score": 0,
"selected": false,
"text": "<p>I did some research, and this is gdb <a href=\"http://sourceware.org/cgi-bin/gnatsweb.pl?cmd=view&database=gdb&pr=716\" rel=\"nofollow noreferrer\">PR716</a>, <a href=\"http://sourceware.org/cgi-bin/gnatsweb.pl?cmd=view&database=gdb&pr=1998\" rel=\"nofollow noreferrer\">PR1998</a>, <a href=\"http://sourceware.org/cgi-bin/gnatsweb.pl?cmd=view&database=gdb&pr=2264\" rel=\"nofollow noreferrer\">PR2264</a>. Apparently this is an often-requested feature that is not yet implemented.</p>\n"
},
{
"answer_id": 1406427,
"author": "Ben Bryant",
"author_id": 28953,
"author_profile": "https://Stackoverflow.com/users/28953",
"pm_score": 3,
"selected": false,
"text": "<p><code>call printf %ls</code> only works sometimes, but to get it to work at all in gdb 6.3 you need the <code>void</code> cast and linefeed <code>\\n</code> shown here:</p>\n\n<pre>call (void)printf(\"\\\"%ls\\\"\\n\",str.c_str())</pre>\n\n<p>here is a more reliable command you can put in your .gdbinit that also shows non-ASCII code points:</p>\n\n<pre>define wc_print\necho \"\nset $c = (wchar_t*)$arg0\nwhile ( *$c )\n if ( *$c > 0x7f )\n printf \"[%x]\", *$c\n else\n printf \"%c\", *$c\n end\n set $c++\nend\necho \"\\n\nend</pre>\n\n<p>just enter <code>wc</code> (short for <code>wc_print</code>) with either a <code>std::wstring</code> or <code>wchar_t*</code>.</p>\n\n<p>More detail at <a href=\"http://www.firstobject.com/wchar_t-gdb.htm\" rel=\"noreferrer\">http://www.firstobject.com/wchar_t-gdb.htm</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18382/"
]
| How can I print wstring in gdb? | `call printf %ls` only works sometimes, but to get it to work at all in gdb 6.3 you need the `void` cast and linefeed `\n` shown here:
```
call (void)printf("\"%ls\"\n",str.c_str())
```
here is a more reliable command you can put in your .gdbinit that also shows non-ASCII code points:
```
define wc_print
echo "
set $c = (wchar_t*)$arg0
while ( *$c )
if ( *$c > 0x7f )
printf "[%x]", *$c
else
printf "%c", *$c
end
set $c++
end
echo "\n
end
```
just enter `wc` (short for `wc_print`) with either a `std::wstring` or `wchar_t*`.
More detail at <http://www.firstobject.com/wchar_t-gdb.htm> |
105,653 | <p>I'm having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read_matrix(). But then i want to be able to free the memory later on. So in my main method the second printf should result in a bus error since it should not have any memory allocated to it. How would i go about creating this?</p>
<pre><code>int** first_matrix;
int** second_matrix;
int** result_matrix;
int** read_matrix(int size_x, int size_y)
{
int** matrix;
matrix = calloc(size_x, sizeof(int*));
for(int i = 0;i<size_x;i++) {
matrix[i] = calloc(size_y, sizeof(int));
}
for(int i = 0;i<size_x;i++) {
for(int j = 0;j<size_y;j++) {
matrix[i][j] = i*10+j;
}
}
return matrix;
}
int main(int stackc, char** stack)
{
first_matrix = read_matrix(10,10);
printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]);
free(*first_matrix);
free(first_matrix);
printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]);
}
</code></pre>
| [
{
"answer_id": 105677,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>You need to free each row individually:</p>\n\n<pre><code>\nvoid free_matrix(int **matrix, int size_x)\n{\n for(int i = 0; i < size_x; i++)\n free(matrix[i]);\n free(matrix);\n}\n</code></pre>\n"
},
{
"answer_id": 105682,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 0,
"selected": false,
"text": "<p>You only freed the first row (or column) of first_matrix. Write another function like this:</p>\n\n<pre><code>void free_matrix(int **matrix, int rows)\n{\n int i;\n for(i=0; i<rows; i++)\n {\n free(matrix[i]);\n }\n free(matrix);\n}\n</code></pre>\n\n<p>You might want to make the matrix into a struct to store it's row and column count.</p>\n"
},
{
"answer_id": 105687,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>Freeing the memory doesn't make it go away, it just means that another allocation might grab that same chunk of memory. Whatever you put in it will still be there until something else overwrites it.</p>\n\n<p>Also, you're not freeing everything you allocated. You're only freeing the array of pointers and the first row. But even if you free everything correctly, you would still have the same effect.</p>\n\n<p>If you want to create a \"bus error\" you need to point to memory that doesn't belong to your process. Why do you want to do that anyway?</p>\n"
},
{
"answer_id": 105689,
"author": "Sam Reynolds",
"author_id": 9192,
"author_profile": "https://Stackoverflow.com/users/9192",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend using valgrind to track down unfree'd memory, as opposed to trying to make a bus error occur. It rocks for lots of other stuff as well.</p>\n\n<p>Sam</p>\n"
},
{
"answer_id": 105700,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 0,
"selected": false,
"text": "<p>You're getting memory leaks because you're freeing the first row of the matrix and the list of rows, but none of the 1 to nth rows. You need to call free in a loop.</p>\n\n<p>There are a couple of alternatives, however:\n- Allocate sizeof(int*)<em>rows + rows</em>cols*sizeof(int) bytes and use the first bytes for the row pointers. That way, you only have a single chunk of memory to free (and it's easier on the allocator, too)\n- Use a struct that contains the number of rows. Then you can avoid the row list altogether (saving memory). The only downside is that you have to use a function, a macro, or some messy notation to address the matrix.</p>\n\n<p>If you go with the second option, you can use a struct like this in any C99 compiler, and again only have to allocate a single block of memory (of size numints*sizeof(int)+sizeof(int)):</p>\n\n<pre><code>struct matrix {\n int rows;\n int data[0];\n}\n</code></pre>\n"
},
{
"answer_id": 105706,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": true,
"text": "<p>Just because the memory has been free'd doesn't mean you can't access it! Of course, it's a <strong>very bad</strong> idea to access it after it's been free'd, but that's why it works in your example.</p>\n\n<p>Note that <code>free( *first_matrix )</code> only free's <code>first_matrix[0]</code>, not the other arrays. You probably want some kind of marker to signify the last array (unless you will always know when you free the outer array how many inner arrays you allocated). Something like:</p>\n\n<pre><code>int** read_matrix(int size_x, int size_y)\n{\n int** matrix;\n matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr\n for(int i = 0;i<size_x;i++) {\n matrix[i] = calloc(size_y, sizeof(int));\n }\n matrix[size_x] = NULL; // set the extra ptr to NULL\n for(int i = 0;i<size_x;i++) {\n for(int j = 0;j<size_y;j++) {\n matrix[i][j] = i*10+j;\n }\n }\n return matrix;\n}\n</code></pre>\n\n<p>Then when you're freeing them:</p>\n\n<pre><code>// keep looping until you find the NULL one\nfor( int i=0; first_matrix[i] != NULL; i++ ) {\n free( first_matrix[i] );\n}\nfree( first_matrix );\n</code></pre>\n"
},
{
"answer_id": 105737,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 0,
"selected": false,
"text": "<p>The concept you are missing here, is that for every calloc, there must be a free.\nand that free must be applied to the pointer passed back from calloc.</p>\n\n<p>I recommend you create a function (named delete_matrix)\nthat uses a loop to free all of the pointers that you allocate in here</p>\n\n<p><strong>for(int i = 0;i < size_x;i++) {\n matrix[i] = calloc(size_y, sizeof(int));\n }</strong></p>\n\n<p>then, once that is done, free the pointer allocated by this.</p>\n\n<p><strong>matrix = calloc(size_x, sizeof(int*));</strong></p>\n\n<p>The way you are doing it now, </p>\n\n<p><strong>free(*first_matrix);\n free(first_matrix);</strong></p>\n\n<p>won't do what you want it to do.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9191/"
]
| I'm having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read\_matrix(). But then i want to be able to free the memory later on. So in my main method the second printf should result in a bus error since it should not have any memory allocated to it. How would i go about creating this?
```
int** first_matrix;
int** second_matrix;
int** result_matrix;
int** read_matrix(int size_x, int size_y)
{
int** matrix;
matrix = calloc(size_x, sizeof(int*));
for(int i = 0;i<size_x;i++) {
matrix[i] = calloc(size_y, sizeof(int));
}
for(int i = 0;i<size_x;i++) {
for(int j = 0;j<size_y;j++) {
matrix[i][j] = i*10+j;
}
}
return matrix;
}
int main(int stackc, char** stack)
{
first_matrix = read_matrix(10,10);
printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]);
free(*first_matrix);
free(first_matrix);
printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]);
}
``` | Just because the memory has been free'd doesn't mean you can't access it! Of course, it's a **very bad** idea to access it after it's been free'd, but that's why it works in your example.
Note that `free( *first_matrix )` only free's `first_matrix[0]`, not the other arrays. You probably want some kind of marker to signify the last array (unless you will always know when you free the outer array how many inner arrays you allocated). Something like:
```
int** read_matrix(int size_x, int size_y)
{
int** matrix;
matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr
for(int i = 0;i<size_x;i++) {
matrix[i] = calloc(size_y, sizeof(int));
}
matrix[size_x] = NULL; // set the extra ptr to NULL
for(int i = 0;i<size_x;i++) {
for(int j = 0;j<size_y;j++) {
matrix[i][j] = i*10+j;
}
}
return matrix;
}
```
Then when you're freeing them:
```
// keep looping until you find the NULL one
for( int i=0; first_matrix[i] != NULL; i++ ) {
free( first_matrix[i] );
}
free( first_matrix );
``` |
105,671 | <p>Does any one have a preference on how to check if a value is <code>DBNull</code>? I've found these two statements give me the results I want, but just wondering if there's a preference?</p>
<p><code>if (any is System.DBNull)</code></p>
<p>same as:</p>
<p><code>if (any == System.DBNull.Value)</code></p>
<p>Thanks!</p>
| [
{
"answer_id": 105678,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 3,
"selected": true,
"text": "<pre><code>if (any == System.DBNull.Value) ...\n</code></pre>\n\n<p>I prefer that one, simply because I read that as comparing values, not types.</p>\n"
},
{
"answer_id": 105696,
"author": "Kevlar",
"author_id": 19252,
"author_profile": "https://Stackoverflow.com/users/19252",
"pm_score": 0,
"selected": false,
"text": "<p>if you're in c#, you should use <code>==</code>; <code>is</code> uses reflection which is more expensive to compute, especially since there's only ever one instance of <code>System.DBNull</code>.</p>\n"
},
{
"answer_id": 105701,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": -1,
"selected": false,
"text": "<p>I like the \"is System.DBNull\" more because I hate the idea of comparing something to NULL and having it be true. Many other syntaxes (what the hell is the plural of that?) would have anything==NULL return NULL.</p>\n\n<p>I understand that there's DBNull.Value for a reason. I know. I'm listing my PREFERENCE :)</p>\n"
},
{
"answer_id": 105726,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": 4,
"selected": false,
"text": "<p>I tend to use</p>\n\n<pre><code>if (DBNull.Value.Equals(value)) {\n //\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (Convert.IsDBNull(value)) {\n //\n}\n</code></pre>\n"
},
{
"answer_id": 109650,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 3,
"selected": false,
"text": "<p><code>is</code> does not use reflection as Kevlar623 says. It maps to the <code>isinst</code> operation in IL. On that level, comparing performance is downright silly, unless you're working on a missile guidance system.</p>\n\n<p><strong>I use <code>value is DBNull</code>.</strong> It just sounds right and as a paranoid developer, I can't trust that the only value ever in existence is <code>DBNull.Value</code>. Bugs happen.</p>\n"
},
{
"answer_id": 389725,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": -1,
"selected": false,
"text": "<p>This is a good example of form follows function. Whichever one executes more efficiently is the way to go. What it looks like, reads like, or bad names it calls you is irrelevant. Use the language efficiently, don't mold the language into a new one.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19314/"
]
| Does any one have a preference on how to check if a value is `DBNull`? I've found these two statements give me the results I want, but just wondering if there's a preference?
`if (any is System.DBNull)`
same as:
`if (any == System.DBNull.Value)`
Thanks! | ```
if (any == System.DBNull.Value) ...
```
I prefer that one, simply because I read that as comparing values, not types. |
105,676 | <p>Greetings,</p>
<p>I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. </p>
<p>Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.</p>
| [
{
"answer_id": 105693,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 1,
"selected": false,
"text": "<p>Ping everything in the rage, then you can get netbios info from the systems that respond to identify it's name.</p>\n"
},
{
"answer_id": 105703,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://nmap.org/\" rel=\"noreferrer\">Nmap</a> is good for this - use the -O option for OS fingerprinting and -oX \"filename.xml\" for <a href=\"http://nmap.org/book/man-output.html\" rel=\"noreferrer\">output</a> as xml that you can then parse from c#.</p>\n\n<p>A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan):</p>\n\n<pre><code>nmap -O -oX \"filename.xml\" 192.168.0.0/24\n</code></pre>\n\n<p>leave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options.</p>\n"
},
{
"answer_id": 106092,
"author": "EricSch",
"author_id": 12192,
"author_profile": "https://Stackoverflow.com/users/12192",
"pm_score": 1,
"selected": false,
"text": "<p>In one of my web app I used the NetApi32 function for network browsing. </p>\n\n<p>Code:\n<a href=\"http://gist.github.com/11668\" rel=\"nofollow noreferrer\">http://gist.github.com/11668</a></p>\n"
},
{
"answer_id": 114558,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "<p>To expand on what Unkwntech has said -</p>\n\n<p>You can also do a \"broadcast\" ping to avoid having to ping each IP address individually.</p>\n\n<p>Immediately after than you can use \"arp\" to examine the ARP cache and get a list of which IP addresses are on which MAC address.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5021/"
]
| Greetings,
I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network.
Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work. | [Nmap](http://nmap.org/) is good for this - use the -O option for OS fingerprinting and -oX "filename.xml" for [output](http://nmap.org/book/man-output.html) as xml that you can then parse from c#.
A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan):
```
nmap -O -oX "filename.xml" 192.168.0.0/24
```
leave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options. |
105,688 | <p>I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message. </p>
<p>The XML schema definition for a field in the message looks like this:</p>
<pre><code><xs:element name="value" type="xs:string" nillable="true" />
</code></pre>
<p>How do I send a null value that meets this spec?</p>
<p>I sent <code><value xsi:nil="true" /></code>
but this caused the XML parser to barf.</p>
| [
{
"answer_id": 105713,
"author": "aaronsw",
"author_id": 4300,
"author_profile": "https://Stackoverflow.com/users/4300",
"pm_score": 4,
"selected": false,
"text": "<p>What about <code><value xsi:nil=\"true\"></value></code>? That's what's <a href=\"http://www.w3.org/TR/xmlschema-0/#Nils\" rel=\"noreferrer\">in the spec</a>.</p>\n"
},
{
"answer_id": 105714,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 1,
"selected": false,
"text": "<p>In the past when I've had XML elements that were null I could either not include them or send them empty so, in your case it'd be:\n<code><value /></code></p>\n\n<p>Have you tried that?</p>\n"
},
{
"answer_id": 105740,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 1,
"selected": true,
"text": "<p>That's the right way of sending a nil value (assuming that the default namespace and the <code>xsi</code> namespace are set to the correct values, namely <code>\"http://www.w3.org/2001/XMLSchema-instance\"</code> for <code>xsi</code>.) so it looks like you might have come up against a bug in the CML parser you're using. What's the error message?</p>\n\n<p>You might try using <code>xsi:nil=\"1\"</code> or using separate open and close tags (<code><value xsi:nil=\"true\"></value></code>) to try working around the bug.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7222/"
]
| I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message.
The XML schema definition for a field in the message looks like this:
```
<xs:element name="value" type="xs:string" nillable="true" />
```
How do I send a null value that meets this spec?
I sent `<value xsi:nil="true" />`
but this caused the XML parser to barf. | That's the right way of sending a nil value (assuming that the default namespace and the `xsi` namespace are set to the correct values, namely `"http://www.w3.org/2001/XMLSchema-instance"` for `xsi`.) so it looks like you might have come up against a bug in the CML parser you're using. What's the error message?
You might try using `xsi:nil="1"` or using separate open and close tags (`<value xsi:nil="true"></value>`) to try working around the bug. |
105,702 | <p>I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django.</p>
<p>I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block.</p>
<p>How should I do this? It's a fairly large project, so adding code to every view is far from ideal.</p>
<hr>
<p>That solution works well. The Middleware Class I ended up with this this:</p>
<pre><code>from django.http import HttpResponseRedirect
class BetaMiddleware(object):
"""
Require beta code session key in order to view any page.
"""
def process_request(self, request):
if request.path != '/beta/' and not request.session.get('in_beta'):
return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))
</code></pre>
| [
{
"answer_id": 105756,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to add <code>@login_required</code> decorators across the board and be done with it. Unless you have a boat-load of view functions, it shouldn't be too horrible.</p>\n"
},
{
"answer_id": 105764,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 2,
"selected": false,
"text": "<p>You can probably restrict access to the entire site via apache with htaccess, taking the problem out of the django's project space entirely.</p>\n"
},
{
"answer_id": 105945,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 2,
"selected": false,
"text": "<p>Do what StackOverflow did.</p>\n\n<p>They had a simple email/password form. It had a single hard-coded password (falkensmaze). When the user gets the password right set a cookie. eg. auth=1</p>\n\n<p>Don't worry about it being unsecure. Who care's if someone hacks into the beta?</p>\n\n<p>Apache/htaccess is also a nice and simple solution.</p>\n"
},
{
"answer_id": 106212,
"author": "AdamKG",
"author_id": 16361,
"author_profile": "https://Stackoverflow.com/users/16361",
"pm_score": 5,
"selected": true,
"text": "<p>Start with <a href=\"http://www.djangosnippets.org/snippets/136/\" rel=\"noreferrer\">this Django snippet</a>, but modify it to check <code>request.session['has_beta_access']</code>. If they don't have it, then have it return a redirect to a \"enter beta code\" page that, when posted to with the right code, sets that session variable to <code>True</code>.</p>\n\n<p>Making it a public beta then just consists of removing that middleware from your <code>MIDDLEWARE_CLASSES</code> setting.</p>\n"
},
{
"answer_id": 1249496,
"author": "John Debs",
"author_id": 151577,
"author_profile": "https://Stackoverflow.com/users/151577",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what version of the Pinax code you're using, but they've built in the ability to close the site off for a private beta so you don't need to do much work yourself.</p>\n\n<p>The link to the specific project template for a private beta site is here: <a href=\"http://github.com/pinax/pinax/tree/3ad73d1ba44f37365333bae17b507668b0eb7e16/pinax/projects/private_beta_project\" rel=\"nofollow noreferrer\">http://github.com/pinax/pinax/tree/3ad73d1ba44f37365333bae17b507668b0eb7e16/pinax/projects/private_beta_project</a> although I think they might have since added that functionality to all the project templates.</p>\n"
},
{
"answer_id": 1770902,
"author": "ercu",
"author_id": 73292,
"author_profile": "https://Stackoverflow.com/users/73292",
"pm_score": 0,
"selected": false,
"text": "<p>Great snippet but it resulted lots of problems for me related OpenId sessions. So I end up relying on Cookies instead of the Session:</p>\n\n<pre><code>class BetaMiddleware(object):\n \"\"\"\n Require beta code cookie key in order to view any page.\n \"\"\"\n set_beta = False\n def process_request(self, request):\n referer = request.META.get('HTTP_REFERER', '')\n\n if request.method == 'GET' and not 'is_in_beta' in request.COOKIES:\n return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))\n\n if request.method == 'POST' and 'pass' in request.POST:\n code = request.POST['pass']\n\n if code=='beta':\n self.set_beta = True\n return HttpResponseRedirect('%s' % '/')\n\n def process_response(self, request, response): \n\n if self.set_beta is True:\n response.set_cookie('is_in_beta', '1')\n return response\n</code></pre>\n\n<p>It's not secure but that's enough for me. This also works with just a beta html page.</p>\n"
},
{
"answer_id": 59790291,
"author": "user1387219",
"author_id": 1387219,
"author_profile": "https://Stackoverflow.com/users/1387219",
"pm_score": 0,
"selected": false,
"text": "<p>use this middleware:</p>\n\n<pre><code>class BetaForm(Form):\n beta_pass = CharField(required=True)\n\n def clean_beta_pass(self):\n data = self.cleaned_data['beta_pass']\n if data != settings.BETA_PASS:\n raise forms.ValidationError(\"Invalid Beta pass!\")\n return data\n\n\nclass BetaView(FormView):\n form_class = BetaForm\n template_name = \"beta.html\"\n\n def form_valid(self, form):\n response = HttpResponseRedirect(self.request.GET.get(\"next\", \"/\"))\n response.set_cookie(settings.BETA_PASS, '')\n return response\n\n\ndef beta_middleware(get_response):\n def middleware(request):\n\n if request.path == reverse(\"beta\"):\n return get_response(request)\n else:\n if settings.BETA_PASS in request.COOKIES:\n return get_response(request)\n else:\n return HttpResponseRedirect(\n '%s?%s' % (reverse(\"beta\"), urlencode({\"next\": request.get_full_path()})))\n return middleware\n</code></pre>\n\n<p>this template:</p>\n\n<pre><code><!doctype html>\n<title>Welcome to the beta!</title>\n<style>\n body { text-align: center; padding: 150px; }\n h1 { font-size: 50px; }\n body { font: 20px Helvetica, sans-serif; color: #333; }\n article { display: block; text-align: left; width: 650px; margin: 0 auto; }\n a { color: #dc8100; text-decoration: none; }\n a:hover { color: #333; text-decoration: none; }\n</style>\n\n<article>\n\n <h1>>Welcome to the beta lucky user!</h1>\n <div>\n <form method=\"POST\">\n {% csrf_token %}\n {{form}}\n <input type=\"submit\">\n </form>\n </div>\n</article>\n</code></pre>\n\n<p>this settings:</p>\n\n<pre><code>BETA_PASS=\"beta\"\n</code></pre>\n\n<p>this path:</p>\n\n<pre><code>path(\"beta\",BetaView.as_view(),name=\"beta\"),\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007/"
]
| I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django.
I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block.
How should I do this? It's a fairly large project, so adding code to every view is far from ideal.
---
That solution works well. The Middleware Class I ended up with this this:
```
from django.http import HttpResponseRedirect
class BetaMiddleware(object):
"""
Require beta code session key in order to view any page.
"""
def process_request(self, request):
if request.path != '/beta/' and not request.session.get('in_beta'):
return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))
``` | Start with [this Django snippet](http://www.djangosnippets.org/snippets/136/), but modify it to check `request.session['has_beta_access']`. If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to `True`.
Making it a public beta then just consists of removing that middleware from your `MIDDLEWARE_CLASSES` setting. |
105,724 | <p>In this code I am debugging, I have this code snipit:</p>
<pre><code>ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0');
</code></pre>
<p>What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year.</p>
<p>UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me.</p>
| [
{
"answer_id": 105752,
"author": "RKitson",
"author_id": 16947,
"author_profile": "https://Stackoverflow.com/users/16947",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like it's grabbing the substring from the 3rd character (if 0 based) to the end, then if the substring has a length less than 2 it's making the length equal to 2 by adding 0 to the left side.</p>\n"
},
{
"answer_id": 105753,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": 3,
"selected": true,
"text": "<p>It takes the last two digits of the year and pads the left side with zeroes to a maximum of 2 characters. Looks like a \"just in case\" for expiration years ending in 08, 07, etc., making sure that the leading zero is present.</p>\n"
},
{
"answer_id": 105759,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": -1,
"selected": false,
"text": "<p>OK so it's taking the value from the drop down, ABCD</p>\n\n<p>Then it takes the substring from position 2, CD</p>\n\n<p>And then it err, left pads it with 2 zeros if it needs too, CD</p>\n\n<p>Or, if you've just ended X, then it would substring to X and pad to OX</p>\n"
},
{
"answer_id": 105760,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": -1,
"selected": false,
"text": "<p>It's taking the last two digits of the year, then pad to the left with a \"0\". </p>\n\n<p>So 2010 would be 10, 2009 would be 09.</p>\n\n<p>Not sure why the developer didn't just set the value on the dropdown to the last two digits, or why you would need to left pad it (unless you were dealing with years 0-9 AD).</p>\n"
},
{
"answer_id": 105766,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 2,
"selected": false,
"text": "<p>This prints \"98\" to the console.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Console.Write(\"1998\".Substring(2).PadLeft(2, '0'));\n Console.Read();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 105767,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 0,
"selected": false,
"text": "<p>PadLeft ensures that you receive at least two characters from the input, padding the input (on the left side) with the appropriate character. So input, in this case, might be 12. You get \"12\" back. Or input might be 9, in which case, you get \"09\" back. </p>\n\n<p>This is an example of complex chaining (see <a href=\"https://stackoverflow.com/questions/105504/is-there-any-performance-benefit-with-chaining-statements-in-net\">\"Is there any benefit in Chaining\"</a> post) gone awry, and making code appear overly complex. </p>\n"
},
{
"answer_id": 105773,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 1,
"selected": false,
"text": "<p>Of course you can run this. You just can't run it in the application you're debugging. To find out what it's doing, and not just what it looks like it's doing, make a new web application, put in a DropDownList, put a few static years in it, and then put in the code you've mentioned and see what it does. Then you'll know for certain.</p>\n"
},
{
"answer_id": 105787,
"author": "Chris",
"author_id": 19290,
"author_profile": "https://Stackoverflow.com/users/19290",
"pm_score": 0,
"selected": false,
"text": "<p>The substring returns the value with the first two characters skipped, the padleft pads the result with leading zeros:</p>\n\n<pre><code> string s = \"2014\";\n MessageBox.Show(s.Substring(2).PadLeft(2, 'x')); //14\n string s2 = \"14\";\n MessageBox.Show(s2.Substring(2).PadLeft(2, 'x')); //xx\n</code></pre>\n\n<p>My guess is the code is trying to convert the year to a 2 digit value.</p>\n"
},
{
"answer_id": 105806,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 1,
"selected": false,
"text": "<p>something stupid. It's getting the value of the selected item and taking the everything after the first two characters. If that is only one character, then it adds a '0' to the beginning of it, and if it is zero characters, the it returns '00'. The reason I say this is stupid is because if you need the value to be two characters long, why not just set it like that to begin with when you are creating the drop down list?</p>\n"
},
{
"answer_id": 105846,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<p>The PadLeft only does something if the user enters a year that is either 2 or 3 digits long.</p>\n\n<p>With a 1-digit year, you get an exception (Subsring errs).</p>\n\n<p>With a 2-digit year (07, 08, etc), it will return 00. I would say this is an error.</p>\n\n<p>With a 3-digit year (207, 208), which the author may have assumed to be typos, it would return the last digit padded with a zero -- 207 -> 07; 208 -> 08.</p>\n\n<p>As long as the user must choose a year and isn't allowed to enter a year, the PadLeft is unnecessary -- the Substring(2) does exactly what you need given a 4-digit year.</p>\n"
},
{
"answer_id": 11404489,
"author": "McKay",
"author_id": 8384,
"author_profile": "https://Stackoverflow.com/users/8384",
"pm_score": 0,
"selected": false,
"text": "<p>This code seems to be trying to grab a 2 digit year from a four digit year (ddlexpyear is the hint)</p>\n\n<p>It takes strings and returns strings, so I will eschew the string delimiters:</p>\n\n<ul>\n<li>1998 -> 98</li>\n<li>2000 -> 00</li>\n<li>2001 -> 01</li>\n<li>2012 -> 12</li>\n</ul>\n\n<p>Problem is that it doesn't do a good job. In these cases, the padding doesn't actually help. Removing the pad code does not affect the cases it gets correct.</p>\n\n<p>So the code works (with or without the pad) for 4 digit years, what does it do for strings of other lengths?</p>\n\n<ul>\n<li>null: exception</li>\n<li>0: exception</li>\n<li>1: exception</li>\n<li>2: always returns \"00\". e.g. the year 49 (when the Jews were expulsed from rome) becomes \"00\". This is bad.</li>\n<li>3: saves the last digit, and puts a \"0\" in front of it. Correct in 10% of cases (when the second digit is actually a zero, like 304, or 908), but quite wrong in the remainder (like 915, 423, and 110)</li>\n<li>5: just saves the 3rd and 4th digits, which is also wrong, \"10549\" should probably be \"49\" but is instead \"54\".</li>\n<li>as you can expect the problem continues in higher digits.</li>\n</ul>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
| In this code I am debugging, I have this code snipit:
```
ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0');
```
What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year.
UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me. | It takes the last two digits of the year and pads the left side with zeroes to a maximum of 2 characters. Looks like a "just in case" for expiration years ending in 08, 07, etc., making sure that the leading zero is present. |
105,725 | <p>I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source. </p>
<p>some solutions --</p>
<p><a href="http://www.cprogramming.com/challenges/solutions/self_print.html" rel="noreferrer">http://www.cprogramming.com/challenges/solutions/self_print.html</a></p>
<p><strong><a href="http://www.nyx.net/~gthompso/quine.htm" rel="noreferrer">Quine Page solution in many languages</a></strong></p>
<p>There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...</p>
| [
{
"answer_id": 105745,
"author": "Roland",
"author_id": 15965,
"author_profile": "https://Stackoverflow.com/users/15965",
"pm_score": -1,
"selected": false,
"text": "<p>In ruby:</p>\n\n<p>puts File.read(_ _ FILE _ _)</p>\n"
},
{
"answer_id": 105755,
"author": "aaronsw",
"author_id": 4300,
"author_profile": "https://Stackoverflow.com/users/4300",
"pm_score": 3,
"selected": false,
"text": "<p>There are a couple of different strategies to writing quines. The obvious one is to just write code that opens the code and prints it out. But the more interesting ones involve language features that allow for self-embedding, like the %s-style printf feature in many languages. You have to figure out how to embed something so that it ends up resolving to the request to be embedded. I suspect, like palindromes, a lot of trial and error is involved.</p>\n"
},
{
"answer_id": 105765,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 1,
"selected": false,
"text": "<p>The usual approach (when you can't cheat*) is to write something that encodes its source in a string constant, then prints out that constant twice: Once as a string literal, and once as code. That gets around the \"every time I write a line of code, I have to write another to print it out!\" problem.</p>\n\n<p>'Cheating' includes:\n- Using an interpreted language and simply loading the source and printing it\n- 0-byte long files, which are valid in some languages, such as C.</p>\n"
},
{
"answer_id": 105779,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 0,
"selected": false,
"text": "<p>One idea to think about encoding and how to give something a double meaning so that it can be used to output something in a couple of forms. There is also the cavaet that this type of problem comes with restrictions to make it harder as without any rules other than the program output itself, the empty program is a solution.</p>\n"
},
{
"answer_id": 106650,
"author": "vog",
"author_id": 19163,
"author_profile": "https://Stackoverflow.com/users/19163",
"pm_score": 7,
"selected": true,
"text": "<p>Aside from cheating¹ there is no difference between compiled and interpreted languages. </p>\n\n<p>The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:</p>\n\n<pre>\nprint ...\n</pre>\n\n<p>However, what should it print? Itself. So it needs to print the \"print\" command:</p>\n\n<pre>\nprint \"print ...\"\n</pre>\n\n<p>What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with \"print\", too:</p>\n\n<pre>\nprint \"print \\\"print ...\\\"\"\n</pre>\n\n<p>Now the program grew again, so there's again more to print:</p>\n\n<pre>\nprint \"print \\\"print \\\\\\\"...\\\\\\\"\\\"\"\n</pre>\n\n<p>And so on.\nWith every added code there's more code to print.\nThis approach is getting nowhere,\nbut it reveals an interesting pattern:\nThe string \"print \\\"\" is repeated over and over again.\nIt would be nice to put the repeating part\ninto a variable:</p>\n\n<pre>\na = \"print \\\"\"\nprint a\n</pre>\n\n<p>However, the program just changed,\nso we need to adjust a:</p>\n\n<pre>\na = \"a = ...\\nprint a\"\nprint a\n</pre>\n\n<p>When we now try to fill in the \"...\",\nwe run into the same problems as before.\nUltimately, we want to write something like this:</p>\n\n<pre>\na = \"a = \" + (quoted contents of a) + \"\\nprint a\"\nprint a\n</pre>\n\n<p>But that is not possible,\nbecause even if we had such a function <code>quoted()</code> for quoting,\nthere's still the problem that we define <code>a</code> in terms of itself:</p>\n\n<pre>\na = \"a = \" + quoted(a) + \"\\nprint a\"\nprint a\n</pre>\n\n<p>So the only thing we can do is putting a place holder into <code>a</code>:</p>\n\n<pre>\na = \"a = @\\nprint a\"\nprint a\n</pre>\n\n<p>And that's the whole trick!\nAnything else is now clear.\nSimply replace the place holder\nwith the quoted contents of <code>a</code>:</p>\n\n<pre>\na = \"a = @\\nprint a\"\nprint a.replace(\"@\", quoted(a))\n</pre>\n\n<p>Since we have changed the code,\nwe need to adjust the string:</p>\n\n<pre>\na = \"a = @\\nprint a.replace(\\\"@\\\", quoted(a))\"\nprint a.replace(\"@\", quoted(a))\n</pre>\n\n<p>And that's it!\nAll quines in all languages work that way\n(except the cheating ones).</p>\n\n<p>Well, you should ensure that you replace only\nthe first occurence of the place holder.\nAnd if you use a second place holder,\nyou can avoid needing to quote the string.</p>\n\n<p>But those are minor issues\nand easy to solve.\nIf fact, the realization of <code>quoted()</code> and <code>replace()</code>\nare the only details in which the various quines really differ.</p>\n\n<hr>\n\n<p>¹ by making the program read its source file</p>\n"
},
{
"answer_id": 195039,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>For fun, I came up with one in Scheme, which I was pretty proud of for about 5 minutes until I discovered has been discovered before. Anyways, there's a slight modification to the \"rules\" of the game to better count for the duality of data and code in Lisp: instead of printing out the source of the program, it's an S-expression that returns itself:</p>\n\n<pre><code>((lambda (x) (list x `',x)) '(lambda (x) (list x `',x)))\n</code></pre>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Quines#Scheme_.28also_valid_Common_Lisp.29\" rel=\"nofollow noreferrer\">one on Wikipedia</a> has the same concept, but with a slightly different (more verbose) mechanism for quoting. I like mine better though.</p>\n"
},
{
"answer_id": 14112707,
"author": "Rishu Prakamya Dutt",
"author_id": 1935161,
"author_profile": "https://Stackoverflow.com/users/1935161",
"pm_score": 0,
"selected": false,
"text": "<p>How about actually reading and printing your source code? Its not difficult at all!! Heres one in php:</p>\n\n<pre><code><?php\n{\nheader(\"Content-Type: text/plain\");\n $f=fopen(\"5.php\",\"r\");\n while(!feof($f))\n {\n echo fgetc($f);\n } \n fclose($f);\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 18016320,
"author": "Rabih Kodeih",
"author_id": 698585,
"author_profile": "https://Stackoverflow.com/users/698585",
"pm_score": 0,
"selected": false,
"text": "<p>In python, you can write:</p>\n\n<pre><code>s='c=chr(39);print\"s=\"+c+s+c+\";\"+s';c=chr(39);print\"s=\"+c+s+c+\";\"+s\n</code></pre>\n\n<p>inspired from this self printing pseudo-code:</p>\n\n<pre><code>Print the following line twice, the second time with quotes.\n\"Print the following line twice, the second time with quotes.\"\n</code></pre>\n"
},
{
"answer_id": 20525545,
"author": "Taires",
"author_id": 1677280,
"author_profile": "https://Stackoverflow.com/users/1677280",
"pm_score": 0,
"selected": false,
"text": "<p>I've done a AS3 example for those interested in this</p>\n\n<pre><code>var program = \"var program = @; function main(){trace(program.replace('@', \n\nString.fromCharCode(34) + program + String.fromCharCode(34)))} main()\"; \nfunction main(){\n trace(program.replace('@', String.fromCharCode(34) + program + String.fromCharCode(34)))\n}\nmain()\n</code></pre>\n"
},
{
"answer_id": 64608912,
"author": "Paul Meisel",
"author_id": 14549080,
"author_profile": "https://Stackoverflow.com/users/14549080",
"pm_score": -1,
"selected": false,
"text": "<p>In bash it is really easy</p>\n<p>touch test; chmod oug+x test; ./test</p>\n<p>Empty file, Empty output</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8786/"
]
| I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source.
some solutions --
<http://www.cprogramming.com/challenges/solutions/self_print.html>
**[Quine Page solution in many languages](http://www.nyx.net/~gthompso/quine.htm)**
There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages... | Aside from cheating¹ there is no difference between compiled and interpreted languages.
The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:
```
print ...
```
However, what should it print? Itself. So it needs to print the "print" command:
```
print "print ..."
```
What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too:
```
print "print \"print ...\""
```
Now the program grew again, so there's again more to print:
```
print "print \"print \\\"...\\\"\""
```
And so on.
With every added code there's more code to print.
This approach is getting nowhere,
but it reveals an interesting pattern:
The string "print \"" is repeated over and over again.
It would be nice to put the repeating part
into a variable:
```
a = "print \""
print a
```
However, the program just changed,
so we need to adjust a:
```
a = "a = ...\nprint a"
print a
```
When we now try to fill in the "...",
we run into the same problems as before.
Ultimately, we want to write something like this:
```
a = "a = " + (quoted contents of a) + "\nprint a"
print a
```
But that is not possible,
because even if we had such a function `quoted()` for quoting,
there's still the problem that we define `a` in terms of itself:
```
a = "a = " + quoted(a) + "\nprint a"
print a
```
So the only thing we can do is putting a place holder into `a`:
```
a = "a = @\nprint a"
print a
```
And that's the whole trick!
Anything else is now clear.
Simply replace the place holder
with the quoted contents of `a`:
```
a = "a = @\nprint a"
print a.replace("@", quoted(a))
```
Since we have changed the code,
we need to adjust the string:
```
a = "a = @\nprint a.replace(\"@\", quoted(a))"
print a.replace("@", quoted(a))
```
And that's it!
All quines in all languages work that way
(except the cheating ones).
Well, you should ensure that you replace only
the first occurence of the place holder.
And if you use a second place holder,
you can avoid needing to quote the string.
But those are minor issues
and easy to solve.
If fact, the realization of `quoted()` and `replace()`
are the only details in which the various quines really differ.
---
¹ by making the program read its source file |
105,731 | <p>How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?</p>
<p>I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.</p>
<p>The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.</p>
<p>I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either. </p>
<p>Does anyone have a sample of how to get this to work?</p>
| [
{
"answer_id": 106421,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 3,
"selected": true,
"text": "<p>What's \"not working\" with the CCommandBar for you? You should be able to add a CCommandBar member to your dialog class, then in teh DIalog's InitDialog you call Create and InsertMenuBar on the command bar - something like this:</p>\n\n<pre><code>m_cmdBar.Create(this);\nm_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID);\n</code></pre>\n\n<p>Your menu resource might look something like this:</p>\n\n<pre><code>IDR_MENU_RESRC_ID MENU DISCARDABLE\nBEGIN\nMENUITEM \"OK\", IDOK\nMENUITEM \"Cancel\", IDCANCEL\nEND\n</code></pre>\n"
},
{
"answer_id": 107096,
"author": "snctln",
"author_id": 3494,
"author_profile": "https://Stackoverflow.com/users/3494",
"pm_score": 0,
"selected": false,
"text": "<p>thank you so much... I was going crazy with this...</p>\n\n<p>your code worked exactly as expected... </p>\n\n<p>At first I used it and had the same results, the softkey area would be blank except for the SIP input button.</p>\n\n<p>After an hour or so of debugging I tried putting those 2 lines of code at the END of my OnInitDIalog() and it worked :)</p>\n\n<p>My problem ende dup being that in my OnIitDialog() I am creating some child dialogs. when I put the CCommandBar.InsertMenuBar() before I create child dialogs I do not get my \"ok\" or \"Cancel\" soft keys, when I put that line after the creation of child dialogs the softkeys show as expected and work great.</p>\n\n<p>Thanks again</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3494/"
]
| How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?
I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.
The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.
I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either.
Does anyone have a sample of how to get this to work? | What's "not working" with the CCommandBar for you? You should be able to add a CCommandBar member to your dialog class, then in teh DIalog's InitDialog you call Create and InsertMenuBar on the command bar - something like this:
```
m_cmdBar.Create(this);
m_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID);
```
Your menu resource might look something like this:
```
IDR_MENU_RESRC_ID MENU DISCARDABLE
BEGIN
MENUITEM "OK", IDOK
MENUITEM "Cancel", IDCANCEL
END
``` |
105,754 | <p>We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using <code>mod_proxy_jk</code> as the connector.</p>
<p>Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each).</p>
<p>Relevant server.xml portions:</p>
<pre><code><Connector port="8009"
address="${jboss.bind.address}"
protocol="AJP/1.3"
emptySessionPath="true"
enableLookups="false"
redirectPort="8443"
maxThreads="320"
connectionTimeout="45000"
/>
</code></pre>
<p>Relevant httpd.conf portions: </p>
<pre><code><IfModule prefork.c>
StartServers 8
MinSpareServers 5
MaxSpareServers 20
ServerLimit 256
MaxClients 256
MaxRequestsPerChild 0
</IfModule>
</code></pre>
| [
{
"answer_id": 105928,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": false,
"text": "<h3>MaxClients</h3>\n\n<p>This is the fundamental cap of parallel client connections your apache should handle at once.</p>\n\n<p>With prefork, only one request can be handled per process. Therefore the whole apache can process <em>at most</em> $MaxClients requests in the time it takes to handle a <em>single</em> request. Of course, this ideal maximum can only be reached if the application needs less than 1/$MaxClients resources per request.</p>\n\n<p>If, for example, the application takes a second of cpu-time to answer a single request, setting MaxClients to four will limit your throughput to four requests per second: Each request uses up an apache connection and apache will only handle four at a time. But if the server has only two CPUs, not even this can be reached, because every wall-clock second only has two cpu seconds, but the requests would need four cpu seconds.</p>\n\n<h3>MinSpareServers</h3>\n\n<p>This tells apache how many idle processes should hang around. The bigger this number the more burst load apache can swallow before needing to spawn extra processes, which is expensive and thus slows down the current request.</p>\n\n<p>The correct setting of this depends on your workload. If you have pages with many sub-requests (pictures, iframes, javascript, css) then hitting a single page might use up many more processes for a short time.</p>\n\n<h3>MaxSpareServers</h3>\n\n<p>Having too many unused apache processes hanging around just wastes memory, thus apache uses the MaxSpareServers number to limit the amount of spare processes it is holding in reserve for bursts of requests.</p>\n\n<h3>MaxRequestsPerChild</h3>\n\n<p>This limits the number of requests a single process will handle throughout its lifetime. If you are very concerned about stability, you should put an actual limit here to continually recycle the apache processes to prevent resource leaks from affecting the system.</p>\n\n<h3>StartServers</h3>\n\n<p>This is just the amount of processes apache starts by default. Set this to the usual amount of running apache processes to reduce warm-up time of your system. Even if you ignore this setting, apache will use the Min-/MaxSpareServers values to spawn new processes as required.</p>\n\n<h3>More information</h3>\n\n<p>See also <a href=\"http://httpd.apache.org/docs/2.0/mod/mpm_common.html\" rel=\"noreferrer\">the documentation for apache's multi-processing modules</a>.</p>\n"
},
{
"answer_id": 106655,
"author": "f4nt",
"author_id": 14838,
"author_profile": "https://Stackoverflow.com/users/14838",
"pm_score": 1,
"selected": false,
"text": "<p>The default settings are generally decent starting points to see what your applications is really going to need. I don't know how much traffic you're expecting, so guessing at the MaxThreads, MaxClients, and MaxServers is a bit difficult. I can tell you that most of the customers I deal with (work for a linux web host, that deals mainly with customers running Java apps in Tomcat) use the default settings for quite some time without too many tweaks needed.</p>\n\n<p>If you're not expecting much traffic, then these settings being \"too high\" really shouldn't effect you too much either. Apache's not going to allocate resources for the whole 256 potential clients unless it becomes necessary. The same goes for Tomcat as well. </p>\n"
},
{
"answer_id": 110080,
"author": "Zizzencs",
"author_id": 686,
"author_profile": "https://Stackoverflow.com/users/686",
"pm_score": 4,
"selected": true,
"text": "<p>You should consider the workload the servers might get.</p>\n\n<p>The most important factor might be the number of simultaneously connected clients at peak times. Try to determine it and tune your settings in a way where:</p>\n\n<ul>\n<li>there are enough processing threads in both Apache and Tomcat that they don't need to spawn new threads when the server is heavily loaded</li>\n<li>there are not way more processing threads in the servers than needed as they would waste resources.</li>\n</ul>\n\n<p>With this kind of setup you can minimize the internal maintenance overhead of the servers, that could help a lot, especially when your load is sporadic.</p>\n\n<p>For example consider an application where you have ~300 new requests/second. Each request requires on average 2.5 seconds to serve. It means that at any given time you have ~750 requests that need to be handled simultaneously. In this situation you probably want to tune your servers so that they have ~750 processing threads at startup and you might want to add something like ~1000 processing threads at maximum to handle extremely high loads.</p>\n\n<p>Also consider for exactly what do you require a thread for. In the previous example each request was independent from the others, there was no session tracking used. In a more \"web-ish\" scenario you might have users logged in to your website, and depending on your software used, Apache and/or Tomcat might need to use the same thread to serve the requests that come in one session. In this case, you might need more threads. However as I know Tomcat at least, you won't really need to consider this as it works with thread pools internally anyways.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4419/"
]
| We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using `mod_proxy_jk` as the connector.
Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each).
Relevant server.xml portions:
```
<Connector port="8009"
address="${jboss.bind.address}"
protocol="AJP/1.3"
emptySessionPath="true"
enableLookups="false"
redirectPort="8443"
maxThreads="320"
connectionTimeout="45000"
/>
```
Relevant httpd.conf portions:
```
<IfModule prefork.c>
StartServers 8
MinSpareServers 5
MaxSpareServers 20
ServerLimit 256
MaxClients 256
MaxRequestsPerChild 0
</IfModule>
``` | You should consider the workload the servers might get.
The most important factor might be the number of simultaneously connected clients at peak times. Try to determine it and tune your settings in a way where:
* there are enough processing threads in both Apache and Tomcat that they don't need to spawn new threads when the server is heavily loaded
* there are not way more processing threads in the servers than needed as they would waste resources.
With this kind of setup you can minimize the internal maintenance overhead of the servers, that could help a lot, especially when your load is sporadic.
For example consider an application where you have ~300 new requests/second. Each request requires on average 2.5 seconds to serve. It means that at any given time you have ~750 requests that need to be handled simultaneously. In this situation you probably want to tune your servers so that they have ~750 processing threads at startup and you might want to add something like ~1000 processing threads at maximum to handle extremely high loads.
Also consider for exactly what do you require a thread for. In the previous example each request was independent from the others, there was no session tracking used. In a more "web-ish" scenario you might have users logged in to your website, and depending on your software used, Apache and/or Tomcat might need to use the same thread to serve the requests that come in one session. In this case, you might need more threads. However as I know Tomcat at least, you won't really need to consider this as it works with thread pools internally anyways. |
105,770 | <p>I want to add a comma in the thousands place for a number.</p>
<p>Would <code>String.Format()</code> be the correct path to take? What format would I use?</p>
| [
{
"answer_id": 105793,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 12,
"selected": true,
"text": "<pre><code>String.Format(\"{0:n}\", 1234); // Output: 1,234.00\nString.Format(\"{0:n0}\", 9876); // No digits after the decimal point. Output: 9,876\n</code></pre>\n"
},
{
"answer_id": 105794,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": false,
"text": "<pre><code>String.Format(\"{0:#,###,###.##}\", MyNumber)\n</code></pre>\n\n<p>That will give you commas at the relevant points.</p>\n"
},
{
"answer_id": 194902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Note that the value that you're formatting should be numeric.\nIt doesn't look like it will take a string representation of a number and format is with commas.</p>\n"
},
{
"answer_id": 295821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<pre><code>int number = 1000000000;\nstring whatYouWant = number.ToString(\"#,##0\");\n//You get: 1,000,000,000\n</code></pre>\n"
},
{
"answer_id": 2875323,
"author": "p.campbell",
"author_id": 23199,
"author_profile": "https://Stackoverflow.com/users/23199",
"pm_score": 4,
"selected": false,
"text": "<pre><code>int num = 98765432;\nConsole.WriteLine(string.Format(\"{0:#,#}\", num));\n</code></pre>\n"
},
{
"answer_id": 3965472,
"author": "alchemical",
"author_id": 61639,
"author_profile": "https://Stackoverflow.com/users/61639",
"pm_score": 9,
"selected": false,
"text": "<p>I found this to be the simplest way:</p>\n\n<pre><code>myInteger.ToString(\"N0\")\n</code></pre>\n"
},
{
"answer_id": 4022273,
"author": "prabir",
"author_id": 157260,
"author_profile": "https://Stackoverflow.com/users/157260",
"pm_score": 7,
"selected": false,
"text": "<p>If you want culture specific, you might want to try this:</p>\n<p>use namespace:"using System.Globalization;"</p>\n<p><code>(19950000.0).ToString("N",new CultureInfo("en-US"))</code> = 19,950,000.00</p>\n<p><code>(19950000.0).ToString("N",new CultureInfo("is-IS"))</code> = 19.950.000,00</p>\n<p>Indian culture:\n<code>(19950000.0).ToString("N",new CultureInfo("hi-IN"))</code>= 1,99,50,000.00</p>\n<p>Note: Some cultures use <code>,</code> to mean decimal rather than <code>.</code> so be careful.</p>\n"
},
{
"answer_id": 11012418,
"author": "8 John Volante",
"author_id": 1452875,
"author_profile": "https://Stackoverflow.com/users/1452875",
"pm_score": -1,
"selected": false,
"text": "<p>The method I used to not worry anymore about cultures and potential formatting issues is that I formatted it as currency and took out the currency symbol afterwards.</p>\n\n<p><code>if (decimal.TryParse(tblCell, out result))</code></p>\n\n<pre><code>{\n formattedValue = result.ToString(\"C\").Substring(1);\n}\n</code></pre>\n"
},
{
"answer_id": 13039425,
"author": "cmujica",
"author_id": 491479,
"author_profile": "https://Stackoverflow.com/users/491479",
"pm_score": 4,
"selected": false,
"text": "<p>For example <code>String.Format(\"{0:0,0}\", 1);</code> returns 01, for me is not valid</p>\n\n<p>This works for me</p>\n\n<pre><code>19950000.ToString(\"#,#\", CultureInfo.InvariantCulture));\n</code></pre>\n\n<p>output\n19,950,000</p>\n"
},
{
"answer_id": 15168787,
"author": "CoderTao",
"author_id": 122228,
"author_profile": "https://Stackoverflow.com/users/122228",
"pm_score": 7,
"selected": false,
"text": "<p>Standard formats, with their related outputs,</p>\n\n<pre><code>Console.WriteLine(\"Standard Numeric Format Specifiers\");\nString s = String.Format(\"(C) Currency: . . . . . . . . {0:C}\\n\" +\n \"(D) Decimal:. . . . . . . . . {0:D}\\n\" +\n \"(E) Scientific: . . . . . . . {1:E}\\n\" +\n \"(F) Fixed point:. . . . . . . {1:F}\\n\" +\n \"(G) General:. . . . . . . . . {0:G}\\n\" +\n \" (default):. . . . . . . . {0} (default = 'G')\\n\" +\n \"(N) Number: . . . . . . . . . {0:N}\\n\" +\n \"(P) Percent:. . . . . . . . . {1:P}\\n\" +\n \"(R) Round-trip: . . . . . . . {1:R}\\n\" +\n \"(X) Hexadecimal:. . . . . . . {0:X}\\n\",\n - 1234, -1234.565F);\nConsole.WriteLine(s);\n</code></pre>\n\n<p>Example output (en-us culture):</p>\n\n<pre><code>(C) Currency: . . . . . . . . ($1,234.00)\n(D) Decimal:. . . . . . . . . -1234\n(E) Scientific: . . . . . . . -1.234565E+003\n(F) Fixed point:. . . . . . . -1234.57\n(G) General:. . . . . . . . . -1234\n (default):. . . . . . . . -1234 (default = 'G')\n(N) Number: . . . . . . . . . -1,234.00\n(P) Percent:. . . . . . . . . -123,456.50 %\n(R) Round-trip: . . . . . . . -1234.565\n(X) Hexadecimal:. . . . . . . FFFFFB2E\n</code></pre>\n"
},
{
"answer_id": 15668208,
"author": "Ravi Desai",
"author_id": 2217216,
"author_profile": "https://Stackoverflow.com/users/2217216",
"pm_score": 4,
"selected": false,
"text": "<p>If you wish to force a \",\" separator regardless of culture (for example in a trace or log message), the following code will work and has the added benefit of telling the next guy who stumbles across it exactly what you are doing.</p>\n\n<pre><code>int integerValue = 19400320; \nstring formatted = string.Format(CultureInfo.InvariantCulture, \"{0:N0}\", integerValue);\n</code></pre>\n\n<p>sets formatted to \"19,400,320\"</p>\n"
},
{
"answer_id": 20257270,
"author": "Ali",
"author_id": 1661809,
"author_profile": "https://Stackoverflow.com/users/1661809",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to show it in DataGridview , you should change its type , because default is String and since you change it to decimal it considers as Number with floating point </p>\n\n<pre><code>Dim dt As DataTable = New DataTable\ndt.Columns.Add(\"col1\", GetType(Decimal))\ndt.Rows.Add(1)\ndt.Rows.Add(10)\ndt.Rows.Add(2)\n\nDataGridView1.DataSource = dt\n</code></pre>\n"
},
{
"answer_id": 27619220,
"author": "dunwan",
"author_id": 1390025,
"author_profile": "https://Stackoverflow.com/users/1390025",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a function such as this to format numbers and optionally pass in the desired decimal places. If decimal places are not specified it will use two decimal places.</p>\n\n<pre><code> public static string formatNumber(decimal valueIn=0, int decimalPlaces=2)\n {\n return string.Format(\"{0:n\" + decimalPlaces.ToString() + \"}\", valueIn);\n }\n</code></pre>\n\n<p>I use decimal but you can change the type to any other or use an anonymous object. You could also add error checking for negative decimal place values.</p>\n"
},
{
"answer_id": 31330178,
"author": "Dennis",
"author_id": 2796794,
"author_profile": "https://Stackoverflow.com/users/2796794",
"pm_score": 6,
"selected": false,
"text": "<p>This is the best format. Works in all of those cases:</p>\n\n<pre><code>String.Format( \"{0:#,##0.##}\", 0 ); // 0\nString.Format( \"{0:#,##0.##}\", 0.5 ); // 0.5 - some of the formats above fail here. \nString.Format( \"{0:#,##0.##}\", 12314 ); // 12,314\nString.Format( \"{0:#,##0.##}\", 12314.23123 ); // 12,314.23\nString.Format( \"{0:#,##0.##}\", 12314.2 ); // 12,314.2\nString.Format( \"{0:#,##0.##}\", 1231412314.2 ); // 1,231,412,314.2\n</code></pre>\n"
},
{
"answer_id": 31955257,
"author": "von v.",
"author_id": 815073,
"author_profile": "https://Stackoverflow.com/users/815073",
"pm_score": 6,
"selected": false,
"text": "<p>The most voted answer was great and has been helpful for about 7 years. With the introduction of C# 6.0 and specifically the String Interpolation there's a neater and, IMO safer, way to do what has been asked <code>to add commas in thousands place for a number</code>:</p>\n\n<pre><code>var i = 5222000;\nvar s = $\"{i:n} is the number\"; // results to > 5,222,000.00 is the number\ns = $\"{i:n0} has no decimal\"; // results to > 5,222,000 has no decimal\n</code></pre>\n\n<p>Where the variable <code>i</code> is put in place of the placeholder (i.e. <code>{0}</code>). So there's no need to remember which object goes to which position. The formatting (i.e. <code>:n</code>) hasn't changed. For a complete feature of what's new, you may <a href=\"https://msdn.microsoft.com/en-us/magazine/dn879355.aspx\">go to this page</a>.</p>\n"
},
{
"answer_id": 40389099,
"author": "brakeroo",
"author_id": 7070657,
"author_profile": "https://Stackoverflow.com/users/7070657",
"pm_score": 4,
"selected": false,
"text": "<p>Simpler, using string interpolation instead of String.Format</p>\n\n<pre><code> $\"{12456:n0}\"; // 12,456\n $\"{12456:n2}\"; // 12,456.00\n</code></pre>\n\n<p>or using yourVariable</p>\n\n<pre><code> double yourVariable = 12456.0;\n $\"{yourVariable:n0}\"; \n $\"{yourVariable:n2}\"; \n</code></pre>\n"
},
{
"answer_id": 42419283,
"author": "Yitzhak Weinberg",
"author_id": 4871015,
"author_profile": "https://Stackoverflow.com/users/4871015",
"pm_score": 5,
"selected": false,
"text": "<p>The following example displays several values that are formatted by using custom format strings that include zero placeholders.</p>\n\n<pre><code>String.Format(\"{0:N1}\", 29255.0);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>29255.0.ToString(\"N1\")\n</code></pre>\n\n<p>result \"29,255.0\"</p>\n\n<pre><code>String.Format(\"{0:N2}\", 29255.0);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>29255.0.ToString(\"N2\")\n</code></pre>\n\n<p>result \"29,255.00\"</p>\n"
},
{
"answer_id": 45853346,
"author": "amdev",
"author_id": 5354341,
"author_profile": "https://Stackoverflow.com/users/5354341",
"pm_score": 5,
"selected": false,
"text": "<p>just simple as this: </p>\n\n<pre><code>float num = 23658; // for example \nnum = num.ToString(\"N0\"); // Returns 23,658\n</code></pre>\n\n<p>more info is in <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings\" rel=\"noreferrer\">Here</a></p>\n"
},
{
"answer_id": 48766729,
"author": "Abolfazl Rastgou",
"author_id": 8259471,
"author_profile": "https://Stackoverflow.com/users/8259471",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String.Format(\"0,###.###\"); also works with decimal places\n</code></pre>\n"
},
{
"answer_id": 54606626,
"author": "Mark Z.",
"author_id": 5938759,
"author_profile": "https://Stackoverflow.com/users/5938759",
"pm_score": 4,
"selected": false,
"text": "<p>C# 7.1 (perhaps earlier?) makes this as easy and nice-looking as it should be, with string interpolation:</p>\n<pre><code>var jackpot = 1_000_000; // underscore separators in numeric literals also available since C# 7.0\nvar niceNumberString = $"Jackpot is {jackpot:n}";\nvar niceMoneyString = $"Jackpot is {jackpot:C}";\n</code></pre>\n"
},
{
"answer_id": 67434558,
"author": "belal ahmad",
"author_id": 7289038,
"author_profile": "https://Stackoverflow.com/users/7289038",
"pm_score": 2,
"selected": false,
"text": "<p>You want same Format value and culture specific.</p>\n<pre><code> Double value= 1234567;\n value.ToString("#,#.##", CultureInfo.CreateSpecificCulture("hi-IN"));\n</code></pre>\n<p>Output: 12,34,567</p>\n"
},
{
"answer_id": 70309316,
"author": "Yusuff Sodiq",
"author_id": 7162741,
"author_profile": "https://Stackoverflow.com/users/7162741",
"pm_score": 1,
"selected": false,
"text": "<p>I tried many of the suggestions above but the below work better for me:</p>\n<pre><code>string.Format("{0:##,###.00}", myValue)\n</code></pre>\n<p>but this fails when you have values like 0.2014 where it gives .21 For this I use</p>\n<pre><code>string.Format("{0:#,##0.00}", myValue)\n</code></pre>\n"
},
{
"answer_id": 72783657,
"author": "Sepideh I",
"author_id": 1826353,
"author_profile": "https://Stackoverflow.com/users/1826353",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n<pre><code>var number = 123456789;\nvar str = number.ToString("N0");\n</code></pre>\n<p>Result is: "123,456,789"</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
]
| I want to add a comma in the thousands place for a number.
Would `String.Format()` be the correct path to take? What format would I use? | ```
String.Format("{0:n}", 1234); // Output: 1,234.00
String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876
``` |
105,776 | <p>I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.</p>
<p>I tried using MySQL Administrator, but I got the following error:</p>
<blockquote>
<p>The selected file was generated by
mysqldump and cannot be restored by
this application.</p>
</blockquote>
<p>How do I get this working?</p>
| [
{
"answer_id": 105798,
"author": "Justin Bennett",
"author_id": 271,
"author_profile": "https://Stackoverflow.com/users/271",
"pm_score": 10,
"selected": true,
"text": "<p>It should be as simple as running this: </p>\n\n<pre><code>mysql -u <user> -p < db_backup.dump\n</code></pre>\n\n<p>If the dump is of a single database you may have to add a line at the top of the file:</p>\n\n<pre><code>USE <database-name-here>;\n</code></pre>\n\n<p>If it was a dump of many databases, the use statements are already in there.</p>\n\n<p>To run these commands, open up a command prompt (in Windows) and <code>cd</code> to the directory where the <code>mysql.exe</code> executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above.</p>\n"
},
{
"answer_id": 105821,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 5,
"selected": false,
"text": "<p>When we make a dump file with <code>mysqldump</code>, what it contains is a big SQL script for recreating the databse contents. So we restore it by using starting up MySQL’s command-line client:</p>\n\n<pre><code>mysql -uroot -p \n</code></pre>\n\n<p>(where <code>root</code> is our admin user name for MySQL), and once connected to the database we need commands to create the database and read the file in to it:</p>\n\n<pre><code>create database new_db;\nuse new_db;\n\\. dumpfile.sql\n</code></pre>\n\n<p>Details will vary according to which options were used when creating the dump file.</p>\n"
},
{
"answer_id": 105898,
"author": "vog",
"author_id": 19163,
"author_profile": "https://Stackoverflow.com/users/19163",
"pm_score": 8,
"selected": false,
"text": "<p>You simply need to run this:</p>\n\n<pre><code>mysql -p -u[user] [database] < db_backup.dump\n</code></pre>\n\n<p>If the dump contains multiple databases you should omit the database name:</p>\n\n<pre><code>mysql -p -u[user] < db_backup.dump\n</code></pre>\n\n<p>To run these commands, open up a command prompt (in Windows) and <code>cd</code> to the directory where the <code>mysql.exe</code> executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command.</p>\n"
},
{
"answer_id": 157696,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 4,
"selected": false,
"text": "<p>I got it to work following these steps…</p>\n\n<ol>\n<li><p>Open MySQL Administrator and connect to server</p></li>\n<li><p>Select \"Catalogs\" on the left</p></li>\n<li><p>Right click in the lower-left box and choose \"Create New Schema\"</p>\n\n<p><a href=\"http://img204.imageshack.us/img204/7528/adminsx9.th.gif\" rel=\"noreferrer\">MySQL Administrator http://img204.imageshack.us/img204/7528/adminsx9.th.gif</a> <a href=\"http://img204.imageshack.us/img204/7528/adminsx9.gif\" rel=\"noreferrer\">enlarge image</a></p></li>\n<li><p>Name the new schema (example: \"dbn\")</p>\n\n<p><a href=\"http://img262.imageshack.us/img262/4374/newwa4.th.gif\" rel=\"noreferrer\">MySQL New Schema http://img262.imageshack.us/img262/4374/newwa4.th.gif</a> <a href=\"http://img262.imageshack.us/img262/4374/newwa4.gif\" rel=\"noreferrer\">enlarge image</a></p></li>\n<li><p>Open Windows Command Prompt (cmd)</p>\n\n<p><a href=\"http://img206.imageshack.us/img206/941/startef7.th.gif\" rel=\"noreferrer\">Windows Command Prompt http://img206.imageshack.us/img206/941/startef7.th.gif</a> <a href=\"http://img206.imageshack.us/img206/941/startef7.gif\" rel=\"noreferrer\">enlarge image</a></p></li>\n<li><p>Change directory to MySQL installation folder</p></li>\n<li><p>Execute command:</p>\n\n<pre><code>mysql -u root -p dbn < C:\\dbn_20080912.dump\n</code></pre>\n\n<p>…where \"root\" is the name of the user, \"dbn\" is the database name, and \"C:\\dbn_20080912.dump\" is the path/filename of the mysqldump .dump file</p>\n\n<p><a href=\"http://img388.imageshack.us/img388/2489/cmdjx0.th.gif\" rel=\"noreferrer\">MySQL dump restore command line http://img388.imageshack.us/img388/2489/cmdjx0.th.gif</a> <a href=\"http://img388.imageshack.us/img388/2489/cmdjx0.gif\" rel=\"noreferrer\">enlarge image</a></p></li>\n<li><p>Enjoy!</p></li>\n</ol>\n"
},
{
"answer_id": 275575,
"author": "user26087",
"author_id": 26087,
"author_profile": "https://Stackoverflow.com/users/26087",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use the restore menu in MySQL Administrator. You just have to open the back-up file, and then click the restore button.</p>\n"
},
{
"answer_id": 971858,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 10,
"selected": false,
"text": "<p>If the database you want to restore doesn't already exist, you need to create it first.</p>\n\n<p>On the command-line, if you're in the same directory that contains the dumped file, use these commands (with appropriate substitutions):</p>\n\n<pre><code>C:\\> mysql -u root -p\n\nmysql> create database mydb;\nmysql> use mydb;\nmysql> source db_backup.dump;\n</code></pre>\n"
},
{
"answer_id": 998423,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot use the Restore menu in MySQL Admin if the backup / dump wasn't created from there. It's worth a shot though. If you choose to \"ignore errors\" with the checkbox for that, it will say it completed successfully, although it clearly exits with only a fraction of rows imported...this is with a dump, mind you.</p>\n"
},
{
"answer_id": 9157300,
"author": "Hengjie",
"author_id": 914986,
"author_profile": "https://Stackoverflow.com/users/914986",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to view the progress of the dump try this:</p>\n\n<p><code>pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME</code></p>\n\n<p>You'll of course need 'pv' installed. This command works only on *nix.</p>\n"
},
{
"answer_id": 12052821,
"author": "Ashwin A",
"author_id": 679766,
"author_profile": "https://Stackoverflow.com/users/679766",
"pm_score": 4,
"selected": false,
"text": "<p>You can try <a href=\"http://www.webyog.com\" rel=\"noreferrer\">SQLyog</a> 'Execute SQL script' tool to import sql/dump files. </p>\n\n<p><img src=\"https://i.stack.imgur.com/i2zon.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 14143512,
"author": "Jerome_B",
"author_id": 590442,
"author_profile": "https://Stackoverflow.com/users/590442",
"pm_score": 3,
"selected": false,
"text": "<p>Using a 200MB dump file created on Linux to restore on Windows w/ mysql 5.5 , I had more success with the</p>\n\n<pre><code>source file.sql\n</code></pre>\n\n<p>approach from the mysql prompt than with the</p>\n\n<pre><code>mysql < file.sql\n</code></pre>\n\n<p>approach on the command line, that caused some Error 2006 \"server has gone away\" (on windows)</p>\n\n<p>Weirdly, the service created during (mysql) install refers to a my.ini file that did not exist. I copied the \"large\" example file to my.ini \nwhich I already had modified with the advised increases. </p>\n\n<p>My values are</p>\n\n<pre><code>[mysqld]\nmax_allowed_packet = 64M\ninteractive_timeout = 250\nwait_timeout = 250\n</code></pre>\n"
},
{
"answer_id": 16902160,
"author": "womd",
"author_id": 657525,
"author_profile": "https://Stackoverflow.com/users/657525",
"pm_score": 6,
"selected": false,
"text": "<pre><code>mysql -u username -p -h localhost DATA-BASE-NAME < data.sql\n</code></pre>\n\n<p>look <a href=\"http://www.cyberciti.biz/faq/import-mysql-dumpfile-sql-datafile-into-my-database/\">here - step 3</a>: this way you dont need the USE statement</p>\n"
},
{
"answer_id": 36307683,
"author": "vkrishna17",
"author_id": 3597604,
"author_profile": "https://Stackoverflow.com/users/3597604",
"pm_score": 3,
"selected": false,
"text": "<pre><code>./mysql -u <username> -p <password> -h <host-name like localhost> <database-name> < db_dump-file\n</code></pre>\n"
},
{
"answer_id": 41644285,
"author": "Michael",
"author_id": 328326,
"author_profile": "https://Stackoverflow.com/users/328326",
"pm_score": 4,
"selected": false,
"text": "<p>As a specific example of a previous answer:</p>\n\n<p>I needed to restore a backup so I could import/migrate it into SQL Server. I installed MySql only, but did not register it as a service or add it to my path as I don't have the need to keep it running. </p>\n\n<p>I used windows explorer to put my dump file in C:\\code\\dump.sql. Then opened MySql from the start menu item. Created the DB, then ran the source command with the full path like so:</p>\n\n<pre><code>mysql> create database temp\nmysql> use temp\nmysql> source c:\\code\\dump.sql\n</code></pre>\n"
},
{
"answer_id": 47995250,
"author": "Jossef Harush Kadouri",
"author_id": 3191896,
"author_profile": "https://Stackoverflow.com/users/3191896",
"pm_score": 2,
"selected": false,
"text": "<p>One-liner command to restore the generated SQL from <code>mysqldump</code></p>\n\n<pre><code>mysql -u <username> -p<password> -e \"source <path to sql file>;\"\n</code></pre>\n"
},
{
"answer_id": 49569208,
"author": "Javeed Shakeel",
"author_id": 8295551,
"author_profile": "https://Stackoverflow.com/users/8295551",
"pm_score": 5,
"selected": false,
"text": "<p>Run the command to enter into the DB </p>\n\n<pre><code> # mysql -u root -p \n</code></pre>\n\n<p>Enter the password for the user Then Create a New DB </p>\n\n<pre><code>mysql> create database MynewDB;\nmysql> exit\n</code></pre>\n\n<p>And make exit.Afetr that.Run this Command</p>\n\n<pre><code># mysql -u root -p MynewDB < MynewDB.sql\n</code></pre>\n\n<p>Then enter into the db and type</p>\n\n<pre><code>mysql> show databases;\nmysql> use MynewDB;\nmysql> show tables;\nmysql> exit\n</code></pre>\n\n<p>Thats it ........ Your dump will be restored from one DB to another DB</p>\n\n<p><strong>Or else there is an Alternate way for dump restore</strong></p>\n\n<pre><code># mysql -u root -p \n</code></pre>\n\n<p>Then enter into the db and type</p>\n\n<pre><code>mysql> create database MynewDB;\nmysql> show databases;\nmysql> use MynewDB;\nmysql> source MynewDB.sql;\nmysql> show tables;\nmysql> exit\n</code></pre>\n"
},
{
"answer_id": 54545347,
"author": "CTS_AE",
"author_id": 349659,
"author_profile": "https://Stackoverflow.com/users/349659",
"pm_score": 0,
"selected": false,
"text": "<h1>How to Restore MySQL Database with MySQLWorkbench</h1>\n\n<p>You can run the drop and create commands in a query tab.</p>\n\n<h2>Drop the Schema if it Currently Exists</h2>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DROP DATABASE `your_db_name`;\n</code></pre>\n\n<h2>Create a New Schema</h2>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE SCHEMA `your_db_name`;\n</code></pre>\n\n<h2>Open Your Dump File</h2>\n\n<p><a href=\"https://i.stack.imgur.com/eUYHJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eUYHJ.png\" alt=\"MySQLWorkbench open sql file\"></a></p>\n\n<ol>\n<li>Click the <strong>Open an SQL script in a new query tab</strong> icon and choose your db dump file.</li>\n<li>Then Click <strong>Run SQL Script...</strong></li>\n<li>It will then let you preview the first lines of the SQL dump script.</li>\n<li>You will then choose the <strong>Default Schema Name</strong></li>\n<li>Next choose the <strong>Default Character Set</strong> utf8 is normally a safe bet, but you may be able to discern it from looking at the preview lines for something like <strong>character_set</strong>.</li>\n<li>Click <strong>Run</strong></li>\n<li>Be patient for large DB restore scripts and watch as your drive space melts away! </li>\n</ol>\n"
},
{
"answer_id": 56589379,
"author": "Suragch",
"author_id": 3681880,
"author_profile": "https://Stackoverflow.com/users/3681880",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you already have the blank database created, you can also restore a database from the command line like this:</p>\n<pre><code>mysql databasename < backup.sql\n</code></pre>\n"
},
{
"answer_id": 69474133,
"author": "Raja G",
"author_id": 1293013,
"author_profile": "https://Stackoverflow.com/users/1293013",
"pm_score": 1,
"selected": false,
"text": "<p>If you are already inside <code>mysql</code> prompt and assume your dump file <code>dump.sql</code>, then we can also use command as below to restore the dump</p>\n<pre class=\"lang-sh prettyprint-override\"><code>mysql> \\. dump.sql\n</code></pre>\n<p>If your dump size is larger set <code>max_allowed_packet</code> value to higher. Setting this value will help you to faster restoring of dump.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
]
| I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.
I tried using MySQL Administrator, but I got the following error:
>
> The selected file was generated by
> mysqldump and cannot be restored by
> this application.
>
>
>
How do I get this working? | It should be as simple as running this:
```
mysql -u <user> -p < db_backup.dump
```
If the dump is of a single database you may have to add a line at the top of the file:
```
USE <database-name-here>;
```
If it was a dump of many databases, the use statements are already in there.
To run these commands, open up a command prompt (in Windows) and `cd` to the directory where the `mysql.exe` executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above. |
105,777 | <p>I've an issue with the same piece of code running fine on my live website but not on my local development server.</p>
<p>I've an Ajax function that updates a div. The following code works on the live site:</p>
<pre>self.xmlHttpReq.open("POST", PageURL, true);
self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);
//..update div stuff...
self.xmlHttpReq.send(QueryString);</pre>
<p>When I try to run this on my local machine, nothing is passed to the QueryString.</p>
<p>However, to confuse matters, the following code <strong>does</strong> work locally:</p>
<pre>self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
//..div update stuff..
self.xmlHttpReq.send(QueryString);</pre>
<p>But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)!</p>
<p>I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue.</p>
<p>Live Site is running IIS 6 (on a WIN 2003 box I think)</p>
<p>Local Site is running IIS 5.1 (On XP Pro)</p>
<p>Are there some updates or something I'm missing or something?</p>
| [
{
"answer_id": 105828,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a reason you're explicitly setting the <code>Content-Length</code> header in the first example? You... <em>shouldn't</em> need to do this, and i wouldn't be surprised to find it causing problems. </p>\n\n<p>Oh, and check your encoding routine. The rules are not <em>quite</em> the same for querystrings and POSTed form data.</p>\n"
},
{
"answer_id": 105849,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>I would guess that Shog9 is right, and that IIS 6 i smart enough to ignore your request and send the correct headers, while 5.2 throws an error.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I've an issue with the same piece of code running fine on my live website but not on my local development server.
I've an Ajax function that updates a div. The following code works on the live site:
```
self.xmlHttpReq.open("POST", PageURL, true);
self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);
//..update div stuff...
self.xmlHttpReq.send(QueryString);
```
When I try to run this on my local machine, nothing is passed to the QueryString.
However, to confuse matters, the following code **does** work locally:
```
self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
//..div update stuff..
self.xmlHttpReq.send(QueryString);
```
But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)!
I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue.
Live Site is running IIS 6 (on a WIN 2003 box I think)
Local Site is running IIS 5.1 (On XP Pro)
Are there some updates or something I'm missing or something? | Is there a reason you're explicitly setting the `Content-Length` header in the first example? You... *shouldn't* need to do this, and i wouldn't be surprised to find it causing problems.
Oh, and check your encoding routine. The rules are not *quite* the same for querystrings and POSTed form data. |
105,810 | <p>Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).</p>
<p>In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)</p>
<p>Here's the code in C# - problem is this doesn't work for values above 127. Any ideas?</p>
<p>Calling code :</p>
<pre><code>// S is Hex number!!!
return Convert.ToChar(HexStringToInt(s)).ToString();
</code></pre>
<p>Helper method:</p>
<pre><code>private static int HexStringToInt(string hexString)
{
int i;
try
{
i = Int32.Parse(hexString, NumberStyles.HexNumber);
}
catch (Exception ex)
{
throw new ApplicationException("Error trying to convert hex value: " + hexString, ex);
}
return i;
}
</code></pre>
| [
{
"answer_id": 105823,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 0,
"selected": false,
"text": "<pre><code>private static int HexStringToInt(string hexString)\n{\n try\n {\n return Convert.ToChar(hexString);\n }\n catch (FormatException ex)\n {\n throw new ArgumentException(\"Is not a valid hex character.\", \"hexString\", ex);\n }\n // Convert.ToChar() will throw an ArgumentException also\n // if hexString is bad\n}\n</code></pre>\n"
},
{
"answer_id": 105911,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 0,
"selected": false,
"text": "<p>My guess would be that a Char in .NET is actually two bytes (16 bits), as they are UTF-16 encoded. Maybe you are only catching/writing the first byte of the value?</p>\n\n<p>Basically, are you doing something with the char value afterwards that assumes it is 8-bits instead of 16, and is therefore truncating it?</p>\n"
},
{
"answer_id": 105986,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 0,
"selected": false,
"text": "<p>You are probably using the default character encoding when reading in the RTF file, which is UTF-8, when the RTF file is actually stored using the \"windows-1252\" extended ASCII latin encoding.</p>\n\n<p>C# strings use a 16 unicode bit wide character format. Translating windows-1252 character 0x85 to its unicode equivalent involves a complicated mapping, since the the code points (character numbers) are very different. Luckily Windows can do the work for you.</p>\n\n<p>You can change the way the characters are converted when reading in the text by explicitly specifying the source encoding when opening the stream.</p>\n\n<pre><code>using System.IO;\nusing System.Text.Encoding;\n\nusing (TextReader tr = new StreamReader(path_to_RTF_file, Encoding.GetEncoding(1252)))\n{\n // Read from the file as usual.\n}\n</code></pre>\n"
},
{
"answer_id": 106003,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": 1,
"selected": false,
"text": "<p>Your original code works prefectly fine for me. It is able to convert any Hex from 00 to FF into the appropriate character. Using vs2008.</p>\n"
},
{
"answer_id": 106018,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 2,
"selected": false,
"text": "<p>This looks like a character encoding issue to me. Unicode doesn't include any characters with numbers in the upper-ASCII 128-255 range, so trying to convert character 133 will fail.</p>\n\n<p>Need to convert it first to a character using the proper decoding, Convert.toChar appears to be using UTF-16.</p>\n\n<p>Sometimes there's a manual bit manipulation hack to convert the character from upper ASCII to the appropriate unicode char, but since the ellipsis wasn't in most of the widely used extended ASCII codepages, that's unlikely to work here.</p>\n\n<p>What you really want to do is use the <a href=\"http://msdn.microsoft.com/en-us/library/744y86tc.aspx\" rel=\"nofollow noreferrer\">Encoding.GetString(Byte[])</a> method, with the proper encoding. Put your value into a byte array, then GetString to get the C# native string for the character.</p>\n\n<p>You can learn more about RTF character encodings on the <a href=\"http://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding\" rel=\"nofollow noreferrer\">RTF Wikipedia page</a>.</p>\n\n<p>FYI: The horizontal ellipsis is <a href=\"http://unicode.org/charts/PDF/U2000.pdf\" rel=\"nofollow noreferrer\">character U+2026 (pdf)</a>.</p>\n"
},
{
"answer_id": 107348,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here's some rough code that should work for you:</p>\n\n<pre><code>// Convert hex number, which represents an RTF code-page escaped character, \n// to the desired character (uses '85' from your example as a literal):\nvar number = int.Parse(\"85\", System.Globalization.NumberStyles.HexNumber);\nDebug.Assert(number <= byte.MaxValue); \n\nbyte[] bytes = new byte[1] { (byte)number };\nchar[] chars = Encoding.GetEncoding(1252).GetString(bytes).ToCharArray();\n// or, use:\n// char[] chars = Encoding.Default.GetString(bytes).ToCharArray(); \n\nstring result = new string(chars);\n</code></pre>\n"
},
{
"answer_id": 452505,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Just use this function I modified (very slightly) from Chris' website:</p>\n\n<pre><code> private static string charScrubber(string content)\n {\n StringBuilder sbTemp = new StringBuilder(content.Length);\n foreach (char currentChar in content)\n {\n if ((currentChar != 127 && currentChar > 1))\n {\n sbTemp.Append(currentChar);\n }\n }\n\n content = sbTemp.ToString();\n return content;\n }\n</code></pre>\n\n<p>You can modify the \"current Char\" condition to remove whatever character is needed to be eliminated (as appearing here, you will not get any 0x00 characters, or the (char)127, or 0x57 character).</p>\n\n<p>ASCII/Hex table here: <a href=\"http://www.cs.mun.ca/~michael/c/ascii-table.html\" rel=\"nofollow noreferrer\">http://www.cs.mun.ca/~michael/c/ascii-table.html</a></p>\n\n<p>Chris' site: <a href=\"http://seattlesoftware.wordpress.com/2008/09/11/hexadecimal-value-0-is-an-invalid-character/\" rel=\"nofollow noreferrer\">http://seattlesoftware.wordpress.com/2008/09/11/hexadecimal-value-0-is-an-invalid-character/</a></p>\n\n<p>-Tom</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19327/"
]
| Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).
In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)
Here's the code in C# - problem is this doesn't work for values above 127. Any ideas?
Calling code :
```
// S is Hex number!!!
return Convert.ToChar(HexStringToInt(s)).ToString();
```
Helper method:
```
private static int HexStringToInt(string hexString)
{
int i;
try
{
i = Int32.Parse(hexString, NumberStyles.HexNumber);
}
catch (Exception ex)
{
throw new ApplicationException("Error trying to convert hex value: " + hexString, ex);
}
return i;
}
``` | This looks like a character encoding issue to me. Unicode doesn't include any characters with numbers in the upper-ASCII 128-255 range, so trying to convert character 133 will fail.
Need to convert it first to a character using the proper decoding, Convert.toChar appears to be using UTF-16.
Sometimes there's a manual bit manipulation hack to convert the character from upper ASCII to the appropriate unicode char, but since the ellipsis wasn't in most of the widely used extended ASCII codepages, that's unlikely to work here.
What you really want to do is use the [Encoding.GetString(Byte[])](http://msdn.microsoft.com/en-us/library/744y86tc.aspx) method, with the proper encoding. Put your value into a byte array, then GetString to get the C# native string for the character.
You can learn more about RTF character encodings on the [RTF Wikipedia page](http://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding).
FYI: The horizontal ellipsis is [character U+2026 (pdf)](http://unicode.org/charts/PDF/U2000.pdf). |
105,816 | <p>I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char ** (array of strings). If I declare my function as <code>(_fun _pointer -> _pointer)</code>, how do I convert the result to a list of strings in scheme?</p>
<p>Here are the relevant C-declarations:</p>
<pre><code>typedef char **MYSQL_ROW; /* return data as array of strings */
// ...
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
</code></pre>
| [
{
"answer_id": 105938,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 0,
"selected": false,
"text": "<p>I know it's not exactly what you are looking for, but it might help a little bit. I've done some work on a basic Gambit Scheme FFI for MySQL. I don't know how PLT Scheme and Gambit differ in terms of their FFI implementation (I'd venture with \"quite a bit\") but maybe you can get something out of it:</p>\n\n<p><a href=\"http://bunny.jonnay.net/zengarden/trunk/lib/mysql/mysql-ffi.scm\" rel=\"nofollow noreferrer\">http://bunny.jonnay.net/zengarden/trunk/lib/mysql/mysql-ffi.scm</a></p>\n"
},
{
"answer_id": 105990,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 2,
"selected": true,
"text": "<p>I <em>think</em> that what you want is the cvector:</p>\n\n<p><a href=\"http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)\" rel=\"nofollow noreferrer\">http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)</a></p>\n\n<p>A cvector of _string/utf-8 or whichever encoding you need seems reasanable.</p>\n\n<p>But that's from a quick survey of the docs - I haven't tried this myself. Please let me know if it works!</p>\n"
},
{
"answer_id": 106133,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 0,
"selected": false,
"text": "<p>Aha, I figured it out myself.</p>\n\n<p>I have to use the <code>_cpointer</code> procedure, described at the page that mike linked to:</p>\n\n<pre><code>(_fun _pointer -> (_cpointer/null 'mysql-row (make-ctype _pointer #f #f)))\n</code></pre>\n\n<p>It also seems that <a href=\"http://software.pupeno.com/mr-mysql/libmysqlclient.scm\" rel=\"nofollow noreferrer\">someone already beat me</a> to creating a ffi to mysqlclient. Not to worry; My main goal is understanding the ffi api, and it's going forward.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18180/"
]
| I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char \*\* (array of strings). If I declare my function as `(_fun _pointer -> _pointer)`, how do I convert the result to a list of strings in scheme?
Here are the relevant C-declarations:
```
typedef char **MYSQL_ROW; /* return data as array of strings */
// ...
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
``` | I *think* that what you want is the cvector:
<http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)>
A cvector of \_string/utf-8 or whichever encoding you need seems reasanable.
But that's from a quick survey of the docs - I haven't tried this myself. Please let me know if it works! |
105,852 | <p>After reading "<a href="http://web.archive.org/web/20090117062700/http://stackoverflow.com:80/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity" rel="noreferrer">What’s your/a good limit for cyclomatic complexity?</a>", I realize many of my colleagues were quite annoyed with this new <a href="http://en.wikipedia.org/wiki/Quality_assurance" rel="noreferrer">QA</a> policy on our project: no more 10 <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">cyclomatic complexity</a> per function.</p>
<p>Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in '<a href="https://stackoverflow.com/questions/105007/do-you-test-private-method#105114">Do you test private method?</a>', such a policy has many good side-effects.</p>
<p>But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of '<a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="noreferrer">Aspect-oriented programming</a>' approach for logs).</p>
<pre><code>myLogger.info("A String");
myLogger.fine("A more complicated String");
...
</code></pre>
<p>And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the <em>log parameters</em> (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place!</p>
<p>So QA came back and urged our programmers to do conditional logging. Always.</p>
<pre><code>if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String");
if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String");
...
</code></pre>
<p>But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity!</p>
<p>So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be <em>really</em> part of said complexity of that function...</p>
<p>How would you address this situation ?<br>
I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first.</p>
<hr>
<p>Thank you for all the answers.<br>
I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)<br>
So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the <em>obligation</em> to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...)</p>
<p>I now get the '<a href="http://en.wikipedia.org/wiki/Variadic_function" rel="noreferrer">variadic</a> function' point advanced by some of you (thank you John).<br>
Note: a quick test in java6 shows that my <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">varargs function</a> does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it.</p>
<p>I have now posted my experience on this topic.<br>
I will leave it there until next Tuesday for voting, then I will select one of your answers.<br>
Again, thank you for all the suggestions :)</p>
| [
{
"answer_id": 105876,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 2,
"selected": false,
"text": "<p>In C or C++ I'd use the preprocessor instead of the if statements for the conditional logging.</p>\n"
},
{
"answer_id": 105905,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Pass the log level to the logger and let it decide whether or not to write the log statement:</p>\n\n<pre><code>//if(myLogger.isLoggable(Level.INFO) {myLogger.info(\"A String\");\nmyLogger.info(Level.INFO,\"A String\");\n</code></pre>\n\n<p>UPDATE: Ah, I see that you want to conditionally create the log string without a conditional statement. Presumably at runtime rather than compile time.</p>\n\n<p>I'll just say that the way we've solved this is to put the formatting code in the logger class so that the formatting only takes place if the level passes. Very similar to a built-in sprintf. For example:</p>\n\n<pre><code>myLogger.info(Level.INFO,\"A String %d\",some_number); \n</code></pre>\n\n<p>That should meet your criteria.</p>\n"
},
{
"answer_id": 105908,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": false,
"text": "<h3>With current logging frameworks, the question is moot</h3>\n\n<p>Current logging frameworks like slf4j or log4j 2 don't require guard statements in most cases. They use a parameterized log statement so that an event can be logged unconditionally, but message formatting only occurs if the event is enabled. Message construction is performed as needed by the logger, rather than pre-emptively by the application.</p>\n\n<p>If you have to use an antique logging library, you can read on to get more background and a way to retrofit the old library with parameterized messages.</p>\n\n<h3>Are guard statements really adding complexity?</h3>\n\n<p>Consider excluding logging guards statements from the cyclomatic complexity calculation.</p>\n\n<p>It could be argued that, due to their predictable form, conditional logging checks really don't contribute to the complexity of the code.</p>\n\n<p>Inflexible metrics can make an otherwise good programmer turn bad. Be careful!</p>\n\n<p>Assuming that your tools for calculating complexity can't be tailored to that degree, the following approach may offer a work-around.</p>\n\n<h3>The need for conditional logging</h3>\n\n<p>I assume that your guard statements were introduced because you had code like this:</p>\n\n<pre><code>private static final Logger log = Logger.getLogger(MyClass.class);\n\nConnection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n{\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle \" + d, ex);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: \" + c);\n return c;\n}\n</code></pre>\n\n<p>In Java, each of the log statements creates a new <code>StringBuilder</code>, and invokes the <code>toString()</code> method on each object concatenated to the string. These <code>toString()</code> methods, in turn, are likely to create <code>StringBuilder</code> instances of their own, and invoke the <code>toString()</code> methods of their members, and so on, across a potentially large object graph. (Before Java 5, it was even more expensive, since <code>StringBuffer</code> was used, and all of its operations are synchronized.)</p>\n\n<p>This can be relatively costly, especially if the log statement is in some heavily-executed code path. And, written as above, that expensive message formatting occurs even if the logger is bound to discard the result because the log level is too high.</p>\n\n<p>This leads to the introduction of guard statements of the form:</p>\n\n<pre><code> if (log.isDebugEnabled())\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n</code></pre>\n\n<p>With this guard, the evaluation of arguments <code>d</code> and <code>w</code> and the string concatenation is performed only when necessary.</p>\n\n<h3>A solution for simple, efficient logging</h3>\n\n<p>However, if the logger (or a wrapper that you write around your chosen logging package) takes a formatter and arguments for the formatter, the message construction can be delayed until it is certain that it will be used, while eliminating the guard statements and their cyclomatic complexity.</p>\n\n<pre><code>public final class FormatLogger\n{\n\n private final Logger log;\n\n public FormatLogger(Logger log)\n {\n this.log = log;\n }\n\n public void debug(String formatter, Object... args)\n {\n log(Level.DEBUG, formatter, args);\n }\n\n … &c. for info, warn; also add overloads to log an exception …\n\n public void log(Level level, String formatter, Object... args)\n {\n if (log.isEnabled(level)) {\n /* \n * Only now is the message constructed, and each \"arg\"\n * evaluated by having its toString() method invoked.\n */\n log.log(level, String.format(formatter, args));\n }\n }\n\n}\n\nclass MyClass \n{\n\n private static final FormatLogger log = \n new FormatLogger(Logger.getLogger(MyClass.class));\n\n Connection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n {\n log.debug(\"Attempting connection of dongle %s to widget %s.\", d, w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle %s.\", d);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: %s\", c);\n return c;\n }\n\n}\n</code></pre>\n\n<p>Now, <strong>none of the cascading <code>toString()</code> calls with their buffer allocations will occur</strong> unless they are necessary! This effectively eliminates the performance hit that led to the guard statements. One small penalty, in Java, would be auto-boxing of any primitive type arguments you pass to the logger.</p>\n\n<p>The code doing the logging is arguably even cleaner than ever, since untidy string concatenation is gone. It can be even cleaner if the format strings are externalized (using a <code>ResourceBundle</code>), which could also assist in maintenance or localization of the software. </p>\n\n<h3>Further enhancements</h3>\n\n<p>Also note that, in Java, a <code>MessageFormat</code> object could be used in place of a \"format\" <code>String</code>, which gives you additional capabilities such as a choice format to handle cardinal numbers more neatly. Another alternative would be to implement your own formatting capability that invokes some interface that you define for \"evaluation\", rather than the basic <code>toString()</code> method.</p>\n"
},
{
"answer_id": 105916,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 1,
"selected": false,
"text": "<p>As much as I hate macros in C/C++, at work we have #defines for the if part, which if false ignores (does not evaluate) the following expressions, but if true returns a stream into which stuff can be piped using the '<<' operator.\nLike this:</p>\n\n<pre><code>LOGGER(LEVEL_INFO) << \"A String\";\n</code></pre>\n\n<p>I assume this would eliminate the extra 'complexity' that your tool sees, and also eliminates any calculating of the string, or any expressions to be logged if the level was not reached.</p>\n"
},
{
"answer_id": 105934,
"author": "pointernil",
"author_id": 16769,
"author_profile": "https://Stackoverflow.com/users/16769",
"pm_score": 3,
"selected": false,
"text": "<p>In languages supporting lambda expressions or code blocks as parameters, one solution for this would be to give just that to the logging method. That one could evaluate the configuration and only if needed actually call/execute the provided lambda/code block.\nDid not try it yet, though. </p>\n\n<p><strong>Theoretically</strong> this is possible. I would not like to use it in production due to performance issues i expect with that heavy use of lamdas/code blocks for logging.</p>\n\n<p>But as always: if in doubt, test it and measure the impact on cpu load and memory.</p>\n"
},
{
"answer_id": 106031,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "<p>In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting.</p>\n\n<pre><code>log.info (\"a = %s, b = %s\", a, b)\n</code></pre>\n\n<p>You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc).</p>\n\n<hr>\n\n<p>This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing <code>mylist.toString()</code> will take a while to no benefit, as the result will be thrown away. So you pass <code>mylist</code> as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed.</p>\n\n<hr>\n\n<p>Since the OP's question specifically mentions Java, here's how the above can be used:</p>\n\n<blockquote>\n <p>I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)</p>\n</blockquote>\n\n<p>The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination.</p>\n\n<p>Say you have a function <code>get_everything()</code>. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called <code>LazyGetEverything</code>:</p>\n\n<pre><code>public class MainClass {\n private class LazyGetEverything { \n @Override\n public String toString() { \n return getEverything().toString(); \n }\n }\n\n private Object getEverything() {\n /* returns what you want to .toString() in the inner class */\n }\n\n public void logEverything() {\n log.info(new LazyGetEverything());\n }\n}\n</code></pre>\n\n<p>In this code, the call to <code>getEverything()</code> is wrapped so that it won't actually be executed until it's needed. The logging function will execute <code>toString()</code> on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full <code>getEverything()</code> call.</p>\n"
},
{
"answer_id": 107515,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>Thank you for all your answers! You guys rock :)</p>\n\n<p>Now my feedback is not as straight-forward as yours: </p>\n\n<p>Yes, for <em>one project</em> (as in 'one program deployed and running on its own on a single production platform'), I suppose you can go all technical on me: </p>\n\n<ul>\n<li>dedicated 'Log Retriever' objects, which can be pass to a Logger wrapper only calling toString() is necessary</li>\n<li>used in conjunction with a logging <a href=\"http://en.wikipedia.org/wiki/Variadic_function\" rel=\"nofollow noreferrer\">variadic function</a> (or a plain Object[] array!)</li>\n</ul>\n\n<p>and there you have it, as explained by @John Millikin and @erickson.</p>\n\n<p>However, this issue forced us to think a little about 'Why exactly we were logging in the first place ?'<br>\nOur project is actually 30 different projects (5 to 10 people each) deployed on various production platforms, with asynchronous communication needs and central bus architecture.<br>\nThe simple logging described in the question was fine for each project <em>at the beginning</em> (5 years ago), but since then, we has to step up. Enter the <a href=\"http://en.wikipedia.org/wiki/Key_performance_indicator\" rel=\"nofollow noreferrer\">KPI</a>.</p>\n\n<p>Instead of asking to a logger to log anything, we ask to an automatically created object (called KPI) to register an event. It is a simple call (myKPI.I_am_signaling_myself_to_you()), and does not need to be conditional (which solves the 'artificial increase of cyclomatic complexity' issue).</p>\n\n<p>That KPI object knows who calls it and since he runs from the beginning of the application, he is able to retrieve lots of data we were previously computing on the spot when we were logging.<br>\nPlus that KPI object can be monitored independently and compute/publish on demand its information on a single and separate publication bus.<br>\nThat way, each client can ask for the information he actually wants (like, 'has my process begun, and if yes, since when ?'), instead of looking for the correct log file and grepping for a cryptic String...</p>\n\n<p>Indeed, the question 'Why exactly we were logging in the first place ?' made us realize we were not logging just for the programmer and his unit or integration tests, but for a much broader community including some of the final clients themselves. Our 'reporting' mechanism had to be centralized, asynchronous, 24/7.</p>\n\n<p>The specific of that KPI mechanism is way out of the scope of this question. Suffice it to say its proper calibration is by far, hands down, the single most complicated non-functional issue we are facing. It still does bring the system on its knee from time to time! Properly calibrated however, it is a life-saver.</p>\n\n<p>Again, thank you for all the suggestions. We will consider them for some parts of our system when simple logging is still in place.<br>\nBut the other point of this question was to illustrate to you a specific problem in a much larger and more complicated context.<br>\nHope you liked it. I might ask a question on KPI (which, believe or not, is not in any question on SOF so far!) later next week.</p>\n\n<p>I will leave this answer up for voting until next Tuesday, then I will select an answer (not this one obviously ;) )</p>\n"
},
{
"answer_id": 144922,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe this is too simple, but what about using the \"extract method\" refactoring around the guard clause? Your example code of this:</p>\n\n<pre><code>public void Example()\n{\n if(myLogger.isLoggable(Level.INFO))\n myLogger.info(\"A String\");\n if(myLogger.isLoggable(Level.FINE))\n myLogger.fine(\"A more complicated String\");\n // +1 for each test and log message\n}\n</code></pre>\n\n<p>Becomes this:</p>\n\n<pre><code>public void Example()\n{\n _LogInfo();\n _LogFine();\n // +0 for each test and log message\n}\n\nprivate void _LogInfo()\n{\n if(!myLogger.isLoggable(Level.INFO))\n return;\n\n // Do your complex argument calculations/evaluations only when needed.\n}\n\nprivate void _LogFine(){ /* Ditto ... */ }\n</code></pre>\n"
},
{
"answer_id": 1431138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an elegant solution using ternary expression</p>\n\n<p>logger.info(logger.isInfoEnabled() ? \"Log Statement goes here...\" : null);</p>\n"
},
{
"answer_id": 3292596,
"author": "oluies",
"author_id": 203968,
"author_profile": "https://Stackoverflow.com/users/203968",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/BpHoC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BpHoC.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.scala-lang.org/sites/default/files/newsflash_logo.png\" rel=\"nofollow noreferrer\">scala-lang.org</a>)</sub> </p>\n\n<p><a href=\"https://www.scala-lang.org/\" rel=\"nofollow noreferrer\">Scala</a> has a annontation <a href=\"https://daily-scala.blogspot.com/2010/04/elidable-remove-method-calls-at-compile.html\" rel=\"nofollow noreferrer\">@elidable()</a> that allows you to remove methods with a compiler flag. </p>\n\n<p>With the scala REPL: </p>\n\n<blockquote>\n <p>C:>scala </p>\n \n <p>Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.\n 6.0_16).\n Type in expressions to have them evaluated.\n Type :help for more information.</p>\n \n <p>scala> import scala.annotation.elidable\n import scala.annotation.elidable</p>\n \n <p>scala> import scala.annotation.elidable._\n import scala.annotation.elidable._</p>\n \n <p>scala> @elidable(FINE) def logDebug(arg :String) = println(arg)</p>\n \n <p>logDebug: (arg: String)Unit</p>\n \n <p>scala> logDebug(\"testing\")</p>\n \n <p>scala></p>\n</blockquote>\n\n<p>With elide-beloset</p>\n\n<blockquote>\n <p>C:>scala -Xelide-below 0</p>\n \n <p>Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.\n 6.0_16).\n Type in expressions to have them evaluated.\n Type :help for more information.</p>\n \n <p>scala> import scala.annotation.elidable\n import scala.annotation.elidable</p>\n \n <p>scala> import scala.annotation.elidable._\n import scala.annotation.elidable._</p>\n \n <p>scala> @elidable(FINE) def logDebug(arg :String) = println(arg)</p>\n \n <p>logDebug: (arg: String)Unit</p>\n \n <p>scala> logDebug(\"testing\")</p>\n \n <p>testing</p>\n \n <p>scala></p>\n</blockquote>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/2425091/slow-scala-assert/2437515#2437515\">Scala assert definition</a></p>\n"
},
{
"answer_id": 6559894,
"author": "simon",
"author_id": 980640,
"author_profile": "https://Stackoverflow.com/users/980640",
"pm_score": 2,
"selected": false,
"text": "<p>Conditional logging is evil. It adds unnecessary clutter to your code.</p>\n\n<p>You should always send in the objects you have to the logger:</p>\n\n<pre><code>Logger logger = ...\nlogger.log(Level.DEBUG,\"The foo is {0} and the bar is {1}\",new Object[]{foo, bar});\n</code></pre>\n\n<p>and then have a java.util.logging.Formatter that uses MessageFormat to flatten foo and bar into the string to be output. It will only be called if the logger and handler will log at that level.</p>\n\n<p>For added pleasure you could have some kind of expression language to be able to get fine control over how to format the logged objects (toString may not always be useful).</p>\n"
},
{
"answer_id": 8227871,
"author": "johnlon",
"author_id": 1059904,
"author_profile": "https://Stackoverflow.com/users/1059904",
"pm_score": 1,
"selected": false,
"text": "<p>Consider a logging util function ... </p>\n\n<pre><code>void debugUtil(String s, Object… args) {\n if (LOG.isDebugEnabled())\n LOG.debug(s, args);\n }\n);\n</code></pre>\n\n<p>Then make the call with a \"closure\" round the expensive evaluation that you want to avoid.</p>\n\n<pre><code>debugUtil(“We got a %s”, new Object() {\n @Override String toString() { \n // only evaluated if the debug statement is executed\n return expensiveCallToGetSomeValue().toString;\n }\n }\n);\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6309/"
]
| After reading "[What’s your/a good limit for cyclomatic complexity?](http://web.archive.org/web/20090117062700/http://stackoverflow.com:80/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity)", I realize many of my colleagues were quite annoyed with this new [QA](http://en.wikipedia.org/wiki/Quality_assurance) policy on our project: no more 10 [cyclomatic complexity](http://en.wikipedia.org/wiki/Cyclomatic_complexity) per function.
Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in '[Do you test private method?](https://stackoverflow.com/questions/105007/do-you-test-private-method#105114)', such a policy has many good side-effects.
But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of '[Aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming)' approach for logs).
```
myLogger.info("A String");
myLogger.fine("A more complicated String");
...
```
And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the *log parameters* (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place!
So QA came back and urged our programmers to do conditional logging. Always.
```
if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String");
if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String");
...
```
But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity!
So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be *really* part of said complexity of that function...
How would you address this situation ?
I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first.
---
Thank you for all the answers.
I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)
So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the *obligation* to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...)
I now get the '[variadic](http://en.wikipedia.org/wiki/Variadic_function) function' point advanced by some of you (thank you John).
Note: a quick test in java6 shows that my [varargs function](http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html) does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it.
I have now posted my experience on this topic.
I will leave it there until next Tuesday for voting, then I will select one of your answers.
Again, thank you for all the suggestions :) | In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting.
```
log.info ("a = %s, b = %s", a, b)
```
You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc).
---
This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing `mylist.toString()` will take a while to no benefit, as the result will be thrown away. So you pass `mylist` as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed.
---
Since the OP's question specifically mentions Java, here's how the above can be used:
>
> I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)
>
>
>
The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination.
Say you have a function `get_everything()`. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called `LazyGetEverything`:
```
public class MainClass {
private class LazyGetEverything {
@Override
public String toString() {
return getEverything().toString();
}
}
private Object getEverything() {
/* returns what you want to .toString() in the inner class */
}
public void logEverything() {
log.info(new LazyGetEverything());
}
}
```
In this code, the call to `getEverything()` is wrapped so that it won't actually be executed until it's needed. The logging function will execute `toString()` on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full `getEverything()` call. |
105,884 | <p>I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure.</p>
<p>Does anyone know a solution for this?</p>
| [
{
"answer_id": 105876,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 2,
"selected": false,
"text": "<p>In C or C++ I'd use the preprocessor instead of the if statements for the conditional logging.</p>\n"
},
{
"answer_id": 105905,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Pass the log level to the logger and let it decide whether or not to write the log statement:</p>\n\n<pre><code>//if(myLogger.isLoggable(Level.INFO) {myLogger.info(\"A String\");\nmyLogger.info(Level.INFO,\"A String\");\n</code></pre>\n\n<p>UPDATE: Ah, I see that you want to conditionally create the log string without a conditional statement. Presumably at runtime rather than compile time.</p>\n\n<p>I'll just say that the way we've solved this is to put the formatting code in the logger class so that the formatting only takes place if the level passes. Very similar to a built-in sprintf. For example:</p>\n\n<pre><code>myLogger.info(Level.INFO,\"A String %d\",some_number); \n</code></pre>\n\n<p>That should meet your criteria.</p>\n"
},
{
"answer_id": 105908,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": false,
"text": "<h3>With current logging frameworks, the question is moot</h3>\n\n<p>Current logging frameworks like slf4j or log4j 2 don't require guard statements in most cases. They use a parameterized log statement so that an event can be logged unconditionally, but message formatting only occurs if the event is enabled. Message construction is performed as needed by the logger, rather than pre-emptively by the application.</p>\n\n<p>If you have to use an antique logging library, you can read on to get more background and a way to retrofit the old library with parameterized messages.</p>\n\n<h3>Are guard statements really adding complexity?</h3>\n\n<p>Consider excluding logging guards statements from the cyclomatic complexity calculation.</p>\n\n<p>It could be argued that, due to their predictable form, conditional logging checks really don't contribute to the complexity of the code.</p>\n\n<p>Inflexible metrics can make an otherwise good programmer turn bad. Be careful!</p>\n\n<p>Assuming that your tools for calculating complexity can't be tailored to that degree, the following approach may offer a work-around.</p>\n\n<h3>The need for conditional logging</h3>\n\n<p>I assume that your guard statements were introduced because you had code like this:</p>\n\n<pre><code>private static final Logger log = Logger.getLogger(MyClass.class);\n\nConnection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n{\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle \" + d, ex);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: \" + c);\n return c;\n}\n</code></pre>\n\n<p>In Java, each of the log statements creates a new <code>StringBuilder</code>, and invokes the <code>toString()</code> method on each object concatenated to the string. These <code>toString()</code> methods, in turn, are likely to create <code>StringBuilder</code> instances of their own, and invoke the <code>toString()</code> methods of their members, and so on, across a potentially large object graph. (Before Java 5, it was even more expensive, since <code>StringBuffer</code> was used, and all of its operations are synchronized.)</p>\n\n<p>This can be relatively costly, especially if the log statement is in some heavily-executed code path. And, written as above, that expensive message formatting occurs even if the logger is bound to discard the result because the log level is too high.</p>\n\n<p>This leads to the introduction of guard statements of the form:</p>\n\n<pre><code> if (log.isDebugEnabled())\n log.debug(\"Attempting connection of dongle \" + d + \" to widget \" + w);\n</code></pre>\n\n<p>With this guard, the evaluation of arguments <code>d</code> and <code>w</code> and the string concatenation is performed only when necessary.</p>\n\n<h3>A solution for simple, efficient logging</h3>\n\n<p>However, if the logger (or a wrapper that you write around your chosen logging package) takes a formatter and arguments for the formatter, the message construction can be delayed until it is certain that it will be used, while eliminating the guard statements and their cyclomatic complexity.</p>\n\n<pre><code>public final class FormatLogger\n{\n\n private final Logger log;\n\n public FormatLogger(Logger log)\n {\n this.log = log;\n }\n\n public void debug(String formatter, Object... args)\n {\n log(Level.DEBUG, formatter, args);\n }\n\n … &c. for info, warn; also add overloads to log an exception …\n\n public void log(Level level, String formatter, Object... args)\n {\n if (log.isEnabled(level)) {\n /* \n * Only now is the message constructed, and each \"arg\"\n * evaluated by having its toString() method invoked.\n */\n log.log(level, String.format(formatter, args));\n }\n }\n\n}\n\nclass MyClass \n{\n\n private static final FormatLogger log = \n new FormatLogger(Logger.getLogger(MyClass.class));\n\n Connection connect(Widget w, Dongle d, Dongle alt) \n throws ConnectionException\n {\n log.debug(\"Attempting connection of dongle %s to widget %s.\", d, w);\n Connection c;\n try {\n c = w.connect(d);\n } catch(ConnectionException ex) {\n log.warn(\"Connection failed; attempting alternate dongle %s.\", d);\n c = w.connect(alt);\n }\n log.debug(\"Connection succeeded: %s\", c);\n return c;\n }\n\n}\n</code></pre>\n\n<p>Now, <strong>none of the cascading <code>toString()</code> calls with their buffer allocations will occur</strong> unless they are necessary! This effectively eliminates the performance hit that led to the guard statements. One small penalty, in Java, would be auto-boxing of any primitive type arguments you pass to the logger.</p>\n\n<p>The code doing the logging is arguably even cleaner than ever, since untidy string concatenation is gone. It can be even cleaner if the format strings are externalized (using a <code>ResourceBundle</code>), which could also assist in maintenance or localization of the software. </p>\n\n<h3>Further enhancements</h3>\n\n<p>Also note that, in Java, a <code>MessageFormat</code> object could be used in place of a \"format\" <code>String</code>, which gives you additional capabilities such as a choice format to handle cardinal numbers more neatly. Another alternative would be to implement your own formatting capability that invokes some interface that you define for \"evaluation\", rather than the basic <code>toString()</code> method.</p>\n"
},
{
"answer_id": 105916,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 1,
"selected": false,
"text": "<p>As much as I hate macros in C/C++, at work we have #defines for the if part, which if false ignores (does not evaluate) the following expressions, but if true returns a stream into which stuff can be piped using the '<<' operator.\nLike this:</p>\n\n<pre><code>LOGGER(LEVEL_INFO) << \"A String\";\n</code></pre>\n\n<p>I assume this would eliminate the extra 'complexity' that your tool sees, and also eliminates any calculating of the string, or any expressions to be logged if the level was not reached.</p>\n"
},
{
"answer_id": 105934,
"author": "pointernil",
"author_id": 16769,
"author_profile": "https://Stackoverflow.com/users/16769",
"pm_score": 3,
"selected": false,
"text": "<p>In languages supporting lambda expressions or code blocks as parameters, one solution for this would be to give just that to the logging method. That one could evaluate the configuration and only if needed actually call/execute the provided lambda/code block.\nDid not try it yet, though. </p>\n\n<p><strong>Theoretically</strong> this is possible. I would not like to use it in production due to performance issues i expect with that heavy use of lamdas/code blocks for logging.</p>\n\n<p>But as always: if in doubt, test it and measure the impact on cpu load and memory.</p>\n"
},
{
"answer_id": 106031,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "<p>In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting.</p>\n\n<pre><code>log.info (\"a = %s, b = %s\", a, b)\n</code></pre>\n\n<p>You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc).</p>\n\n<hr>\n\n<p>This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing <code>mylist.toString()</code> will take a while to no benefit, as the result will be thrown away. So you pass <code>mylist</code> as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed.</p>\n\n<hr>\n\n<p>Since the OP's question specifically mentions Java, here's how the above can be used:</p>\n\n<blockquote>\n <p>I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)</p>\n</blockquote>\n\n<p>The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination.</p>\n\n<p>Say you have a function <code>get_everything()</code>. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called <code>LazyGetEverything</code>:</p>\n\n<pre><code>public class MainClass {\n private class LazyGetEverything { \n @Override\n public String toString() { \n return getEverything().toString(); \n }\n }\n\n private Object getEverything() {\n /* returns what you want to .toString() in the inner class */\n }\n\n public void logEverything() {\n log.info(new LazyGetEverything());\n }\n}\n</code></pre>\n\n<p>In this code, the call to <code>getEverything()</code> is wrapped so that it won't actually be executed until it's needed. The logging function will execute <code>toString()</code> on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full <code>getEverything()</code> call.</p>\n"
},
{
"answer_id": 107515,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>Thank you for all your answers! You guys rock :)</p>\n\n<p>Now my feedback is not as straight-forward as yours: </p>\n\n<p>Yes, for <em>one project</em> (as in 'one program deployed and running on its own on a single production platform'), I suppose you can go all technical on me: </p>\n\n<ul>\n<li>dedicated 'Log Retriever' objects, which can be pass to a Logger wrapper only calling toString() is necessary</li>\n<li>used in conjunction with a logging <a href=\"http://en.wikipedia.org/wiki/Variadic_function\" rel=\"nofollow noreferrer\">variadic function</a> (or a plain Object[] array!)</li>\n</ul>\n\n<p>and there you have it, as explained by @John Millikin and @erickson.</p>\n\n<p>However, this issue forced us to think a little about 'Why exactly we were logging in the first place ?'<br>\nOur project is actually 30 different projects (5 to 10 people each) deployed on various production platforms, with asynchronous communication needs and central bus architecture.<br>\nThe simple logging described in the question was fine for each project <em>at the beginning</em> (5 years ago), but since then, we has to step up. Enter the <a href=\"http://en.wikipedia.org/wiki/Key_performance_indicator\" rel=\"nofollow noreferrer\">KPI</a>.</p>\n\n<p>Instead of asking to a logger to log anything, we ask to an automatically created object (called KPI) to register an event. It is a simple call (myKPI.I_am_signaling_myself_to_you()), and does not need to be conditional (which solves the 'artificial increase of cyclomatic complexity' issue).</p>\n\n<p>That KPI object knows who calls it and since he runs from the beginning of the application, he is able to retrieve lots of data we were previously computing on the spot when we were logging.<br>\nPlus that KPI object can be monitored independently and compute/publish on demand its information on a single and separate publication bus.<br>\nThat way, each client can ask for the information he actually wants (like, 'has my process begun, and if yes, since when ?'), instead of looking for the correct log file and grepping for a cryptic String...</p>\n\n<p>Indeed, the question 'Why exactly we were logging in the first place ?' made us realize we were not logging just for the programmer and his unit or integration tests, but for a much broader community including some of the final clients themselves. Our 'reporting' mechanism had to be centralized, asynchronous, 24/7.</p>\n\n<p>The specific of that KPI mechanism is way out of the scope of this question. Suffice it to say its proper calibration is by far, hands down, the single most complicated non-functional issue we are facing. It still does bring the system on its knee from time to time! Properly calibrated however, it is a life-saver.</p>\n\n<p>Again, thank you for all the suggestions. We will consider them for some parts of our system when simple logging is still in place.<br>\nBut the other point of this question was to illustrate to you a specific problem in a much larger and more complicated context.<br>\nHope you liked it. I might ask a question on KPI (which, believe or not, is not in any question on SOF so far!) later next week.</p>\n\n<p>I will leave this answer up for voting until next Tuesday, then I will select an answer (not this one obviously ;) )</p>\n"
},
{
"answer_id": 144922,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe this is too simple, but what about using the \"extract method\" refactoring around the guard clause? Your example code of this:</p>\n\n<pre><code>public void Example()\n{\n if(myLogger.isLoggable(Level.INFO))\n myLogger.info(\"A String\");\n if(myLogger.isLoggable(Level.FINE))\n myLogger.fine(\"A more complicated String\");\n // +1 for each test and log message\n}\n</code></pre>\n\n<p>Becomes this:</p>\n\n<pre><code>public void Example()\n{\n _LogInfo();\n _LogFine();\n // +0 for each test and log message\n}\n\nprivate void _LogInfo()\n{\n if(!myLogger.isLoggable(Level.INFO))\n return;\n\n // Do your complex argument calculations/evaluations only when needed.\n}\n\nprivate void _LogFine(){ /* Ditto ... */ }\n</code></pre>\n"
},
{
"answer_id": 1431138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an elegant solution using ternary expression</p>\n\n<p>logger.info(logger.isInfoEnabled() ? \"Log Statement goes here...\" : null);</p>\n"
},
{
"answer_id": 3292596,
"author": "oluies",
"author_id": 203968,
"author_profile": "https://Stackoverflow.com/users/203968",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/BpHoC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BpHoC.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.scala-lang.org/sites/default/files/newsflash_logo.png\" rel=\"nofollow noreferrer\">scala-lang.org</a>)</sub> </p>\n\n<p><a href=\"https://www.scala-lang.org/\" rel=\"nofollow noreferrer\">Scala</a> has a annontation <a href=\"https://daily-scala.blogspot.com/2010/04/elidable-remove-method-calls-at-compile.html\" rel=\"nofollow noreferrer\">@elidable()</a> that allows you to remove methods with a compiler flag. </p>\n\n<p>With the scala REPL: </p>\n\n<blockquote>\n <p>C:>scala </p>\n \n <p>Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.\n 6.0_16).\n Type in expressions to have them evaluated.\n Type :help for more information.</p>\n \n <p>scala> import scala.annotation.elidable\n import scala.annotation.elidable</p>\n \n <p>scala> import scala.annotation.elidable._\n import scala.annotation.elidable._</p>\n \n <p>scala> @elidable(FINE) def logDebug(arg :String) = println(arg)</p>\n \n <p>logDebug: (arg: String)Unit</p>\n \n <p>scala> logDebug(\"testing\")</p>\n \n <p>scala></p>\n</blockquote>\n\n<p>With elide-beloset</p>\n\n<blockquote>\n <p>C:>scala -Xelide-below 0</p>\n \n <p>Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.\n 6.0_16).\n Type in expressions to have them evaluated.\n Type :help for more information.</p>\n \n <p>scala> import scala.annotation.elidable\n import scala.annotation.elidable</p>\n \n <p>scala> import scala.annotation.elidable._\n import scala.annotation.elidable._</p>\n \n <p>scala> @elidable(FINE) def logDebug(arg :String) = println(arg)</p>\n \n <p>logDebug: (arg: String)Unit</p>\n \n <p>scala> logDebug(\"testing\")</p>\n \n <p>testing</p>\n \n <p>scala></p>\n</blockquote>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/2425091/slow-scala-assert/2437515#2437515\">Scala assert definition</a></p>\n"
},
{
"answer_id": 6559894,
"author": "simon",
"author_id": 980640,
"author_profile": "https://Stackoverflow.com/users/980640",
"pm_score": 2,
"selected": false,
"text": "<p>Conditional logging is evil. It adds unnecessary clutter to your code.</p>\n\n<p>You should always send in the objects you have to the logger:</p>\n\n<pre><code>Logger logger = ...\nlogger.log(Level.DEBUG,\"The foo is {0} and the bar is {1}\",new Object[]{foo, bar});\n</code></pre>\n\n<p>and then have a java.util.logging.Formatter that uses MessageFormat to flatten foo and bar into the string to be output. It will only be called if the logger and handler will log at that level.</p>\n\n<p>For added pleasure you could have some kind of expression language to be able to get fine control over how to format the logged objects (toString may not always be useful).</p>\n"
},
{
"answer_id": 8227871,
"author": "johnlon",
"author_id": 1059904,
"author_profile": "https://Stackoverflow.com/users/1059904",
"pm_score": 1,
"selected": false,
"text": "<p>Consider a logging util function ... </p>\n\n<pre><code>void debugUtil(String s, Object… args) {\n if (LOG.isDebugEnabled())\n LOG.debug(s, args);\n }\n);\n</code></pre>\n\n<p>Then make the call with a \"closure\" round the expensive evaluation that you want to avoid.</p>\n\n<pre><code>debugUtil(“We got a %s”, new Object() {\n @Override String toString() { \n // only evaluated if the debug statement is executed\n return expensiveCallToGetSomeValue().toString;\n }\n }\n);\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
]
| I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure.
Does anyone know a solution for this? | In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting.
```
log.info ("a = %s, b = %s", a, b)
```
You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc).
---
This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing `mylist.toString()` will take a while to no benefit, as the result will be thrown away. So you pass `mylist` as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed.
---
Since the OP's question specifically mentions Java, here's how the above can be used:
>
> I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)
>
>
>
The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination.
Say you have a function `get_everything()`. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called `LazyGetEverything`:
```
public class MainClass {
private class LazyGetEverything {
@Override
public String toString() {
return getEverything().toString();
}
}
private Object getEverything() {
/* returns what you want to .toString() in the inner class */
}
public void logEverything() {
log.info(new LazyGetEverything());
}
}
```
In this code, the call to `getEverything()` is wrapped so that it won't actually be executed until it's needed. The logging function will execute `toString()` on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full `getEverything()` call. |
105,932 | <p>It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:</p>
<ul>
<li>Window position same as it was
<ul>
<li>Unless the screen has resized and the old position is now off screen.</li>
</ul></li>
<li>Splitters should retain their position</li>
<li>Tab containers should retain their selection</li>
<li>Some dropdowns should retain their selection</li>
<li>Window state (maximize, minimize, normal) is the same as it was.
<ul>
<li>Maybe you should never start minimized, I haven't decided.</li>
</ul></li>
</ul>
<p>I'll add my current solutions as an answer along with the limitations.</p>
| [
{
"answer_id": 105969,
"author": "Don Kirkby",
"author_id": 4794,
"author_profile": "https://Stackoverflow.com/users/4794",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest solution I've found is to use data binding with the application settings. I bind the location and clientSize properties on the window along with the splitterDistance on the splitter.</p>\n\n<p>Drawbacks: </p>\n\n<ul>\n<li>If you close the window while minimized, it opens hidden the next time. It's really hard to get the window back.</li>\n<li>If you close the window while maximized, it opens filling the whole screen, but not maximized (minor issue).</li>\n<li>Resizing the window using the top-right corner or the bottom-left corner is just ugly. I guess the two databound properties are fighting each other.</li>\n</ul>\n\n<p>If you'd like to experiment with the strange behaviour, I posted a <a href=\"http://dl.getdropbox.com/u/194081/WindowSettings.zip\" rel=\"noreferrer\">sample solution</a> using this technique.</p>\n"
},
{
"answer_id": 105987,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 2,
"selected": false,
"text": "<p>A hack you can use Settings to store that information. All you have to do is bind the desired property (ex. form.Size and form.Location) to a specific setting and it get saved and updated automatically. </p>\n"
},
{
"answer_id": 106010,
"author": "Don Kirkby",
"author_id": 4794,
"author_profile": "https://Stackoverflow.com/users/4794",
"pm_score": 5,
"selected": true,
"text": "<p>My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding.</p>\n\n<p>Drawbacks:</p>\n\n<ul>\n<li>More code to write.</li>\n<li>Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window size before you set the splitter distance.</li>\n</ul>\n\n<p>Right now, this is my preferred solution, but it seems like too much work. To reduce the work, I created a WindowSettings class that serializes the window location, size, state, and any splitter positions to a single application setting. Then I can just create a setting of that type for each form in my application, save on close, and restore on load.</p>\n\n<p>I posted <a href=\"https://github.com/donkirkby/donkirkby/blob/master/WindowSettings/WindowSettings.cs\" rel=\"nofollow noreferrer\">the source code</a>, including the WindowSettings class and some forms that use it. Instructions on adding it to a project are included in the WindowSettings.cs file. The trickiest part was figuring out how to add an application setting with a custom type. You choose Browse... from the type dropdown, and then manually enter the namespace and class name. Types from your project don't show up in the list.</p>\n\n<p><strong>Update:</strong> I added some static methods to simplify the boilerplate code that you add to each form. Once you've followed the instructions for adding the WindowSettings class to your project and creating an application setting, here's an example of the code that has to be added to each form whose position you want to record and restore.</p>\n\n<pre><code> private void MyForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n Settings.Default.CustomWindowSettings = WindowSettings.Record(\n Settings.Default.CustomWindowSettings,\n this, \n splitContainer1);\n }\n\n private void MyForm_Load(object sender, EventArgs e)\n {\n WindowSettings.Restore(\n Settings.Default.CustomWindowSettings, \n this, \n splitContainer1);\n }\n</code></pre>\n"
},
{
"answer_id": 106012,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the application settings to set which control properties will be persisted, in the Form_closed event you have to use the save method on the application settings to write these to disk:</p>\n\n<pre><code>Properties.Settings.Default.Save();\n</code></pre>\n"
},
{
"answer_id": 106020,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example of a few I use myself. It only takes into consideration the primary monitor, so it might be better to handle it differently if used on multiple monitors.</p>\n\n<pre><code>Size size;\nint x;\nint y;\nif (WindowState.Equals(FormWindowState.Normal))\n{\n size = Size;\n if (Location.X + size.Width > Screen.PrimaryScreen.Bounds.Width)\n x = Screen.PrimaryScreen.Bounds.Width - size.Width;\n else\n x = Location.X;\n if (Location.Y + Size.Height > Screen.PrimaryScreen.Bounds.Height)\n y = Screen.PrimaryScreen.Bounds.Height - size.Height;\n else\n y = Location.Y;\n}\nelse\n{\nsize = RestoreBounds.Size;\nx = (Screen.PrimaryScreen.Bounds.Width - size.Width)/2;\ny = (Screen.PrimaryScreen.Bounds.Height - size.Height)/2;\n}\nProperties.Settings.Position.AsPoint = new Point(x, y); // Property setting is type of Point\nProperties.Settings.Size.AsSize = size; // Property setting is type of Size\nProperties.Settings.SplitterDistance.Value = splitContainer1.SplitterDistance; // Property setting is type of int\nProperties.Settings.IsMaximized = WindowState == FormWindowState.Maximized; // Property setting is type of bool\nProperties.Settings.DropDownSelection = DropDown1.SelectedValue;\nProperties.Settings.Save();\n</code></pre>\n"
},
{
"answer_id": 106598,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 3,
"selected": false,
"text": "<p>I make a Setting for each value I want to save, and use code like this:</p>\n\n<pre><code>private void MainForm_Load(object sender, EventArgs e) {\n RestoreState();\n}\n\nprivate void MainForm_FormClosing(object sender, FormClosingEventArgs e) {\n SaveState();\n}\n\nprivate void SaveState() {\n if (WindowState == FormWindowState.Normal) {\n Properties.Settings.Default.MainFormLocation = Location;\n Properties.Settings.Default.MainFormSize = Size;\n } else {\n Properties.Settings.Default.MainFormLocation = RestoreBounds.Location;\n Properties.Settings.Default.MainFormSize = RestoreBounds.Size;\n }\n Properties.Settings.Default.MainFormState = WindowState;\n Properties.Settings.Default.SplitterDistance = splitContainer1.SplitterDistance;\n Properties.Settings.Default.Save();\n}\n\nprivate void RestoreState() {\n if (Properties.Settings.Default.MainFormSize == new Size(0, 0)) {\n return; // state has never been saved\n }\n StartPosition = FormStartPosition.Manual;\n Location = Properties.Settings.Default.MainFormLocation;\n Size = Properties.Settings.Default.MainFormSize;\n // I don't like an app to be restored minimized, even if I closed it that way\n WindowState = Properties.Settings.Default.MainFormState == \n FormWindowState.Minimized ? FormWindowState.Normal : Properties.Settings.Default.MainFormState;\n splitContainer1.SplitterDistance = Properties.Settings.Default.SplitterDistance;\n}\n</code></pre>\n\n<p>Keep in mind that recompiling wipes the config file where the settings are stored, so test it without making code changes in between a save and a restore.</p>\n"
},
{
"answer_id": 108217,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<p>The sample below shows how I do it</p>\n\n<ul>\n<li><p>SavePreferences is called when closing the form and saves the form's size, and a flag indicating if it's maximized (in this version I don't save if it's minimized - it will come back up restored or maximized next time).</p></li>\n<li><p>LoadPreferences is called from OnLoad.</p></li>\n<li><p>First save the design-time WindowState and set it to Normal. You can only successfully set the form size if it's WindowState is Normal.</p></li>\n<li><p>Next restore the Size from your persisted settings.</p></li>\n<li><p>Now make sure the form fits on your screen (call to FitToScreen). The screen resolution may have changed since you last ran the application.</p></li>\n<li><p>Finally set the WindowState back to Maximized (if persisted as such), or to the design-time value saved earlier.</p></li>\n</ul>\n\n<p>This could obviously be adapted to persist the start position and whether the form was minimized when closed - I didn't need to do that. Other settings for controls on your form such as splitter position and tab container are straightforward.</p>\n\n<pre><code>private void FitToScreen()\n{\n if (this.Width > Screen.PrimaryScreen.WorkingArea.Width)\n {\n this.Width = Screen.PrimaryScreen.WorkingArea.Width;\n }\n if (this.Height > Screen.PrimaryScreen.WorkingArea.Height)\n {\n this.Height = Screen.PrimaryScreen.WorkingArea.Height;\n }\n} \nprivate void LoadPreferences()\n{\n // Called from Form.OnLoad\n\n // Remember the initial window state and set it to Normal before sizing the form\n FormWindowState initialWindowState = this.WindowState;\n this.WindowState = FormWindowState.Normal;\n this.Size = UserPreferencesManager.LoadSetting(\"_Size\", this.Size);\n _currentFormSize = Size;\n // Fit to the current screen size in case the screen resolution\n // has changed since the size was last persisted.\n FitToScreen();\n bool isMaximized = UserPreferencesManager.LoadSetting(\"_Max\", initialWindowState == FormWindowState.Maximized);\n WindowState = isMaximized ? FormWindowState.Maximized : FormWindowState.Normal;\n}\nprivate void SavePreferences()\n{\n // Called from Form.OnClosed\n UserPreferencesManager.SaveSetting(\"_Size\", _currentFormSize);\n UserPreferencesManager.SaveSetting(\"_Max\", this.WindowState == FormWindowState.Maximized);\n ... save other settings\n}\n</code></pre>\n\n<p>x</p>\n"
},
{
"answer_id": 5577540,
"author": "takrl",
"author_id": 520044,
"author_profile": "https://Stackoverflow.com/users/520044",
"pm_score": 2,
"selected": false,
"text": "<p>Based on the accepted answer by Don Kirkby and the WindowSettings class he wrote, you could derive a CustomForm from the standard one to reduce the amount of identical code written for each and every form, maybe like this:</p>\n\n<pre><code>using System;\nusing System.Configuration;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nnamespace CustomForm\n{\n public class MyCustomForm : Form\n {\n private ApplicationSettingsBase _appSettings = null;\n private string _settingName = \"\";\n\n public Form() : base() { }\n\n public Form(ApplicationSettingsBase settings, string settingName)\n : base()\n {\n _appSettings = settings;\n _settingName = settingName;\n\n this.Load += new EventHandler(Form_Load);\n this.FormClosing += new FormClosingEventHandler(Form_FormClosing);\n }\n\n private void Form_Load(object sender, EventArgs e)\n {\n if (_appSettings == null) return;\n\n PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);\n if (settingProperty == null) return;\n\n WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;\n if (previousSettings == null) return;\n\n previousSettings.Restore(this);\n }\n\n private void Form_FormClosing(object sender, FormClosingEventArgs e)\n {\n if (_appSettings == null) return;\n\n PropertyInfo settingProperty = _appSettings.GetType().GetProperty(_settingName);\n if (settingProperty == null) return;\n\n WindowSettings previousSettings = settingProperty.GetValue(_appSettings, null) as WindowSettings;\n if (previousSettings == null)\n previousSettings = new WindowSettings();\n\n previousSettings.Record(this);\n\n settingProperty.SetValue(_appSettings, previousSettings, null);\n\n _appSettings.Save();\n }\n }\n}\n</code></pre>\n\n<p>To use this, pass your application settings class and setting name in the constructor:</p>\n\n<pre><code>CustomForm.MyCustomForm f = new CustomForm.MyCustomForm(Properties.Settings.Default, \"formSettings\");\n</code></pre>\n\n<p>This uses Reflection to get/set the previous settings from/to the settings class. It may not be optimal to put the Save call into the Form_Closing routine, one could remove that and save the settings file whenever the main app exits.</p>\n\n<p>To use it as a regular form, just use the parameterless constructor.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4794/"
]
| It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:
* Window position same as it was
+ Unless the screen has resized and the old position is now off screen.
* Splitters should retain their position
* Tab containers should retain their selection
* Some dropdowns should retain their selection
* Window state (maximize, minimize, normal) is the same as it was.
+ Maybe you should never start minimized, I haven't decided.
I'll add my current solutions as an answer along with the limitations. | My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding.
Drawbacks:
* More code to write.
* Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window size before you set the splitter distance.
Right now, this is my preferred solution, but it seems like too much work. To reduce the work, I created a WindowSettings class that serializes the window location, size, state, and any splitter positions to a single application setting. Then I can just create a setting of that type for each form in my application, save on close, and restore on load.
I posted [the source code](https://github.com/donkirkby/donkirkby/blob/master/WindowSettings/WindowSettings.cs), including the WindowSettings class and some forms that use it. Instructions on adding it to a project are included in the WindowSettings.cs file. The trickiest part was figuring out how to add an application setting with a custom type. You choose Browse... from the type dropdown, and then manually enter the namespace and class name. Types from your project don't show up in the list.
**Update:** I added some static methods to simplify the boilerplate code that you add to each form. Once you've followed the instructions for adding the WindowSettings class to your project and creating an application setting, here's an example of the code that has to be added to each form whose position you want to record and restore.
```
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Default.CustomWindowSettings = WindowSettings.Record(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
private void MyForm_Load(object sender, EventArgs e)
{
WindowSettings.Restore(
Settings.Default.CustomWindowSettings,
this,
splitContainer1);
}
``` |
105,935 | <p>This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.</p>
| [
{
"answer_id": 106125,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately there is no more efficient way than a linear search, unless you know that your listbox is sorted or indexed in some particular fashion.</p>\n\n<pre><code>For i = 1 To TheComboBoxControl.ListCount\n if TheComboBoxControl.ItemData(i) = \"Item to search for\" Then do_something()\nNext i\n</code></pre>\n"
},
{
"answer_id": 106157,
"author": "Rikalous",
"author_id": 4271,
"author_profile": "https://Stackoverflow.com/users/4271",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't mind resorting to the Windows API you can search for a string like this: </p>\n\n<pre><code>Private Declare Function SendMessage Lib \"user32\" Alias \"SendMessageA\" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long \nPrivate Const LB_FINDSTRINGEXACT = &H1A2\n\nDim index as Integer\nDim searchString as String\nsearchString = \"Target\" & Chr(0)\n\nindex = SendMessage(ListBox1.hWnd, LB_FINDSTRINGEXACT , -1, searchString)\n</code></pre>\n\n<p>Which should return the index of the row that contains the target string.</p>\n"
},
{
"answer_id": 106322,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a sample function that might be adapted to suit.</p>\n\n<pre><code>Function CheckForItem(strItem, ListB As ListBox) As Boolean\nDim rs As DAO.Recordset\nDim db As Database\nDim tdf As TableDef\n\n Set db = CurrentDb\n\n CheckForItem = False\n\n Select Case ListB.RowSourceType\n Case \"Value List\"\n CheckForItem = InStr(ListB.RowSource, strItem) > 0\n\n Case \"Table/Query\"\n Set rs = db.OpenRecordset(ListB.RowSource)\n\n For i = 0 To rs.Fields.Count - 1\n strList = strList & \" & \"\",\"\" & \" & rs.Fields(i).Name\n Next\n\n rs.FindFirst \"Instr(\" & Mid(strList, 10) & \",'\" & strItem & \"')>0\"\n\n If Not rs.EOF Then CheckForItem = True\n\n Case \"Field List\"\n\n Set tdf = db.TableDefs(ListB.RowSource)\n\n For Each itm In tdf.Fields\n If itm.Name = strItem Then CheckForItem = True\n Next\n\n End Select\n\nEnd Function\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3155/"
]
| This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control. | Here is a sample function that might be adapted to suit.
```
Function CheckForItem(strItem, ListB As ListBox) As Boolean
Dim rs As DAO.Recordset
Dim db As Database
Dim tdf As TableDef
Set db = CurrentDb
CheckForItem = False
Select Case ListB.RowSourceType
Case "Value List"
CheckForItem = InStr(ListB.RowSource, strItem) > 0
Case "Table/Query"
Set rs = db.OpenRecordset(ListB.RowSource)
For i = 0 To rs.Fields.Count - 1
strList = strList & " & "","" & " & rs.Fields(i).Name
Next
rs.FindFirst "Instr(" & Mid(strList, 10) & ",'" & strItem & "')>0"
If Not rs.EOF Then CheckForItem = True
Case "Field List"
Set tdf = db.TableDefs(ListB.RowSource)
For Each itm In tdf.Fields
If itm.Name = strItem Then CheckForItem = True
Next
End Select
End Function
``` |
105,950 | <p>I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.</p>
| [
{
"answer_id": 105965,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": true,
"text": "<p>from: <a href=\"http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm\" rel=\"noreferrer\">http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm</a></p>\n\n<pre><code>sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'\n</code></pre>\n"
},
{
"answer_id": 105985,
"author": "Scott W",
"author_id": 3032,
"author_profile": "https://Stackoverflow.com/users/3032",
"pm_score": 1,
"selected": false,
"text": "<p>If you're trying to change which database you are using after you are logged in, you can use the USE command. E.g. USE Northwind.</p>\n\n<p><a href=\"https://www.tutorialspoint.com/sql/sql-select-database.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/sql/sql-select-database.htm</a></p>\n"
},
{
"answer_id": 106015,
"author": "Tim",
"author_id": 10363,
"author_profile": "https://Stackoverflow.com/users/10363",
"pm_score": 5,
"selected": false,
"text": "<p><code>ALTER LOGIN</code> should be used for SQL Server 2005 or later:</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms189828.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/ms189828.aspx</a></p>\n\n<pre><code>ALTER LOGIN <login_name> WITH DEFAULT_DATABASE = <default_database>\n</code></pre>\n\n<p><code>sp_defaultdb</code> eventually will be removed from SQL Server:</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms181738.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/ms181738.aspx</a></p>\n"
},
{
"answer_id": 106017,
"author": "Brian",
"author_id": 320,
"author_profile": "https://Stackoverflow.com/users/320",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks Stephen. </p>\n\n<p>As a note, if you are using Windows Authentication, the <code>@loginname</code> is <code>YourDomain\\YourLogin</code> (probably obvious to everybody else, but took me a couple tries.</p>\n\n<pre><code>sp_defaultdb @loginame='YourDomain\\YourLogin', @defdb='YourDatabase'\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320/"
]
| I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio. | from: <http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm>
```
sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'
``` |
105,971 | <p>I am working on a bash script where I need to conditionally execute some things if a particular file exists. This is happening multiple times, so I abstracted the following function:</p>
<pre><code>function conditional-do {
if [ -f $1 ]
then
echo "Doing stuff"
$2
else
echo "File doesn't exist!"
end
}
</code></pre>
<p>Now, when I want to execute this, I do something like:</p>
<pre><code>function exec-stuff {
echo "do some command"
echo "do another command"
}
conditional-do /path/to/file exec-stuff
</code></pre>
<p>The problem is, I am bothered that I am defining 2 things: the function of a group of commands to execute, and then invoking my first function.</p>
<p>I would like to pass this block of commands (often 2 or more) directly to "conditional-do" in a clean manner, but I have no idea how this is doable (or if it is even possible)... does anyone have any ideas?</p>
<p>Note, I need it to be a readable solution... otherwise I would rather stick with what I have.</p>
| [
{
"answer_id": 105982,
"author": "Alex Gartrell",
"author_id": 10307,
"author_profile": "https://Stackoverflow.com/users/10307",
"pm_score": 0,
"selected": false,
"text": "<p>One (possibly-hack) solution is to store the separate functions as separate scripts altogether.</p>\n"
},
{
"answer_id": 105999,
"author": "Ludvig A. Norin",
"author_id": 16909,
"author_profile": "https://Stackoverflow.com/users/16909",
"pm_score": 4,
"selected": true,
"text": "<p>This should be readable to most C programmers:</p>\n\n<pre><code>function file_exists {\n if ( [ -e $1 ] ) then \n echo \"Doing stuff\"\n else\n echo \"File $1 doesn't exist\" \n false\n fi\n}\n\nfile_exists filename && (\n echo \"Do your stuff...\"\n)\n</code></pre>\n\n<p>or the one-liner</p>\n\n<pre><code>file_exists filename && echo \"Do your stuff...\"\n</code></pre>\n\n<p>Now, if you really want the code to be run from the function, this is how you can do that:</p>\n\n<pre><code>function file_exists {\n if ( [ -e $1 ] ) then \n echo \"Doing stuff\"\n shift\n $*\n else\n echo \"File $1 doesn't exist\" \n false\n fi\n}\n\nfile_exists filename echo \"Do your stuff...\"\n</code></pre>\n\n<p>I don't like that solution though, because you will eventually end up doing escaping of the command string.</p>\n\n<p>EDIT: Changed \"eval $*\" to $ *. Eval is not required, actually. As is common with bash scripts, it was written when I had had a couple of beers ;-)</p>\n"
},
{
"answer_id": 110919,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 0,
"selected": false,
"text": "<p>The cannonical answer:</p>\n\n<pre><code>[ -f $filename ] && echo \"it has worked!\"\n</code></pre>\n\n<p>or you can wrap it up if you really want to:</p>\n\n<pre><code>function file-exists {\n [ \"$1\" ] && [ -f $1 ]\n}\n\nfile-exists $filename && echo \"It has worked\"\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
| I am working on a bash script where I need to conditionally execute some things if a particular file exists. This is happening multiple times, so I abstracted the following function:
```
function conditional-do {
if [ -f $1 ]
then
echo "Doing stuff"
$2
else
echo "File doesn't exist!"
end
}
```
Now, when I want to execute this, I do something like:
```
function exec-stuff {
echo "do some command"
echo "do another command"
}
conditional-do /path/to/file exec-stuff
```
The problem is, I am bothered that I am defining 2 things: the function of a group of commands to execute, and then invoking my first function.
I would like to pass this block of commands (often 2 or more) directly to "conditional-do" in a clean manner, but I have no idea how this is doable (or if it is even possible)... does anyone have any ideas?
Note, I need it to be a readable solution... otherwise I would rather stick with what I have. | This should be readable to most C programmers:
```
function file_exists {
if ( [ -e $1 ] ) then
echo "Doing stuff"
else
echo "File $1 doesn't exist"
false
fi
}
file_exists filename && (
echo "Do your stuff..."
)
```
or the one-liner
```
file_exists filename && echo "Do your stuff..."
```
Now, if you really want the code to be run from the function, this is how you can do that:
```
function file_exists {
if ( [ -e $1 ] ) then
echo "Doing stuff"
shift
$*
else
echo "File $1 doesn't exist"
false
fi
}
file_exists filename echo "Do your stuff..."
```
I don't like that solution though, because you will eventually end up doing escaping of the command string.
EDIT: Changed "eval $\*" to $ \*. Eval is not required, actually. As is common with bash scripts, it was written when I had had a couple of beers ;-) |
105,996 | <ul>
<li>I want to obtain maximum performance out of a process with many variables, many of which cannot be controlled. </li>
<li>I cannot run thousands of experiments, so it'd be nice if I could run hundreds of experiments and
<ul>
<li>vary many controllable parameters</li>
<li>collect data on many parameters indicating performance</li>
<li>'correct,' as much as possible, for those parameters I couldn't control</li>
<li>Tease out the 'best' values for those things I can control, and start all over again</li>
</ul></li>
</ul>
<p>It feels like this would be called data mining, where you're going through tons of data which doesn't immediately appear to relate, but does show correlation after some effort.</p>
<p>So... Where do I start looking at algorithms, concepts, theory of this sort of thing? Even related terms for purposes of search would be useful.</p>
<p>Background: I like to do ultra-marathon cycling, and keep logs of each ride. I'd like to keep more data, and after hundreds of rides be able to pull out information about how I perform.</p>
<p>However, everything varies - routes, environment (temp, pres., hum., sun load, wind, precip., etc), fuel, attitude, weight, water load, etc, etc, etc. I can control a few things, but running the same route 20 times to test out a new fuel regime would just be depressing, and take years to perform all the experiments that I'd like to do. I can, however, record all these things and more(telemetry on bicycle FTW).</p>
| [
{
"answer_id": 106013,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": true,
"text": "<p>It sounds like you want to do some <a href=\"http://en.wikipedia.org/wiki/Regression_analysis\" rel=\"nofollow noreferrer\">regression analysis</a>. You certainly have plenty of data!</p>\n\n<hr>\n\n<p>Regression analysis is an extremely common modeling technique in statistics and science. (It could be argued that statistics is the art and science of regression analysis.) There are many statistics packages out there to do the computation you'll need. (I'd recommend one, but I'm years out of date.)</p>\n\n<p>Data mining has gotten a bad name because far too often people assume correlation equals causation. I found that a good technique is to start with variables you know have an influence and build a statistical model around them first. So you know that wind, weight and climb have an influence on how fast you can travel and statistical software can take your dataset and calculate what the correlation between those factors are. That will give you a statistical model or linear equation:</p>\n\n<pre><code>speed = x*weight + y*wind + z*climb + constant\n</code></pre>\n\n<p>When you explore new variables, you will be able to see if the model is improved or not by comparing a goodness of fit metric like R-squared. So you might check if temperature or time of day adds anything to the model.</p>\n\n<p>You may want to apply a transformation to you data. For instance, you might find that you perform better on colder days. But really cold days and really hot days might hurt performance. In that case, you could assign temperatures to bins or <a href=\"http://en.wikipedia.org/wiki/Segmented_regression\" rel=\"nofollow noreferrer\">segments</a>: < 0°C; 0°C to 40°C; > 40°C, or some such. The key is to transform the data in a way that matches a rational model of what is going on in the real world, not just the data itself.</p>\n\n<hr>\n\n<p>In case someone thinks this is not a programming related topic, notice that you can use these same techniques to analyze system performance.</p>\n"
},
{
"answer_id": 106231,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 1,
"selected": false,
"text": "<p>I have used the Perl module <a href=\"http://search.cpan.org/~iawelch/Statistics-Regression-0.53/Regression.pm\" rel=\"nofollow noreferrer\">Statistics::Regression</a> for somewhat similar problems in the past. Be warned, however, that regression analysis is definitely an art. As the warning in the Perl module says, it won't make sense to you if you haven't learned the appropriate math.</p>\n"
},
{
"answer_id": 106254,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 2,
"selected": false,
"text": "<p>With that many variables you have too many dimensions and you may want to look at <a href=\"http://en.wikipedia.org/wiki/Principal_components_analysis\" rel=\"nofollow noreferrer\">Principal Component Analysis</a>. It takes some of the \"art\" out of regression analysis and lets the data speak for itself. Some software to do that sort of analysis is shown at the bottom of the link.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
| * I want to obtain maximum performance out of a process with many variables, many of which cannot be controlled.
* I cannot run thousands of experiments, so it'd be nice if I could run hundreds of experiments and
+ vary many controllable parameters
+ collect data on many parameters indicating performance
+ 'correct,' as much as possible, for those parameters I couldn't control
+ Tease out the 'best' values for those things I can control, and start all over again
It feels like this would be called data mining, where you're going through tons of data which doesn't immediately appear to relate, but does show correlation after some effort.
So... Where do I start looking at algorithms, concepts, theory of this sort of thing? Even related terms for purposes of search would be useful.
Background: I like to do ultra-marathon cycling, and keep logs of each ride. I'd like to keep more data, and after hundreds of rides be able to pull out information about how I perform.
However, everything varies - routes, environment (temp, pres., hum., sun load, wind, precip., etc), fuel, attitude, weight, water load, etc, etc, etc. I can control a few things, but running the same route 20 times to test out a new fuel regime would just be depressing, and take years to perform all the experiments that I'd like to do. I can, however, record all these things and more(telemetry on bicycle FTW). | It sounds like you want to do some [regression analysis](http://en.wikipedia.org/wiki/Regression_analysis). You certainly have plenty of data!
---
Regression analysis is an extremely common modeling technique in statistics and science. (It could be argued that statistics is the art and science of regression analysis.) There are many statistics packages out there to do the computation you'll need. (I'd recommend one, but I'm years out of date.)
Data mining has gotten a bad name because far too often people assume correlation equals causation. I found that a good technique is to start with variables you know have an influence and build a statistical model around them first. So you know that wind, weight and climb have an influence on how fast you can travel and statistical software can take your dataset and calculate what the correlation between those factors are. That will give you a statistical model or linear equation:
```
speed = x*weight + y*wind + z*climb + constant
```
When you explore new variables, you will be able to see if the model is improved or not by comparing a goodness of fit metric like R-squared. So you might check if temperature or time of day adds anything to the model.
You may want to apply a transformation to you data. For instance, you might find that you perform better on colder days. But really cold days and really hot days might hurt performance. In that case, you could assign temperatures to bins or [segments](http://en.wikipedia.org/wiki/Segmented_regression): < 0°C; 0°C to 40°C; > 40°C, or some such. The key is to transform the data in a way that matches a rational model of what is going on in the real world, not just the data itself.
---
In case someone thinks this is not a programming related topic, notice that you can use these same techniques to analyze system performance. |
105,998 | <p>According to what I have found so far, I can use the following code:</p>
<pre>
LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean)super.getApplicationContext().getBean("&sessionFactory");
System.out.println(sessionFactory.getConfiguration().buildSettings().getJdbcBatchSize());
</pre>
<p>but then I get a Hibernate Exception:</p>
<blockquote>
<p>org.hibernate.HibernateException: No local DataSource found for
configuration - dataSource property must be set on
LocalSessionFactoryBean</p>
</blockquote>
<p>Can somebody shed some light?</p>
| [
{
"answer_id": 106165,
"author": "Matt Solnit",
"author_id": 6198,
"author_profile": "https://Stackoverflow.com/users/6198",
"pm_score": 3,
"selected": true,
"text": "<p>Try the following (I can't test it since I don't use Spring):</p>\n\n<pre><code>System.out.println(sessionFactory.getConfiguration().getProperty(\"hibernate.jdbc.batch_size\"))\n</code></pre>\n"
},
{
"answer_id": 107359,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 2,
"selected": false,
"text": "<p>On the versions of Hibernate that I've checked, getConfiguration is not a public method of SessionFactory. In a few desperate cases, I've cast a Session or SessionFactory into its underlying implementation to get at some values that weren't publicly available. In this case that would be:</p>\n\n<pre><code>((SessionFactoryImplementor)sessionFactory).getSettings().getJdbcBatchSize()\n</code></pre>\n\n<p>Of course, that's dangerous because it could break if they change the implementation. I usually only do this for optimizations that I can live without and then wrap the whole thing in a try/catch Throwable block just to make sure it won't hurt anything if it fails. A better idea might be to set the value yourself when you initialize Hibernate so you already know what it is from the beginning.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/105998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14068/"
]
| According to what I have found so far, I can use the following code:
```
LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean)super.getApplicationContext().getBean("&sessionFactory");
System.out.println(sessionFactory.getConfiguration().buildSettings().getJdbcBatchSize());
```
but then I get a Hibernate Exception:
>
> org.hibernate.HibernateException: No local DataSource found for
> configuration - dataSource property must be set on
> LocalSessionFactoryBean
>
>
>
Can somebody shed some light? | Try the following (I can't test it since I don't use Spring):
```
System.out.println(sessionFactory.getConfiguration().getProperty("hibernate.jdbc.batch_size"))
``` |
106,000 | <p>I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list?</p>
<p>I have been searching for awhile but I cannot seem to find a comprehensive list.</p>
<p>Thanks :)</p>
| [
{
"answer_id": 106165,
"author": "Matt Solnit",
"author_id": 6198,
"author_profile": "https://Stackoverflow.com/users/6198",
"pm_score": 3,
"selected": true,
"text": "<p>Try the following (I can't test it since I don't use Spring):</p>\n\n<pre><code>System.out.println(sessionFactory.getConfiguration().getProperty(\"hibernate.jdbc.batch_size\"))\n</code></pre>\n"
},
{
"answer_id": 107359,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 2,
"selected": false,
"text": "<p>On the versions of Hibernate that I've checked, getConfiguration is not a public method of SessionFactory. In a few desperate cases, I've cast a Session or SessionFactory into its underlying implementation to get at some values that weren't publicly available. In this case that would be:</p>\n\n<pre><code>((SessionFactoryImplementor)sessionFactory).getSettings().getJdbcBatchSize()\n</code></pre>\n\n<p>Of course, that's dangerous because it could break if they change the implementation. I usually only do this for optimizations that I can live without and then wrap the whole thing in a try/catch Throwable block just to make sure it won't hurt anything if it fails. A better idea might be to set the value yourself when you initialize Hibernate so you already know what it is from the beginning.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14281/"
]
| I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list?
I have been searching for awhile but I cannot seem to find a comprehensive list.
Thanks :) | Try the following (I can't test it since I don't use Spring):
```
System.out.println(sessionFactory.getConfiguration().getProperty("hibernate.jdbc.batch_size"))
``` |
106,001 | <p>I have some code which utilizes parameterized queries to prevent against injection, but I also need to be able to dynamically construct the query regardless of the structure of the table. What is the proper way to do this?</p>
<p>Here's an example, say I have a table with columns Name, Address, Telephone. I have a web page where I run <b>Show Columns</b> and populate a select drop-down with them as options.</p>
<p>Next, I have a textbox called <b>Search</b>. This textbox is used as the parameter.</p>
<p>Currently my code looks something like this:</p>
<pre>
result = pquery('SELECT * FROM contacts WHERE `' + escape(column) + '`=?', search);
</pre>
<p>I get an icky feeling from it though. The reason I'm using parameterized queries is to avoid using <b>escape</b>. Also, <b>escape</b> is likely not designed for escaping column names.</p>
<p>How can I make sure this works the way I intend?</p>
<p><b>Edit:</b>
The reason I require dynamic queries is that the schema is user-configurable, and I will not be around to fix anything hard-coded.</p>
| [
{
"answer_id": 106014,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 4,
"selected": true,
"text": "<p>Instead of passing the column names, just pass an identifier that you code will translate to a column name using a hardcoded table. This means you don't need to worry about malicious data being passed, since all the data is either translated legally, or is known to be invalid. Psudoish code:</p>\n\n<pre><code>@columns = qw/Name Address Telephone/;\nif ($columns[$param]) {\n $query = \"select * from contacts where $columns[$param] = ?\";\n} else {\n die \"Invalid column!\";\n}\n\nrun_sql($query, $search);\n</code></pre>\n"
},
{
"answer_id": 106059,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 0,
"selected": false,
"text": "<p>The trick is to be confident in your escaping and validating routines. I use my own SQL escape function that is overloaded for literals of different types. Nowhere do I insert expressions (as opposed to quoted literal values) directly from user input.</p>\n\n<p>Still, it can be done, I recommend a separate — and strict — function for validating the column name. Allow it to accept only a single identifier, something like</p>\n\n<pre>\n/^\\w[\\w\\d_]*$/\n</pre>\n\n<p>You'll have to rely on assumptions you can make about your own column names.</p>\n"
},
{
"answer_id": 106066,
"author": "Brad Osterloo",
"author_id": 9162,
"author_profile": "https://Stackoverflow.com/users/9162",
"pm_score": 0,
"selected": false,
"text": "<p>I use ADO.NET and the use of SQL Commands and SQLParameters to those commands which take care of the Escape problem. So if you are in a Microsoft-tool environment as well, I can say that I use this very sucesfully to build dynamic SQL and yet protect my parameters</p>\n\n<p>best of luck</p>\n"
},
{
"answer_id": 106084,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 0,
"selected": false,
"text": "<p>Make the column based on the results of another query to a table that enumerates the possible schema values. In that second query you can hardcode the select to the column name that is used to define the schema. if no rows are returned then the entered column is invalid.</p>\n"
},
{
"answer_id": 106089,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>In standard SQL, you enclose delimited identifiers in double quotes. This means that:</p>\n\n<pre><code>SELECT * FROM \"SomeTable\" WHERE \"SomeColumn\" = ?\n</code></pre>\n\n<p>will select from a table called SomeTable with the shown capitalization (not a case-converted version of the name), and will apply a condition to a column called SomeColumn with the shown capitalization.</p>\n\n<p>Of itself, that's not very helpful, but...if you can apply the escape() technique with double quotes to the names entered via your web form, then you can build up your query reasonably confidently.</p>\n\n<p>Of course, you said you wanted to avoid using escape - and indeed you don't have to use it on the parameters where you provide the ? place-holders. But where you are putting user-provided data into the query, you need to protect yourself from malicious people.</p>\n\n<p>Different DBMS have different ways of providing delimited identifiers. MS SQL Server, for instance, seems to use square brackets [SomeTable] instead of double quotes.</p>\n"
},
{
"answer_id": 106090,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 0,
"selected": false,
"text": "<p>Column names in some databases can contain spaces, which mean you'd have to quote the column name, but if your database contains no such columns, just run the column name through a regular expression or some sort of check before splicing into the SQL:</p>\n\n<pre><code>if ( $column !~ /^\\w+$/ ) {\n die \"Bad column name [$column]\";\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
]
| I have some code which utilizes parameterized queries to prevent against injection, but I also need to be able to dynamically construct the query regardless of the structure of the table. What is the proper way to do this?
Here's an example, say I have a table with columns Name, Address, Telephone. I have a web page where I run **Show Columns** and populate a select drop-down with them as options.
Next, I have a textbox called **Search**. This textbox is used as the parameter.
Currently my code looks something like this:
```
result = pquery('SELECT * FROM contacts WHERE `' + escape(column) + '`=?', search);
```
I get an icky feeling from it though. The reason I'm using parameterized queries is to avoid using **escape**. Also, **escape** is likely not designed for escaping column names.
How can I make sure this works the way I intend?
**Edit:**
The reason I require dynamic queries is that the schema is user-configurable, and I will not be around to fix anything hard-coded. | Instead of passing the column names, just pass an identifier that you code will translate to a column name using a hardcoded table. This means you don't need to worry about malicious data being passed, since all the data is either translated legally, or is known to be invalid. Psudoish code:
```
@columns = qw/Name Address Telephone/;
if ($columns[$param]) {
$query = "select * from contacts where $columns[$param] = ?";
} else {
die "Invalid column!";
}
run_sql($query, $search);
``` |
106,033 | <p>Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes?</p>
| [
{
"answer_id": 106050,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 0,
"selected": false,
"text": "<p>You can wrap the .NET component in a COM component - which is quite easy with the .NET tools - and call it via COM.</p>\n"
},
{
"answer_id": 106060,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 0,
"selected": false,
"text": "<p>If the low level parts in in C++ then typically you call that from the C# code passing in the values that are needed. This should work in the standard way that you're probably accustomed to. You'll need to read up on marshalling for example.</p>\n\n<p>You could look at this <a href=\"http://blogs.msdn.com/deeptanshuv/archive/2005/06/26/432870.aspx\" rel=\"nofollow noreferrer\">blog</a> to get some concrete details.</p>\n"
},
{
"answer_id": 106097,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "<p>Create your .NET assembly as normal, but be sure to mark the class with the ClassInterface(ClassInterfaceType.AutoDual) and be sure an assembly info SetAssemblyAtribute to ComVisible( true ).</p>\n\n<p>Then, create the COM wrapper with REGASM:</p>\n\n<p>regasm mydll.dll /tlb:mydll.tbl /codebase f:_code\\ClassLibraryForCom</p>\n\n<p>be sure to use the /codebase directive -- it is necessary if you aren't going to give the assembly a strong name. </p>\n\n<p>rp</p>\n"
},
{
"answer_id": 106101,
"author": "Francis B.",
"author_id": 17067,
"author_profile": "https://Stackoverflow.com/users/17067",
"pm_score": 5,
"selected": true,
"text": "<pre><code>[Guid(\"123565C4-C5FA-4512-A560-1D47F9FDFA20\")]\npublic interface IConfig\n{\n [DispId(1)]\n string Destination{ get; }\n\n [DispId(2)]\n void Unserialize();\n\n [DispId(3)]\n void Serialize();\n}\n\n[ComVisible(true)]\n[Guid(\"12AC8095-BD27-4de8-A30B-991940666927\")]\n[ClassInterface(ClassInterfaceType.None)]\npublic sealed class Config : IConfig\n{\n public Config()\n {\n }\n\n public string Destination\n {\n get { return \"\"; }\n }\n\n public void Serialize()\n {\n }\n\n public void Unserialize()\n {\n }\n}\n</code></pre>\n\n<p>After that, you need to regasm your assembly. Regasm will add the necessary registry entries to allow your .NET component to be see as a COM Component. After, you can call your .NET Component in C++ in the same way as any other COM component.</p>\n"
},
{
"answer_id": 106136,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 0,
"selected": false,
"text": "<p>Since C# can import C++ standard exports, it might be easier to load up your C++ dll inside of a C# application instead of using COM from C++.</p>\n\n<p>See documentation for System.Runtime.InteropServices.DllImport.</p>\n\n<p>Also, here is a complete list of the types of Interop that you can do between managed and unmanaged code:</p>\n\n<p><a href=\"http://blogs.msdn.com/deeptanshuv/archive/2005/06/26/432870.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/deeptanshuv/archive/2005/06/26/432870.aspx</a></p>\n\n<p>In a nutshell:</p>\n\n<p>(a) Using COM-Interop</p>\n\n<p>(b) Using imports/pinvoke (explicit method calls)</p>\n\n<p>(c) IJW and MC++ apps : MC++ & IJW apps can freely call back and forth to each other.</p>\n\n<p>(d) Hosting. This is rare, but the CLR can be hosted by an unmanaged app which means that the runtime invokes a bunch of hosting callbacks.</p>\n"
},
{
"answer_id": 106144,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 1,
"selected": false,
"text": "<p>If you can have both managed and unmanaged code in your process, you can create a C++ class with virtual functions. Implement the class with mixed mode C++/CLI. Inject the implementation to your C++ code, so that the (high-level) implementation can be called from your (low-level) C++ code.</p>\n"
},
{
"answer_id": 106163,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 4,
"selected": false,
"text": "<p>You should really look into C++/CLI. It makes tasks like this nearly trivial. </p>\n\n<p>Otherwise, you'll have to generate COM wrappers around the C# code and have your C++ app call the COM wrappers.</p>\n"
},
{
"answer_id": 106241,
"author": "cwick",
"author_id": 4828,
"author_profile": "https://Stackoverflow.com/users/4828",
"pm_score": 0,
"selected": false,
"text": "<p>I found this link to embedding Mono:\n<a href=\"http://www.mono-project.com/Embedding_Mono\" rel=\"nofollow noreferrer\">http://www.mono-project.com/Embedding_Mono</a></p>\n\n<p>It provides what seems to be a pretty straightforward interface for interacting with assemblies. This could be an attractive option, especially if you want to be cross-platform</p>\n"
},
{
"answer_id": 106751,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>I would definitely investigate C++/CLI for this and avoid COM and all the registration hassles that tends to produce.</p>\n\n<p>What is the motivation for using C++? If it is simply style then you might find you can write everything in C++/CLI. If it is performance then calling back and forth between managed C++ and unmanaged code is relatively straight forward. But it is never going to be transparent. You can't pass a managed pointer to unmanaged code first without pinning it so that the garbage collector won't move it, and of course unmanaged code won't know about your managed types. But managed (C++) code can know about your unmanaged types.</p>\n\n<p>One other thing to note is that C++/CLI assemblies that include <strong>unmanaged</strong> code will be architecture specific. You will need separates builds for x86 and x64 (and IA64).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
]
| Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes? | ```
[Guid("123565C4-C5FA-4512-A560-1D47F9FDFA20")]
public interface IConfig
{
[DispId(1)]
string Destination{ get; }
[DispId(2)]
void Unserialize();
[DispId(3)]
void Serialize();
}
[ComVisible(true)]
[Guid("12AC8095-BD27-4de8-A30B-991940666927")]
[ClassInterface(ClassInterfaceType.None)]
public sealed class Config : IConfig
{
public Config()
{
}
public string Destination
{
get { return ""; }
}
public void Serialize()
{
}
public void Unserialize()
{
}
}
```
After that, you need to regasm your assembly. Regasm will add the necessary registry entries to allow your .NET component to be see as a COM Component. After, you can call your .NET Component in C++ in the same way as any other COM component. |
106,053 | <p>I already know the obvious answer to this question: "just download <insert favorite windows grep or grep-like tool here>". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep":</p>
<pre>
perl -n -e "print $_ if (m![expression]!);" [filename]
</pre>
<p>How do I write a batch script that I can do something like, for example:</p>
<pre>
dir | grep.bat mypattern
grep.bat mypattern myfile.txt
</pre>
<p><strong>EDIT</strong>: Even though I marked another "answer", I wanted to give kudos to <a href="https://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099">Ray Hayes answer</a>, as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.</p>
| [
{
"answer_id": 106099,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 5,
"selected": false,
"text": "<p>Most of the power of grep is already available on your machine in the Windows application FindStr.exe which is part of all Windows 2000, XP and Vista machines! It offers RegExpr etc.</p>\n\n<p>Far easier than a batch file which in turn calls Perl!</p>\n\n<pre><code>c:\\>FindStr /? \nSearches for strings in files.\n\nFINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]\n [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]\n strings [[drive:][path]filename[ ...]]\n\n /B Matches pattern if at the beginning of a line.\n /E Matches pattern if at the end of a line.\n /L Uses search strings literally.\n /R Uses search strings as regular expressions.\n /S Searches for matching files in the current directory and all\n subdirectories.\n /I Specifies that the search is not to be case-sensitive.\n /X Prints lines that match exactly.\n /V Prints only lines that do not contain a match.\n /N Prints the line number before each line that matches.\n /M Prints only the filename if a file contains a match.\n /O Prints character offset before each matching line.\n /P Skip files with non-printable characters.\n /OFF[LINE] Do not skip files with offline attribute set.\n /A:attr Specifies color attribute with two hex digits. See \"color /?\"\n /F:file Reads file list from the specified file(/ stands for console).\n /C:string Uses specified string as a literal search string.\n /G:file Gets search strings from the specified file(/ stands for console).\n /D:dir Search a semicolon delimited list of directories\n strings Text to be searched for.\n [drive:][path]filename\n Specifies a file or files to search.\n\nUse spaces to separate multiple search strings unless the argument is prefixed\nwith /C. For example, 'FINDSTR \"hello there\" x.y' searches for \"hello\" or\n\"there\" in file x.y. 'FINDSTR /C:\"hello there\" x.y' searches for\n\"hello there\" in file x.y.\n\nRegular expression quick reference:\n . Wildcard: any character\n * Repeat: zero or more occurances of previous character or class\n ^ Line position: beginning of line\n $ Line position: end of line\n [class] Character class: any one character in set\n [^class] Inverse class: any one character not in set\n [x-y] Range: any characters within the specified range\n \\x Escape: literal use of metacharacter x\n \\<xyz Word position: beginning of word\n xyz\\> Word position: end of word\n</code></pre>\n"
},
{
"answer_id": 106102,
"author": "ian93",
"author_id": 93438,
"author_profile": "https://Stackoverflow.com/users/93438",
"pm_score": 1,
"selected": false,
"text": "<p>You need to do something like this:</p>\n\n<pre><code>@echo off\nperl -x -S script.pl %1\n</code></pre>\n\n<p>The \"%1\" will pass the argument to the Perl script. Save it as a .bat file, and you're good to go.</p>\n"
},
{
"answer_id": 106140,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 4,
"selected": true,
"text": "<p>I wrote this a while back:</p>\n\n<pre><code>@rem = '--*-Perl-*--\n@echo off\nperl -x -S %0 %*\ngoto endofperl\n\n\n@rem -- BEGIN PERL -- ';\n#!d:/Perl/bin/perl.exe -w\n#line 10\nuse strict; \n#use Test::Setup;\nuse Getopt::Long;\n\nGetopt::Long::Configure (\"bundling\");\n\nmy $ignore_case = 0;\nmy $number_line = 0;\nmy $invert_results = 0;\nmy $verbose = 0;\n\nmy $result = GetOptions( \n 'i|ignore_case' => \\$ignore_case, \n 'n|number' => \\$number_line,\n 'v|invert' => \\$invert_results,\n 'verbose' => \\$verbose,\n);\nmy $regex = shift;\n\nif ( $ignore_case ) { \n $regex = \"(?i:$regex)\";\n}\n$regex = qr/$regex/;\nprint \"\\$regex=$regex\\n\";\nif ( $verbose ) { \n print \"Verbose: Ignoring case.\\n\" if $ignore_case;\n print \"Verbose: Printing file name and line number.\\n\" if $number_line;\n print \"Verbose: Inverting result set.\\n\" if $invert_results;\n print \"\\n\";\n}\n\n@ARGV = map { glob \"$_\" } @ARGV;\n\nwhile ( <> ) { \n my $matches = m/$regex/;\n next unless $matches ^ $invert_results;\n print \"$ARGV\\:$.:\" if $number_line;\n print;\n}\n\n__END__\n:endofperl\n</code></pre>\n"
},
{
"answer_id": 106187,
"author": "Jim Olsen",
"author_id": 15603,
"author_profile": "https://Stackoverflow.com/users/15603",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Axeman and Mr. Hayes about using a better tool for the job. That said, you could try something like this in your batch file to run your custom script against a file wildcard expression:</p>\n\n<pre><code>@echo off\n\nfor /f \"usebackq delims==\" %%f in (`dir /w /b %2`) do (\n perl -n -e \"print $_ if (m!%1!);\" \"%%f\"\n REM or something like: myperlscript.pl %1 \"%%f\"\n)\n</code></pre>\n\n<p>In this way, you can do things like \"grep mypattern myfile.txt\", \"grep mypattern .\", \"grep mypattern *.doc\", etc.</p>\n"
},
{
"answer_id": 106239,
"author": "hexten",
"author_id": 10032,
"author_profile": "https://Stackoverflow.com/users/10032",
"pm_score": 4,
"selected": false,
"text": "<p>Download and install <a href=\"http://search.cpan.org/dist/ack/\" rel=\"noreferrer\">ack</a>. It's a superior replacement to grep and - thanks to Perl's magic dual mode .BAT / Perl script magic - it'll work on the command line for you.</p>\n"
},
{
"answer_id": 106326,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "<p>First, turn it into a real script instead of a one-liner:</p>\n\n<pre><code>use strict;\nuse warnings;\n\nmy $pattern = shift or die \"Usage: $0 <pattern> [files|-]\\n\";\nwhile (<>) { print if /$pattern/ }\n</code></pre>\n\n<p>Then turn it into a batch file using pl2bat:</p>\n\n<pre><code>pl2bat mygrep.pl\n</code></pre>\n\n<p>This will create \"mygrep.bat\".</p>\n\n<p>For a full-featured grep (and many other Unix applications) written completely in Perl, see the <a href=\"http://search.cpan.org/dist/ppt/\" rel=\"nofollow noreferrer\">Perl Power Tools</a> project.</p>\n\n<p>While the Perl Power Tools are good if you can only run Perl, I generally prefer the set of <a href=\"http://gnuwin32.sourceforge.net/\" rel=\"nofollow noreferrer\">GnuWin32</a> tools. They don't require installation. (You don't need administrative privileges, just a directory you can write to.)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13140/"
]
| I already know the obvious answer to this question: "just download <insert favorite windows grep or grep-like tool here>". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep":
```
perl -n -e "print $_ if (m![expression]!);" [filename]
```
How do I write a batch script that I can do something like, for example:
```
dir | grep.bat mypattern
grep.bat mypattern myfile.txt
```
**EDIT**: Even though I marked another "answer", I wanted to give kudos to [Ray Hayes answer](https://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099), as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted. | I wrote this a while back:
```
@rem = '--*-Perl-*--
@echo off
perl -x -S %0 %*
goto endofperl
@rem -- BEGIN PERL -- ';
#!d:/Perl/bin/perl.exe -w
#line 10
use strict;
#use Test::Setup;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
my $ignore_case = 0;
my $number_line = 0;
my $invert_results = 0;
my $verbose = 0;
my $result = GetOptions(
'i|ignore_case' => \$ignore_case,
'n|number' => \$number_line,
'v|invert' => \$invert_results,
'verbose' => \$verbose,
);
my $regex = shift;
if ( $ignore_case ) {
$regex = "(?i:$regex)";
}
$regex = qr/$regex/;
print "\$regex=$regex\n";
if ( $verbose ) {
print "Verbose: Ignoring case.\n" if $ignore_case;
print "Verbose: Printing file name and line number.\n" if $number_line;
print "Verbose: Inverting result set.\n" if $invert_results;
print "\n";
}
@ARGV = map { glob "$_" } @ARGV;
while ( <> ) {
my $matches = m/$regex/;
next unless $matches ^ $invert_results;
print "$ARGV\:$.:" if $number_line;
print;
}
__END__
:endofperl
``` |
106,058 | <p>Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some.</p>
<p>Is there a <em>practical</em> code example of Lisp's power?<br/>(Preferably alongside equivalent logic coded in a regular language.)</p>
| [
{
"answer_id": 106075,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 3,
"selected": false,
"text": "<p>Have you taken a look at <a href=\"https://web.archive.org/web/20170702100142/http://www.weitz.de/macros.lisp\" rel=\"nofollow noreferrer\">this</a> explanation of why macros are powerful and flexible? No examples in other languages though, sorry, but it might sell you on macros.</p>\n"
},
{
"answer_id": 106088,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 4,
"selected": false,
"text": "<p>The best example I can think of that is widely available is the book by Paul Graham, <a href=\"http://www.paulgraham.com/onlisp.html\" rel=\"noreferrer\">On Lisp</a>. The full PDF can be downloaded from the link I just gave. You could also try <a href=\"http://gigamonkeys.com/book/\" rel=\"noreferrer\">Practical Common Lisp</a> (also fully available on the web).</p>\n\n<p>I have a lot of unpractical examples. I once wrote a program in about 40 lines of lisp which could parse itself, treat its source as a lisp list, do a tree traversal of the list and build an expression that evaluated to WALDO if the waldo identifier existed in the source or evaluate to nil if waldo was not present. The returned expression was constructed by adding calls to car/cdr to the original source that was parsed. I have no idea how to do this in other languages in 40 lines of code. Perhaps perl can do it in even fewer lines.</p>\n"
},
{
"answer_id": 106176,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": -1,
"selected": false,
"text": "<p>John Ousterhout made this interesting observation regarding Lisp in 1994:</p>\n\n<blockquote>\n <p>Language designers love to argue about why this language or that language\n <strong>must</strong> be better or worse a priori, but none of these arguments really\n matter a lot. Ultimately all language issues get settled when users vote\n with their feet.</p>\n \n <p><strong><em>If [a language] makes people more productive then they will use\n it; when some other language comes along that is better (or if it is\n here already), then people will switch to that language. This is The\n Law, and it is good. The Law says to me that Scheme (or any other Lisp\n dialect) is probably not the \"right\" language: too many people have\n voted with their feet over the last 30 years.</em></strong></p>\n</blockquote>\n\n<p><a href=\"http://www.vanderburg.org/OldPages/Tcl/war/0009.html\" rel=\"nofollow noreferrer\">http://www.vanderburg.org/OldPages/Tcl/war/0009.html</a></p>\n"
},
{
"answer_id": 106190,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 4,
"selected": false,
"text": "<p>You may find this article helpful: <a href=\"http://www.defmacro.org/ramblings/lisp.html\" rel=\"noreferrer\">http://www.defmacro.org/ramblings/lisp.html</a></p>\n\n<p>That said, it's very, very hard to give short, practical examples of Lisp's power because it really shines only in non-trivial code. When your project grows to a certain size, you will appreciate Lisp's abstraction facilities and be glad that you've been using them. Reasonably short code samples, on the other hand, will never give you a satisfying demonstration of what makes Lisp great because other languages' predefined abbreviations will look more attractive in small examples than Lisp's flexibility in managing domain-specific abstractions.</p>\n"
},
{
"answer_id": 106246,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>@Mark,</p>\n\n<p>While there is some truth to what you are saying, I believe it is not always as straight forward.</p>\n\n<p>Programmers and people in general don't always take the time to evaluate all the possibilities and decide to switch languages. Often It's the managers that decide, or the schools that teach the first languages ... and programmers never have the need to invest enough amount of time to get to a certain level were they can decide this language saves me more time than that language.</p>\n\n<p>Plus you have to admit that languages that have the backing of huge commercial entities such as Microsoft or Sun will always have an advantage in the market compared to languages without such backing.</p>\n\n<p>In order to answer the original question, Paul Graham tries to give an example <a href=\"http://www.paulgraham.com/accgen.html\" rel=\"nofollow noreferrer\">here</a> even though I admit it is not necessarily as <em>practical</em> as I would like :-)</p>\n"
},
{
"answer_id": 106320,
"author": "drewr",
"author_id": 3227,
"author_profile": "https://Stackoverflow.com/users/3227",
"pm_score": 2,
"selected": false,
"text": "<p>You might find <a href=\"http://www.lispcast.com/drupal/node/42\" rel=\"nofollow noreferrer\">this post</a> by Eric Normand helpful. He describes how as a codebase grows, Lisp helps by letting you build the language up to your application. While this often takes extra effort early on, it gives you a big advantage later.</p>\n"
},
{
"answer_id": 106426,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 4,
"selected": false,
"text": "<p>Actually, a good practical example is the Lisp LOOP Macro.</p>\n\n<p><a href=\"http://www.ai.sri.com/pkarp/loop.html\" rel=\"noreferrer\">http://www.ai.sri.com/pkarp/loop.html</a></p>\n\n<p>The LOOP macro is simply that -- a Lisp macro. Yet it basically defines a mini looping DSL (Domain Specific Language).</p>\n\n<p>When you browse through that little tutorial, you can see (even as a novice) that it's difficult to know what part of the code is part of the Loop macro, and which is \"normal\" Lisp.</p>\n\n<p>And that's one of the key components of Lisps expressiveness, that the new code really can't be distinguished from the system. </p>\n\n<p>While in, say, Java, you may not (at a glance) be able to know what part of a program comes from the standard Java library versus your own code, or even a 3rd party library, you DO know what part of the code is the Java language rather than simply method calls on classes. Granted, it's ALL the \"Java language\", but as programmer, you are limited to only expressing your application as a combination of classes and methods (and now, annotations). Whereas in Lisp, literally everything is up for grabs.</p>\n\n<p>Consider the Common SQL interface to connect Common Lisp to SQL. Here, <a href=\"http://clsql.b9.com/manual/loop-tuples.html\" rel=\"noreferrer\">http://clsql.b9.com/manual/loop-tuples.html</a>, they show how the CL Loop macro is extended to make the SQL binding a \"first class citizen\". </p>\n\n<p>You can also observe constructs such as \"[select [first-name] [last-name] :from [employee] :order-by [last-name]]\". This is part of the CL-SQL package and implemented as a \"reader macro\".</p>\n\n<p>See, in Lisp, not only can you make macros to create new constructs, like data structures, control structures, etc. But you can even change the syntax of the language through a reader macro. Here, they're using a reader macro (in the case, the '[' symbol) to drop in to a SQL mode to make SQL work like embedded SQL, rather than as just raw strings like in many other languages. </p>\n\n<p>As application developers, our task is to convert our processes and constructs in to a form that the processor can understand. That means we, inevitably, have to \"talk down\" to the computer language, since it \"doesn't understand\" us.</p>\n\n<p>Common Lisp is one of the few environments where we can not only build our application from the top down, but where we can lift the language and environment up to meet us half way. We can code at both ends.</p>\n\n<p>Mind, as elegant as this can be, it's no panacea. Obviously there are other factors that influence language and environment choice. But it's certainly worth learning and playing with. I think learning Lisp is a great way to advance your programming, even in other languages.</p>\n"
},
{
"answer_id": 107544,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 6,
"selected": false,
"text": "<p>I like macros.</p>\n\n<p>Here's code to stuff away attributes for people from LDAP. I just happened to have that code lying around and fiigured it'd be useful for others.</p>\n\n<p>Some people are confused over a supposed runtime penalty of macros, so I've added an attempt at clarifying things at the end.</p>\n\n<h1>In The Beginning, There Was Duplication</h1>\n\n<pre><code>(defun ldap-users ()\n (let ((people (make-hash-table :test 'equal)))\n (ldap:dosearch (ent (ldap:search *ldap* \"(&(telephonenumber=*) (cn=*))\"))\n (let ((mail (car (ldap:attr-value ent 'mail)))\n (uid (car (ldap:attr-value ent 'uid)))\n (name (car (ldap:attr-value ent 'cn)))\n (phonenumber (car (ldap:attr-value ent 'telephonenumber))))\n (setf (gethash uid people)\n (list mail name phonenumber))))\n people))\n</code></pre>\n\n<p>You can think of a \"let binding\" as a local variable, that disappears outside the LET form. Notice the form of the bindings -- they are very similar, differing only in the attribute of the LDAP entity and the name (\"local variable\") to bind the value to. Useful, but a bit verbose and contains duplication.</p>\n\n<h1>On the Quest for Beauty</h1>\n\n<p>Now, wouldn't it be nice if we didn't have to have all that duplication? A common idiom is is WITH-... macros, that binds values based on an expression that you can grab the values from. Let's introduce our own macro that works like that, WITH-LDAP-ATTRS, and replace it in our original code.</p>\n\n<pre><code>(defun ldap-users ()\n (let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal!\n (ldap:dosearch (ent (ldap:search *ldap* \"(&(telephonenumber=*) (cn=*))\"))\n (with-ldap-attrs (mail uid name phonenumber) ent\n (setf (gethash uid people)\n (list mail name phonenumber))))\n people))\n</code></pre>\n\n<p>Did you see how a bunch of lines suddenly disappeared, and was replaced with just one single line? How to do this? Using macros, of course -- code that writes code! Macros in Lisp is a totally different animal than the ones you can find in C/C++ through the use of the pre-processor: here, you can run <em>real</em> Lisp code (not the <code>#define</code> fluff in cpp) that generates Lisp code, before the other code is compiled. Macros can use any real Lisp code, i.e., ordinary functions. Essentially no limits.</p>\n\n<h1>Getting Rid of Ugly</h1>\n\n<p>So, let's see how this was done. To replace one attribute, we define a function.</p>\n\n<pre><code>(defun ldap-attr (entity attr)\n `(,attr (car (ldap:attr-value ,entity ',attr))))\n</code></pre>\n\n<p>The backquote syntax looks a bit hairy, but what it does is easy. When you call LDAP-ATTRS, it'll spit out a list that contains the <em>value</em> of <code>attr</code> (that's the comma), followed by <code>car</code> (\"first element in the list\" (cons pair, actually), and there is in fact a function called <code>first</code> you can use, too), which receives the first value in the list returned by <code>ldap:attr-value</code>. Because this isn't code we want to run when we compile the code (getting the attribute values is what we want to do when we <em>run</em> the program), we don't add a comma before the call.</p>\n\n<p>Anyway. Moving along, to the rest of the macro.</p>\n\n<pre><code>(defmacro with-ldap-attrs (attrs ent &rest body)\n `(let ,(loop for attr in attrs\n collecting `,(ldap-attr ent attr))\n ,@body)) \n</code></pre>\n\n<p>The <code>,@</code>-syntax is to put the contents of a list somewhere, instead of the actual list. </p>\n\n<h1>Result</h1>\n\n<p>You can easily verify that this will give you the right thing. Macros are often written this way: you start off with code you want to make simpler (the output), what you want to write instead (the input), and then you start molding the macro until your input gives the correct output. The function <code>macroexpand-1</code> will tell you if your macro is correct:</p>\n\n<pre><code>(macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent\n (format t \"~a with ~a\" mail phonenumber)))\n</code></pre>\n\n<p>evaluates to</p>\n\n<pre><code>(let ((mail (car (trivial-ldap:attr-value ent 'mail)))\n (phonenumber (car (trivial-ldap:attr-value ent 'phonenumber))))\n (format t \"~a with ~a\" mail phonenumber))\n</code></pre>\n\n<p>If you compare the LET-bindings of the expanded macro with the code in the beginning, you'll find that it is in the same form!</p>\n\n<h1>Compile-time vs Runtime: Macros vs Functions</h1>\n\n<p>A macro is code that is run at <em>compile-time</em>, with the added twist that they can call any <em>ordinary</em> function or macro as they please! It's not much more than a fancy filter, taking some arguments, applying some transformations and then feeding the compiler the resulting s-exps.</p>\n\n<p>Basically, it lets you write your code in verbs that can be found in the problem domain, instead of low-level primitives from the language! As a silly example, consider the following (if <code>when</code> wasn't already a built-in)::</p>\n\n<pre><code>(defmacro my-when (test &rest body)\n `(if ,test \n (progn ,@body)))\n</code></pre>\n\n<p><code>if</code> is a built-in primitive that will only let you execute <em>one</em> form in the branches, and if you want to have more than one, well, you need to use <code>progn</code>::</p>\n\n<pre><code>;; one form\n(if (numberp 1)\n (print \"yay, a number\"))\n\n;; two forms\n(if (numberp 1)\n (progn\n (assert-world-is-sane t)\n (print \"phew!\"))))\n</code></pre>\n\n<p>With our new friend, <code>my-when</code>, we could both a) use the more appropriate verb if we don't have a false branch, and b) add an implicit sequencing operator, i.e. <code>progn</code>::</p>\n\n<pre><code>(my-when (numberp 1)\n (assert-world-is-sane t)\n (print \"phew!\"))\n</code></pre>\n\n<p>The compiled code will never contain <code>my-when</code>, though, because in the first pass, all macros are expanded so there is <em>no runtime penalty</em> involved!</p>\n\n<pre><code>Lisp> (macroexpand-1 '(my-when (numberp 1)\n (print \"yay!\")))\n\n(if (numberp 1)\n (progn (print \"yay!\")))\n</code></pre>\n\n<p>Note that <code>macroexpand-1</code> only does one level of expansions; it's possible (most likely, in fact!) that the expansion continues further down. However, eventually you'll hit the compiler-specific implementation details which are often not very interesting. But continuing expanding the result will eventually either get you more details, or just your input s-exp back.</p>\n\n<p>Hope that clarifies things. Macros is a powerful tool, and one of the features in Lisp I like.</p>\n"
},
{
"answer_id": 108068,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 4,
"selected": false,
"text": "<p>I like <a href=\"https://en.wikipedia.org/wiki/Common_Lisp_Object_System\" rel=\"nofollow noreferrer\">Common Lisp Object System</a> (CLOS) and multimethods.</p>\n\n<p>Most, if not all, object-oriented programming languages have the basic notions of classes and methods. The following snippet in <a href=\"http://en.wikipedia.org/wiki/Python_%28programming_language%29\" rel=\"nofollow noreferrer\">Python</a> defines the classes PeelingTool and Vegetable (something similar to the Visitor pattern):</p>\n\n<pre><code>class PeelingTool:\n \"\"\"I'm used to peel things. Mostly fruit, but anything peelable goes.\"\"\"\n def peel(self, veggie):\n veggie.get_peeled(self)\n\nclass Veggie:\n \"\"\"I'm a defenseless Veggie. I obey the get_peeled protocol\n used by the PeelingTool\"\"\"\n def get_peeled(self, tool):\n pass\n\nclass FingerTool(PeelingTool):\n ...\n\nclass KnifeTool(PeelingTool):\n ...\n\nclass Banana(Veggie):\n def get_peeled(self, tool):\n if type(tool) == FingerTool:\n self.hold_and_peel(tool)\n elif type(tool) == KnifeTool:\n self.cut_in_half(tool)\n</code></pre>\n\n<p>You put the <code>peel</code> method in the PeelingTool and have the Banana accept it. But, it must belong to the PeelingTool class, so it can only be used if you have an instance of the PeelingTool class.</p>\n\n<p>The Common Lisp Object System version:</p>\n\n<pre><code>(defclass peeling-tool () ())\n(defclass knife-tool (peeling-tool) ())\n(defclass finger-tool (peeling-tool) ())\n\n(defclass veggie () ())\n(defclass banana (veggie) ())\n\n(defgeneric peel (veggie tool)\n (:documentation \"I peel veggies, or actually anything that wants to be peeled\"))\n\n;; It might be possible to peel any object using any tool,\n;; but I have no idea how. Left as an exercise for the reader\n(defmethod peel (veggie tool)\n ...)\n\n;; Bananas are easy to peel with our fingers!\n(defmethod peel ((veggie banana) (tool finger-tool))\n (with-hands (left-hand right-hand) *me*\n (hold-object left-hand banana)\n (peel-with-fingers right-hand tool banana)))\n\n;; Slightly different using a knife\n(defmethod peel ((veggie banana) (tool knife-tool))\n (with-hands (left-hand right-hand) *me*\n (hold-object left-hand banana)\n (cut-in-half tool banana)))\n</code></pre>\n\n<p>Anything can be written in any language that's Turing complete; the difference between the languages is how many hoops you have to jump through to get the equivalent result.</p>\n\n<p>A powerful languages like <a href=\"https://en.wikipedia.org/wiki/Common_Lisp\" rel=\"nofollow noreferrer\">Common Lisp</a>, with functionality such as macros and the CLOS, allows you to achieve results fast and easy without jumping through so many hoops that you either settle for a subpar solution, or find yourself becoming a kangaroo.</p>\n"
},
{
"answer_id": 108102,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 3,
"selected": false,
"text": "<p>The thing that I like most about Lisp (and <a href=\"http://en.wikipedia.org/wiki/Smalltalk\" rel=\"nofollow noreferrer\">Smalltalk</a>) systems, is that they feel alive. You can easily probe & modify Lisp systems while they are running.</p>\n\n<p>If this sounds mysterious, start <a href=\"http://en.wikipedia.org/wiki/Emacs\" rel=\"nofollow noreferrer\">Emacs</a>, and type some Lisp code. Type <code>C-M-x</code> and voilà! You just changed Emacs from within Emacs. You can go on and redefine all Emacs functions while it is running.</p>\n\n<p>Another thing is that the code = list equivalence make the frontier between code and data very thin. And thanks to macros, it is very easy to extend the language and make quick <a href=\"http://en.wikipedia.org/wiki/Domain-specific_language\" rel=\"nofollow noreferrer\">DSLs</a>.</p>\n\n<p>For instance, it is possible to code a basic HTML builder with which the code is very close to the produced HTML output:</p>\n\n<pre><code>(html\n (head\n (title \"The Title\"))\n (body\n (h1 \"The Headline\" :class \"headline\")\n (p \"Some text here\" :id \"content\")))\n</code></pre>\n\n<p>=></p>\n\n<pre><code><html>\n <head>\n <title>The title</title>\n </head>\n <body>\n <h1 class=\"headline\">The Headline</h1>\n <p id=\"contents\">Some text here</p>\n </body>\n</html>\n</code></pre>\n\n<p>In the Lisp code, auto indentation make the code look like the output, except there aren't any closing tags.</p>\n"
},
{
"answer_id": 109131,
"author": "Attila Lendvai",
"author_id": 14464,
"author_profile": "https://Stackoverflow.com/users/14464",
"pm_score": 3,
"selected": false,
"text": "<p>See how you can <strong>extend Common Lisp with XML templating</strong>: <a href=\"http://common-lisp.net/project/cl-quasi-quote/present-class.html\" rel=\"nofollow noreferrer\">cl-quasi-quote XML example</a>, <a href=\"http://common-lisp.net/project/cl-quasi-quote/\" rel=\"nofollow noreferrer\">project page</a>,</p>\n\n<pre><code>(babel:octets-to-string\n (with-output-to-sequence (*html-stream*)\n <div (constantAttribute 42\n someJavaScript `js-inline(print (+ 40 2))\n runtimeAttribute ,(concatenate 'string \"&foo\" \"&bar\"))\n <someRandomElement\n <someOther>>>))\n\n =>\n\n \"<div constantAttribute=\\\"42\\\"\n someJavaScript=\\\"javascript: print((40 + 2))\\\"\n runtimeAttribute=\\\"&amp;foo&amp;bar\\\">\n <someRandomElement>\n <someOther/>\n </someRandomElement>\n </div>\"\n</code></pre>\n\n<p>This is basically the same thing as Lisp's backtick reader (which is for list quasi quoting), but it also works for various other things like XML (installed on a special <> syntax), JavaScript (installed on `js-inline), etc.</p>\n\n<p>To make it clear, this is implemented in a <strong>user library</strong>! And it compiles the static XML, JavaScript, etc. parts into <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">UTF-8</a> encoded literal byte arrays that are ready to be written to the network stream. With a simple <code>,</code> (comma) you can get back to lisp and interleave runtime generated data into the literal byte arrays.</p>\n\n<p>This is not for the faint of heart, but this is what the library compiles the above into:</p>\n\n<pre><code>(progn\n (write-sequence\n #(60 100 105 118 32 99 111 110 115 116 97 110 116 65 116 116 114 105 98\n 117 116 101 61 34 52 50 34 32 115 111 109 101 74 97 118 97 83 99 114\n 105 112 116 61 34 106 97 118 97 115 99 114 105 112 116 58 32 112 114\n 105 110 116 40 40 52 48 32 43 32 50 41 41 34 32 114 117 110 116 105\n 109 101 65 116 116 114 105 98 117 116 101 61 34)\n *html-stream*)\n (write-quasi-quoted-binary\n (let ((*transformation*\n #<quasi-quoted-string-to-quasi-quoted-binary {1006321441}>))\n (transform-quasi-quoted-string-to-quasi-quoted-binary\n (let ((*transformation*\n #<quasi-quoted-xml-to-quasi-quoted-string {1006326E51}>))\n (locally\n (declare (sb-ext:muffle-conditions sb-ext:compiler-note))\n (let ((it (concatenate 'string \"runtime calculated: \" \"&foo\" \"&bar\")))\n (if it\n (transform-quasi-quoted-xml-to-quasi-quoted-string/attribute-value it)\n nil))))))\n *html-stream*)\n (write-sequence\n #(34 62 10 32 32 60 115 111 109 101 82 97 110 100 111 109 69 108 101 109\n 101 110 116 62 10 32 32 32 32 60 115 111 109 101 79 116 104 101 114 47\n 62 10 32 32 60 47 115 111 109 101 82 97 110 100 111 109 69 108 101 109\n 101 110 116 62 10 60 47 100 105 118 62 10)\n *html-stream*)\n +void+)\n</code></pre>\n\n<p>For reference, the two big byte vectors in the above look like this when converted to string:</p>\n\n<pre><code>\"<div constantAttribute=\\\"42\\\"\n someJavaScript=\\\"javascript: print((40 + 2))\\\"\n runtimeAttribute=\\\"\"\n</code></pre>\n\n<p>And the second one:</p>\n\n<pre><code>\"\\\">\n <someRandomElement>\n <someOther/>\n </someRandomElement>\n</div>\"\n</code></pre>\n\n<p>And it combines well with other Lisp structures like macros and functions. now, compare this to <a href=\"http://en.wikipedia.org/wiki/JavaServer_Pages\" rel=\"nofollow noreferrer\">JSPs</a>...</p>\n"
},
{
"answer_id": 118924,
"author": "Nowhere man",
"author_id": 400277,
"author_profile": "https://Stackoverflow.com/users/400277",
"pm_score": 4,
"selected": false,
"text": "<p>There are plenty of killer features in Lisp, but macros is one I love particularily, because there's not really a barrier anymore between what the language defines and what I define. For example, Common Lisp doesn't have a <strong>while</strong> construct. I once implemented it in my head, while walking. It's straightforward and clean:</p>\n\n<pre><code>(defmacro while (condition &body body)\n `(if ,condition\n (progn\n ,@body\n (do nil ((not ,condition))\n ,@body))))\n</code></pre>\n\n<p>Et voilà! You just extended the Common Lisp language with a new fundamental construct. You can now do:</p>\n\n<pre><code>(let ((foo 5))\n (while (not (zerop (decf foo)))\n (format t \"still not zero: ~a~%\" foo)))\n</code></pre>\n\n<p>Which would print:</p>\n\n<pre><code>still not zero: 4\nstill not zero: 3\nstill not zero: 2\nstill not zero: 1\n</code></pre>\n\n<p>Doing that in any non-Lisp language is left as an exercise for the reader...</p>\n"
},
{
"answer_id": 197430,
"author": "Nelson",
"author_id": 27366,
"author_profile": "https://Stackoverflow.com/users/27366",
"pm_score": 3,
"selected": false,
"text": "<p>I found this article quite interesting:</p>\n\n<p><a href=\"https://web.archive.org/web/20120419015920/http://www.antigreen.org/vadim/ProgLanguageComparison/lisp-cmp-with-cpp-java-etc/C++-vs-Lisp.html\" rel=\"nofollow noreferrer\">Programming Language Comparison: Lisp vs C++</a></p>\n\n<p>The author of the article, Brandon Corfman, writes about a study that compares solutions in Java, C++ and Lisp to a programming problem, and then writes his own solution in C++. The benchmark solution is Peter Norvig's 45 lines of Lisp (written in 2 hours).</p>\n\n<p>Corfman finds that it is difficult to reduce his solution to less than 142 lines of C++/STL. His analysis of why, is an interesting read.</p>\n"
},
{
"answer_id": 443123,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 3,
"selected": false,
"text": "<p>One thing I like is the fact that I can upgrade code \"run-time\" without losing application state. It's a thing only useful in some cases, but when it is useful, having it already there (or, for only a minimal cost during development) is MUCH cheaper than having to implement it from scratch. Especially since this comes at \"no to almost no\" cost.</p>\n"
},
{
"answer_id": 600372,
"author": "temp2290",
"author_id": 72071,
"author_profile": "https://Stackoverflow.com/users/72071",
"pm_score": 2,
"selected": false,
"text": "<p>The simple fact that it's a multi-paradigm language makes it very very flexible.</p>\n"
},
{
"answer_id": 811362,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 3,
"selected": false,
"text": "<p>I was an AI student at MIT in the 1970s. Like every other student, I thought language was paramount. Nevertheless, Lisp was the primary language. These are some things I still think it is pretty good for:</p>\n\n<ul>\n<li><p>Symbolic math. It is easy and instructive to write symbolic differentiation of an expression, and algebraic simplification. I still do those, even though I do them in C-whatever.</p></li>\n<li><p>Theorem proving. Every now & then I go on a temporary AI binge, like trying to prove that insertion sort is correct. For that I need to do symbolic manipulation, and I usually fall back on Lisp.</p></li>\n<li><p>Little domain-specific-languages. I know Lisp isn't <em>really</em> practical, but if I want to try out a little <a href=\"http://en.wikipedia.org/wiki/Domain-specific_language\" rel=\"nofollow noreferrer\">DSL</a> without having to get all wrapped up in parsing, etc., Lisp macros make it easy.</p></li>\n<li><p>Little play algorithms like minimax game tree search can be done in like three lines.</p></li>\n<li>Want to try <a href=\"https://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"nofollow noreferrer\">lambda calculus</a>? It's easy in Lisp.</li>\n</ul>\n\n<p>Mainly what Lisp does for me is mental exercise. Then I can carry that over into more practical languages.</p>\n\n<p>P.S. Speaking of lambda calculus, what also started in the 1970s, in that same AI millieu, was that OO started invading everybody's brain, and somehow, interest in what it <em>is</em> seems to have crowded out much interest in what it is <em>good for</em>. I.e. work on machine learning, natural language, vision, problem solving, all sort of went to the back of the room while classes, messages, types, polymorphism, etc. went to the front.</p>\n"
},
{
"answer_id": 936728,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 2,
"selected": false,
"text": "<p>One specific thing that impressed me is the ability to write your own object-oriented programming extension, if you happen not to like the included CLOS.</p>\n\n<p>One of them is in <a href=\"http://garnetlisp.sourceforge.net/\" rel=\"nofollow noreferrer\">Garnet</a>, and one in Paul Graham's <a href=\"http://www.paulgraham.com/onlisp.html\" rel=\"nofollow noreferrer\"><em>On Lisp</em></a>.</p>\n\n<p>There's also a package called <a href=\"http://clocc.sourceforge.net/clocc/src/screamer/README\" rel=\"nofollow noreferrer\">Screamer</a> that allows nondeterministic programming (which I haven't evaluated).</p>\n\n<p>Any language that allows you to change it to support different programming paradigms has to be flexible. </p>\n"
},
{
"answer_id": 1315646,
"author": "Lispnik",
"author_id": 161234,
"author_profile": "https://Stackoverflow.com/users/161234",
"pm_score": 3,
"selected": false,
"text": "<p>I like this macro example from <a href=\"http://common-lisp.net/cgi-bin/viewcvs.cgi/cl-selenium/?root=cl-selenium\" rel=\"noreferrer\">http://common-lisp.net/cgi-bin/viewcvs.cgi/cl-selenium/?root=cl-selenium</a> It's a Common Lisp binding to Selenium (a web browser test framework), but instead of mapping every method, it reads Selenium's own API definition XML document at compile time and generates the mapping code using macros. You can see the generated API here: common-lisp.net/project/cl-selenium/api/selenium-package/index.html</p>\n\n<p>This is essentially driving macros with external data, which happens to be an XML document in this case, but could have been as complex is reading from a database or network. This is the power of having the entire Lisp environment available to you at compile time.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9360/"
]
| Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some.
Is there a *practical* code example of Lisp's power?
(Preferably alongside equivalent logic coded in a regular language.) | I like macros.
Here's code to stuff away attributes for people from LDAP. I just happened to have that code lying around and fiigured it'd be useful for others.
Some people are confused over a supposed runtime penalty of macros, so I've added an attempt at clarifying things at the end.
In The Beginning, There Was Duplication
=======================================
```
(defun ldap-users ()
(let ((people (make-hash-table :test 'equal)))
(ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))"))
(let ((mail (car (ldap:attr-value ent 'mail)))
(uid (car (ldap:attr-value ent 'uid)))
(name (car (ldap:attr-value ent 'cn)))
(phonenumber (car (ldap:attr-value ent 'telephonenumber))))
(setf (gethash uid people)
(list mail name phonenumber))))
people))
```
You can think of a "let binding" as a local variable, that disappears outside the LET form. Notice the form of the bindings -- they are very similar, differing only in the attribute of the LDAP entity and the name ("local variable") to bind the value to. Useful, but a bit verbose and contains duplication.
On the Quest for Beauty
=======================
Now, wouldn't it be nice if we didn't have to have all that duplication? A common idiom is is WITH-... macros, that binds values based on an expression that you can grab the values from. Let's introduce our own macro that works like that, WITH-LDAP-ATTRS, and replace it in our original code.
```
(defun ldap-users ()
(let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal!
(ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))"))
(with-ldap-attrs (mail uid name phonenumber) ent
(setf (gethash uid people)
(list mail name phonenumber))))
people))
```
Did you see how a bunch of lines suddenly disappeared, and was replaced with just one single line? How to do this? Using macros, of course -- code that writes code! Macros in Lisp is a totally different animal than the ones you can find in C/C++ through the use of the pre-processor: here, you can run *real* Lisp code (not the `#define` fluff in cpp) that generates Lisp code, before the other code is compiled. Macros can use any real Lisp code, i.e., ordinary functions. Essentially no limits.
Getting Rid of Ugly
===================
So, let's see how this was done. To replace one attribute, we define a function.
```
(defun ldap-attr (entity attr)
`(,attr (car (ldap:attr-value ,entity ',attr))))
```
The backquote syntax looks a bit hairy, but what it does is easy. When you call LDAP-ATTRS, it'll spit out a list that contains the *value* of `attr` (that's the comma), followed by `car` ("first element in the list" (cons pair, actually), and there is in fact a function called `first` you can use, too), which receives the first value in the list returned by `ldap:attr-value`. Because this isn't code we want to run when we compile the code (getting the attribute values is what we want to do when we *run* the program), we don't add a comma before the call.
Anyway. Moving along, to the rest of the macro.
```
(defmacro with-ldap-attrs (attrs ent &rest body)
`(let ,(loop for attr in attrs
collecting `,(ldap-attr ent attr))
,@body))
```
The `,@`-syntax is to put the contents of a list somewhere, instead of the actual list.
Result
======
You can easily verify that this will give you the right thing. Macros are often written this way: you start off with code you want to make simpler (the output), what you want to write instead (the input), and then you start molding the macro until your input gives the correct output. The function `macroexpand-1` will tell you if your macro is correct:
```
(macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent
(format t "~a with ~a" mail phonenumber)))
```
evaluates to
```
(let ((mail (car (trivial-ldap:attr-value ent 'mail)))
(phonenumber (car (trivial-ldap:attr-value ent 'phonenumber))))
(format t "~a with ~a" mail phonenumber))
```
If you compare the LET-bindings of the expanded macro with the code in the beginning, you'll find that it is in the same form!
Compile-time vs Runtime: Macros vs Functions
============================================
A macro is code that is run at *compile-time*, with the added twist that they can call any *ordinary* function or macro as they please! It's not much more than a fancy filter, taking some arguments, applying some transformations and then feeding the compiler the resulting s-exps.
Basically, it lets you write your code in verbs that can be found in the problem domain, instead of low-level primitives from the language! As a silly example, consider the following (if `when` wasn't already a built-in)::
```
(defmacro my-when (test &rest body)
`(if ,test
(progn ,@body)))
```
`if` is a built-in primitive that will only let you execute *one* form in the branches, and if you want to have more than one, well, you need to use `progn`::
```
;; one form
(if (numberp 1)
(print "yay, a number"))
;; two forms
(if (numberp 1)
(progn
(assert-world-is-sane t)
(print "phew!"))))
```
With our new friend, `my-when`, we could both a) use the more appropriate verb if we don't have a false branch, and b) add an implicit sequencing operator, i.e. `progn`::
```
(my-when (numberp 1)
(assert-world-is-sane t)
(print "phew!"))
```
The compiled code will never contain `my-when`, though, because in the first pass, all macros are expanded so there is *no runtime penalty* involved!
```
Lisp> (macroexpand-1 '(my-when (numberp 1)
(print "yay!")))
(if (numberp 1)
(progn (print "yay!")))
```
Note that `macroexpand-1` only does one level of expansions; it's possible (most likely, in fact!) that the expansion continues further down. However, eventually you'll hit the compiler-specific implementation details which are often not very interesting. But continuing expanding the result will eventually either get you more details, or just your input s-exp back.
Hope that clarifies things. Macros is a powerful tool, and one of the features in Lisp I like. |
106,067 | <p>In java, which regular expression can be used to replace these,
for example:</p>
<p>before:
aaabbb
after:
ab</p>
<p>before:
14442345
after:
142345</p>
<p>thanks!</p>
| [
{
"answer_id": 106096,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 6,
"selected": true,
"text": "<p>In perl</p>\n\n<pre><code>s/(.)\\1+/$1/g;\n</code></pre>\n\n<p>Does the trick, I assume if java has perl compatible regexps it should work too.</p>\n\n<p>Edit: Here is what it means</p>\n\n<pre><code>s {\n (.) # match any charater ( and capture it )\n \\1 # if it is followed by itself \n + # One or more times\n}{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences)\n</code></pre>\n\n<p>Edit: As others have pointed out, the syntax in Java would become </p>\n\n<pre><code>original.replaceAll(\"(.)\\\\1+\", \"$1\");\n</code></pre>\n\n<p>remember to escape the \\1</p>\n"
},
{
"answer_id": 106107,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": false,
"text": "<pre><code>String a = \"aaabbb\";\nString b = a.replaceAll(\"(.)\\\\1+\", \"$1\");\nSystem.out.println(\"'\" + a + \"' -> '\" + b + \"'\");\n</code></pre>\n"
},
{
"answer_id": 106109,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 2,
"selected": false,
"text": "<pre><code>\"14442345\".replaceAll(\"(.)\\\\1+\", \"$1\");\n</code></pre>\n"
},
{
"answer_id": 106110,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 2,
"selected": false,
"text": "<pre><code>originalString.replaceAll( \"(.)\\\\1+\", \"$1\" );\n</code></pre>\n"
},
{
"answer_id": 106143,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>in TextEdit (assuming posix expressions)\nfind: [a]+[b]+\nreplace with: ab</p>\n"
},
{
"answer_id": 106145,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 1,
"selected": false,
"text": "<p><strong>match pattern</strong> (in Java/languages where \\ must be escaped): </p>\n\n<pre><code>(.)\\\\1+\n</code></pre>\n\n<p>or (in languages where you can use strings which don't treat \\ as escape character)</p>\n\n<pre><code>(.)\\1+ \n</code></pre>\n\n<p><strong>replacement</strong>: </p>\n\n<pre><code>$1\n</code></pre>\n"
},
{
"answer_id": 111796,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>In Perl:</p>\n\n<pre><code>tr/a-z0-9//s;\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ perl -E'@a = (aaabbb, 14442345); for(@a) { tr/a-z0-9//s; say }'\nab\n142345 \n</code></pre>\n\n<p>If Java has no <code>tr</code> analog then:</p>\n\n<pre><code>s/(.)\\1+/$1/sg; \n#NOTE: `s` modifier. It takes into account consecutive newlines.\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ perl -E'@a = (aaabbb, 14442345); for(@a) { s/(.)\\1+/$1/sg; say }'\nab\n142345 \n</code></pre>\n"
},
{
"answer_id": 24529905,
"author": "kunwar.sangram",
"author_id": 2280300,
"author_profile": "https://Stackoverflow.com/users/2280300",
"pm_score": 0,
"selected": false,
"text": "<p>Sugared with a Java 7 : Named Groups</p>\n\n<pre><code>static String cleanDuplicates(@NonNull final String val) { \n assert val != null;\n return val.replaceAll(\"(?<dup>.)\\\\k<dup>+\",\"${dup}\");\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
]
| In java, which regular expression can be used to replace these,
for example:
before:
aaabbb
after:
ab
before:
14442345
after:
142345
thanks! | In perl
```
s/(.)\1+/$1/g;
```
Does the trick, I assume if java has perl compatible regexps it should work too.
Edit: Here is what it means
```
s {
(.) # match any charater ( and capture it )
\1 # if it is followed by itself
+ # One or more times
}{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences)
```
Edit: As others have pointed out, the syntax in Java would become
```
original.replaceAll("(.)\\1+", "$1");
```
remember to escape the \1 |
106,095 | <p>Using ASP.NET 2.0, I have a web app where I am trying to use JavaScript to make one tab in a tab-container the active tab.</p>
<p>The recommendations have been based on:</p>
<pre><code>var mX=document.getElementById('<%= tc1.ClientID%>')
$find('<%= tc1.ClientID%>').set_activeTabIndex(1);
</code></pre>
<p>Which both produce the error:</p>
<pre><code>The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
</code></pre>
<p>I've tried moving the code out of the head tag and into the body tag; same error.</p>
<p>I've also tried the alternative <code><%# tc1.ClientID%></code>, as in:</p>
<pre><code>var mX = document.getElementById('<%# tc1.ClientID %>')
mX.ActiveTabIndex="2";
</code></pre>
<p>Generates a null error - code above is rendered in the html as: </p>
<pre><code>var mX = document.getElementById('')
mX.ActiveTabIndex="2";
</code></pre>
<p>Can anyone explain in plain(er) language what this means and what the solution is?</p>
| [
{
"answer_id": 106139,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 0,
"selected": false,
"text": "<p>It looks and sounds like the code snippets are not themselves offensive, but some <em>other</em> code that was modifying the controls collection is now upset about them. Can you tell where in your program the error is actually occuring?</p>\n\n<p>By the way, the <%# %> is not appropriate here — it's only for data-bound controls.</p>\n"
},
{
"answer_id": 106297,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 0,
"selected": false,
"text": "<p>You can't have code blocks mixed with controls, instead store the value in javascript and assign it that way... something like this:</p>\n\n<pre><code><div runat=\"server\" id=\"rawr\">\n <span id=\"myspan\">HI</span>\n</div>\n</form>\n\n<script type=\"text/javascript\">\n var obj = '<%= DateTime.Now.ToShortDateString() %>';\n var ele = document.getElementById(\"myspan\");\n ele.innerHTML = obj;\n</script>\n</code></pre>\n"
},
{
"answer_id": 106355,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 2,
"selected": false,
"text": "<p>I've actually run into that before. <strong>Here's an explanation: <a href=\"http://west-wind.com/WebLog/posts/6148.aspx\" rel=\"nofollow noreferrer\">http://west-wind.com/WebLog/posts/6148.aspx</a></strong></p>\n\n<p>For example, if your markup looks like:</p>\n\n<pre><code><asp:Panel id=\"whatever\" runat=\"server\">\n <script type=\"text/javascript\">\n var mX=document.getElementById('<%= tc1.ClientID%>');\n //and so on...\n </script>\n</asp:Panel>\n</code></pre>\n\n<p>And if you try to programatically add a control to that Panel it'll fail with the error you're getting.</p>\n\n<p>One solution is to put your Javascript somewhere else in the page. Another way (although a hack) is this:</p>\n\n<pre><code><asp:Panel id=\"whatever\" runat=\"server\">\n <asp:PlaceHolder id=\"dontCare\" runat=\"server\">\n <script type=\"text/javascript\">\n var mX=document.getElementById('<%= tc1.ClientID%>');\n //and so on...\n </script>\n </asp:PlaceHolder>\n</asp:Panel>\n</code></pre>\n\n<p>Now the <%= ... %> part is inside the PlaceHolder, not directly inside the Panel. Adding controls in your C# or VB code to the Panel should now work (although adding controls to the PlaceHolder would fail.)</p>\n\n<p><strong>EDIT:</strong><br>\nYeah, I tried using <%# ... %> instead too, but that's only for inside a DataBound control. For example, that would work if it was in the middle of a DataGrid and I called it's DataBind() method this PostBack.</p>\n"
},
{
"answer_id": 660021,
"author": "wallyqs",
"author_id": 9082,
"author_profile": "https://Stackoverflow.com/users/9082",
"pm_score": 2,
"selected": false,
"text": "<p>This is a fix to this obscure error if you're just beginning to use ASP.NET MVC. I leave this note here in case another person just like me is having this problem and I really want to save that guy from wasting hours of his time due to this lame error: </p>\n\n<p>CHANGE THE LOCATION OF THE <SCRIPT> tags!!! </p>\n\n<p>Most likely you wanted to put some javascript on the Site.Master page but when you did it, you did it below the tags when you included jQuery. No sir! Please include the <script> tag with the javascript code out of the <head> and into the <body> . Good luck!</p>\n"
},
{
"answer_id": 9427256,
"author": "Ranadheer Reddy",
"author_id": 1215594,
"author_profile": "https://Stackoverflow.com/users/1215594",
"pm_score": 0,
"selected": false,
"text": "<p>move the javascript from head..\n and make sure that you added scriptmanager to your default.aspx while using ajaxextenders..</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Using ASP.NET 2.0, I have a web app where I am trying to use JavaScript to make one tab in a tab-container the active tab.
The recommendations have been based on:
```
var mX=document.getElementById('<%= tc1.ClientID%>')
$find('<%= tc1.ClientID%>').set_activeTabIndex(1);
```
Which both produce the error:
```
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
```
I've tried moving the code out of the head tag and into the body tag; same error.
I've also tried the alternative `<%# tc1.ClientID%>`, as in:
```
var mX = document.getElementById('<%# tc1.ClientID %>')
mX.ActiveTabIndex="2";
```
Generates a null error - code above is rendered in the html as:
```
var mX = document.getElementById('')
mX.ActiveTabIndex="2";
```
Can anyone explain in plain(er) language what this means and what the solution is? | I've actually run into that before. **Here's an explanation: <http://west-wind.com/WebLog/posts/6148.aspx>**
For example, if your markup looks like:
```
<asp:Panel id="whatever" runat="server">
<script type="text/javascript">
var mX=document.getElementById('<%= tc1.ClientID%>');
//and so on...
</script>
</asp:Panel>
```
And if you try to programatically add a control to that Panel it'll fail with the error you're getting.
One solution is to put your Javascript somewhere else in the page. Another way (although a hack) is this:
```
<asp:Panel id="whatever" runat="server">
<asp:PlaceHolder id="dontCare" runat="server">
<script type="text/javascript">
var mX=document.getElementById('<%= tc1.ClientID%>');
//and so on...
</script>
</asp:PlaceHolder>
</asp:Panel>
```
Now the <%= ... %> part is inside the PlaceHolder, not directly inside the Panel. Adding controls in your C# or VB code to the Panel should now work (although adding controls to the PlaceHolder would fail.)
**EDIT:**
Yeah, I tried using <%# ... %> instead too, but that's only for inside a DataBound control. For example, that would work if it was in the middle of a DataGrid and I called it's DataBind() method this PostBack. |
106,117 | <p>Please bear with me, I'm just learning C++. </p>
<p>I'm trying to write my header file (for class) and I'm running into an odd error.</p>
<pre><code>cards.h:21: error: expected unqualified-id before ')' token
cards.h:22: error: expected `)' before "str"
cards.h:23: error: expected `)' before "r"
</code></pre>
<p>What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? </p>
<p>Edit: Sorry, I didn't post the entire code.</p>
<pre><code>/*
Card header file
[Author]
*/
// NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/
#define Card
#define Hand
#define AppError
#include <string>
using namespace std;
// TODO: Docs here
class Card { // line 17
public:
enum Suit {Club, Diamond, Spade, Heart};
enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine,
Ten, Jack, Queen, King, Ace};
Card(); // line 22
Card(string str);
Card(Rank r, Suit s);
</code></pre>
<p>Edit: I'm just trying to compile the header file by itself using "g++ file.h". </p>
<p>Edit: Closed question. My code is working now. Thanks everyone!
Edit: Reopened question after reading <a href="https://stackoverflow.com/questions/34456/etiquette-closing-your-posts">Etiquette: Closing your posts</a></p>
| [
{
"answer_id": 106126,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "<p>Remove the <strong>#define Card</strong>.</p>\n"
},
{
"answer_id": 106127,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>(edited for updated question)</p>\n\n<p>Remove the <code>#define</code> statements, they're mangling the file. Were you trying to implement an include guard? That would be something like this:</p>\n\n<pre><code>#ifndef CARD_H\n#define CARD_H\n\nclass Card ...\n...\n\n#endif\n</code></pre>\n\n<hr>\n\n<p>old answer:</p>\n\n<p>It means that <code>string</code> is not defined in the current line. Try <code>std::string</code>.</p>\n"
},
{
"answer_id": 106170,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 5,
"selected": true,
"text": "<p>Your issue is your <code>#define</code>. You did <code>#define Card</code>, so now everywhere <code>Card</code> is seen as a token, it will be replaced.</p>\n\n<p>Usually a <code>#define Token</code> with no additional token, as in <code>#define Token Replace</code> will use the value <code>1</code>.</p>\n\n<p>Remove the <code>#define Card</code>, it's making line 22 read: <code>1();</code> or <code>();</code>, which is causing the complaint.</p>\n"
},
{
"answer_id": 107858,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<p>Just my two cents, but I guess you used the pre-compiled header</p>\n\n<pre><code>#define Card\n#define Hand\n#define AppError\n</code></pre>\n\n<p>as if you wanted to tell the compiler \"Hey, the classes Card, Hand and AppError are defined elsewhere\" (i.e. forward-declarations).</p>\n\n<p>Even if we ignore the fact macros are a pain for the exact reasons your code did not compile (as John Millikin put it, mangling your file), perhaps what you wanted to write was something like:</p>\n\n<pre><code>class Card ;\nclass Hand ;\nclass AppError ;\n</code></pre>\n\n<p>Which are <em>forward-declarations</em> of those classes.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16204/"
]
| Please bear with me, I'm just learning C++.
I'm trying to write my header file (for class) and I'm running into an odd error.
```
cards.h:21: error: expected unqualified-id before ')' token
cards.h:22: error: expected `)' before "str"
cards.h:23: error: expected `)' before "r"
```
What does "expected unqualified-id before ')' token" mean? And what am I doing wrong?
Edit: Sorry, I didn't post the entire code.
```
/*
Card header file
[Author]
*/
// NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/
#define Card
#define Hand
#define AppError
#include <string>
using namespace std;
// TODO: Docs here
class Card { // line 17
public:
enum Suit {Club, Diamond, Spade, Heart};
enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine,
Ten, Jack, Queen, King, Ace};
Card(); // line 22
Card(string str);
Card(Rank r, Suit s);
```
Edit: I'm just trying to compile the header file by itself using "g++ file.h".
Edit: Closed question. My code is working now. Thanks everyone!
Edit: Reopened question after reading [Etiquette: Closing your posts](https://stackoverflow.com/questions/34456/etiquette-closing-your-posts) | Your issue is your `#define`. You did `#define Card`, so now everywhere `Card` is seen as a token, it will be replaced.
Usually a `#define Token` with no additional token, as in `#define Token Replace` will use the value `1`.
Remove the `#define Card`, it's making line 22 read: `1();` or `();`, which is causing the complaint. |
106,137 | <p>When you want to add whitespace between HTML elements (using CSS), to which element do you attach it?</p>
<p>I'm regularly in situations along these lines:</p>
<pre><code><body>
<h1>This is the heading</h1>
<p>This is a paragraph</p>
<h1>Here's another heading</h1>
<div>This is a footer</div>
</body>
</code></pre>
<p>Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it?</p>
<p>Obviously, there's no real <strong>technical</strong> difference between this:</p>
<pre><code>h1, p { margin-bottom: 1em; }
</code></pre>
<p>...and this...</p>
<pre><code>div { margin-top: 1em; }
p { margin-top: 1em; margin-bottom: 1em }
</code></pre>
<p>What I'm interested is secondary factors: </p>
<ol>
<li>Consistency</li>
<li>Applicability to all situations</li>
<li>Ease / Simplicity</li>
<li>Ease of making changes</li>
</ol>
<p>For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument?</p>
| [
{
"answer_id": 106153,
"author": "Pavling",
"author_id": 18197,
"author_profile": "https://Stackoverflow.com/users/18197",
"pm_score": 4,
"selected": true,
"text": "<p>I tend to use a bottom margin on elements when I want them to have space before the next element, and then to use a \".last\" class in the css to remove the margin from the last element.</p>\n\n<pre><code><body>\n <h1>This is the heading</h1>\n <p>This is a paragraph</p>\n <h1>Here's another heading</h1>\n <div class=\"last\">This is a footer</div>\n</body>\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>div { margin-bottom: 1em; }\np { margin-bottom: 1em; }\nh1 { margin-bottom: 1em; }\n.last {margin-bottom: 0; }\n</code></pre>\n\n<p>In your example though, this probably isn't <em>that</em> applicable, as a footer div would most likely have it's own class and specific styling.\nStill the \".last\" approach I used works for me when I have several identical elements one after the other (paragraphs and what-not).\nOf course, I cherry-picked the technique from the \"Elements\" CSS framework.</p>\n"
},
{
"answer_id": 106155,
"author": "Bryan Friedman",
"author_id": 16985,
"author_profile": "https://Stackoverflow.com/users/16985",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to agree with you that the first option is better. It's generally what I like to do. However, there is an argument to be made that you should specify a margin for each one of those elements and zero it out if you don't want to apply it since browsers all handle margins differently. The <p> (and the <h1> tag too I think) will usually have default margins given by the browser if none are specified.</p>\n"
},
{
"answer_id": 106166,
"author": "Josh Millard",
"author_id": 13600,
"author_profile": "https://Stackoverflow.com/users/13600",
"pm_score": 2,
"selected": false,
"text": "<p>This going to be driven partly by the specifics of what you're designing for, but there's a sort of rough heirarchy to these things in, say, a typical blog index:</p>\n\n<ul>\n<li>You're going to have one footer on a page.</li>\n<li>You're going to have one header per <em>entry</em>.</li>\n<li>You're going to have n paragraphs per entry.</li>\n</ul>\n\n<p>Establish whitespace for your paragraphs knowing that they're going to sometimes occur in sequence -- you need to worry about how they look as a series. From there, adjust your headers to deal with boundaries between entries. Finally, adjust your footer/body spacing to make sure the bottom of the page looks decent.</p>\n\n<p>It's a thumbnail sketch. How you ultimately end up assigning your padding is entirely up to you, but if you approach it from an bottom-up perspective you'll likely see less surprises as you tweak <i>first</i> the most common/plentiful elements and then <i>later</i> the less common ones.</p>\n"
},
{
"answer_id": 106286,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>If you want some space around an element, give it a margin. That means, in this case, don't just give the <code><h1></code> a bottom margin, but give <code><p></code> a top margin.</p>\n\n<p>Remember, when two elements are vertically adjacent and they don't have a border or padding between them, their margins collapse. That means that only the larger of the two margins is considered - they don't add together. So this:</p>\n\n<pre><code>h1, p { margin: 1em; }\n\n<h1>...</h1>\n<p>...</p>\n</code></pre>\n\n<p>...would result in a 1em space between the heading and the paragraph.</p>\n"
},
{
"answer_id": 110329,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 2,
"selected": false,
"text": "<p>The point that Jim is making is the key. Margins collapse between elements, they are not additive. If what you want is to ensure that there is a 1em margin above and below paragraphs and headings and that there is a 1em margin below the header and above the footer, then your css should reflect that.</p>\n\n<p>Given this markup (I've added a header and placed ids on the header/footer):</p>\n\n<pre><code><body>\n <div id=\"header\"></div>\n <h1>This is the heading</h1>\n <p>This is a paragraph</p>\n <h1>Here's another heading</h1>\n <div id=\"footer\">This is a footer</div>\n</body>\n</code></pre>\n\n<p>You should use this css:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#header {\n margin-bottom: 1em;\n}\n\n#footer {\n margin-top: 1em;\n}\n\nh1, p {\n margin: 1em 0;\n}\n</code></pre>\n\n<p>Now the order of your elements doesn't matter. If you use two consecutive headings, or start the page with a paragraph instead of a heading it will still render the way that you indended.</p>\n"
},
{
"answer_id": 111524,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Using advanced CSS 2 selectors, another solution would be possible that does not rely on a class <code>last</code> to introduce layout info into the HTML.</p>\n\n<p>The solution uses the <a href=\"http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors\" rel=\"nofollow noreferrer\">adjacent selectors</a>.\nUnfortunately, MSIE 6 doesn't support it yet so reluctance to use it is understandable.</p>\n\n<pre><code>h1 {\n margin: 0 0 1em;\n}\n\ndiv, p, p + h1, div + h1 {\n margin: 1em 0 0;\n}\n</code></pre>\n\n<p>This way, the first <code>h1</code> won't have a top margin while any <code>h1</code> that immediately follows a paragraph or a box <em>has</em> a top margin.</p>\n"
},
{
"answer_id": 788641,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a relative newbie, but my own solution to the thing I think both you and I came up against (changing margins for one tag may sort out spacing in one part of a site, only to disturb a previously good spacing elsewhere?) is now to allocate an equal margin top and bottom for all tags. You might well want more space above and below an H1 than for an H3 or a p, but in general I think pages look good with equal spaces above and below any given piece of text, so this solution works well for me and meets your 'simple rule of thumb' spec too, hopefully! </p>\n"
},
{
"answer_id": 33955089,
"author": "JDavies",
"author_id": 1256637,
"author_profile": "https://Stackoverflow.com/users/1256637",
"pm_score": 0,
"selected": false,
"text": "<p>I've just used first-child and last child. So for example in plain CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>h1{\n margin-top:10px;\n margin-bottom:10px;\n}\nh1:first-child{\n margin-top:0px;\n}\np{\n margin:10px;\n}\np:first-child{\n margin-top:0px;\n}\np:last-child{\n margin-bottom:0px;\n}\n</code></pre>\n\n<p>This is a basic example, but you can apply this to more elements and structure is nicer if using SASS, LESS etc :)</p>\n"
},
{
"answer_id": 34799717,
"author": "tao",
"author_id": 1891677,
"author_profile": "https://Stackoverflow.com/users/1891677",
"pm_score": 1,
"selected": false,
"text": "<p>This is how it should be done:</p>\n\n<pre><code>body > * {\n margin-bottom: 1em;\n}\nbody > *:last-child {\n margin-bottom: 0;\n}\n</code></pre>\n\n<p>Now you don't have to worry about what element is first and what element is last, and you don't have to always place a special class on your last element. </p>\n\n<p>The only time this won't \"work\" is when the last child is one that is not rendered. In this situation you might consider applying <code>margin-bottom:0;</code> using a class on your last visible child.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
]
| When you want to add whitespace between HTML elements (using CSS), to which element do you attach it?
I'm regularly in situations along these lines:
```
<body>
<h1>This is the heading</h1>
<p>This is a paragraph</p>
<h1>Here's another heading</h1>
<div>This is a footer</div>
</body>
```
Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it?
Obviously, there's no real **technical** difference between this:
```
h1, p { margin-bottom: 1em; }
```
...and this...
```
div { margin-top: 1em; }
p { margin-top: 1em; margin-bottom: 1em }
```
What I'm interested is secondary factors:
1. Consistency
2. Applicability to all situations
3. Ease / Simplicity
4. Ease of making changes
For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument? | I tend to use a bottom margin on elements when I want them to have space before the next element, and then to use a ".last" class in the css to remove the margin from the last element.
```
<body>
<h1>This is the heading</h1>
<p>This is a paragraph</p>
<h1>Here's another heading</h1>
<div class="last">This is a footer</div>
</body>
```
```css
div { margin-bottom: 1em; }
p { margin-bottom: 1em; }
h1 { margin-bottom: 1em; }
.last {margin-bottom: 0; }
```
In your example though, this probably isn't *that* applicable, as a footer div would most likely have it's own class and specific styling.
Still the ".last" approach I used works for me when I have several identical elements one after the other (paragraphs and what-not).
Of course, I cherry-picked the technique from the "Elements" CSS framework. |
106,175 | <p><a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a> has a very handy "with" statement, but it also lets you use it on an unnamed variable, like this:</p>
<pre><code>With New FancyClass()
.Level = "SuperSpiffy"
.Style = Slimming
.Execute()
End With
</code></pre>
<p>Is there a way to get at the "hidden" instance, so I can view its properties in the Immediate window? I doubt I'll get it in the watch windows, so immediate is fine.</p>
<p>If you try to access the instance the same way (say, when <code>.Execute()</code> throws an exception) from the Immediate window, you get an error:</p>
<pre><code>? .Style
'With' contexts and statements are not valid in debug windows.
</code></pre>
<p>Is there any trick that can be used to get this, or do I have to convert the code to another style? If <code>With</code> functioned more like a <code>Using</code> statement, (e.g. "With v = New FancyClass()") this wouldn't pose a problem.</p>
<p>I know how <code>With</code> is working, what alternatives exist, what the compiler does, etc. I just want to know if this is possible.</p>
| [
{
"answer_id": 106284,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 1,
"selected": false,
"text": "<p>What's wrong with defining a variable on one line and using it in a with-statement on the next? I realise it keeps the variable alive longer but is that <em>so</em> appalling?</p>\n\n<pre><code>Dim x = new SomethingOrOther()\nWith x\n .DoSomething()\nEnd With\nx = Nothing ' for the memory conscious\n</code></pre>\n\n<p>Two extra lines wont kill you =)</p>\n\n<p>Edit: If you're just looking for a yes/no, I'd have to say: No.</p>\n"
},
{
"answer_id": 106308,
"author": "Jeremy",
"author_id": 8557,
"author_profile": "https://Stackoverflow.com/users/8557",
"pm_score": 0,
"selected": false,
"text": "<p>You're creating a variable either way - in the first case (your example) the compiler is creating an implicit variable that you aren't allowed to really get to, and the in the second case (another answer, by Oli) you'd be creating the variable explicitly. </p>\n\n<p>If you create it explicitly you can use it in the immediate window, and you can explicitly destroy it when you're through with it (I'm one of the memory conscious, I guess!), instead of leaving those clean up details to the magic processes. I don't think there is any way to get at an implicit variable in the immediate window. (and I don't trust the magic processes, either. I never use multiple-dot notation or implicit variables for this reason)</p>\n"
},
{
"answer_id": 121635,
"author": "MikeScott8",
"author_id": 1889,
"author_profile": "https://Stackoverflow.com/users/1889",
"pm_score": 2,
"selected": true,
"text": "<p>As answered, the simple answer is \"no\".</p>\n\n<p>But isn't another way to do it: instead of declaring and then cleaning up the variable is to use the \"Using\".</p>\n\n<pre><code>Using fc as new FancyClass()\n With fc \n .Level = \"SuperSpiffy\" \n .Style = Slimming \n .Execute()\n End With\nEnd Using\n</code></pre>\n\n<p>Then you can use fc in the immediate window and don't have to remember to write a</p>\n\n<pre><code>fc=nothing \n</code></pre>\n\n<p>line.</p>\n\n<p>Just some more thoughts on it ;)</p>\n"
},
{
"answer_id": 125796,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 1,
"selected": false,
"text": "<p>I hope there really isn't a way to get at it, since the easy answer is \"no\", and I haven't found a way yet either. Either way, nothing said so far really has a rationale for being \"no\", just that no one has =) It's just one of those things you figure the vb debugger team would have put in, considering how classic \"with\" is =)</p>\n\n<p>Anyway, I know all about usings and Idisposable, I know how to <em>fix</em> the code, as some would call it, but I might not always want to. </p>\n\n<p>As for Using, I don't like implementing IDisposable on my classes just to gain a bit of sugar. </p>\n\n<p>What we really need is a \"With var = New FancyClass()\", but that might just be confusing!</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15127/"
]
| [VB.NET](http://en.wikipedia.org/wiki/Visual_Basic_.NET) has a very handy "with" statement, but it also lets you use it on an unnamed variable, like this:
```
With New FancyClass()
.Level = "SuperSpiffy"
.Style = Slimming
.Execute()
End With
```
Is there a way to get at the "hidden" instance, so I can view its properties in the Immediate window? I doubt I'll get it in the watch windows, so immediate is fine.
If you try to access the instance the same way (say, when `.Execute()` throws an exception) from the Immediate window, you get an error:
```
? .Style
'With' contexts and statements are not valid in debug windows.
```
Is there any trick that can be used to get this, or do I have to convert the code to another style? If `With` functioned more like a `Using` statement, (e.g. "With v = New FancyClass()") this wouldn't pose a problem.
I know how `With` is working, what alternatives exist, what the compiler does, etc. I just want to know if this is possible. | As answered, the simple answer is "no".
But isn't another way to do it: instead of declaring and then cleaning up the variable is to use the "Using".
```
Using fc as new FancyClass()
With fc
.Level = "SuperSpiffy"
.Style = Slimming
.Execute()
End With
End Using
```
Then you can use fc in the immediate window and don't have to remember to write a
```
fc=nothing
```
line.
Just some more thoughts on it ;) |
106,179 | <p>Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?</p>
<p>It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames.</p>
| [
{
"answer_id": 106223,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 10,
"selected": true,
"text": "<p>You can use the following regular expressions separately or by combining them in a joint OR expression.</p>\n<pre><code>ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";\n\nValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$";\n</code></pre>\n<p><strong>ValidIpAddressRegex</strong> matches valid IP addresses and <strong>ValidHostnameRegex</strong> valid host names. Depending on the language you use \\ could have to be escaped with \\.</p>\n<hr />\n<p><strong>ValidHostnameRegex</strong> is valid as per <a href=\"https://www.rfc-editor.org/rfc/rfc1123\" rel=\"noreferrer\">RFC 1123</a>. Originally, <a href=\"https://www.rfc-editor.org/rfc/rfc952\" rel=\"noreferrer\">RFC 952</a> specified that hostname segments could not start with a digit.</p>\n<p><a href=\"http://en.wikipedia.org/wiki/Hostname\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Hostname</a></p>\n<blockquote>\n<p>The original specification of\nhostnames in <a href=\"https://www.rfc-editor.org/rfc/rfc952\" rel=\"noreferrer\">RFC\n952</a>,\nmandated that labels could not start\nwith a digit or with a hyphen, and\nmust not end with a hyphen. However, a\nsubsequent specification (<a href=\"https://www.rfc-editor.org/rfc/rfc1123\" rel=\"noreferrer\">RFC\n1123</a>)\npermitted hostname labels to start\nwith digits.</p>\n</blockquote>\n<pre><code>Valid952HostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$";\n</code></pre>\n"
},
{
"answer_id": 2296904,
"author": "Bill Stephens",
"author_id": 277020,
"author_profile": "https://Stackoverflow.com/users/277020",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a regex that I used in Ant to obtain a proxy host IP or hostname out of ANT_OPTS. This was used to obtain the proxy IP so that I could run an Ant \"isreachable\" test before configuring a proxy for a forked JVM. </p>\n\n<pre><code>^.*-Dhttp\\.proxyHost=(\\w{1,}\\.\\w{1,}\\.\\w{1,}\\.*\\w{0,})\\s.*$\n</code></pre>\n"
},
{
"answer_id": 2375080,
"author": "Alex Volkov",
"author_id": 86294,
"author_profile": "https://Stackoverflow.com/users/86294",
"pm_score": 3,
"selected": false,
"text": "<p>I don't seem to be able to edit the top post, so I'll add my answer here.</p>\n\n<p>For hostname - easy answer, on egrep example here -- http: //www.linuxinsight.com/how_to_grep_for_ip_addresses_using_the_gnu_egrep_utility.html</p>\n\n<pre><code>egrep '([[:digit:]]{1,3}\\.){3}[[:digit:]]{1,3}'\n</code></pre>\n\n<p>Though the case doesn't account for values like 0 in the fist octet, and values greater than 254 (ip addres) or 255 (netmask). Maybe an additional if statement would help.</p>\n\n<p>As for legal dns hostname, provided that you are checking for internet hostnames only (and not intranet), I wrote the following snipped, a mix of shell/php but it should be applicable as any regular expression.</p>\n\n<p>first go to ietf website, download and parse a list of legal level 1 domain names:</p>\n\n<pre><code>tld=$(curl -s http://data.iana.org/TLD/tlds-alpha-by-domain.txt | sed 1d | cut -f1 -d'-' | tr '\\n' '|' | sed 's/\\(.*\\)./\\1/')\necho \"($tld)\"\n</code></pre>\n\n<p>That should give you a nice piece of re code that checks for legality of top domain name, like .com .org or .ca</p>\n\n<p>Then add first part of the expression according to guidelines found here -- http: //www.domainit.com/support/faq.mhtml?category=Domain_FAQ&question=9 (any alphanumeric combination and '-' symbol, dash should not be in the beginning or end of an octet.</p>\n\n<pre><code>(([a-z0-9]+|([a-z0-9]+[-]+[a-z0-9]+))[.])+\n</code></pre>\n\n<p>Then put it all together (PHP preg_match example):</p>\n\n<pre><code>$pattern = '/^(([a-z0-9]+|([a-z0-9]+[-]+[a-z0-9]+))[.])+(AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN|XN|XN|XN|XN|XN|XN|XN|XN|XN|XN|YE|YT|YU|ZA|ZM|ZW)[.]?$/i';\n\n if (preg_match, $pattern, $matching_string){\n ... do stuff\n }\n</code></pre>\n\n<p>You may also want to add an if statement to check that string that you checking is shorter than 256 characters -- <a href=\"http://www.ops.ietf.org/lists/namedroppers/namedroppers.2003/msg00964.html\" rel=\"noreferrer\">http://www.ops.ietf.org/lists/namedroppers/namedroppers.2003/msg00964.html</a></p>\n"
},
{
"answer_id": 3824105,
"author": "Sakari A. Maaranen",
"author_id": 462036,
"author_profile": "https://Stackoverflow.com/users/462036",
"pm_score": 6,
"selected": false,
"text": "<p>The hostname regex of <em>smink</em> does not observe the limitation on the length of individual labels within a hostname. <strong>Each label within a valid hostname may be no more than 63 octets long.</strong></p>\n\n<pre>ValidHostnameRegex=\"^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])\\\n(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$\"</pre>\n\n<p>Note that the backslash at the end of the first line (above) is Unix shell syntax for splitting the long line. It's not a part of the regular expression itself.</p>\n\n<p>Here's just the regular expression alone on a single line:</p>\n\n<pre>^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$</pre>\n\n<p>You should also check separately that <strong>the total length of the hostname must not exceed 255 characters</strong>. For more information, please consult RFC-952 and RFC-1123.</p>\n"
},
{
"answer_id": 6342447,
"author": "PythonDev",
"author_id": 736327,
"author_profile": "https://Stackoverflow.com/users/736327",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def isValidHostname(hostname):\n\n if len(hostname) > 255:\n return False\n if hostname[-1:] == \".\":\n hostname = hostname[:-1] # strip exactly one dot from the right,\n # if present\n allowed = re.compile(\"(?!-)[A-Z\\d-]{1,63}(?<!-)$\", re.IGNORECASE)\n return all(allowed.match(x) for x in hostname.split(\".\"))\n</code></pre>\n"
},
{
"answer_id": 8818278,
"author": "Thangaraj",
"author_id": 1143035,
"author_profile": "https://Stackoverflow.com/users/1143035",
"pm_score": -1,
"selected": false,
"text": "<p>Checking for host names like... mywebsite.co.in, thangaraj.name, 18thangaraj.in, thangaraj106.in etc.,</p>\n\n<pre><code>[a-z\\d+].*?\\\\.\\w{2,4}$\n</code></pre>\n"
},
{
"answer_id": 9250864,
"author": "Prakash Thapa",
"author_id": 854054,
"author_profile": "https://Stackoverflow.com/users/854054",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is the best Ip validation regex. please check it once!!! </p>\n\n<pre><code>^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$\n</code></pre>\n"
},
{
"answer_id": 14453696,
"author": "Alban",
"author_id": 1911082,
"author_profile": "https://Stackoverflow.com/users/1911082",
"pm_score": 5,
"selected": false,
"text": "<p>To match a valid <strong>IP address</strong> use the following regex:</p>\n\n<pre><code>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}\n</code></pre>\n\n<h3>Explanation</h3>\n\n<p>Many regex engine match the first possibility in the <code>OR</code> sequence. For instance, try the following regex: </p>\n\n<pre><code>10.48.0.200\n</code></pre>\n\n<h3>Test</h3>\n\n<p>Test the difference between <a href=\"http://regexr.com?37hh1\" rel=\"noreferrer\">good</a> vs <a href=\"http://regexr.com?37hh4\" rel=\"noreferrer\">bad</a></p>\n"
},
{
"answer_id": 15887225,
"author": "Saikrishna Rao",
"author_id": 1128212,
"author_profile": "https://Stackoverflow.com/users/1128212",
"pm_score": -1,
"selected": false,
"text": "<p>how about this?</p>\n\n<pre><code>([0-9]{1,3}\\.){3}[0-9]{1,3}\n</code></pre>\n"
},
{
"answer_id": 16134774,
"author": "user2240578",
"author_id": 2240578,
"author_profile": "https://Stackoverflow.com/users/2240578",
"pm_score": 1,
"selected": false,
"text": "<pre><code>/^(?:[a-zA-Z0-9]+|[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9])(?:\\.[a-zA-Z0-9]+|[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9])?$/\n</code></pre>\n"
},
{
"answer_id": 18992661,
"author": "Andrew",
"author_id": 925047,
"author_profile": "https://Stackoverflow.com/users/925047",
"pm_score": 0,
"selected": false,
"text": "<p>I found this works pretty well for IP addresses. It validates like the top answer but it also makes sure the ip is isolated so no text or more numbers/decimals are after or before the ip. </p>\n\n<blockquote>\n <blockquote>\n <blockquote>\n <p>(?<!\\S)(?:(?:\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\b|.\\b){7}(?!\\S)</p>\n </blockquote>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 22137739,
"author": "zangw",
"author_id": 3011380,
"author_profile": "https://Stackoverflow.com/users/3011380",
"pm_score": 1,
"selected": false,
"text": "<pre><code>\"^((\\\\d{1,2}|1\\\\d{2}|2[0-4]\\\\d|25[0-5])\\.){3}(\\\\d{1,2}|1\\\\d{2}|2[0-4]\\\\d|25[0-5])$\"\n</code></pre>\n"
},
{
"answer_id": 24402376,
"author": "ayu for u",
"author_id": 2971220,
"author_profile": "https://Stackoverflow.com/users/2971220",
"pm_score": 0,
"selected": false,
"text": "<pre><code>AddressRegex = \"^(ftp|http|https):\\/\\/([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}:[0-9]{1,5})$\";\n\nHostnameRegex = /^(ftp|http|https):\\/\\/([a-z0-9]+\\.)?[a-z0-9][a-z0-9-]*((\\.[a-z]{2,6})|(\\.[a-z]{2,6})(\\.[a-z]{2,6}))$/i\n</code></pre>\n\n<p>this re are used only for for this type validation</p>\n\n<p><strong>work only if</strong>\n<a href=\"http://www.kk.com\" rel=\"nofollow\">http://www.kk.com</a>\n<a href=\"http://www.kk.co.in\" rel=\"nofollow\">http://www.kk.co.in</a></p>\n\n<p><strong>not works for</strong></p>\n\n<p><a href=\"http://www.kk.com/\" rel=\"nofollow\">http://www.kk.com/</a>\n<a href=\"http://www.kk.co.in.kk\" rel=\"nofollow\">http://www.kk.co.in.kk</a></p>\n\n<p><a href=\"http://www.kk.com/dfas\" rel=\"nofollow\">http://www.kk.com/dfas</a>\n<a href=\"http://www.kk.co.in/\" rel=\"nofollow\">http://www.kk.co.in/</a></p>\n"
},
{
"answer_id": 28230259,
"author": "aliasav",
"author_id": 3725732,
"author_profile": "https://Stackoverflow.com/users/3725732",
"pm_score": 1,
"selected": false,
"text": "<p>This works for valid IP addresses:</p>\n\n<pre><code>regex = '^([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])$'\n</code></pre>\n"
},
{
"answer_id": 30472389,
"author": "seraphim",
"author_id": 962682,
"author_profile": "https://Stackoverflow.com/users/962682",
"pm_score": 0,
"selected": false,
"text": "<p>try this:</p>\n\n<pre><code>((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\n</code></pre>\n\n<p>it works in my case.</p>\n"
},
{
"answer_id": 31600964,
"author": "Thom Anderson",
"author_id": 3821279,
"author_profile": "https://Stackoverflow.com/users/3821279",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding IP addresses, it appears that there is some debate on whether to include leading zeros. It was once the common practice and is generally accepted, so I would argue that they <em>should</em> be flagged as valid regardless of the current preference. There is also some ambiguity over whether text before and after the string should be validated and, again, I think it should. 1.2.3.4 is a valid IP but 1.2.3.4.5 is not and neither the 1.2.3.4 portion nor the 2.3.4.5 portion should result in a match. Some of the concerns can be handled with this expression:</p>\n\n<pre><code>grep -E '(^|[^[:alnum:]+)(([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\\.){3}([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])([^[:alnum:]]|$)' \n</code></pre>\n\n<p>The unfortunate part here is the fact that the regex portion that validates an octet is repeated as is true in many offered solutions. Although this is better than for instances of the pattern, the repetition can be eliminated entirely if subroutines are supported in the regex being used. The next example enables those functions with the <code>-P</code> switch of <code>grep</code> and also takes advantage of lookahead and lookbehind functionality. (The function name I selected is 'o' for octet. I could have used 'octet' as the name but wanted to be terse.)</p>\n\n<pre><code>grep -P '(?<![\\d\\w\\.])(?<o>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\\.\\g<o>){3}(?![\\d\\w\\.])'\n</code></pre>\n\n<p>The handling of the dot might actually create a false negatives if IP addresses are in a file with text in the form of sentences since the a period could follow without it being part of the dotted notation. A variant of the above would fix that:</p>\n\n<pre><code>grep -P '(?<![\\d\\w\\.])(?<x>([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(\\.\\g<x>){3}(?!([\\d\\w]|\\.\\d))'\n</code></pre>\n"
},
{
"answer_id": 33624143,
"author": "Dody",
"author_id": 3781218,
"author_profile": "https://Stackoverflow.com/users/3781218",
"pm_score": -1,
"selected": false,
"text": "<p>I thought about this simple regex matching pattern for IP address matching\n\\d+[.]\\d+[.]\\d+[.]\\d+</p>\n"
},
{
"answer_id": 34721398,
"author": "sirjay",
"author_id": 1802225,
"author_profile": "https://Stackoverflow.com/users/1802225",
"pm_score": -1,
"selected": false,
"text": "<p>on php: <code>filter_var(gethostbyname($dns), FILTER_VALIDATE_IP) == true ? 'ip' : 'not ip'</code></p>\n"
},
{
"answer_id": 36564531,
"author": "Mohammad Shahid Siddiqui",
"author_id": 1591700,
"author_profile": "https://Stackoverflow.com/users/1591700",
"pm_score": 1,
"selected": false,
"text": "<pre><code>>>> my_hostname = \"testhostn.ame\"\n>>> print bool(re.match(\"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\", my_hostname))\nTrue\n>>> my_hostname = \"testhostn....ame\"\n>>> print bool(re.match(\"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\", my_hostname))\nFalse\n>>> my_hostname = \"testhostn.A.ame\"\n>>> print bool(re.match(\"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$\", my_hostname))\nTrue\n</code></pre>\n"
},
{
"answer_id": 50192885,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth noting that there are libraries for most languages that do this for you, often built into the standard library. And those libraries are likely to get updated a lot more often than code that you copied off a Stack Overflow answer four years ago and forgot about. And of course they'll also generally parse the address into some usable form, rather than just giving you a match with a bunch of groups.</p>\n\n<p>For example, detecting and parsing IPv4 in (POSIX) C:</p>\n\n<pre><code>#include <arpa/inet.h>\n#include <stdio.h>\n\nint main(int argc, char *argv[]) {\n for (int i=1; i!=argc; ++i) {\n struct in_addr addr = {0};\n printf(\"%s: \", argv[i]);\n if (inet_pton(AF_INET, argv[i], &addr) != 1)\n printf(\"invalid\\n\");\n else\n printf(\"%u\\n\", addr.s_addr);\n }\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>Obviously, such functions won't work if you're trying to, e.g., find all valid addresses in a chat message—but even there, it may be easier to use a simple but overzealous regex to find potential matches, and then use the library to parse them.</p>\n\n<p>For example, in Python:</p>\n\n<pre><code>>>> import ipaddress\n>>> import re\n>>> msg = \"My address is 192.168.0.42; 192.168.0.420 is not an address\"\n>>> for maybeip in re.findall(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', msg):\n... try:\n... print(ipaddress.ip_address(maybeip))\n... except ValueError:\n... pass\n</code></pre>\n"
},
{
"answer_id": 54954504,
"author": "Darrell Root",
"author_id": 9722622,
"author_profile": "https://Stackoverflow.com/users/9722622",
"pm_score": 1,
"selected": false,
"text": "<p>The new Network framework has failable initializers for struct IPv4Address and struct IPv6Address which handle the IP address portion very easily. Doing this in IPv6 with a regex is tough with all the shortening rules.</p>\n\n<p>Unfortunately I don't have an elegant answer for hostname.</p>\n\n<p>Note that Network framework is recent, so it may force you to compile for recent OS versions.</p>\n\n<pre><code>import Network\nlet tests = [\"192.168.4.4\",\"fkjhwojfw\",\"192.168.4.4.4\",\"2620:3\",\"2620::33\"]\n\nfor test in tests {\n if let _ = IPv4Address(test) {\n debugPrint(\"\\(test) is valid ipv4 address\")\n } else if let _ = IPv6Address(test) {\n debugPrint(\"\\(test) is valid ipv6 address\")\n } else {\n debugPrint(\"\\(test) is not a valid IP address\")\n }\n}\n\noutput:\n\"192.168.4.4 is valid ipv4 address\"\n\"fkjhwojfw is not a valid IP address\"\n\"192.168.4.4.4 is not a valid IP address\"\n\"2620:3 is not a valid IP address\"\n\"2620::33 is valid ipv6 address\"\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10452/"
]
| Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?
It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames. | You can use the following regular expressions separately or by combining them in a joint OR expression.
```
ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
```
**ValidIpAddressRegex** matches valid IP addresses and **ValidHostnameRegex** valid host names. Depending on the language you use \ could have to be escaped with \.
---
**ValidHostnameRegex** is valid as per [RFC 1123](https://www.rfc-editor.org/rfc/rfc1123). Originally, [RFC 952](https://www.rfc-editor.org/rfc/rfc952) specified that hostname segments could not start with a digit.
<http://en.wikipedia.org/wiki/Hostname>
>
> The original specification of
> hostnames in [RFC
> 952](https://www.rfc-editor.org/rfc/rfc952),
> mandated that labels could not start
> with a digit or with a hyphen, and
> must not end with a hyphen. However, a
> subsequent specification ([RFC
> 1123](https://www.rfc-editor.org/rfc/rfc1123))
> permitted hostname labels to start
> with digits.
>
>
>
```
Valid952HostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";
``` |
106,201 | <p>In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here. </p>
<p><strong>Problem</strong></p>
<p>I have:</p>
<p>An application that has to be installed on on Redhat or SuSE enterprise. </p>
<p>It has huge system requirements and requires OpenGL.</p>
<p>It is part of a suite of tools that need to operate together on one machine.</p>
<p>This application is used for a time intensive task in terms of man hours.</p>
<p>I don't want to sit in the server room working on this application.</p>
<p>So, the question came up... how do I run this application from a remote windows machine?</p>
<p>I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.</p>
| [
{
"answer_id": 106218,
"author": "scubabbl",
"author_id": 9450,
"author_profile": "https://Stackoverflow.com/users/9450",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Solution</strong></p>\n\n<p>I installed two pieces of software:</p>\n\n<p><a href=\"http://www.chiark.greenend.org.uk/~sgtatham/putty/\" rel=\"noreferrer\">PuTTY</a></p>\n\n<p><a href=\"http://www.straightrunning.com/XmingNotes/\" rel=\"noreferrer\">XMing-mesa</a> The mesa part is important.</p>\n\n<p><strong>PuTTY configuration</strong></p>\n\n<pre><code>Connection->Seconds Between Keepalives: 30\nConnection->Enable TCP Keepalives: Yes\n\nConnection->SSH->X11->Enable X11 forwarding: Yes\nConnection->SSH->X11->X display location: localhost:0:0\n</code></pre>\n\n<p><strong>Lauching</strong></p>\n\n<p>Run <em>Xming</em> which will put simply start a process and put an icon in your system tray.\nLaunch putty, pointing to your linux box, with the above configuration.\nRun program</p>\n\n<p>Hopefully, <strong>Success!</strong></p>\n"
},
{
"answer_id": 106225,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 2,
"selected": false,
"text": "<p>You could also use VNC ( like cross platform remote desktop )\nX is more efficent since it only sends draw commands rather than pixels, but if you are using opengl it is likely that most of the data is a rendered image anyway.</p>\n\n<p>Another big advantage of VNC is that you can start the program locally on the server and then connect to it with VNC, drop the connection, reconnect from another machine etc without disturbing the main running program. </p>\n"
},
{
"answer_id": 106270,
"author": "tkerwin",
"author_id": 19141,
"author_profile": "https://Stackoverflow.com/users/19141",
"pm_score": 3,
"selected": false,
"text": "<p>If you want the OpenGL rendering to be performed on your local machine, using a Windows X server, like Xming is a good solution. However, if you want rendering to be done on the remote end with just images sent to the local machine, you want a specialized VNC system that can handle remote OpenGL rendering, like <a href=\"http://www.virtualgl.org/\" rel=\"noreferrer\">VirtualGL</a>.</p>\n"
},
{
"answer_id": 327831,
"author": "Ivan Vučica",
"author_id": 39974,
"author_profile": "https://Stackoverflow.com/users/39974",
"pm_score": 0,
"selected": false,
"text": "<p>For OpenGL, running an X server is definitely a better solution. Just make sure the application is developed to be networked. It should NOT use immediate mode for rendering and textures should be RARELY transferred. </p>\n\n<p>Why is X server a better solution in this case (as opposed to VNC)? Because you get acceleration on workstation, while VNC'ed solution is usually not even accelerated on the mainframe. So as long as data is buffered on the X server (using vertex arrays, vertex buffer objects, texture objects, etc) you should get much higher speed than using VNC, especially with complex scenes since VNC has to analyze, transfer and decode them as pixels.</p>\n"
},
{
"answer_id": 61294376,
"author": "Rafael Duarte",
"author_id": 5395184,
"author_profile": "https://Stackoverflow.com/users/5395184",
"pm_score": 0,
"selected": false,
"text": "<p>If you need server glx version 1.2 the free version of <a href=\"https://sourceforge.net/projects/xming/\" rel=\"nofollow noreferrer\">Xming</a> (Mesa 2007) works fine. But if your application needs version 1.4, example qt5, the X Server from Cygwin works free to run it use this commands:</p>\n<p>[On server]</p>\n<pre><code>sudo vi /etc/ssh/ssh_config\n</code></pre>\n<p>Add:</p>\n<blockquote>\n<p>X11Forwarding yes</p>\n<p>X11DisplayOffset 10</p>\n<p>X11UseLocalHost no</p>\n<p>AllowTcpForwarding yes</p>\n<p>TCPKeepAlive yes</p>\n<p>ClientAliveInterval 30</p>\n<p>ClientAliveCountMax 10000</p>\n</blockquote>\n<pre><code>sudo vi ~/.bashrc\n</code></pre>\n<p>Add:</p>\n<blockquote>\n<p>export DISPLAY=ip_from_remote:0</p>\n</blockquote>\n<p>Now restart ssh server</p>\n<p>[On Client slide]</p>\n<p>Install <a href=\"https://cygwin.com/install.html\" rel=\"nofollow noreferrer\">Cygwin64</a> (with support to X package) after that run this command:</p>\n<pre><code>d:\\cygwin64\\bin\\run.exe --quote /usr/bin/bash.exe -l -c "cd; /usr/bin/xinit /etc/X11/xinit/startxwinrc -- /usr/bin/XWin :0 -ac -multiwindow -listen tcp"\n</code></pre>\n<p>Now execute ssh client:</p>\n<pre><code>d:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico -e /usr/bin/ssh -Y user_name@ip_from_server\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
]
| In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here.
**Problem**
I have:
An application that has to be installed on on Redhat or SuSE enterprise.
It has huge system requirements and requires OpenGL.
It is part of a suite of tools that need to operate together on one machine.
This application is used for a time intensive task in terms of man hours.
I don't want to sit in the server room working on this application.
So, the question came up... how do I run this application from a remote windows machine?
I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme. | **Solution**
I installed two pieces of software:
[PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/)
[XMing-mesa](http://www.straightrunning.com/XmingNotes/) The mesa part is important.
**PuTTY configuration**
```
Connection->Seconds Between Keepalives: 30
Connection->Enable TCP Keepalives: Yes
Connection->SSH->X11->Enable X11 forwarding: Yes
Connection->SSH->X11->X display location: localhost:0:0
```
**Lauching**
Run *Xming* which will put simply start a process and put an icon in your system tray.
Launch putty, pointing to your linux box, with the above configuration.
Run program
Hopefully, **Success!** |
106,206 | <p>I'm writing an import utility that is using phone numbers as a unique key within the import.</p>
<p>I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is <strong>slow</strong> and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.</p>
<p>I tried using the script from this post:<br>
<a href="https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters">T-SQL trim &nbsp (and other non-alphanumeric characters)</a></p>
<p>But that didn't speed it up any.</p>
<p>Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.</p>
<p>Whatever is done needs to perform <strong>fast</strong>.</p>
<p><strong>Update</strong><br>
Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. </p>
<p>To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). </p>
<p>Could comparing BIGINT to BIGINT be slowing things down?</p>
<p>I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.</p>
| [
{
"answer_id": 106217,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 1,
"selected": false,
"text": "<p>can you remove them in a nightly process, storing them in a separate field, then do an update on changed records right before you run the process?</p>\n\n<p>Or on the insert/update, store the \"numeric\" format, to reference later. A trigger would be an easy way to do it.</p>\n"
},
{
"answer_id": 106226,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 5,
"selected": true,
"text": "<p>I may misunderstand, but you've got two sets of data to remove the strings from one for current data in the database and then a new set whenever you import.</p>\n\n<p>For updating the existing records, I would just use SQL, that only has to happen once.</p>\n\n<p>However, SQL isn't optimized for this sort of operation, since you said you are writing an import utility, I would do those updates in the context of the import utility itself, not in SQL. This would be much better performance wise. What are you writing the utility in?</p>\n\n<p>Also, I may be completely misunderstanding the process, so I apologize if off-base.</p>\n\n<p><b>Edit: </b><br>\nFor the initial update, if you are using SQL Server 2005, you could try a CLR function. Here's a quick one using regex. Not sure how the performance would compare, I've never used this myself except for a quick test right now.</p>\n\n<pre><code>using System; \nusing System.Data; \nusing System.Text.RegularExpressions; \nusing System.Data.SqlClient; \nusing System.Data.SqlTypes; \nusing Microsoft.SqlServer.Server; \n\npublic partial class UserDefinedFunctions \n{ \n [Microsoft.SqlServer.Server.SqlFunction] \n public static SqlString StripNonNumeric(SqlString input) \n { \n Regex regEx = new Regex(@\"\\D\"); \n return regEx.Replace(input.Value, \"\"); \n } \n}; \n</code></pre>\n\n<p>After this is deployed, to update you could just use:</p>\n\n<pre><code>UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber)\n</code></pre>\n"
},
{
"answer_id": 106260,
"author": "epochwolf",
"author_id": 16204,
"author_profile": "https://Stackoverflow.com/users/16204",
"pm_score": -1,
"selected": false,
"text": "<p>I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)</p>\n\n<p>Database: 5555555555x555</p>\n\n<p>Display: (555) 555-5555 ext 555</p>\n\n<p>Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)</p>\n"
},
{
"answer_id": 106331,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 1,
"selected": false,
"text": "<p>Working with varchars is fundamentally slow and inefficient compared to working with numerics, for obvious reasons. The functions you link to in the original post will indeed be quite slow, as they loop through each character in the string to determine whether or not it's a number. Do that for thousands of records and the process is bound to be slow. This is the perfect job for Regular Expressions, but they're not natively supported in SQL Server. You can add support using a CLR function, but it's hard to say how slow this will be without trying it I would definitely expect it to be significantly faster than looping through each character of each phone number, however!</p>\n\n<p>Once you get the phone numbers formatted in your database so that they're only numbers, you could switch to a numeric type in SQL which would yield lightning-fast comparisons against other numeric types. You might find that, depending on how fast your new data is coming in, doing the trimming and conversion to numeric on the database side is plenty fast enough once what you're comparing to is properly formatted, but if possible, you would be better off writing an import utility in a .NET language that would take care of these formatting issues before hitting the database.</p>\n\n<p>Either way though, you're going to have a big problem regarding optional formatting. Even if your numbers are guaranteed to be only North American in origin, some people will put the 1 in front of a fully area-code qualified phone number and others will not, which will cause the potential for multiple entries of the same phone number. Furthermore, depending on what your data represents, some people will be using their home phone number which might have several people living there, so a unique constraint on it would only allow one database member per household. Some would use their work number and have the same problem, and some would or wouldn't include the extension which would cause artificial uniqueness potential again.</p>\n\n<p>All of that may or may not impact you, depending on your particular data and usages, but it's important to keep in mind!</p>\n"
},
{
"answer_id": 106448,
"author": "Mike L",
"author_id": 4796,
"author_profile": "https://Stackoverflow.com/users/4796",
"pm_score": 1,
"selected": false,
"text": "<p>I would try Scott's CLR function first but add a WHERE clause to reduce the number of records updated.</p>\n\n<pre><code>UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber) \nWHERE phonenumber like '%[^0-9]%'\n</code></pre>\n\n<p>If you know that the great majority of your records have non-numeric characters it might not help though.</p>\n"
},
{
"answer_id": 106463,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>\"Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.\"</p>\n\n<p>Fire up SQL Profiler and take a look. Take the resulting queries and check their execution plans to make sure that index is being used.</p>\n"
},
{
"answer_id": 106913,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Thousands of records against thousands of records is not normally a problem. I've used SSIS to import millions of records with de-duping like this.</p>\n\n<p>I would clean up the database to remove the non-numeric characters in the first place and keep them out.</p>\n"
},
{
"answer_id": 2596080,
"author": "Dennis Allen",
"author_id": 214691,
"author_profile": "https://Stackoverflow.com/users/214691",
"pm_score": 1,
"selected": false,
"text": "<p>I know it is late to the game, but here is a function that I created for T-SQL that quickly removes non-numeric characters. Of note, I have a schema \"String\" that I put utility functions for strings into...</p>\n\n<pre><code>CREATE FUNCTION String.ComparablePhone( @string nvarchar(32) ) RETURNS bigint AS\nBEGIN\n DECLARE @out bigint;\n\n-- 1. table of unique characters to be kept\n DECLARE @keepers table ( chr nchar(1) not null primary key );\n INSERT INTO @keepers ( chr ) VALUES (N'0'),(N'1'),(N'2'),(N'3'),(N'4'),(N'5'),(N'6'),(N'7'),(N'8'),(N'9');\n\n-- 2. Identify the characters in the string to remove\n WITH found ( id, position ) AS\n (\n SELECT \n ROW_NUMBER() OVER (ORDER BY (n1+n10) DESC), -- since we are using stuff, for the position to continue to be accurate, start from the greatest position and work towards the smallest\n (n1+n10)\n FROM \n (SELECT 0 AS n1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS d1,\n (SELECT 0 AS n10 UNION SELECT 10 UNION SELECT 20 UNION SELECT 30) AS d10\n WHERE\n (n1+n10) BETWEEN 1 AND len(@string)\n AND substring(@string, (n1+n10), 1) NOT IN (SELECT chr FROM @keepers)\n )\n-- 3. Use stuff to snuff out the identified characters\n SELECT \n @string = stuff( @string, position, 1, '' )\n FROM \n found\n ORDER BY\n id ASC; -- important to process the removals in order, see ROW_NUMBER() above\n\n-- 4. Try and convert the results to a bigint \n IF len(@string) = 0\n RETURN NULL; -- an empty string converts to 0\n\n RETURN convert(bigint,@string); \nEND\n</code></pre>\n\n<p>Then to use it to compare for inserting, something like this;</p>\n\n<pre><code>INSERT INTO Contacts ( phone, first_name, last_name )\nSELECT i.phone, i.first_name, i.last_name\nFROM Imported AS i\nLEFT JOIN Contacts AS c ON String.ComparablePhone(c.phone) = String.ComparablePhone(i.phone)\nWHERE c.phone IS NULL -- Exclude those that already exist\n</code></pre>\n"
},
{
"answer_id": 4087219,
"author": "Debayan Samaddar",
"author_id": 495923,
"author_profile": "https://Stackoverflow.com/users/495923",
"pm_score": 3,
"selected": false,
"text": "<pre><code>create function dbo.RemoveNonNumericChar(@str varchar(500)) \nreturns varchar(500) \nbegin \ndeclare @startingIndex int \nset @startingIndex=0 \nwhile 1=1 \nbegin \n set @startingIndex= patindex('%[^0-9]%',@str) \n if @startingIndex <> 0 \n begin \n set @str = replace(@str,substring(@str,@startingIndex,1),'') \n end \n else break; \nend \nreturn @str \nend\n\ngo \n\nselect dbo.RemoveNonNumericChar('aisdfhoiqwei352345234@#$%^$@345345%^@#$^') \n</code></pre>\n"
},
{
"answer_id": 6267337,
"author": "Tim",
"author_id": 787723,
"author_profile": "https://Stackoverflow.com/users/787723",
"pm_score": 0,
"selected": false,
"text": "<p>Looking for a super simple solution:</p>\n\n<pre><code>SUBSTRING([Phone], CHARINDEX('(', [Phone], 1)+1, 3)\n + SUBSTRING([Phone], CHARINDEX(')', [Phone], 1)+1, 3)\n + SUBSTRING([Phone], CHARINDEX('-', [Phone], 1)+1, 4) AS Phone\n</code></pre>\n"
},
{
"answer_id": 6529463,
"author": "David Coster",
"author_id": 1022942,
"author_profile": "https://Stackoverflow.com/users/1022942",
"pm_score": 7,
"selected": false,
"text": "<p>I saw this solution with T-SQL code and PATINDEX. I like it :-)</p>\n\n<pre><code>CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))\nRETURNS VARCHAR(1000)\nAS\nBEGIN\n WHILE PATINDEX('%[^0-9]%', @strText) > 0\n BEGIN\n SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')\n END\n RETURN @strText\nEND\n</code></pre>\n"
},
{
"answer_id": 7033123,
"author": "Tom",
"author_id": 780032,
"author_profile": "https://Stackoverflow.com/users/780032",
"pm_score": 4,
"selected": false,
"text": "<p>In case you didn't want to create a function, or you needed just a single inline call in T-SQL, you could try:</p>\n\n<pre><code>set @Phone = REPLACE(REPLACE(REPLACE(REPLACE(@Phone,'(',''),' ',''),'-',''),')','')\n</code></pre>\n\n<p>Of course this is specific to removing phone number formatting, not a generic remove all special characters from string function.</p>\n"
},
{
"answer_id": 17950550,
"author": "Brainwater",
"author_id": 2634647,
"author_profile": "https://Stackoverflow.com/users/2634647",
"pm_score": 5,
"selected": false,
"text": "<p><code>replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string</code>,</p>\n\n<p>:)</p>\n"
},
{
"answer_id": 22532045,
"author": "AdamE",
"author_id": 3441873,
"author_profile": "https://Stackoverflow.com/users/3441873",
"pm_score": 3,
"selected": false,
"text": "<p>Simple function:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[RemoveAlphaCharacters](@InputString VARCHAR(1000))\nRETURNS VARCHAR(1000)\nAS\nBEGIN\n WHILE PATINDEX('%[^0-9]%',@InputString)>0\n SET @InputString = STUFF(@InputString,PATINDEX('%[^0-9]%',@InputString),1,'') \n RETURN @InputString\nEND\n\nGO\n</code></pre>\n"
},
{
"answer_id": 40070177,
"author": "hkravitz",
"author_id": 2919045,
"author_profile": "https://Stackoverflow.com/users/2919045",
"pm_score": 1,
"selected": false,
"text": "<p>I'd use an Inline Function from performance perspective, see below:\n<strong><em>Note that symbols like '+','-' etc will not be removed</em></strong></p>\n\n<pre><code>CREATE FUNCTION [dbo].[UDF_RemoveNumericStringsFromString]\n (\n @str varchar(100)\n )\n RETURNS TABLE AS RETURN\n WITH Tally (n) as \n (\n -- 100 rows\n SELECT TOP (Len(@Str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))\n FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)\n CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)\n )\n\n SELECT OutStr = STUFF(\n (SELECT SUBSTRING(@Str, n,1) st\n FROM Tally\n WHERE ISNUMERIC(SUBSTRING(@Str, n,1)) = 1\n FOR XML PATH(''),type).value('.', 'varchar(100)'),1,0,'')\n GO\n\n /*Use it*/\n SELECT OutStr\n FROM dbo.UDF_RemoveNumericStringsFromString('fjkfhk759734977fwe9794t23')\n /*Result set\n 759734977979423 */\n</code></pre>\n\n<p>You can define it with more than 100 characters...</p>\n"
},
{
"answer_id": 74276585,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 1,
"selected": false,
"text": "<p>From SQL Server 2017 the native <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-ver16\" rel=\"nofollow noreferrer\"><code>TRANSLATE</code></a> function is available.</p>\n<p>If you have a known list of all characters to remove then you can simply use the following (to first convert all bad characters to a single known bad character and then to strip that specific character out with a <code>REPLACE</code>)</p>\n<pre><code>DECLARE @BadCharacters VARCHAR(256) = 'abcdefghijklmnopqrstuvwxyz';\n \nSELECT REPLACE(\n TRANSLATE(YourColumn, \n @BadCharacters, \n REPLICATE(LEFT(@BadCharacters,1),LEN(@BadCharacters))),\n LEFT(@BadCharacters,1),\n '')\nFROM @YourTable\n</code></pre>\n<p>If the list of possible "bad" characters is too extensive to enumerate all in advance then you can use a double <code>TRANSLATE</code></p>\n<pre><code>DECLARE @CharactersToKeep VARCHAR(30) = '0123456789', \n @ExampleBadCharacter CHAR(1) = CHAR(26); \n \nSELECT REPLACE(TRANSLATE(YourColumn, bad_chars, REPLICATE(@ExampleBadCharacter, LEN(bad_chars + 'X') - 1)), @ExampleBadCharacter, '')\nFROM @YourTable\n CROSS APPLY (SELECT REPLACE(\n TRANSLATE(YourColumn, \n @CharactersToKeep, \n REPLICATE(LEFT(@CharactersToKeep, 1), LEN(@CharactersToKeep))), \n LEFT(@CharactersToKeep, 1), \n '')) ca(bad_chars)\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
| I'm writing an import utility that is using phone numbers as a unique key within the import.
I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is **slow** and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.
I tried using the script from this post:
[T-SQL trim   (and other non-alphanumeric characters)](https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters)
But that didn't speed it up any.
Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.
Whatever is done needs to perform **fast**.
**Update**
Given what people responded with, I think I'm going to have to clean the fields before I run the import utility.
To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records).
Could comparing BIGINT to BIGINT be slowing things down?
I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is. | I may misunderstand, but you've got two sets of data to remove the strings from one for current data in the database and then a new set whenever you import.
For updating the existing records, I would just use SQL, that only has to happen once.
However, SQL isn't optimized for this sort of operation, since you said you are writing an import utility, I would do those updates in the context of the import utility itself, not in SQL. This would be much better performance wise. What are you writing the utility in?
Also, I may be completely misunderstanding the process, so I apologize if off-base.
**Edit:**
For the initial update, if you are using SQL Server 2005, you could try a CLR function. Here's a quick one using regex. Not sure how the performance would compare, I've never used this myself except for a quick test right now.
```
using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString StripNonNumeric(SqlString input)
{
Regex regEx = new Regex(@"\D");
return regEx.Replace(input.Value, "");
}
};
```
After this is deployed, to update you could just use:
```
UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber)
``` |
106,234 | <p>lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.</p>
<p>What are some of the most common and useful ways of using lsof, and which command-line switches are used for that? </p>
| [
{
"answer_id": 106249,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p><code>lsof -i</code> will provide a list of open network sockets. The <code>-n</code> option will prevent DNS lookups, which is useful when your network connection is slow or unreliable.</p>\n"
},
{
"answer_id": 106255,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 4,
"selected": false,
"text": "<p>See what files a running application or daemon has open:</p>\n\n<pre><code>lsof -p pid\n</code></pre>\n\n<p>Where <strong>pid</strong> is the process ID of the application or daemon.</p>\n"
},
{
"answer_id": 106259,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 5,
"selected": false,
"text": "<pre><code>lsof -i :port \n</code></pre>\n\n<p>will tell you what programs are listening on a specific port.</p>\n"
},
{
"answer_id": 319997,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>To show all networking related to a given <code>port</code>:</p>\n\n<pre><code>lsof -iTCP -i :port\nlsof -i :22\n</code></pre>\n\n<p>To show connections to a specific host, use <code>@host</code></p>\n\n<pre><code>lsof [email protected]\n</code></pre>\n\n<p>Show connections based on the host and the port using <code>@host:port</code>\n lsof [email protected]:22</p>\n\n<p><code>grep</code>ping for <code>LISTEN</code> shows what ports your system is waiting for connections on:</p>\n\n<pre><code>lsof -i| grep LISTEN\n</code></pre>\n\n<p>Show what a given user has open using <code>-u</code>:</p>\n\n<pre><code>lsof -u daniel\n</code></pre>\n\n<p>See what files and network connections a command is using with <code>-c</code></p>\n\n<pre><code>lsof -c syslog-ng\n</code></pre>\n\n<p>The <code>-p</code> switch lets you see what a given process ID has open, which is good for learning more about unknown processes:</p>\n\n<pre><code>lsof -p 10075\n</code></pre>\n\n<p>The <code>-t</code> option returns just a <code>PID</code></p>\n\n<pre><code>lsof -t -c Mail\n</code></pre>\n\n<p>Using the <code>-t</code> and <code>-c</code> options together you can <code>HUP</code> processes</p>\n\n<pre><code>kill -HUP $(lsof -t -c sshd)\n</code></pre>\n\n<p>You can also use the <code>-t</code> with <code>-u</code> to kill everything a user has open</p>\n\n<pre><code>kill -9 $(lsof -t -u daniel)\n</code></pre>\n"
},
{
"answer_id": 1084508,
"author": "mas",
"author_id": 19007,
"author_profile": "https://Stackoverflow.com/users/19007",
"pm_score": 3,
"selected": false,
"text": "<pre><code>lsof +f -- /mountpoint\n</code></pre>\n\n<p>lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.</p>\n"
},
{
"answer_id": 11494954,
"author": "siesta",
"author_id": 1366793,
"author_profile": "https://Stackoverflow.com/users/1366793",
"pm_score": 4,
"selected": false,
"text": "<pre><code>lsof +D /some/directory\n</code></pre>\n\n<p>Will display recursively all the files opened in a directory. +d for just the top-level.</p>\n\n<p>This is useful when you have high wait% for IO, correlated to use on a particular FS and want to see which processes are chewing up your io.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
]
| lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.
What are some of the most common and useful ways of using lsof, and which command-line switches are used for that? | To show all networking related to a given `port`:
```
lsof -iTCP -i :port
lsof -i :22
```
To show connections to a specific host, use `@host`
```
lsof [email protected]
```
Show connections based on the host and the port using `@host:port`
lsof [email protected]:22
`grep`ping for `LISTEN` shows what ports your system is waiting for connections on:
```
lsof -i| grep LISTEN
```
Show what a given user has open using `-u`:
```
lsof -u daniel
```
See what files and network connections a command is using with `-c`
```
lsof -c syslog-ng
```
The `-p` switch lets you see what a given process ID has open, which is good for learning more about unknown processes:
```
lsof -p 10075
```
The `-t` option returns just a `PID`
```
lsof -t -c Mail
```
Using the `-t` and `-c` options together you can `HUP` processes
```
kill -HUP $(lsof -t -c sshd)
```
You can also use the `-t` with `-u` to kill everything a user has open
```
kill -9 $(lsof -t -u daniel)
``` |
106,251 | <p>In my model I have:</p>
<pre><code>validate :my_custom_validation
def my_custom_validation
errors.add_to_base("error message") if condition.exists?
end
</code></pre>
<p>I would like to add some parameters to mycustomer vaildation like so:</p>
<pre><code>validate :my_custom_validation, :parameter1 => x, :parameter2 => y
</code></pre>
<p>How do I write the mycustomvalidation function to account for parameters? </p>
| [
{
"answer_id": 106267,
"author": "Bill Turner",
"author_id": 17773,
"author_profile": "https://Stackoverflow.com/users/17773",
"pm_score": 1,
"selected": false,
"text": "<p>You can just do something like this:</p>\n\n<pre><code>def validate\n errors.add('That particular field', 'can not be the value you presented') if !self.field_to_check.blank? && self.field_to_check == 'I AM COOL'\nend\n</code></pre>\n\n<p>No need to call reference it, as I believe the validate method is processed (if it exists) after any validates_uniqueness_of -like validations.</p>\n\n<p>Added: More information in the Rails API docs <a href=\"http://api.rubyonrails.com/classes/ActiveRecord/Validations.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 106294,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 4,
"selected": true,
"text": "<p>Validators usualy have an array parameter indicating, first, the fields to validate and lastly (if it exists) a hash with the options. In your example:</p>\n\n<pre><code>:my_custom_validation, parameter1: x, parameter2: y\n</code></pre>\n\n<p>:my_custom_validation would be a field name, while parameter1: x, parameter2: y would be a hash:</p>\n\n<pre><code>{ parameter1: x, parameter2: y}\n</code></pre>\n\n<p>Therefore, you'd do something like:</p>\n\n<pre><code>def my_custom_validation(*attr)\n options = attr.pop if attr.last.is_a? Hash\n # do something with options\n errors.add_to_base(\"error message\") if condition.exists?\n\nend\n</code></pre>\n"
},
{
"answer_id": 72746111,
"author": "Matt M",
"author_id": 4848156,
"author_profile": "https://Stackoverflow.com/users/4848156",
"pm_score": 0,
"selected": false,
"text": "<p>You should also be able to use a <a href=\"https://www.geeksforgeeks.org/lambda-function-ruby/\" rel=\"nofollow noreferrer\">Ruby lambda</a> to help with method based validation of your model attributes (x, y) like below:</p>\n<pre><code>validate -> { my_custom_validation(parameter1: x, parameter2: y) }\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396/"
]
| In my model I have:
```
validate :my_custom_validation
def my_custom_validation
errors.add_to_base("error message") if condition.exists?
end
```
I would like to add some parameters to mycustomer vaildation like so:
```
validate :my_custom_validation, :parameter1 => x, :parameter2 => y
```
How do I write the mycustomvalidation function to account for parameters? | Validators usualy have an array parameter indicating, first, the fields to validate and lastly (if it exists) a hash with the options. In your example:
```
:my_custom_validation, parameter1: x, parameter2: y
```
:my\_custom\_validation would be a field name, while parameter1: x, parameter2: y would be a hash:
```
{ parameter1: x, parameter2: y}
```
Therefore, you'd do something like:
```
def my_custom_validation(*attr)
options = attr.pop if attr.last.is_a? Hash
# do something with options
errors.add_to_base("error message") if condition.exists?
end
``` |
106,275 | <p>If I have a table field named 'description', what would be the SQL (using MS SQL) to get a list of records of all distinct words used in this field.</p>
<p>For example:</p>
<p>If the table contains the following for the 'description' field:</p>
<pre><code>Record1 "The dog jumped over the fence."
Record2 "The giant tripped on the fence."
...
</code></pre>
<p>The SQL record output would be:</p>
<pre><code>"The","giant","dog","jumped","tripped","on","over","fence"
</code></pre>
| [
{
"answer_id": 106280,
"author": "Jeremy",
"author_id": 8557,
"author_profile": "https://Stackoverflow.com/users/8557",
"pm_score": 0,
"selected": false,
"text": "<p>it'd be a messy stored procedure with a temp table and a SELECT DISTINCT at the end.</p>\n\n<p>if you had the words already as records, you would use SELECT DISTINCT [WordsField] from [owner].[tablename]</p>\n"
},
{
"answer_id": 106282,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": true,
"text": "<p>I do not think you can do this with a SELECT. The best chance is to write a user defined function that returns a table with all the words and then do SELECT DISTINCT on it.</p>\n\n<hr>\n\n<p><strong>Disclaimer:</strong> Function <strong>dbo.Split</strong> is from <a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648\" rel=\"noreferrer\">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648</a></p>\n\n<pre><code>CREATE TABLE test\n(\n id int identity(1, 1) not null,\n description varchar(50) not null\n)\n\nINSERT INTO test VALUES('The dog jumped over the fence')\nINSERT INTO test VALUES('The giant tripped on the fence')\n\nCREATE FUNCTION dbo.Split\n(\n @RowData nvarchar(2000),\n @SplitOn nvarchar(5)\n) \nRETURNS @RtnValue table \n(\n Id int identity(1,1),\n Data nvarchar(100)\n) \nAS \nBEGIN \n Declare @Cnt int\n Set @Cnt = 1\n\n While (Charindex(@SplitOn,@RowData)>0)\n Begin\n Insert Into @RtnValue (data)\n Select \n Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))\n\n Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))\n Set @Cnt = @Cnt + 1\n End\n\n Insert Into @RtnValue (data)\n Select Data = ltrim(rtrim(@RowData))\n\n Return\nEND\n\nCREATE FUNCTION dbo.SplitAll(@SplitOn nvarchar(5))\nRETURNS @RtnValue table\n(\n Id int identity(1,1),\n Data nvarchar(100)\n)\nAS\nBEGIN\nDECLARE My_Cursor CURSOR FOR SELECT Description FROM dbo.test\nDECLARE @description varchar(50)\n\nOPEN My_Cursor\nFETCH NEXT FROM My_Cursor INTO @description\nWHILE @@FETCH_STATUS = 0\nBEGIN\n INSERT INTO @RtnValue\n SELECT Data FROM dbo.Split(@description, @SplitOn)\n FETCH NEXT FROM My_Cursor INTO @description\nEND\nCLOSE My_Cursor\nDEALLOCATE My_Cursor\n\nRETURN\n\nEND\n\nSELECT DISTINCT Data FROM dbo.SplitAll(N' ')\n</code></pre>\n"
},
{
"answer_id": 106318,
"author": "Pavling",
"author_id": 18197,
"author_profile": "https://Stackoverflow.com/users/18197",
"pm_score": 1,
"selected": false,
"text": "<p>In SQL on it's own it would probably need to be a big stored procedure, but if you read all the records out to the scripting language of your choice, you can easily loop over them and split each out into arrays/hashes.</p>\n"
},
{
"answer_id": 746546,
"author": "mjallday",
"author_id": 6084,
"author_profile": "https://Stackoverflow.com/users/6084",
"pm_score": 2,
"selected": false,
"text": "<p>I just had a similar problem and tried using SQL CLR to solve it. Might be handy to someone</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic partial class UserDefinedFunctions\n{\n private class SplitStrings : IEnumerable\n {\n private List<string> splits;\n\n public SplitStrings(string toSplit, string splitOn)\n {\n splits = new List<string>();\n\n // nothing, return empty list\n if (string.IsNullOrEmpty(toSplit))\n {\n return;\n }\n\n // return one word\n if (string.IsNullOrEmpty(splitOn))\n {\n splits.Add(toSplit);\n\n return;\n }\n\n splits.AddRange(\n toSplit.Split(new string[] { splitOn }, StringSplitOptions.RemoveEmptyEntries)\n );\n }\n\n #region IEnumerable Members\n\n public IEnumerator GetEnumerator()\n {\n return splits.GetEnumerator();\n }\n\n #endregion\n }\n\n [Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName = \"readRow\", TableDefinition = \"word nvarchar(255)\")]\n public static IEnumerable fnc_clr_split_string(string toSplit, string splitOn)\n {\n return new SplitStrings(toSplit, splitOn);\n }\n\n public static void readRow(object inWord, out SqlString word)\n {\n string w = (string)inWord;\n\n if (string.IsNullOrEmpty(w))\n {\n word = string.Empty;\n return;\n }\n\n if (w.Length > 255)\n {\n w = w.Substring(0, 254);\n }\n\n word = w;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 15111948,
"author": "user2115248",
"author_id": 2115248,
"author_profile": "https://Stackoverflow.com/users/2115248",
"pm_score": 2,
"selected": false,
"text": "<p>It is not the fastest approach but might be used by somebody for a small amount of data:</p>\n\n<pre><code>declare @tmp table(descr varchar(400))\n\ninsert into @tmp\nselect 'The dog jumped over the fence.'\nunion select 'The giant tripped on the fence.'\n\n/* the actual doing starts here */\nupdate @tmp\nset descr = replace(descr, '.', '') --get rid of dots in the ends of sentences.\n\ndeclare @xml xml\nset @xml = '<c>' + replace(\n (select ' ' + descr\n from @tmp\n for xml path('')\n), ' ', '</c><c>') + '</c>'\n\n;with \nallWords as (\n select section.Cols.value('.', 'varchar(250)') words\n from @xml.nodes('/c') section(Cols)\n )\nselect words\nfrom allWords\nwhere ltrim(rtrim(words)) <> ''\ngroup by words\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
]
| If I have a table field named 'description', what would be the SQL (using MS SQL) to get a list of records of all distinct words used in this field.
For example:
If the table contains the following for the 'description' field:
```
Record1 "The dog jumped over the fence."
Record2 "The giant tripped on the fence."
...
```
The SQL record output would be:
```
"The","giant","dog","jumped","tripped","on","over","fence"
``` | I do not think you can do this with a SELECT. The best chance is to write a user defined function that returns a table with all the words and then do SELECT DISTINCT on it.
---
**Disclaimer:** Function **dbo.Split** is from <http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648>
```
CREATE TABLE test
(
id int identity(1, 1) not null,
description varchar(50) not null
)
INSERT INTO test VALUES('The dog jumped over the fence')
INSERT INTO test VALUES('The giant tripped on the fence')
CREATE FUNCTION dbo.Split
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
CREATE FUNCTION dbo.SplitAll(@SplitOn nvarchar(5))
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
DECLARE My_Cursor CURSOR FOR SELECT Description FROM dbo.test
DECLARE @description varchar(50)
OPEN My_Cursor
FETCH NEXT FROM My_Cursor INTO @description
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @RtnValue
SELECT Data FROM dbo.Split(@description, @SplitOn)
FETCH NEXT FROM My_Cursor INTO @description
END
CLOSE My_Cursor
DEALLOCATE My_Cursor
RETURN
END
SELECT DISTINCT Data FROM dbo.SplitAll(N' ')
``` |
106,298 | <p>You may think that this is a coincidence that the topic of my question is similar to the name of the forum but I actually got here by googling the term "stack overflow".</p>
<p>I use the OPNET network simulator in which I program using C. I think I am having a problem with big array sizes. It seems that I am hitting some sort of memory allocation limitation. It may have to do with OPNET, Windows, my laptop memory or most likely C language. The problem is caused when I try to use nested arrays with a total number of elements coming to several thousand integers. I think I am exceeding an overall memory allocation limit and I am wondering if there is a way to increase this cap.
Here's the exact problem description:</p>
<p>I basically have a routing table. Let's call it routing_tbl[n], meaning I am supporting 30 nodes (routers). Now, for each node in this table, I keep info. about many (hundreds) available paths, in an array called paths[p]. Again, for each path in this array, I keep the list of nodes that belong to it in an array called hops[h]. So, I am using at least nph integers worth of memory but this table contains other information as well. In the same function, I am also using another nested array that consumes almost 40,000 integers as well.
As soon as I run my simulation, it quits complaining about stack overflow. It works when I reduce the total size of the routing table.
What do you think causes the problem and how can it be solved?
Much appreciated
Ali</p>
| [
{
"answer_id": 106306,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 3,
"selected": false,
"text": "<p>It may help if you post some code. Edit the question to include the problem function and the error.</p>\n\n<p>Meanwhile, here's a very generic answer:</p>\n\n<p>The two principal causes of a stack overflow are 1) a recursive function, or 2) the allocation of a large number of local variables.</p>\n\n<p><strong>Recursion</strong></p>\n\n<p>if your function calls itself, like this:</p>\n\n<pre><code>int recurse(int number) {\n\n return (recurse(number));\n}\n</code></pre>\n\n<p>Since local variables and function arguments are stored on the stack, then it will in fill the stack and cause a stack overflow.</p>\n\n<p><strong>Large local variables</strong></p>\n\n<p>If you try to allocate a large array of local variables then you can overflow the stack in one easy go. A function like this may cause the issue:</p>\n\n<pre><code>void hugeStack (void) {\n\n unsigned long long reallyBig[100000000][1000000000];\n\n ...\n}\n</code></pre>\n\n<p>There is quite a detailed answer to this <a href=\"https://stackoverflow.com/questions/26158/how-does-a-stack-overflow-occur-and-how-do-you-prevent-it\">similar question</a>.</p>\n"
},
{
"answer_id": 106321,
"author": "tkerwin",
"author_id": 19141,
"author_profile": "https://Stackoverflow.com/users/19141",
"pm_score": 1,
"selected": false,
"text": "<p>Stack overflows can happen in C when the number of embedded recursive calls is too high. Perhaps you are calling a function from itself too many times?</p>\n\n<p>This error may also be due to allocating too much memory in static declarations. You can switch to dynamic allocations through malloc() to fix this type of problem.</p>\n\n<p>Is there a reason why you cannot use the debugger on this program? </p>\n"
},
{
"answer_id": 106375,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 2,
"selected": false,
"text": "<p>Somehow you are using a lot of stack. Possible causes include that you're creating the routing table on the stack, you're passing it on the stack, or else you're generating lots of calls (eg by recursively processing the whole thing).</p>\n\n<p>In the first two cases you should create it on the heap and pass around a pointer to it. In the third case you'll need to rewrite your algorithm in an iterative form.</p>\n"
},
{
"answer_id": 106584,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on where you have declared the variable.<br></p>\n\n<p>A local variable (i.e. one declared on the stack is limited by the maximum frame size) This is a limit of the compiler you are using (and can usually be adjusted with compiler flags).</p>\n\n<p>A dynamically allocated object (i.e. one that is on the heap) is limited by the amount of available memory. This is a property of the OS (and can technically by larger the physical memory if you have a smart OS).</p>\n"
},
{
"answer_id": 108173,
"author": "mxg",
"author_id": 11157,
"author_profile": "https://Stackoverflow.com/users/11157",
"pm_score": 0,
"selected": false,
"text": "<p>You are unlikely to run into a stack overflow with unthreaded compiled C unless you do something particularly egregious like have runaway recursion or a cosmic memory leak. However, your simulator probably has a threading package which will impose stack size limits. When you start a new thread it will allocate a chunk of memory for the stack for that thread. Likely, there is a parameter you can set somewhere that establishes the the default stack size, or there may be a way to grow the stack dynamically. For example, pthreads has a function pthread_attr_setstacksize() which you call prior to starting a new thread to set its size. Your simulator may or may not be using pthreads. Consult your simulator reference documentation.</p>\n"
},
{
"answer_id": 248268,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 1,
"selected": false,
"text": "<p>Many operating systems dynamically expand the stack as you use more of it. When you start writing to a memory address that's just beyond the stack, the OS assumes your stack has just grown a bit more and allocates it an extra page (usually 4096Kib on x86 - exactly 1024 ints).</p>\n\n<p>The problem is, on the x86 (and some other architectures) the stack grows <em>downwards</em> but C arrays grow <em>upwards</em>. This means if you access the <em>start</em> of a large array, you'll be accessing memory that's more than a page away from the edge of the stack.</p>\n\n<p>If you initialise your array to 0 <em>starting from the end</em> of the array (that's right, make a for loop to do it), the errors might go away. If they do, this is indeed the problem.</p>\n\n<p>You might be able to find some OS API functions to force stack allocation, or compiler pragmas/flags. I'm not sure about how this can be done portably, except of course for using malloc() and free()!</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| You may think that this is a coincidence that the topic of my question is similar to the name of the forum but I actually got here by googling the term "stack overflow".
I use the OPNET network simulator in which I program using C. I think I am having a problem with big array sizes. It seems that I am hitting some sort of memory allocation limitation. It may have to do with OPNET, Windows, my laptop memory or most likely C language. The problem is caused when I try to use nested arrays with a total number of elements coming to several thousand integers. I think I am exceeding an overall memory allocation limit and I am wondering if there is a way to increase this cap.
Here's the exact problem description:
I basically have a routing table. Let's call it routing\_tbl[n], meaning I am supporting 30 nodes (routers). Now, for each node in this table, I keep info. about many (hundreds) available paths, in an array called paths[p]. Again, for each path in this array, I keep the list of nodes that belong to it in an array called hops[h]. So, I am using at least nph integers worth of memory but this table contains other information as well. In the same function, I am also using another nested array that consumes almost 40,000 integers as well.
As soon as I run my simulation, it quits complaining about stack overflow. It works when I reduce the total size of the routing table.
What do you think causes the problem and how can it be solved?
Much appreciated
Ali | It may help if you post some code. Edit the question to include the problem function and the error.
Meanwhile, here's a very generic answer:
The two principal causes of a stack overflow are 1) a recursive function, or 2) the allocation of a large number of local variables.
**Recursion**
if your function calls itself, like this:
```
int recurse(int number) {
return (recurse(number));
}
```
Since local variables and function arguments are stored on the stack, then it will in fill the stack and cause a stack overflow.
**Large local variables**
If you try to allocate a large array of local variables then you can overflow the stack in one easy go. A function like this may cause the issue:
```
void hugeStack (void) {
unsigned long long reallyBig[100000000][1000000000];
...
}
```
There is quite a detailed answer to this [similar question](https://stackoverflow.com/questions/26158/how-does-a-stack-overflow-occur-and-how-do-you-prevent-it). |
106,323 | <p>Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing?</p>
| [
{
"answer_id": 106398,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": -1,
"selected": true,
"text": "<p>Check out the Oracle documentation:</p>\n\n<ul>\n<li><a href=\"http://68.142.116.68/docs/cd/B19306_01/server.102/b14357/ch6.htm#i1081008\" rel=\"nofollow noreferrer\">Formatting SQLPlus Reports</a></li>\n<li><a href=\"http://68.142.116.68/docs/cd/B19306_01/server.102/b14357/ch7.htm#sthref1452\" rel=\"nofollow noreferrer\">Generating HTML Reports from SQLPlus</a></li>\n</ul>\n\n<p>You can generate a tab in Oracle by using the tab's ASCII value 9 and the chr function:</p>\n\n<pre><code>select chr(9) from dual;\n</code></pre>\n"
},
{
"answer_id": 106450,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 2,
"selected": false,
"text": "<p>One particular script that I have stolen on more than one occasion comes from an AskTom thread on <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:68212348056#74643125201557\" rel=\"nofollow noreferrer\">extracting data to a flat file</a>. If I needed a quick and dirty flat file out of SQL*Plus. I would tend to prefer the DUMP_CSV function Tom posted earlier on that thread for any sort of ongoing process, though.</p>\n"
},
{
"answer_id": 7066859,
"author": "user158017",
"author_id": 158017,
"author_profile": "https://Stackoverflow.com/users/158017",
"pm_score": 3,
"selected": false,
"text": "<p>As Justin pointed out in his link, using the <code>set colsep</code> function SQLPlus command saves typing a separator for each column.</p>\n\n<p>But for tab-delimited, <code>set colsep Chr(9)</code> won't work. </p>\n\n<p>For UNIX or LINUX, use <code>set colsep ' '</code> with the space between the single-quotes being a typed tab.</p>\n\n<p>For Windows, use these settings:</p>\n\n<pre><code>col TAB# new_value TAB NOPRINT\nselect chr(9) TAB# from dual;\nset colsep \"&TAB\"\n\nselect * from table;\n</code></pre>\n"
},
{
"answer_id": 27654468,
"author": "Marvin W",
"author_id": 2341528,
"author_profile": "https://Stackoverflow.com/users/2341528",
"pm_score": 1,
"selected": false,
"text": "<p>I got a stupid solution. It worked very well.</p>\n\n<h1>Solution</h1>\n\n<pre><code>SELECT column1 || CHR(9) || column2 || CHR(9) || column3 ... ...\nFROM table\n</code></pre>\n\n<h1>principle behind</h1>\n\n<p>Actually, it's just a <strong>string concatenation</strong>.</p>\n\n<p>CHR(9) <strong>-></strong> '\\t'</p>\n\n<p>column1 || CHR(9) || column2 <strong>-></strong> <strong>concat(column1, '\\t', column2)</strong></p>\n"
},
{
"answer_id": 57429359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Tab characters are invisible, but, if you type the following:-</p>\n\n<p>set colsep Z</p>\n\n<p>but instead of the Z, press the TAB key one your keyboard, followed by enter, it works. SQLPlus understands that the next character after the space (the invisible tab) is the colsep.</p>\n\n<p>I've placed all my settings into a file named /cli.sql so I just do this:-</p>\n\n<p>@/cli.sql</p>\n\n<p>to load them all.</p>\n\n<pre><code>set serveroutput on\nSET NEWPAGE NONE\nset feedback off\nset echo off\nset feedback off\nset heading off\nset colsep \nset pagesize 0 \nSET UNDERLINE OFF\nset pagesize 50000\nset linesize 32767\nconnect use/password\n</code></pre>\n\n<p>(BEWARE - there is an invisible tab after an invisible space on the end of the line:)</p>\n\n<pre><code>set colsep \n</code></pre>\n\n<p>Enjoy!</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19387/"
]
| Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing? | Check out the Oracle documentation:
* [Formatting SQLPlus Reports](http://68.142.116.68/docs/cd/B19306_01/server.102/b14357/ch6.htm#i1081008)
* [Generating HTML Reports from SQLPlus](http://68.142.116.68/docs/cd/B19306_01/server.102/b14357/ch7.htm#sthref1452)
You can generate a tab in Oracle by using the tab's ASCII value 9 and the chr function:
```
select chr(9) from dual;
``` |
106,324 | <p>With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.</p>
<p>Any place where we still have to use delegates and lambda expressions won't work?</p>
| [
{
"answer_id": 106348,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": false,
"text": "<p>lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:</p>\n\n<pre><code> delegate(int i) { Console.WriteLine(i.ToString()) }\n</code></pre>\n\n<p>can be replaced with</p>\n\n<pre><code>f => Console.WriteLine(f.ToString())\n</code></pre>\n"
},
{
"answer_id": 106356,
"author": "Martin C.",
"author_id": 19246,
"author_profile": "https://Stackoverflow.com/users/19246",
"pm_score": 2,
"selected": false,
"text": "<p>Lambda expressions are just \"syntactic sugar\", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.</p>\n"
},
{
"answer_id": 106374,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 2,
"selected": false,
"text": "<p>Lamda's are just syntactic sugar for delegates, they are not just inline, you can do the following:</p>\n\n<pre><code>s.Find(a =>\n{\n if (a.StartsWith(\"H\"))\n return a.Equals(\"HI\");\n else\n return !a.Equals(\"FOO\");\n});\n</code></pre>\n\n<p>And delegates are still used when defining events, or when you have lots of arguments and want to actually strongly type the method being called.</p>\n"
},
{
"answer_id": 106480,
"author": "James Newton-King",
"author_id": 11829,
"author_profile": "https://Stackoverflow.com/users/11829",
"pm_score": 5,
"selected": false,
"text": "<p>Yes there are places where directly using anonymous delegates and lambda expressions won't work.</p>\n\n<p>If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.</p>\n\n<pre><code>public static void Invoke(Delegate d)\n{\n d.DynamicInvoke();\n}\n\nstatic void Main(string[] args)\n{\n // fails\n Invoke(() => Console.WriteLine(\"Test\"));\n\n // works\n Invoke(new Action(() => Console.WriteLine(\"Test\")));\n\n Console.ReadKey();\n}\n</code></pre>\n\n<p>The failing line of code will get the compiler error \"Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type\".</p>\n"
},
{
"answer_id": 144638,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 2,
"selected": false,
"text": "<p>Delegate have two meanings in C#.</p>\n\n<p>The keyword <code>delegate</code> can be used to define a function signature type. This is usually used when defininge the signature of higher-order functions, i.e. functions that take other functions as arguments. This use of delegate is still relevant.</p>\n\n<p>The <code>delegate</code> keyword can also be used to define an inline anonymous function. In the case where the function is just a single expression, the lambda syntax is a simpler alternative.</p>\n"
},
{
"answer_id": 149319,
"author": "Dandikas",
"author_id": 23436,
"author_profile": "https://Stackoverflow.com/users/23436",
"pm_score": 3,
"selected": false,
"text": "<p>Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:</p>\n\n<pre><code>List<string> names = GetNames();\nnames.ForEach(Console.WriteLine);\n</code></pre>\n\n<ol>\n<li>it makes code more readable thus simple to understand.</li>\n<li>It makes code shorter thus less work for us ;)</li>\n</ol>\n\n<p>On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:</p>\n\n<ol>\n<li>Hard to understand for new developers</li>\n<li>Less object oriented</li>\n<li>Much harder to read</li>\n</ol>\n\n<p>So “does it mean we don’t have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.</p>\n"
},
{
"answer_id": 24552532,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 3,
"selected": false,
"text": "<p>One <em>not so big</em> advantage for the older <code>delegate</code> syntax is that you need not specify the parameters if you dont use it in the method body. From <a href=\"http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx\" rel=\"noreferrer\">msdn</a></p>\n\n<blockquote>\n <p>There is one case in which an anonymous method provides functionality\n not found in lambda expressions. Anonymous methods enable you to omit\n the parameter list. This means that an anonymous method can be\n converted to delegates with a variety of signatures. This is not\n possible with lambda expressions.</p>\n</blockquote>\n\n<p>For example you can do:</p>\n\n<pre><code>Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS\n</code></pre>\n\n<p>While this fails:</p>\n\n<pre><code>Action<int> a = => { }; //omitted parameter, doesnt compile.\n</code></pre>\n\n<p>This technique mostly comes handy when writing event-handlers, like:</p>\n\n<pre><code>button.onClicked += delegate { Console.WriteLine(\"clicked\"); };\n</code></pre>\n\n<p>This is not a <em>strong</em> advantage. It's better to adopt the newer syntax always imho.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19306/"
]
| With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.
Any place where we still have to use delegates and lambda expressions won't work? | Yes there are places where directly using anonymous delegates and lambda expressions won't work.
If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.
```
public static void Invoke(Delegate d)
{
d.DynamicInvoke();
}
static void Main(string[] args)
{
// fails
Invoke(() => Console.WriteLine("Test"));
// works
Invoke(new Action(() => Console.WriteLine("Test")));
Console.ReadKey();
}
```
The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type". |
106,336 | <p>I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds? </p>
<p>FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.</p>
| [
{
"answer_id": 106350,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 2,
"selected": false,
"text": "<p>Just call <code>.getClass()</code> on each <code>Object</code> in a loop.</p>\n\n<p>Unfortunately, Java doesn't have <code>map()</code>. :)</p>\n"
},
{
"answer_id": 106351,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 8,
"selected": true,
"text": "<p>In C#:<br/>Fixed with recommendation from <a href=\"https://stackoverflow.com/users/14359/mike-brown\">Mike</a></p>\n\n<pre><code>ArrayList list = ...;\n// List<object> list = ...;\nforeach (object o in list) {\n if (o is int) {\n HandleInt((int)o);\n }\n else if (o is string) {\n HandleString((string)o);\n }\n ...\n}\n</code></pre>\n\n<p>In Java:</p>\n\n<pre><code>ArrayList<Object> list = ...;\nfor (Object o : list) {\n if (o instanceof Integer)) {\n handleInt((Integer o).intValue());\n }\n else if (o instanceof String)) {\n handleString((String)o);\n }\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 106360,
"author": "Fabian Steeg",
"author_id": 18154,
"author_profile": "https://Stackoverflow.com/users/18154",
"pm_score": 6,
"selected": false,
"text": "<pre><code>for (Object object : list) {\n System.out.println(object.getClass().getName());\n}\n</code></pre>\n"
},
{
"answer_id": 106381,
"author": "faran",
"author_id": 19350,
"author_profile": "https://Stackoverflow.com/users/19350",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the <code>getClass()</code> method, or you can use instanceof. For example</p>\n\n<pre><code>for (Object obj : list) {\n if (obj instanceof String) {\n ...\n }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (Object obj : list) {\n if (obj.getClass().equals(String.class)) {\n ...\n }\n}\n</code></pre>\n\n<p>Note that instanceof will match subclasses. For instance, of <code>C</code> is a subclass of <code>A</code>, then the following will be true:</p>\n\n<pre><code>C c = new C();\nassert c instanceof A;\n</code></pre>\n\n<p>However, the following will be false:</p>\n\n<pre><code>C c = new C();\nassert !c.getClass().equals(A.class)\n</code></pre>\n"
},
{
"answer_id": 106489,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 2,
"selected": false,
"text": "<p>Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.</p>\n"
},
{
"answer_id": 106673,
"author": "shoover",
"author_id": 18356,
"author_profile": "https://Stackoverflow.com/users/18356",
"pm_score": 0,
"selected": false,
"text": "<p>You say \"this is a piece of java code being written\", from which I infer that there is still a chance that you could design it a different way. </p>\n\n<p>Having an ArrayList is like having a collection of stuff. Rather than force the instanceof or getClass every time you take an object from the list, why not design the system so that you get the type of the object when you retrieve it from the DB, and store it into a collection of the appropriate type of object?</p>\n\n<p>Or, you could use one of the many data access libraries that exist to do this for you.</p>\n"
},
{
"answer_id": 109840,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 4,
"selected": false,
"text": "<p>You almost never want you use something like:</p>\n\n<pre><code>Object o = ...\nif (o.getClass().equals(Foo.class)) {\n ...\n}\n</code></pre>\n\n<p>because you aren't accounting for possible subclasses. You really want to use Class#isAssignableFrom:</p>\n\n<pre><code>Object o = ...\nif (Foo.class.isAssignableFrom(o)) {\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 359623,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 0,
"selected": false,
"text": "<p>If you expect the data to be numeric in some form, and all you are interested in doing is converting the result to a numeric value, I would suggest:</p>\n\n<pre><code>for (Object o:list) {\n Double.parseDouble(o.toString);\n}\n</code></pre>\n"
},
{
"answer_id": 7755802,
"author": "Reid Mac",
"author_id": 888059,
"author_profile": "https://Stackoverflow.com/users/888059",
"pm_score": 3,
"selected": false,
"text": "<p>In Java just use the instanceof operator. This will also take care of subclasses.</p>\n\n<pre><code>ArrayList<Object> listOfObjects = new ArrayList<Object>();\nfor(Object obj: listOfObjects){\n if(obj instanceof String){\n }else if(obj instanceof Integer){\n }etc...\n}\n</code></pre>\n"
},
{
"answer_id": 14897094,
"author": "potter",
"author_id": 2075930,
"author_profile": "https://Stackoverflow.com/users/2075930",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import java.util.ArrayList;\n\n/**\n * @author potter\n *\n */\npublic class storeAny {\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n\n ArrayList<Object> anyTy=new ArrayList<Object>();\n anyTy.add(new Integer(1));\n anyTy.add(new String(\"Jesus\"));\n anyTy.add(new Double(12.88));\n anyTy.add(new Double(12.89));\n anyTy.add(new Double(12.84));\n anyTy.add(new Double(12.82));\n\n for (Object o : anyTy) {\n if(o instanceof String){\n System.out.println(o.toString());\n } else if(o instanceof Integer) {\n System.out.println(o.toString()); \n } else if(o instanceof Double) {\n System.out.println(o.toString());\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 28350991,
"author": "Sufiyan Ghori",
"author_id": 1149423,
"author_profile": "https://Stackoverflow.com/users/1149423",
"pm_score": 2,
"selected": false,
"text": "<p>instead of using <code>object.getClass().getName()</code> you can use <code>object.getClass().getSimpleName()</code>, because it returns a simple class name without a package name included.</p>\n\n<p>for instance,</p>\n\n<pre><code>Object[] intArray = { 1 }; \n\nfor (Object object : intArray) { \n System.out.println(object.getClass().getName());\n System.out.println(object.getClass().getSimpleName());\n}\n</code></pre>\n\n<p>gives,</p>\n\n<pre><code>java.lang.Integer\nInteger\n</code></pre>\n"
},
{
"answer_id": 30150716,
"author": "Andrew",
"author_id": 2079831,
"author_profile": "https://Stackoverflow.com/users/2079831",
"pm_score": 2,
"selected": false,
"text": "<p>Since Java 8</p>\n\n<p><pre><code>\n mixedArrayList.forEach((o) -> {\n String type = o.getClass().getSimpleName();\n switch (type) {\n case \"String\":\n // treat as a String\n break;\n case \"Integer\":\n // treat as an int\n break;\n case \"Double\":\n // treat as a double\n break;\n ...\n default:\n // whatever\n }\n });\n</pre></code></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13491/"
]
| I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?
FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's. | In C#:
Fixed with recommendation from [Mike](https://stackoverflow.com/users/14359/mike-brown)
```
ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
if (o is int) {
HandleInt((int)o);
}
else if (o is string) {
HandleString((string)o);
}
...
}
```
In Java:
```
ArrayList<Object> list = ...;
for (Object o : list) {
if (o instanceof Integer)) {
handleInt((Integer o).intValue());
}
else if (o instanceof String)) {
handleString((String)o);
}
...
}
``` |
106,367 | <p>What is the best way to add <strong>non-ASCII</strong> file names to a <strong>zip file</strong> using <strong>Java</strong>, in such a way that the files can be properly read in both <strong>Windows</strong> and <strong>Linux?</strong></p>
<p>Here is one attempt, adapted from <a href="https://truezip.dev.java.net/tutorial-6.html#Example" rel="noreferrer">https://truezip.dev.java.net/tutorial-6.html#Example</a>, which works in Windows Vista but fails in Ubuntu Hardy. In Hardy the file name is shown as abc-ЖДФ.txt in file-roller.</p>
<pre><code>import java.io.IOException;
import java.io.PrintStream;
import de.schlichtherle.io.File;
import de.schlichtherle.io.FileOutputStream;
public class Main {
public static void main(final String[] args) throws IOException {
try {
PrintStream ps = new PrintStream(new FileOutputStream(
"outer.zip/abc-åäö.txt"));
try {
ps.println("The characters åäö works here though.");
} finally {
ps.close();
}
} finally {
File.umount();
}
}
}
</code></pre>
<p>Unlike java.util.zip, truezip allows specifying zip file encoding. Here's another sample, this time explicitly specifiying the encoding. Neither IBM437, UTF-8 nor ISO-8859-1 works in Linux. IBM437 works in Windows.</p>
<pre><code>import java.io.IOException;
import de.schlichtherle.io.FileOutputStream;
import de.schlichtherle.util.zip.ZipEntry;
import de.schlichtherle.util.zip.ZipOutputStream;
public class Main {
public static void main(final String[] args) throws IOException {
for (String encoding : new String[] { "IBM437", "UTF-8", "ISO-8859-1" }) {
ZipOutputStream zipOutput = new ZipOutputStream(
new FileOutputStream(encoding + "-example.zip"), encoding);
ZipEntry entry = new ZipEntry("abc-åäö.txt");
zipOutput.putNextEntry(entry);
zipOutput.closeEntry();
zipOutput.close();
}
}
}
</code></pre>
| [
{
"answer_id": 106384,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 0,
"selected": false,
"text": "<p>Did it actually fail or was just a font issue? (e.g. font having different glyphs for those charcodes) I've seen similar issues in Windows where rendering \"broke\" because the font didn't support the charset but the data was actually intact and correct.</p>\n"
},
{
"answer_id": 106447,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<p>Non-ASCII file names are not reliable across ZIP implementations and are best avoided. There is no provision for storing a charset setting in ZIP files; clients tend to guess with 'the current system codepage', which is unlikely to be what you want. Many combinations of client and codepage can result in inaccessible files.</p>\n\n<p>Sorry!</p>\n"
},
{
"answer_id": 106506,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "<p>From a quick look at the TrueZIP <a href=\"https://truezip.dev.java.net/manual-6.html\" rel=\"nofollow noreferrer\">manual</a> - they recommend the JAR format:</p>\n\n<blockquote>\n <p>It uses UTF-8 for file name encoding\n and comments - unlike ZIP, which only\n uses IBM437.</p>\n</blockquote>\n\n<p>This probably means that the API is using the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/zip/package-summary.html\" rel=\"nofollow noreferrer\">java.util.zip</a> package for its implementation; that documentation states that it is still using a <a href=\"ftp://ftp.uu.net/pub/archiving/zip/doc/appnote-970311-iz.zip\" rel=\"nofollow noreferrer\">ZIP format from 1996</a>. Unicode support wasn't added to the <a href=\"http://www.pkware.com/documents/casestudies/APPNOTE.TXT\" rel=\"nofollow noreferrer\">PKWARE .ZIP File Format Specification</a> until 2006.</p>\n"
},
{
"answer_id": 200804,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 3,
"selected": false,
"text": "<p>The encoding for the File-Entries in ZIP is originally specified as IBM Code Page 437. Many characters used in other languages are impossible to use that way.</p>\n\n<p>The <a href=\"http://www.pkware.com/documents/casestudies/APPNOTE.TXT\" rel=\"noreferrer\">PKWARE-specification</a> refers to the problem and adds a bit. But that is a later addition (from 2007, thanks to Cheeso for clearing that up, see comments). If that bit is set, the filename-entry have to be encoded in UTF-8. This extension is described in 'APPENDIX D - Language Encoding (EFS)', that is at the end of the linked document.</p>\n\n<p>For Java it is a known bug, to get into trouble with non-ASCII-characters. See <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499\" rel=\"noreferrer\">bug #4244499</a> and the high number of related bugs.</p>\n\n<p>My colleague used as workaround URL-Encoding for the filenames before storing them into the ZIP and decoding after reading them. If you control both, storing and reading, that may be a workaround.</p>\n\n<p>EDIT: At the bug someone suggests using the ZipOutputStream from Apache Ant as workaround. This implementation allows the specification of an encoding.</p>\n"
},
{
"answer_id": 410407,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 3,
"selected": false,
"text": "<p>In Zip files, according to the spec owned by PKWare, the encoding of file names and file comments is IBM437. In 2007 PKWare extended the spec to also allow UTF-8. This says nothing about the encoding of the files contained within the zip. Only the encoding of the filenames. </p>\n\n<p>I think all tools and libraries (Java and non Java) support IBM437 (which is a superset of ASCII), and fewer tools and libraries support UTF-8. Some tools and libs support other code pages. For example if you zip something using WinRar on a computer running in Shanghai, you will get the Big5 code page. This is not \"allowed\" by the zip spec but it happens anyway. </p>\n\n<p>The <a href=\"http://dotnetzip.codeplex.com\" rel=\"noreferrer\">DotNetZip</a> library for .NET does Unicode, but of course that doesn't help you if you are using Java! </p>\n\n<p>Using the Java built-in support for ZIP, you will always get IBM437. If you want an archive with something other than IBM437, then use a third party library, or create a JAR. </p>\n"
},
{
"answer_id": 3352339,
"author": "Anton Kraievyi",
"author_id": 148926,
"author_profile": "https://Stackoverflow.com/users/148926",
"pm_score": 3,
"selected": false,
"text": "<p>Miracles indeed happen, and Sun/Oracle did really fix the long-living bug/rfe:</p>\n\n<p>Now it's possible to <a href=\"http://www.docjar.org/html/api/java/util/zip/ZipOutputStream.java.html#121\" rel=\"nofollow noreferrer\">set up filename encodings upon creating</a> the zip file/stream (<strong>requires Java 7</strong>).</p>\n"
},
{
"answer_id": 4472331,
"author": "Fengtan",
"author_id": 546263,
"author_profile": "https://Stackoverflow.com/users/546263",
"pm_score": 3,
"selected": false,
"text": "<p>You can still use the Apache Commons implementation of the zip stream : <a href=\"http://commons.apache.org/compress/apidocs/org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream.html#setEncoding%28java.lang.String%29\" rel=\"noreferrer\">http://commons.apache.org/compress/apidocs/org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream.html#setEncoding%28java.lang.String%29</a></p>\n\n<p>Calling setEncoding(\"UTF-8\") on your stream should be enough.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19392/"
]
| What is the best way to add **non-ASCII** file names to a **zip file** using **Java**, in such a way that the files can be properly read in both **Windows** and **Linux?**
Here is one attempt, adapted from <https://truezip.dev.java.net/tutorial-6.html#Example>, which works in Windows Vista but fails in Ubuntu Hardy. In Hardy the file name is shown as abc-ЖДФ.txt in file-roller.
```
import java.io.IOException;
import java.io.PrintStream;
import de.schlichtherle.io.File;
import de.schlichtherle.io.FileOutputStream;
public class Main {
public static void main(final String[] args) throws IOException {
try {
PrintStream ps = new PrintStream(new FileOutputStream(
"outer.zip/abc-åäö.txt"));
try {
ps.println("The characters åäö works here though.");
} finally {
ps.close();
}
} finally {
File.umount();
}
}
}
```
Unlike java.util.zip, truezip allows specifying zip file encoding. Here's another sample, this time explicitly specifiying the encoding. Neither IBM437, UTF-8 nor ISO-8859-1 works in Linux. IBM437 works in Windows.
```
import java.io.IOException;
import de.schlichtherle.io.FileOutputStream;
import de.schlichtherle.util.zip.ZipEntry;
import de.schlichtherle.util.zip.ZipOutputStream;
public class Main {
public static void main(final String[] args) throws IOException {
for (String encoding : new String[] { "IBM437", "UTF-8", "ISO-8859-1" }) {
ZipOutputStream zipOutput = new ZipOutputStream(
new FileOutputStream(encoding + "-example.zip"), encoding);
ZipEntry entry = new ZipEntry("abc-åäö.txt");
zipOutput.putNextEntry(entry);
zipOutput.closeEntry();
zipOutput.close();
}
}
}
``` | The encoding for the File-Entries in ZIP is originally specified as IBM Code Page 437. Many characters used in other languages are impossible to use that way.
The [PKWARE-specification](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) refers to the problem and adds a bit. But that is a later addition (from 2007, thanks to Cheeso for clearing that up, see comments). If that bit is set, the filename-entry have to be encoded in UTF-8. This extension is described in 'APPENDIX D - Language Encoding (EFS)', that is at the end of the linked document.
For Java it is a known bug, to get into trouble with non-ASCII-characters. See [bug #4244499](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499) and the high number of related bugs.
My colleague used as workaround URL-Encoding for the filenames before storing them into the ZIP and decoding after reading them. If you control both, storing and reading, that may be a workaround.
EDIT: At the bug someone suggests using the ZipOutputStream from Apache Ant as workaround. This implementation allows the specification of an encoding. |
106,383 | <p>Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.</p>
<p>e.g.</p>
<pre><code>public DerivedClass : BaseClass {}
</code></pre>
<p>Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?</p>
| [
{
"answer_id": 106392,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 0,
"selected": false,
"text": "<p>If they're defined public in the original class, you cannot override them to be private in your derived class. However, you could make the public method throw an exception and implement your own private function.</p>\n\n<p>Edit: Jorge Ferreira is correct.</p>\n"
},
{
"answer_id": 106397,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 2,
"selected": false,
"text": "<p>The only way to do this that I know of is to use a Has-A relationship and only implement the functions you want to expose.</p>\n"
},
{
"answer_id": 106407,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>@Brian R. Bondy pointed me to an interesting article on Hiding through inheritance and the <strong>new</strong> keyword.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx</a></p>\n\n<p>So as workaround I would suggest:</p>\n\n<pre><code>class BaseClass\n{\n public void A()\n {\n Console.WriteLine(\"BaseClass.A\");\n }\n\n public void B()\n {\n Console.WriteLine(\"BaseClass.B\");\n }\n}\n\nclass DerivedClass : BaseClass\n{\n new public void A()\n {\n throw new NotSupportedException();\n }\n\n new public void B()\n {\n throw new NotSupportedException();\n }\n\n public void C()\n {\n base.A();\n base.B();\n }\n}\n</code></pre>\n\n<p>This way code like this will throw a <strong>NotSupportedException</strong>:</p>\n\n<pre><code> DerivedClass d = new DerivedClass();\n d.A();\n</code></pre>\n"
},
{
"answer_id": 106409,
"author": "Hamish Smith",
"author_id": 15572,
"author_profile": "https://Stackoverflow.com/users/15572",
"pm_score": 3,
"selected": false,
"text": "<p>That sounds like a bad idea. <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"noreferrer\">Liskov</a> would not be impressed. </p>\n\n<p>If you don't want consumers of DerivedClass to be able to access methods DeriveClass.A() and DerivedClass.B() I would suggest that DerivedClass should implement some public interface IWhateverMethodCIsAbout and the consumers of DerivedClass should actually be talking to IWhateverMethodCIsAbout and know nothing about the implementation of BaseClass or DerivedClass at all.</p>\n"
},
{
"answer_id": 106469,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "<p><strong>It's not possible, why?</strong></p>\n\n<p>In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.</p>\n\n<p>Instead of using the is-a relationship, you would have to use the has-a relationship. </p>\n\n<p>The language designers don't allow this on purpose so that you use inheritance more properly. </p>\n\n<p>For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations. </p>\n\n<p>So they don't allow it to protect you from bad inheritance hierarchies.</p>\n\n<p><strong>What should you do instead?</strong></p>\n\n<p>Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship.</p>\n\n<p><strong>Other languages:</strong></p>\n\n<p>In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#.</p>\n\n<p><strong>The restructured code:</strong></p>\n\n<pre><code>interface I\n{\n void C();\n}\n\nclass BaseClass\n{\n public void A() { MessageBox.Show(\"A\"); }\n public void B() { MessageBox.Show(\"B\"); }\n}\n\nclass Derived : I\n{\n public void C()\n {\n b.A();\n b.B();\n }\n\n private BaseClass b;\n}\n</code></pre>\n\n<p>I understand the names of the above classes are a little moot :)</p>\n\n<p><strong>Other suggestions:</strong></p>\n\n<p>Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense. </p>\n"
},
{
"answer_id": 106914,
"author": "Jared",
"author_id": 7388,
"author_profile": "https://Stackoverflow.com/users/7388",
"pm_score": 1,
"selected": false,
"text": "<p>Hiding is a pretty slippery slope. The main issues, IMO, are:</p>\n\n<ul>\n<li><p>It's dependent upon the design-time\ndeclaration type of the instance,\nmeaning if you do something like\nBaseClass obj = new SubClass(), then\ncall obj.A(), hiding is defeated. BaseClass.A() will be executed.</p></li>\n<li><p>Hiding can very easily obscure\nbehavior (or behavior changes) in\nthe base type. This is obviously\nless of a concern when you own both\nsides of the equation, or if calling 'base.xxx' is part of your sub-member.</p></li>\n<li>If you actually <em>do</em> own both sides of the base/sub-class equation, then you should be able to devise a more manageable solution than institutionalized hiding/shadowing.</li>\n</ul>\n"
},
{
"answer_id": 107152,
"author": "Jason Olson",
"author_id": 5418,
"author_profile": "https://Stackoverflow.com/users/5418",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that if you have a codebase that you are wanting to do this with, it is not the best designed code base. It's typically a sign of a class in one level of the heirarchy needing a certain public signature while another class derived from that class doesn't need it. </p>\n\n<p>An upcoming coding paradigm is called \"Composition over Inheritance.\" This plays directly off of the principles of object-oriented development (especially the Single Responsibility Principle and Open/Closed Principle). </p>\n\n<p>Unfortunately, the way a lot of us developers were taught object-orientation, we have formed a habit of immediately thinking about inheritance instead of composition. We tend to have larger classes that have many different responsibilities simply because they might be contained with the same \"Real World\" object. This can lead to class hierarchies that are 5+ levels deep.</p>\n\n<p>An unfortunate side-effect that developers don't normally think about when dealing with inheritance is that inheritance forms one of the strongest forms of dependencies that you can ever introduce into your code. Your derived class is now strongly dependant on the class it was inherited from. This can make your code more brittle in the long run and lead to confounding problems where changing a certain behavior in a base class breaks derived classes in obscure ways.</p>\n\n<p>One way to break your code up is through interfaces like mentioned in another answer. This is a smart thing to do anyways as you want a class's external dependencies to bind to abstractions, not concrete/derived types. This allows you to change the implementation without changing the interface, all without effecting a line of code in your dependent class. </p>\n\n<p>I would much rather than maintain a system with hundreds/thousands/even more classes that are all small and loosely-coupled, than deal with a system that makes heavy use of polymorphism/inheritance and has fewer classes that are more tightly coupled. </p>\n\n<p>Perhaps the <strong>best</strong> resource out there on object-oriented development is Robert C. Martin's book, <a href=\"https://rads.stackoverflow.com/amzn/click/com/0135974445\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Agile Software Development, Principles, Patterns, and Practices</a>. </p>\n"
},
{
"answer_id": 107215,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": false,
"text": "<p><strong>What you need is composition not inheritance.</strong></p>\n\n<pre><code>class Plane\n{\n public Fly() { .. }\n public string GetPilot() {...}\n}\n</code></pre>\n\n<p>Now if you need a special kind of Plane, such as one that has PairOfWings = 2 but otherwise does everything a plane can.. You inherit plane. By this you declare that your derivation meets the contract of the base class and can be substituted without blinking wherever a base class is expected. e.g. LogFlight(Plane) would continue to work with a BiPlane instance.</p>\n\n<p>However if you just need the Fly behavior for a new Bird you want to create and are not willing to support the complete base class contract, you compose instead. In this case, refactor the behavior of methods to reuse into a new type Flight. Now create and hold references to this class in both Plane and Bird.\nYou don't inherit because the Bird does not support the complete base class contract... ( e.g. it cannot provide GetPilot() ). </p>\n\n<p>For the same reason, <strong>you cannot reduce the visibility of base class methods when you override..</strong> you can override and make a base private method public in the derivation but not vice versa. e.g. In this example, if I derive a type of Plane \"BadPlane\" and then override and \"Hide\" GetPilot() - make it private; a client method LogFlight(Plane p) will work for most Planes but will blow up for \"BadPlane\" if the implementation of LogFlight happens to need/call GetPilot(). <strong>Since all derivations of a base class are expected to be 'substitutable' wherever a base class param is expected, this has to be disallowed.</strong></p>\n"
},
{
"answer_id": 3156791,
"author": "nono",
"author_id": 380968,
"author_profile": "https://Stackoverflow.com/users/380968",
"pm_score": 5,
"selected": false,
"text": "<p>When you, for instance, try to inherit from a <code>List<object></code>, and you want to hide the direct <code>Add(object _ob)</code> member:</p>\n\n<pre><code>// the only way to hide\n[Obsolete(\"This is not supported in this class.\", true)]\npublic new void Add(object _ob)\n{\n throw NotImplementedException(\"Don't use!!\");\n}\n</code></pre>\n\n<p>It's not really the most preferable solution, but it does the job. Intellisense still accepts, but at compile time you get an error:</p>\n\n<blockquote>\n <p>error CS0619: 'TestConsole.TestClass.Add(TestConsole.TestObject)' is obsolete: 'This is not supported in this class.'</p>\n</blockquote>\n"
},
{
"answer_id": 49006898,
"author": "James Wilkins",
"author_id": 1236397,
"author_profile": "https://Stackoverflow.com/users/1236397",
"pm_score": 0,
"selected": false,
"text": "<p>While the answer to the question is \"no\", there is one tip I wish to point out for others arriving here (given that the OP was sort of alluding to assembly access by 3rd parties). When others reference an assembly, Visual Studio should be honoring the following attribute so it will not show in intellisense (hidden, but can STILL be called, so beware):</p>\n\n<pre><code>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n</code></pre>\n\n<p>If you had no other choice, you should be able to use <code>new</code> on a method that hides a base type method, return <code>=> throw new NotSupportedException();</code>, and combine it with the attribute above.</p>\n\n<p>Another trick depends on NOT inheriting from a base class if possible, where the base has a corresponding interface (such as <code>IList<T></code> for <code>List<T></code>). Implementing interfaces \"explicitly\" will also hide those methods from intellisense on the class type. For example:</p>\n\n<pre><code>public class GoodForNothing: IDisposable\n{\n void IDisposable.Dispose() { ... }\n}\n</code></pre>\n\n<p>In the case of <code>var obj = new GoodForNothing()</code>, the <code>Dispose()</code> method will not be available on <code>obj</code>. However, it WILL be available to anyone who explicitly type-casts <code>obj</code> to <code>IDisposable</code>.</p>\n\n<p>In addition, you could also wrap a base type instead of inheriting from it, then hide some methods:</p>\n\n<pre><code>public class MyList<T> : IList<T>\n{\n List<T> _Items = new List<T>();\n public T this[int index] => _Items[index];\n public int Count => _Items.Count;\n public void Add(T item) => _Items.Add(item);\n [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n void ICollection<T>.Clear() => throw new InvalidOperationException(\"No you may not!\"); // (hidden)\n /*...etc...*/\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16866/"
]
| Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.
e.g.
```
public DerivedClass : BaseClass {}
```
Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass? | **It's not possible, why?**
In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.
Instead of using the is-a relationship, you would have to use the has-a relationship.
The language designers don't allow this on purpose so that you use inheritance more properly.
For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations.
So they don't allow it to protect you from bad inheritance hierarchies.
**What should you do instead?**
Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship.
**Other languages:**
In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#.
**The restructured code:**
```
interface I
{
void C();
}
class BaseClass
{
public void A() { MessageBox.Show("A"); }
public void B() { MessageBox.Show("B"); }
}
class Derived : I
{
public void C()
{
b.A();
b.B();
}
private BaseClass b;
}
```
I understand the names of the above classes are a little moot :)
**Other suggestions:**
Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense. |
106,387 | <p>I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary?</p>
<p>This will be for Ubuntu machines.</p>
| [
{
"answer_id": 106399,
"author": "shoover",
"author_id": 18356,
"author_profile": "https://Stackoverflow.com/users/18356",
"pm_score": 7,
"selected": true,
"text": "<p>Does</p>\n\n<pre><code>uname -a\n</code></pre>\n\n<p>give you anything you can use? I don't have a 64-bit machine to test on.</p>\n\n<hr>\n\n<p><strong>Note from Mike Stone:</strong> This works, though specifically</p>\n\n<pre><code>uname -m\n</code></pre>\n\n<p>Will give \"x86_64\" for 64 bit, and something else for other 32 bit types (in my 32 bit VM, it's \"i686\").</p>\n"
},
{
"answer_id": 106411,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 2,
"selected": false,
"text": "<p>You could do something like this:</p>\n\n<pre><code>if $(uname -a | grep 'x86_64'); then\n echo \"I'm 64-bit\"\nelse\n echo \"I'm 32-bit\"\nfi\n</code></pre>\n"
},
{
"answer_id": 106416,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 6,
"selected": false,
"text": "<pre><code>MACHINE_TYPE=`uname -m`\nif [ ${MACHINE_TYPE} == 'x86_64' ]; then\n # 64-bit stuff here\nelse\n # 32-bit stuff here\nfi\n</code></pre>\n"
},
{
"answer_id": 106417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, <strong>uname -a</strong> should do the trick. see: <a href=\"http://www.stata.com/support/faqs/win/64bit.html\" rel=\"nofollow noreferrer\">http://www.stata.com/support/faqs/win/64bit.html</a>. </p>\n"
},
{
"answer_id": 106440,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 3,
"selected": false,
"text": "<pre><code>slot8(msd):/opt # uname -a\nLinux slot8a 2.6.21_mvlcge500-electra #1 SMP PREEMPT Wed Jun 18 16:29:33 \\\nEDT 2008 ppc64 GNU/Linux\n</code></pre>\n\n<p><br>Remember, there are other CPU architectures than Intel/AMD...</p>\n"
},
{
"answer_id": 7308155,
"author": "Victor Zamanian",
"author_id": 243089,
"author_profile": "https://Stackoverflow.com/users/243089",
"pm_score": 6,
"selected": false,
"text": "<p><code>getconf LONG_BIT</code> seems to do the trick as well, which makes it even easier to check this since this returns simply the integer instead of some complicated expression.</p>\n\n<pre><code>if [ `getconf LONG_BIT` = \"64\" ]\nthen\n echo \"I'm 64-bit\"\nelse\n echo \"I'm 32-bit\"\nfi\n</code></pre>\n"
},
{
"answer_id": 7813672,
"author": "inukaze",
"author_id": 983309,
"author_profile": "https://Stackoverflow.com/users/983309",
"pm_score": 3,
"selected": false,
"text": "<p>You can use , the follow script (i extract this from officially script of \"ioquake3\") : for example </p>\n\n<pre><code>archs=`uname -m`\ncase \"$archs\" in\n i?86) archs=i386 ;;\n x86_64) archs=\"x86_64 i386\" ;;\n ppc64) archs=\"ppc64 ppc\" ;;\nesac\n\nfor arch in $archs; do\n test -x ./ioquake3.$arch || continue\n exec ./ioquake3.$arch \"$@\"\ndone\n</code></pre>\n\n<p>==================================================================================</p>\n\n<p>I'm making a script to detect the \"Architecture\", this is my simple code (I am using it with wine , for my Windows Games , under Linux , by each game , i use diferrent version of WineHQ, downloaded from \"PlayOnLinux\" site. </p>\n\n<pre><code># First Obtain \"kernel\" name\nKERNEL=$(uname -s)\n\nif [ $KERNEL = \"Darwin\" ]; then\n KERNEL=mac\nelif [ $Nucleo = \"Linux\" ]; then\n KERNEL=linux\nelif [ $Nucleo = \"FreeBSD\" ]; then\n KERNEL=linux\nelse\n echo \"Unsupported OS\"\nfi\n\n# Second get the right Arquitecture\nARCH=$(uname -m)\n\nif [ $ARCH = \"i386\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"i486\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"i586\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$Nucleo/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"i686\" ]; then\n PATH=\"$PWD/wine/$KERNEL/x86/bin:$PATH\"\n export WINESERVER=\"$PWD/wine/$KERNEL/x86/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"32 Bits\"\n elif [ $ARCH = \"x86_64\" ]; then\n export WINESERVER=\"$PWD/wine/$KERNEL/x86_64/bin/wineserver\"\n export WINELOADER=\"$PWD/wine/$KERNEL/x86_64/bin/wine\"\n export WINEPREFIX=\"$PWD/wine/data\"\n export WINEDEBUG=-all:$WINEDEBUG\n ARCH=\"64 Bits\"\n else\n echo \"Unsoportted Architecture\"\nfi\n</code></pre>\n\n<p>==================================================================================</p>\n\n<p><strong>Now i use this in my bash scripts , because works better in any distro .</strong></p>\n\n<pre><code># Get the Kernel Name\nKernel=$(uname -s)\ncase \"$Kernel\" in\n Linux) Kernel=\"linux\" ;;\n Darwin) Kernel=\"mac\" ;;\n FreeBSD) Kernel=\"freebsd\" ;;\n* ) echo \"Your Operating System -> ITS NOT SUPPORTED\" ;;\nesac\n\necho\necho \"Operating System Kernel : $Kernel\"\necho\n# Get the machine Architecture\nArchitecture=$(uname -m)\ncase \"$Architecture\" in\n x86) Architecture=\"x86\" ;;\n ia64) Architecture=\"ia64\" ;;\n i?86) Architecture=\"x86\" ;;\n amd64) Architecture=\"amd64\" ;;\n x86_64) Architecture=\"x86_64\" ;;\n sparc64) Architecture=\"sparc64\" ;;\n* ) echo \"Your Architecture '$Architecture' -> ITS NOT SUPPORTED.\" ;;\nesac\n\necho\necho \"Operating System Architecture : $Architecture\"\necho\n</code></pre>\n"
},
{
"answer_id": 8475731,
"author": "lolesque",
"author_id": 787216,
"author_profile": "https://Stackoverflow.com/users/787216",
"pm_score": 4,
"selected": false,
"text": "<p>Be careful, in a <code>chroot</code>ed 32-bit env, the uname is still answering like the 64-bit host system.</p>\n\n<p><code>getconf LONG_BIT</code> works fine.</p>\n\n<p><code>file /bin/cp</code> or any well-known executable or library should do the trick if you don't have getconf (but you can store programs you can't use, and maybe there are not at this place).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
| I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary?
This will be for Ubuntu machines. | Does
```
uname -a
```
give you anything you can use? I don't have a 64-bit machine to test on.
---
**Note from Mike Stone:** This works, though specifically
```
uname -m
```
Will give "x86\_64" for 64 bit, and something else for other 32 bit types (in my 32 bit VM, it's "i686"). |
106,400 | <p>I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?</p>
<p>Thanks!</p>
| [
{
"answer_id": 106424,
"author": "Mariano",
"author_id": 2542,
"author_profile": "https://Stackoverflow.com/users/2542",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand correctly, you could do:</p>\n\n<pre><code>select * from users order by max(rank) desc limit 0, 49 \nunion \nselect * from users where user = x\n</code></pre>\n\n<p>This way you get 49 top users plus your particular user.</p>\n"
},
{
"answer_id": 106638,
"author": "igelkott",
"author_id": 2052165,
"author_profile": "https://Stackoverflow.com/users/2052165",
"pm_score": 1,
"selected": false,
"text": "<p>Regardless if a single, fancy SQL query could be made, the most maintainable code would probably be two queries:</p>\n\n<pre><code>select user from users where id = \"fred\"; \nselect user from users where id != \"fred\" order by rank limit 49;\n</code></pre>\n\n<p>Of course \"fred\" (or whomever) would usually be replaced by a placeholder but the specifics depend on the environment. </p>\n"
},
{
"answer_id": 106658,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 0,
"selected": false,
"text": "<pre><code>declare @topUsers table(\n userId int primary key,\n username varchar(25)\n)\ninsert into @topUsers\nselect top 50 \n userId, \n userName\nfrom Users\norder by rank desc\n\ninsert into @topUsers\nselect\n userID,\n userName\nfrom Users\nwhere userID = 1234 --userID of special user\n\nselect * from @topUsers\n</code></pre>\n"
},
{
"answer_id": 106735,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest solution depends on your requirements, and what your database supports.</p>\n\n<p>If you don't mind the possibility of having duplicate results, then a simple union (as Mariano Conti demonstrated) is fine.</p>\n\n<p>Otherwise, you could do something like </p>\n\n<pre><code>select distinct <columnlist>\nfrom (select * from users order by max(rank) desc limit 0, 49 \n union \n select * from users where user = x)\n</code></pre>\n\n<p>if you database supports it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13636/"
]
| I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?
Thanks! | If I understand correctly, you could do:
```
select * from users order by max(rank) desc limit 0, 49
union
select * from users where user = x
```
This way you get 49 top users plus your particular user. |
106,401 | <p>The built-in <code>PHP</code> extension for <code>SOAP</code> doesn't validate everything in the incoming <code>SOAP</code> request against the <code>XML Schema</code> in the <code>WSDL</code>. It does check for the existence of basic entities, but when you have something complicated like <code>simpleType</code> restrictions the extension pretty much ignores their existence.</p>
<p>What is the best way to validate the <code>SOAP</code> request against <code>XML Schema</code> contained in the <code>WSDL</code>?</p>
| [
{
"answer_id": 108525,
"author": "user11087",
"author_id": 11087,
"author_profile": "https://Stackoverflow.com/users/11087",
"pm_score": 2,
"selected": false,
"text": "<p>Typically one doesn't validate against the WSDL. If the WSDL is designed properly there should be an underlying xml schema (XSD) to validate the body of the request against. Your XML parser should be able to do this.</p>\n\n<p>The rest is up to how you implement the web service and which SOAP engine you are using. I am not directly familiar with the PHP engine. For WSDL/interface level \"validation\" I usually do something like this:</p>\n\n<ol>\n<li>Does the body of the request match a known request type and is it valid (by XSD)?</li>\n<li>Does the message make sense in this context and can i map it to an operation/handler?</li>\n<li>If so, start processing it</li>\n<li>Otherwise: error</li>\n</ol>\n"
},
{
"answer_id": 110439,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": -1,
"selected": false,
"text": "<p>Some time ago I've create <a href=\"http://hype-free.blogspot.com/2007/01/implementing-web-services-with-open.html\" rel=\"nofollow noreferrer\">a proof of concept</a> web service with PHP using <a href=\"http://sourceforge.net/projects/nusoap\" rel=\"nofollow noreferrer\">NuSOAP</a>. I don't know if it validates the input, but I would assume it does.</p>\n"
},
{
"answer_id": 152289,
"author": "joelhardi",
"author_id": 11438,
"author_profile": "https://Stackoverflow.com/users/11438",
"pm_score": 2,
"selected": false,
"text": "<p>Besides the native PHP5 SOAP libs, I can also tell you that neither the PEAR nor Zend SOAP libs will do schema validation of messages at present. (I don't know of any PHP SOAP implementation that does, unfortunately.)</p>\n\n<p>What I would do is load the XML message into a <a href=\"http://www.php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\">DOMDocument</a> object and use DOMDocument's methods to validate against the schema.</p>\n"
},
{
"answer_id": 554676,
"author": "Glenn Moss",
"author_id": 5726,
"author_profile": "https://Stackoverflow.com/users/5726",
"pm_score": -1,
"selected": false,
"text": "<p>I was not able to find any simple way to perform the validation and in the end had validation code in the business logic.</p>\n"
},
{
"answer_id": 8532467,
"author": "CodeKid",
"author_id": 1101681,
"author_profile": "https://Stackoverflow.com/users/1101681",
"pm_score": 3,
"selected": true,
"text": "<p>Been digging around on this matter a view hours. \nNeither the native PHP SoapServer nore the NuSOAP Library does any Validation.\nPHP SoapServer simply makes a type cast.\nFor Example if you define</p>\n\n<pre><code><xsd:element name=\"SomeParameter\" type=\"xsd:boolean\" />\n</code></pre>\n\n<p>and submit </p>\n\n<pre><code><get:SomeParameter>dfgdfg</get:SomeParameter>\n</code></pre>\n\n<p>you'll get the php Type boolean (true)</p>\n\n<p>NuSOAP simply casts everthing to string although it recognizes simple types:</p>\n\n<p>from the nuSOAP debug log:</p>\n\n<pre><code>nusoap_xmlschema: processing typed element SomeParameter of type http://www.w3.org/2001/XMLSchema:boolean\n</code></pre>\n\n<p>So the best way is joelhardi solution to validate yourself or use some xml Parser like XERCES</p>\n"
},
{
"answer_id": 70744983,
"author": "celsowm",
"author_id": 284932,
"author_profile": "https://Stackoverflow.com/users/284932",
"pm_score": 2,
"selected": false,
"text": "<p>Using <strong>native SoapServer PHP</strong> is a little bit tricky but is possible too:</p>\n<pre><code>function validate(string $xmlEnvelope, string $wsdl) : ?array{\n \n libxml_use_internal_errors(true);\n \n //extracting schema from WSDL\n $xml = new DOMDocument();\n $wsdl_string = file_get_contents($wsdl);\n\n //extracting namespaces from WSDL\n $outer = new SimpleXMLElement($wsdl_string);\n $wsdl_namespaces = $outer->getDocNamespaces();\n \n //extracting the schema tag inside WSDL\n $xml->loadXML($wsdl_string);\n $xpath = new DOMXPath($xml);\n $xpath->registerNamespace('xsd', 'http://www.w3.org/2001/XMLSchema');\n $schemaNode = $xpath->evaluate('//xsd:schema');\n\n $schemaXML = "";\n foreach ($schemaNode as $node) {\n \n //add namespaces from WSDL to schema\n foreach($wsdl_namespaces as $prefix => $ns){\n $node->setAttribute("xmlns:$prefix", $ns);\n }\n $schemaXML .= simplexml_import_dom($node)\n ->asXML();\n }\n \n //capturing de XML envelope\n $xml = new DOMDocument();\n $xml->loadXML($xmlEnvelope);\n \n //extracting namespaces from soap Envelope\n $outer = new SimpleXMLElement($xmlEnvelope);\n $envelope_namespaces = $outer->getDocNamespaces();\n \n $xpath = new DOMXPath($xml);\n $xpath->registerNamespace('soapEnv', 'http://schemas.xmlsoap.org/soap/envelope/');\n $envelopeBody = $xpath->evaluate('//soapEnv:Body/*[1]');\n $envelopeBodyXML = "";\n foreach ($envelopeBody as $node) {\n \n //add namespaces from envelope to the body content\n foreach($envelope_namespaces as $prefix => $ns){\n $node->setAttribute("xmlns:$prefix", $ns);\n }\n $envelopeBodyXML .= simplexml_import_dom($node)\n ->asXML();\n }\n \n $doc = new DOMDocument();\n $doc->loadXML($envelopeBodyXML); // load xml\n $is_valid_xml = $doc->schemaValidateSource($schemaXML); // path to xsd file\n\n return libxml_get_errors(); \n \n}\n</code></pre>\n<p>and inside your SoapServer function implementation:</p>\n<pre><code>function myFunction($param) {\n\n $xmlEnvelope = file_get_contents("php://input");\n $errors = validate($xmlEnvelope, $wsdl);\n\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5726/"
]
| The built-in `PHP` extension for `SOAP` doesn't validate everything in the incoming `SOAP` request against the `XML Schema` in the `WSDL`. It does check for the existence of basic entities, but when you have something complicated like `simpleType` restrictions the extension pretty much ignores their existence.
What is the best way to validate the `SOAP` request against `XML Schema` contained in the `WSDL`? | Been digging around on this matter a view hours.
Neither the native PHP SoapServer nore the NuSOAP Library does any Validation.
PHP SoapServer simply makes a type cast.
For Example if you define
```
<xsd:element name="SomeParameter" type="xsd:boolean" />
```
and submit
```
<get:SomeParameter>dfgdfg</get:SomeParameter>
```
you'll get the php Type boolean (true)
NuSOAP simply casts everthing to string although it recognizes simple types:
from the nuSOAP debug log:
```
nusoap_xmlschema: processing typed element SomeParameter of type http://www.w3.org/2001/XMLSchema:boolean
```
So the best way is joelhardi solution to validate yourself or use some xml Parser like XERCES |
106,425 | <p>How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.</p>
| [
{
"answer_id": 106438,
"author": "Miguel Ventura",
"author_id": 19401,
"author_profile": "https://Stackoverflow.com/users/19401",
"pm_score": 8,
"selected": true,
"text": "<h3>2015 Update</h3>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy\" rel=\"noreferrer\">Content security policy</a> will prevent this from working in many sites now. For example, the code below won't work on Facebook.</p>\n\n<h3>2008 answer</h3>\n\n<p>Use a bookmarklet that creates a script tag which includes your external JS.</p>\n\n<p>As a sample:</p>\n\n<pre><code>javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();\n</code></pre>\n"
},
{
"answer_id": 15943140,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 2,
"selected": false,
"text": "<p>Firefox and perhaps others support multiline bookmarklets, no need for one liner. When you paste in the code it just replaces newlines with spaces.</p>\n\n<pre><code>javascript:\nvar q = document.createElement('script');\nq.src = 'http://svnpenn.github.io/bm/yt.js';\ndocument.body.appendChild(q);\nvoid 0;\n</code></pre>\n\n<p><a href=\"http://github.com/svnpenn/bm/blob/ad7e0c6/index.htm#L27-L32\" rel=\"nofollow\">Example</a></p>\n"
},
{
"answer_id": 47242413,
"author": "naviram",
"author_id": 1265306,
"author_profile": "https://Stackoverflow.com/users/1265306",
"pm_score": -1,
"selected": false,
"text": "<p>I always prefer to use a popular open source project <a href=\"https://github.com/muicss/loadjs/blob/master/dist/loadjs.min.js\" rel=\"nofollow noreferrer\">loadjs</a> </p>\n\n<p>it is cross browser tested and has more functionality/comfort features.</p>\n\n<p>So the code will look like this:</p>\n\n<pre><code>loadjs=function(){function e(e,n){var t,r,i,c=[],o=(e=e.push?e:[e]).length,f=o;for(t=function(e,t){t.length&&c.push(e),--f||n(c)};o--;)r=e[o],(i=s[r])?t(r,i):(u[r]=u[r]||[]).push(t)}function n(e,n){if(e){var t=u[e];if(s[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function t(e,n,r,i){var o,s,u=document,f=r.async,a=(r.numRetries||0)+1,h=r.before||c;i=i||0,/(^css!|\\.css$)/.test(e)?(o=!0,(s=u.createElement(\"link\")).rel=\"stylesheet\",s.href=e.replace(/^css!/,\"\")):((s=u.createElement(\"script\")).src=e,s.async=void 0===f||f),s.onload=s.onerror=s.onbeforeload=function(c){var u=c.type[0];if(o&&\"hideFocus\"in s)try{s.sheet.cssText.length||(u=\"e\")}catch(e){u=\"e\"}if(\"e\"==u&&(i+=1)<a)return t(e,n,r,i);n(e,u,c.defaultPrevented)},!1!==h(e,s)&&u.head.appendChild(s)}function r(e,n,r){var i,c,o=(e=e.push?e:[e]).length,s=o,u=[];for(i=function(e,t,r){if(\"e\"==t&&u.push(e),\"b\"==t){if(!r)return;u.push(e)}--o||n(u)},c=0;c<s;c++)t(e[c],i,r)}function i(e,t,i){var s,u;if(t&&t.trim&&(s=t),u=(s?i:t)||{},s){if(s in o)throw\"LoadJS\";o[s]=!0}r(e,function(e){e.length?(u.error||c)(e):(u.success||c)(),n(s,e)},u)}var c=function(){},o={},s={},u={};return i.ready=function(n,t){return e(n,function(e){e.length?(t.error||c)(e):(t.success||c)()}),i},i.done=function(e){n(e,[])},i.reset=function(){o={},s={},u={}},i.isDefined=function(e){return e in o},i}();\nloadjs('//path/external/js', {\n success: function () {\n console.log('something to run after the script was loaded');\n });\n</code></pre>\n"
},
{
"answer_id": 57921981,
"author": "Tom",
"author_id": 5480147,
"author_profile": "https://Stackoverflow.com/users/5480147",
"pm_score": 1,
"selected": false,
"text": "<p>If I can add method tested in FF & Chrome (for readibility split to multiple lines):</p>\n\n<pre><code>javascript:var r = new XMLHttpRequest();\n r.open(\"GET\", \"https://...my.js\", true);\n r.onloadend = function (oEvent) {\n new Function(r.responseText)();\n /* now you can use your code */\n };\n r.send();\n undefined\n</code></pre>\n"
},
{
"answer_id": 73669489,
"author": "xbtsw",
"author_id": 493978,
"author_profile": "https://Stackoverflow.com/users/493978",
"pm_score": 0,
"selected": false,
"text": "<p>It is no longer recommended to do this as CSP on most website will make it fail. But if you still want to use it: <a href=\"https://www.taosdev.com/bookmarklet-devkit/#EQChEoAIF4D5IN4B0B2l2QMYHsUGcAXSAWwEMBLNaSCGeZNDJgemcgHcAncggU0gCe2AK6cs2ACb8AFr069UTJqQA2cgiAAkIAOQAjSQJ3gA2gAYAugDpKKOQAkAKgFkAMuEUYAvp-Q58RHiY3AAOBACiajCQEtiYwsS8KARWwbykfJG8icm6QaEExr6Q+eRhWVa4KtikEtFklMWl5WpWeJyY0TrSBAQheABcrJgSKFYAVnhSKuQAbpxWdgTMKCHEzOMAjsJyAgACAMxWAGxWAIzMEuSEG9u7VsSUE3g6xbHxOSkGEgJWpCEhJISADC0nIKgkIGaETUHhQXnAEAA3MAgA\" rel=\"nofollow noreferrer\">2022 example</a></p>\n<pre><code>(() => {\n const main = () => {\n // write your code here\n alert($('body')[0].innerHTML)\n }\n const scriptEle = document.createElement('script')\n scriptEle.onload = main\n scriptEle.src = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js'\n document.body.appendChild(scriptEle)\n})();\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401774/"
]
| How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner. | ### 2015 Update
[Content security policy](https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy) will prevent this from working in many sites now. For example, the code below won't work on Facebook.
### 2008 answer
Use a bookmarklet that creates a script tag which includes your external JS.
As a sample:
```
javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();
``` |
106,437 | <p>I have a stateless bean something like:</p>
<pre><code>@Stateless
public class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote {
@PersistenceContext(unitName="myPC")
private EntityManager mgr;
@TransationAttribute(TransactionAttributeType.SUPPORTED)
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
this.process(obj);
}
}
@TransationAttribute(TransactionAttributeType.REQUIRES_NEW)
public void process(Object obj) {
// do some work with obj that must be in the scope of a transaction
this.mgr.merge(obj);
// ...
this.mgr.merge(obj);
// ...
this.mgr.flush();
}
}
</code></pre>
<p>The typically usage then is the client would call processObjects(...), which doesn't actually interact with the entity manager. It does what it needs to do and calls process(...) individually for each object to process. The duration of process(...) is relatively short, but processObjects(...) could take a very long time to run through everything. Therefore I don't want it to maintain an open transaction. I <em>do</em> need the individual process(...) operations to operate within their own transaction. This should be a new transaction for every call. Lastly I'd like to keep the option open for the client to call process(...) directly.</p>
<p>I've tried a number of different transaction types: never, not supported, supported (on processObjects) and required, requires new (on process) but I get TransactionRequiredException every time merge() is called.</p>
<p>I've been able to make it work by splitting up the methods into two different beans:</p>
<pre><code>@Stateless
@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {
@EJB
private MyStatelessBean2 myBean2;
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
this.myBean2.process(obj);
}
}
}
@Stateless
public class MyStatelessBean2 implements MyStatelessLocal2, MyStatelessRemote2 {
@PersistenceContext(unitName="myPC")
private EntityManager mgr;
@TransationAttribute(TransactionAttributeType.REQUIRES_NEW)
public void process(Object obj) {
// do some work with obj that must be in the scope of a transaction
this.mgr.merge(obj);
// ...
this.mgr.merge(obj);
// ...
this.mgr.flush();
}
}
</code></pre>
<p>but I'm still curious if it's possible to accomplish this in one class. It looks to me like the transaction manager only operates at the bean level, even when individual methods are given more specific annotations. So if I mark one method in a way to prevent the transaction from starting calling other methods within that same instance will also not create a transaction, no matter how they're marked?</p>
<p>I'm using JBoss Application Server 4.2.1.GA, but non-specific answers are welcome / preferred.</p>
| [
{
"answer_id": 106483,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "<p>I think has to do with the <em>@TransationAttribute(TransactionAttributeType.Never)</em> on method <strong>processObjects</strong>.</p>\n\n<p><strong>TransactionAttributeType.Never</strong></p>\n\n<p><a href=\"http://docs.sun.com/app/docs/doc/819-3669/6n5sg7cm3?a=view\" rel=\"nofollow noreferrer\">http://docs.sun.com/app/docs/doc/819-3669/6n5sg7cm3?a=view</a></p>\n\n<blockquote>\n <p>If the client is running within a\n transaction and invokes the enterprise\n bean’s method, the container throws a\n RemoteException. If the client is not\n associated with a transaction, the\n container does not start a new\n transaction before running the method.</p>\n</blockquote>\n\n<p>I assume that you are client the method <strong>processObjects</strong> from the client code. Because probably your client is not associated with a transaction the method call with <strong>TransactionAttributeType.Never</strong> is happy in the first place. Then you call the <strong>process</strong> method from <strong>processObjects</strong> that altough having the <strong>TransactionAttributeType.Required</strong> annotation was not a bean method call and the transaction policy is not enforced. When you call <strong>merge</strong> you get the exception because you are still not associated with a transaction.</p>\n\n<p>Try using <strong>TransactionAttributeType.Required</strong> for both bean methods to see if it does the trick.</p>\n"
},
{
"answer_id": 341177,
"author": "Brett Hannah",
"author_id": 42491,
"author_profile": "https://Stackoverflow.com/users/42491",
"pm_score": 1,
"selected": false,
"text": "<p>Matt, for what it's worth I've come to exactly the same conclusion as you. </p>\n\n<p>TransactionAttributeTypes are only taken into consideration when crossing Bean boundaries. When calling methods within the same bean TransactionAttributeTypes have no effect, no matter what Types are put on the methods.</p>\n\n<p>As far as I can see there is nothing in the EJB Persistence Spec that specifies what the behaviour should be under these circumstances.</p>\n\n<p>I've also experienced this in Jboss. I'll also give it a try in Glassfish and let you know the results.</p>\n"
},
{
"answer_id": 341224,
"author": "PEELY",
"author_id": 17641,
"author_profile": "https://Stackoverflow.com/users/17641",
"pm_score": 2,
"selected": false,
"text": "<p>I think the thing is each bean is wrapped in a proxy that controls the transactional behaviour. When you call from one bean to another, you're going via that bean's proxy and the transaction behaviour can be changed by the proxy. </p>\n\n<p>But when a bean calls a method on itself with a different transaction attribute, the call doesn't go via the proxy, so the behaviour doesn't change.</p>\n"
},
{
"answer_id": 511912,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>Another way to do it is actually having both methods on the same bean - and having an <code>@EJB</code> reference to itself! Something like that:</p>\n\n<pre><code>// supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1\n@Stateless\n@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)\npublic class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {\n @EJB\n private MyStatelessLocal1 myBean2;\n\n public void processObjects(List<Object> objs) {\n // this method just processes the data; no need for a transaction\n for(Object obj : objs) {\n this.myBean2.process(obj);\n }\n }\n\n\n @TransationAttribute(TransactionAttributeType.REQUIRES_NEW)\n public void process(Object obj) {\n // do some work with obj that must be in the scope of a transaction\n\n this.mgr.merge(obj);\n // ...\n this.mgr.merge(obj);\n // ...\n this.mgr.flush();\n }\n}\n</code></pre>\n\n<p>This way you actually 'force' the <code>process()</code> method to be accessed via the ejb stack of proxies, therefore taking the <code>@TransactionAttribute</code> in effect - and still keeping only one class. Phew!</p>\n"
},
{
"answer_id": 2660238,
"author": "bluecarbon",
"author_id": 149895,
"author_profile": "https://Stackoverflow.com/users/149895",
"pm_score": 2,
"selected": false,
"text": "<p>Matt, the question you ask is a pretty classic one, I think the self-reference solution by Herval/Pascal is neat. There is a more general solution not mentioned here.</p>\n\n<p>This is a case for EJB \"user\" transactions. Since you are in a session bean you can get the user transaction from the session context. Here's how your code will look with user transactions:</p>\n\n<pre><code>// supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1\n@Stateless\n@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)\npublic class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {\n\n @Resource\n private SessionContext ctx;\n\n @EJB\n private MyStatelessLocal1 myBean2;\n\n public void processObjects(List<Object> objs) {\n // this method just processes the data; no need for a transaction\n for(Object obj : objs) {\n this.myBean2.process(obj);\n }\n }\n\n\n public void process(Object obj) {\n\n UserTransaction tx = ctx.getUserTransaction();\n\n tx.begin();\n\n // do some work with obj that must be in the scope of a transaction\n\n this.mgr.merge(obj);\n // ...\n this.mgr.merge(obj);\n // ...\n this.mgr.flush();\n\n tx.commit();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2791064,
"author": "Kevin",
"author_id": 335747,
"author_profile": "https://Stackoverflow.com/users/335747",
"pm_score": 1,
"selected": false,
"text": "<p>In case someone comes across this one day:</p>\n\n<p>to avoid circular dependencies (allowing self reference for example) in JBoss use the annotation 'IgnoreDependency' for example:</p>\n\n<p>@IgnoreDependency\n@EJB MySelf myselfRef;</p>\n"
},
{
"answer_id": 7556712,
"author": "rainer198",
"author_id": 602856,
"author_profile": "https://Stackoverflow.com/users/602856",
"pm_score": 0,
"selected": false,
"text": "<p>I had these circular dependency issues which Kevin mentioned. However, the proposed annotation @IgnoreDependency is a jboss-specific annotation and there is no counterpart in e.g Glassfish.</p>\n\n<p>Since it does not work with default EJB reference, I felt a bit uncomfortable with this solution. </p>\n\n<p>Therefore, I gave bluecarbon's solution a chance, thus starting the inner transaction \"by hand\".</p>\n\n<p>Beside this, I see no solution but to implement the inner process() in another bean which is also ugly because we simply want to disturb our class model for such technical details.</p>\n"
},
{
"answer_id": 10109028,
"author": "tizzo",
"author_id": 1326940,
"author_profile": "https://Stackoverflow.com/users/1326940",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't tried it yet (I'm about to), but an alternative to injecting a self-reference via the <code>@EJB</code> annotation is the <code>SessionContext.getBusinessObject()</code> method. This would be another way to avoid the possibility of a circular reference blowing things up on you - although at least for stateless beans injection does seem to work.</p>\n\n<p>I'm working on a large system in which both techniques are employed (presumably by different developers), but I'm not sure which is the \"correct\" way to do it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1458/"
]
| I have a stateless bean something like:
```
@Stateless
public class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote {
@PersistenceContext(unitName="myPC")
private EntityManager mgr;
@TransationAttribute(TransactionAttributeType.SUPPORTED)
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
this.process(obj);
}
}
@TransationAttribute(TransactionAttributeType.REQUIRES_NEW)
public void process(Object obj) {
// do some work with obj that must be in the scope of a transaction
this.mgr.merge(obj);
// ...
this.mgr.merge(obj);
// ...
this.mgr.flush();
}
}
```
The typically usage then is the client would call processObjects(...), which doesn't actually interact with the entity manager. It does what it needs to do and calls process(...) individually for each object to process. The duration of process(...) is relatively short, but processObjects(...) could take a very long time to run through everything. Therefore I don't want it to maintain an open transaction. I *do* need the individual process(...) operations to operate within their own transaction. This should be a new transaction for every call. Lastly I'd like to keep the option open for the client to call process(...) directly.
I've tried a number of different transaction types: never, not supported, supported (on processObjects) and required, requires new (on process) but I get TransactionRequiredException every time merge() is called.
I've been able to make it work by splitting up the methods into two different beans:
```
@Stateless
@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {
@EJB
private MyStatelessBean2 myBean2;
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
this.myBean2.process(obj);
}
}
}
@Stateless
public class MyStatelessBean2 implements MyStatelessLocal2, MyStatelessRemote2 {
@PersistenceContext(unitName="myPC")
private EntityManager mgr;
@TransationAttribute(TransactionAttributeType.REQUIRES_NEW)
public void process(Object obj) {
// do some work with obj that must be in the scope of a transaction
this.mgr.merge(obj);
// ...
this.mgr.merge(obj);
// ...
this.mgr.flush();
}
}
```
but I'm still curious if it's possible to accomplish this in one class. It looks to me like the transaction manager only operates at the bean level, even when individual methods are given more specific annotations. So if I mark one method in a way to prevent the transaction from starting calling other methods within that same instance will also not create a transaction, no matter how they're marked?
I'm using JBoss Application Server 4.2.1.GA, but non-specific answers are welcome / preferred. | Another way to do it is actually having both methods on the same bean - and having an `@EJB` reference to itself! Something like that:
```
// supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1
@Stateless
@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 {
@EJB
private MyStatelessLocal1 myBean2;
public void processObjects(List<Object> objs) {
// this method just processes the data; no need for a transaction
for(Object obj : objs) {
this.myBean2.process(obj);
}
}
@TransationAttribute(TransactionAttributeType.REQUIRES_NEW)
public void process(Object obj) {
// do some work with obj that must be in the scope of a transaction
this.mgr.merge(obj);
// ...
this.mgr.merge(obj);
// ...
this.mgr.flush();
}
}
```
This way you actually 'force' the `process()` method to be accessed via the ejb stack of proxies, therefore taking the `@TransactionAttribute` in effect - and still keeping only one class. Phew! |
106,453 | <p>I've been working on an embedded C/C++ project recently using the shell in Tornado 2 as a way of debugging what's going on in our kit. The only problem with this approach is that it's a complicated system and as a result, has a fair bit of output. Tornado 'helpfully' scrolls the window every time some new information arrives which means that if you spot an error, it disappears out of site too quickly to see. Each time you scroll up to look, the system adds more information, so the only way to view it is to disconnect the hardware.</p>
<p>I'd love to know if anyone has a way of redirecting the output from Tornado?</p>
<p>I was hoping there might be a way to log it all from a small python app so that I can apply filters to the incoming information. I've tried connecting into the Tornado process, but the window with the information isn't a standard CEditCtrl so extracting the text that way was a dead end.</p>
<p>Any ideas anyone?</p>
<p><strong>[Edit]</strong> I should have mentioned that we're only running Tornado 2.1.0 and upgrading to a more recent version is beyond my control.</p>
<p><strong>[Edit2]</strong> The window in question in Tornado is an 'AfxFrameOrView42' according to WinID.</p>
| [
{
"answer_id": 106589,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 1,
"selected": false,
"text": "<p>I am making the assumption that you are using the host shell to perform this.</p>\n\n<p>If you are running a test by launching it from the shell like \"runTest()\", you can use the redirection operator (>) to send the output of that function to a text file on your host machine.</p>\n\n<pre>\n > runTest() > mytestResults.txt\n</pre>\n\n<p>This will save any output that runTest generates to the file mytestResults.txt</p>\n\n<p>If you would like to capture everything on the screen all the time, I will have to dig more into this.</p>\n"
},
{
"answer_id": 106626,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 2,
"selected": false,
"text": "<p>The host shell has a recording capability built in.\nThere are 3 environment variables available (in 6.x - not available in 5.x): </p>\n\n<p>RECORD (on/off) : Controls recording of the shell<br>\nRECORD_TYPE (input/output/all): Determines what you will be recording<br>\nRECORD_FILE : Filename to save things to.</p>\n\n<p>you use the ?shConfig command to configure the shell environment variable.\n?shConfig by itself displays the variables.\nHere is how I set mine up:</p>\n\n<pre><code>\n-> ?shConfig\n...\nRECORD = off\nRECORD_FILE = C:/test.txt\nRECORD_TYPE = output\n...\n\n-> ?shConfig RECORD_TYPE all\n-> ?shConfig RECORD_FILE myData.txt\n-> ?shConfig RECORD on\nStarted recording commands in 'myData.txt'.\n</code></pre>\n"
},
{
"answer_id": 107114,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 0,
"selected": false,
"text": "<p>rlogin vxWorks-target | tee redirected-output.txt</p>\n"
},
{
"answer_id": 116954,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 4,
"selected": true,
"text": "<p>here is another potential way:</p>\n\n<pre>\n-> saveFd = open(\"myfile.txt\",0x102, 0777 )\n-> oldFd = ioGlobalStdGet(1)\n-> ioGlobalStdSet(1, saveFd)\n-> runmytest()\n...\n-> ioGlobalStdSet(1, oldFd)\n</pre>\n\n<p>this will redirect <strong>all</strong> stdout activity to the file you opened.\nYou might have to play around with the file name of the open to make it write on the host (e.g. use \"host:/myfile.txt\" or something like this)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
]
| I've been working on an embedded C/C++ project recently using the shell in Tornado 2 as a way of debugging what's going on in our kit. The only problem with this approach is that it's a complicated system and as a result, has a fair bit of output. Tornado 'helpfully' scrolls the window every time some new information arrives which means that if you spot an error, it disappears out of site too quickly to see. Each time you scroll up to look, the system adds more information, so the only way to view it is to disconnect the hardware.
I'd love to know if anyone has a way of redirecting the output from Tornado?
I was hoping there might be a way to log it all from a small python app so that I can apply filters to the incoming information. I've tried connecting into the Tornado process, but the window with the information isn't a standard CEditCtrl so extracting the text that way was a dead end.
Any ideas anyone?
**[Edit]** I should have mentioned that we're only running Tornado 2.1.0 and upgrading to a more recent version is beyond my control.
**[Edit2]** The window in question in Tornado is an 'AfxFrameOrView42' according to WinID. | here is another potential way:
```
-> saveFd = open("myfile.txt",0x102, 0777 )
-> oldFd = ioGlobalStdGet(1)
-> ioGlobalStdSet(1, saveFd)
-> runmytest()
...
-> ioGlobalStdSet(1, oldFd)
```
this will redirect **all** stdout activity to the file you opened.
You might have to play around with the file name of the open to make it write on the host (e.g. use "host:/myfile.txt" or something like this) |
106,476 | <p>I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components. </p>
<p>I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process?</p>
| [
{
"answer_id": 106601,
"author": "Jim Olsen",
"author_id": 15603,
"author_profile": "https://Stackoverflow.com/users/15603",
"pm_score": 2,
"selected": true,
"text": "<p>Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick? For example, if I launch an MSI from a command prompt with process id 4000, I can execute the following command line to find information about msiexec process:</p>\n\n<pre><code>c:\\>wmic PROCESS WHERE ParentProcessId=4000 GET CommandLine, ProcessId \nCommandLine ProcessId\n\"C:\\Windows\\System32\\msiexec.exe\" /i \"C:\\blahblahblah.msi\" 2752\n</code></pre>\n\n<p>That may be one way to find the information you need. Here is a demo of looking up that information in vbs:</p>\n\n<pre><code>Set objWMIService = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2\")\nSet colProcesses = objWMIService.ExecQuery(\"select * from Win32_Process where ParentProcessId = 4000\")\nFor Each objProcess in colProcesses\n Wscript.Echo \"Process ID: \" & objProcess.ProcessId\nNext\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 106608,
"author": "IgorM",
"author_id": 17823,
"author_profile": "https://Stackoverflow.com/users/17823",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using a .NET language (you can do it in Win32, but waaaay easier in .NET) you can enumerate all the Processes in the system (after your initial call to Setup.exe completes) and find all the processes which parent's PID equal to the PID of the Setup.exe - and then monitor all those processes. When they will complete - setup is complete. Make sure that they don't spawn any more child processes as well.</p>\n"
},
{
"answer_id": 107110,
"author": "halr9000",
"author_id": 6637,
"author_profile": "https://Stackoverflow.com/users/6637",
"pm_score": 0,
"selected": false,
"text": "<p>This should do it.</p>\n\n<pre><code>$p1 = [diagnostics.process]::start($pathToExecutable) # this way we know the PID of the initial exe\n$p2 = get-wmiobject win32_process -filter \"ParentProcessId = $($p1.Id)\" # using Jim Olsen's tip\n(get-process -id $p2.ProcessId).WaitForExit() # voila--no messy sleeping\n</code></pre>\n\n<p>Unfortunately, the .NET object doesn't have a ParentProcessId property, and the WMI object doesn't have the WaitForExit() method, so we have to go back and forth.</p>\n\n<p>Props to Jeffrey Snover (always) for <a href=\"http://blogs.msdn.com/powershell/archive/2007/01/16/managing-processes-in-powershell.aspx\" rel=\"nofollow noreferrer\">this article</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/106476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components.
I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process? | Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick? For example, if I launch an MSI from a command prompt with process id 4000, I can execute the following command line to find information about msiexec process:
```
c:\>wmic PROCESS WHERE ParentProcessId=4000 GET CommandLine, ProcessId
CommandLine ProcessId
"C:\Windows\System32\msiexec.exe" /i "C:\blahblahblah.msi" 2752
```
That may be one way to find the information you need. Here is a demo of looking up that information in vbs:
```
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("select * from Win32_Process where ParentProcessId = 4000")
For Each objProcess in colProcesses
Wscript.Echo "Process ID: " & objProcess.ProcessId
Next
```
I hope this helps. |
106,481 | <p>I have this line in a javascript block in a page:</p>
<pre><code>res = foo('<%= @ruby_var %>');
</code></pre>
<p>What is the best way to handle the case where <code>@ruby_var</code> has a single-quote in it? Else it will break the JavaScript code.</p>
| [
{
"answer_id": 106518,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 2,
"selected": false,
"text": "<pre><code>@ruby_var.gsub(/[']/, '\\\\\\\\\\'')\n</code></pre>\n\n<p>That will escape the single quote with an apostrophe, keeping your Javascript safe!</p>\n\n<p>Also, if you're in Rails, there are a bunch of <a href=\"http://rails.rubyonrails.com/classes/ActionView/Helpers/JavaScriptHelper.html#M000440\" rel=\"nofollow noreferrer\">Javascript-specific tools</a>.</p>\n"
},
{
"answer_id": 106557,
"author": "TFKyle",
"author_id": 19208,
"author_profile": "https://Stackoverflow.com/users/19208",
"pm_score": 5,
"selected": true,
"text": "<p>I think I'd use a ruby <a href=\"http://json.org\" rel=\"noreferrer\">JSON</a> library on @ruby_var to get proper js syntax for the string and get rid of the '', fex.:</p>\n\n<pre><code>res = foo(<%= @ruby_var.to_json %>)\n</code></pre>\n\n<p>(after require \"json\"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language)</p>\n\n<p>(on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon)</p>\n"
},
{
"answer_id": 106808,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 2,
"selected": false,
"text": "<p>Could you just put the string in a double-quote?</p>\n\n<pre><code>res = foo(\"<%= @ruby_var %>\"); \n</code></pre>\n"
},
{
"answer_id": 108422,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 0,
"selected": false,
"text": "<p>I don't work with embedded Ruby too much. But how about using <code>p</code> (which invokes <code>inspect</code>) instead of <code><%=</code> which might be doing something like <code>print</code> or <code>puts</code>. <code>p</code> always prints the string as if it were code wrapped in double quotes:</p>\n\n<pre><code>>> p \"String ' \\\" String\"\n\"String ' \\\" String\"\n# => nil \n>> p 'alpha \" \\' alpha'\n\"alpha \\\" ' alpha\"\n# => nil \n</code></pre>\n"
},
{
"answer_id": 192389,
"author": "Caged",
"author_id": 26876,
"author_profile": "https://Stackoverflow.com/users/26876",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use inspect assuming you know it'll be a single quote:</p>\n\n<pre><code>res = foo(<%= @ruby_var.inspect %>);\n</code></pre>\n"
},
{
"answer_id": 9283249,
"author": "Mike Jarema",
"author_id": 1001980,
"author_profile": "https://Stackoverflow.com/users/1001980",
"pm_score": 3,
"selected": false,
"text": "<p>Rails has method specifically dedicated to this task found in <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html\">ActionView::Helpers::JavaScriptHelper</a> called <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript\">escape_javascript</a>.</p>\n\n<p>In your example, you would use the following:</p>\n\n<pre><code>res = foo('<%= escape_javascript @ruby_var %>');\n</code></pre>\n\n<p>Or better yet, use the <strong>j</strong> shortcut:</p>\n\n<pre><code>res = foo('<%= j @ruby_var %>');\n</code></pre>\n"
},
{
"answer_id": 41139801,
"author": "Rakshit Singh",
"author_id": 7165943,
"author_profile": "https://Stackoverflow.com/users/7165943",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to use the following first property, to get rid of the \" from your string and then you can go ahead and use your <code>json</code> function.</p>\n\n<pre><code>res = foo('<%= @ruby_var %>.first'); \n</code></pre>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19409/"
]
| I have this line in a javascript block in a page:
```
res = foo('<%= @ruby_var %>');
```
What is the best way to handle the case where `@ruby_var` has a single-quote in it? Else it will break the JavaScript code. | I think I'd use a ruby [JSON](http://json.org) library on @ruby\_var to get proper js syntax for the string and get rid of the '', fex.:
```
res = foo(<%= @ruby_var.to_json %>)
```
(after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language)
(on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon) |
106,508 | <p>What is a smart pointer and when should I use one?</p>
| [
{
"answer_id": 106515,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Smart_pointer\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Smart_pointer</a></p>\n\n<blockquote>\n <p>In computer science, a smart pointer\n is an abstract data type that\n simulates a pointer while providing\n additional features, such as automatic\n garbage collection or bounds checking.\n These additional features are intended\n to reduce bugs caused by the misuse of\n pointers while retaining efficiency.\n Smart pointers typically keep track of\n the objects that point to them for the\n purpose of memory management. The\n misuse of pointers is a major source\n of bugs: the constant allocation,\n deallocation and referencing that must\n be performed by a program written\n using pointers makes it very likely\n that some memory leaks will occur.\n Smart pointers try to prevent memory\n leaks by making the resource\n deallocation automatic: when the\n pointer to an object (or the last in a\n series of pointers) is destroyed, for\n example because it goes out of scope,\n the pointed object is destroyed too.</p>\n</blockquote>\n"
},
{
"answer_id": 106519,
"author": "markets",
"author_id": 4662,
"author_profile": "https://Stackoverflow.com/users/4662",
"pm_score": 5,
"selected": false,
"text": "<p>A smart pointer is like a regular (typed) pointer, like \"char*\", except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using \"->\", but not if you need an actual pointer to the data. For that, you can use \"&*ptr\".</p>\n\n<p>It is useful for:</p>\n\n<ul>\n<li><p>Objects that must be allocated with new, but that you'd like to have the same lifetime as something on that stack. If the object is assigned to a smart pointer, then they will be deleted when the program exits that function/block.</p></li>\n<li><p>Data members of classes, so that when the object is deleted all the owned data is deleted as well, without any special code in the destructor (you will need to be sure the destructor is virtual, which is almost always a good thing to do).</p></li>\n</ul>\n\n<p>You may <em>not</em> want to use a smart pointer when:</p>\n\n<ul>\n<li>... the pointer shouldn't actually own the data... i.e., when you are just using the data, but you want it to survive the function where you are referencing it.</li>\n<li>... the smart pointer isn't itself going to be destroyed at some point. You don't want it to sit in memory that never gets destroyed (such as in an object that is dynamically allocated but won't be explicitly deleted).</li>\n<li>... two smart pointers might point to the same data. (There are, however, even smarter pointers that will handle that... that is called <a href=\"http://en.wikipedia.org/wiki/Reference_counting\" rel=\"noreferrer\">reference counting</a>.)</li>\n</ul>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)\" rel=\"noreferrer\">garbage collection</a>.</li>\n<li><a href=\"https://stackoverflow.com/questions/94227/smart-pointers-or-who-owns-you-baby\">This stack overflow question</a> regarding data ownership</li>\n</ul>\n"
},
{
"answer_id": 106523,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p>Most kinds of smart pointers handle disposing of the pointer-to object for you. It's very handy because you don't have to think about disposing of objects manually anymore.</p>\n\n<p>The most commonly-used smart pointers are <code>std::tr1::shared_ptr</code> (or <code>boost::shared_ptr</code>), and, less commonly, <code>std::auto_ptr</code>. I recommend regular use of <code>shared_ptr</code>.</p>\n\n<p><code>shared_ptr</code> is very versatile and deals with a large variety of disposal scenarios, including cases where objects need to be \"passed across DLL boundaries\" (the common nightmare case if different <code>libc</code>s are used between your code and the DLLs).</p>\n"
},
{
"answer_id": 106568,
"author": "sergtk",
"author_id": 13441,
"author_profile": "https://Stackoverflow.com/users/13441",
"pm_score": 7,
"selected": false,
"text": "<p><strong>UPDATE:</strong></p>\n<p>This answer is outdated concerning C++ types which were used in the past.<br />\n<code>std::auto_ptr</code> is deprecated and removed in new standards.<br />\nInstead of <code>boost::shared_ptr</code> the <a href=\"https://cplusplus.com/reference/memory/shared_ptr/\" rel=\"nofollow noreferrer\"><code>std::shared_ptr</code></a> should be used which is part of the standard.</p>\n<p>The links to the concepts behind the rationale of smart pointers still mostly relevant.</p>\n<p>Modern C++ has the following smart pointer types and doesn't require <a href=\"https://www.boost.org/doc/libs/1_80_0/libs/smart_ptr/doc/html/smart_ptr.html\" rel=\"nofollow noreferrer\">boost smart pointers</a>:</p>\n<ul>\n<li><a href=\"https://cplusplus.com/reference/memory/shared_ptr/\" rel=\"nofollow noreferrer\"><code>std::shared_ptr</code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/memory/weak_ptr\" rel=\"nofollow noreferrer\"><code>std::weak_ptr</code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a></li>\n</ul>\n<p>There is also 2-nd edition of the book mentioned in the answer: <a href=\"https://rads.stackoverflow.com/amzn/click/com/B075MJNCCH\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">C++ Templates: The Complete Guide 2nd Edition by David Vandevoorde Nicolai, M. Josuttis, Douglas Gregor</a></p>\n<hr />\n<p><strong>OLD ANSWER:</strong></p>\n<p>A <a href=\"http://en.wikipedia.org/wiki/Smart_pointer\" rel=\"nofollow noreferrer\">smart pointer</a> is a pointer-like type with some additional functionality, e.g. automatic memory deallocation, reference counting etc.</p>\n<p>A small intro is available on the page <a href=\"http://ootips.org/yonat/4dev/smart-pointers.html\" rel=\"nofollow noreferrer\">Smart Pointers - What, Why, Which?</a>.</p>\n<p>One of the simple smart-pointer types is <a href=\"http://en.cppreference.com/w/cpp/memory/auto_ptr\" rel=\"nofollow noreferrer\"><code>std::auto_ptr</code></a> (chapter 20.4.5 of C++ standard), which allows one to deallocate memory automatically when it out of scope and which is more robust than simple pointer usage when exceptions are thrown, although less flexible.</p>\n<p>Another convenient type is <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\"><code>boost::shared_ptr</code></a> which implements reference counting and automatically deallocates memory when no references to the object remains. This helps avoiding memory leaks and is easy to use to implement <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow noreferrer\">RAII</a>.</p>\n<p>The subject is covered in depth in book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201734842\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">"C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis</a>, chapter Chapter 20. Smart Pointers.\nSome topics covered:</p>\n<ul>\n<li>Protecting Against Exceptions</li>\n<li>Holders, (note, <a href=\"http://en.cppreference.com/w/cpp/memory/auto_ptr\" rel=\"nofollow noreferrer\">std::auto_ptr</a> is implementation of such type of smart pointer)</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">Resource Acquisition Is Initialization</a> (This is frequently used for exception-safe resource management in C++)</li>\n<li>Holder Limitations</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Reference_counting\" rel=\"nofollow noreferrer\">Reference Counting</a></li>\n<li>Concurrent Counter Access</li>\n<li>Destruction and Deallocation</li>\n</ul>\n"
},
{
"answer_id": 106614,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 12,
"selected": true,
"text": "<p><strong>UPDATE</strong></p>\n\n<p>This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of <a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\"><code>std::unique_ptr</code></a>, <a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"noreferrer\"><code>std::shared_ptr</code></a> and <a href=\"http://en.cppreference.com/w/cpp/memory/weak_ptr\" rel=\"noreferrer\"><code>std::weak_ptr</code></a>. </p>\n\n<p>There was also <a href=\"http://en.cppreference.com/w/cpp/memory/auto_ptr\" rel=\"noreferrer\"><code>std::auto_ptr</code></a>. It was very much like a scoped pointer, except that it also had the \"special\" dangerous ability to be copied — which also unexpectedly transfers ownership.<br>\n<strong>It was deprecated in C++11 and removed in C++17</strong>, so you shouldn't use it.</p>\n\n<pre><code>std::auto_ptr<MyObject> p1 (new MyObject());\nstd::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership. \n // p1 gets set to empty!\np2->DoSomething(); // Works.\np1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.\n</code></pre>\n\n<hr>\n\n<p><strong>OLD ANSWER</strong></p>\n\n<p>A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.</p>\n\n<p>Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you <em>really</em> do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.</p>\n\n<p>With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful.</p>\n\n<pre><code>// Need to create the object to achieve some goal\nMyObject* ptr = new MyObject(); \nptr->DoSomething(); // Use the object in some way\ndelete ptr; // Destroy the object. Done with it.\n// Wait, what if DoSomething() raises an exception...?\n</code></pre>\n\n<p>A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.</p>\n\n<pre><code>SomeSmartPtr<MyObject> ptr(new MyObject());\nptr->DoSomething(); // Use the object in some way.\n\n// Destruction of the object happens, depending \n// on the policy the smart pointer class uses.\n\n// Destruction would happen even if DoSomething() \n// raises an exception\n</code></pre>\n\n<p>The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by <a href=\"http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_ptr.htm\" rel=\"noreferrer\"><code>boost::scoped_ptr</code></a> or <a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\"><code>std::unique_ptr</code></a>. </p>\n\n<pre><code>void f()\n{\n {\n std::unique_ptr<MyObject> ptr(new MyObject());\n ptr->DoSomethingUseful();\n } // ptr goes out of scope -- \n // the MyObject is automatically destroyed.\n\n // ptr->Oops(); // Compile error: \"ptr\" not defined\n // since it is no longer in scope.\n}\n</code></pre>\n\n<p>Note that <code>std::unique_ptr</code> instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.</p>\n\n<p><code>std::unique_ptr</code>s are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.</p>\n\n<p>A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last \"reference\" to the object is destroyed, the object is deleted. This policy is implemented by <a href=\"http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm\" rel=\"noreferrer\"><code>boost::shared_ptr</code></a> and <a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"noreferrer\"><code>std::shared_ptr</code></a>.</p>\n\n<pre><code>void f()\n{\n typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias\n MyObjectPtr p1; // Empty\n\n {\n MyObjectPtr p2(new MyObject());\n // There is now one \"reference\" to the created object\n p1 = p2; // Copy the pointer.\n // There are now two references to the object.\n } // p2 is destroyed, leaving one reference to the object.\n} // p1 is destroyed, leaving a reference count of zero. \n // The object is deleted.\n</code></pre>\n\n<p>Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.</p>\n\n<p>There is one drawback to reference counted pointers — the possibility of creating a dangling reference:</p>\n\n<pre><code>// Create the smart pointer on the heap\nMyObjectPtr* pp = new MyObjectPtr(new MyObject())\n// Hmm, we forgot to destroy the smart pointer,\n// because of that, the object is never destroyed!\n</code></pre>\n\n<p>Another possibility is creating circular references:</p>\n\n<pre><code>struct Owner {\n std::shared_ptr<Owner> other;\n};\n\nstd::shared_ptr<Owner> p1 (new Owner());\nstd::shared_ptr<Owner> p2 (new Owner());\np1->other = p2; // p1 references p2\np2->other = p1; // p2 references p1\n\n// Oops, the reference count of of p1 and p2 never goes to zero!\n// The objects are never destroyed!\n</code></pre>\n\n<p>To work around this problem, both Boost and C++11 have defined a <code>weak_ptr</code> to define a weak (uncounted) reference to a <code>shared_ptr</code>.</p>\n"
},
{
"answer_id": 106759,
"author": "Sridhar Iyer",
"author_id": 13820,
"author_profile": "https://Stackoverflow.com/users/13820",
"pm_score": 6,
"selected": false,
"text": "<p>Definitions provided by Chris, Sergdev and Llyod are correct. I prefer a simpler definition though, just to keep my life simple:\nA smart pointer is simply a class that overloads the <code>-></code> and <code>*</code> operators. Which means that your object semantically looks like a pointer but you can make it do way cooler things, including reference counting, automatic destruction etc.\n<code>shared_ptr</code> and <code>auto_ptr</code> are sufficient in most cases, but come along with their own set of small idiosyncrasies.</p>\n"
},
{
"answer_id": 15357935,
"author": "Saqlain",
"author_id": 1012551,
"author_profile": "https://Stackoverflow.com/users/1012551",
"pm_score": 5,
"selected": false,
"text": "<p>A smart pointer is an object that acts like a pointer, but additionally provides control on construction, destruction, copying, moving and dereferencing.</p>\n\n<p>One can implement one's own smart pointer, but many libraries also provide smart pointer implementations each with different advantages and drawbacks.</p>\n\n<p>For example, <a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost</a> provides the following smart pointer implementations:</p>\n\n<ul>\n<li><code>shared_ptr<T></code> is a pointer to <code>T</code> using a reference count to determine when the object is no longer needed.</li>\n<li><code>scoped_ptr<T></code> is a pointer automatically deleted when it goes out of scope. No assignment is possible.</li>\n<li><code>intrusive_ptr<T></code> is another reference counting pointer. It provides better performance than <code>shared_ptr</code>, but requires the type <code>T</code> to provide its own reference counting mechanism.</li>\n<li><code>weak_ptr<T></code> is a weak pointer, working in conjunction with <code>shared_ptr</code> to avoid circular references.</li>\n<li><code>shared_array<T></code> is like <code>shared_ptr</code>, but for arrays of <code>T</code>.</li>\n<li><code>scoped_array<T></code> is like <code>scoped_ptr</code>, but for arrays of <code>T</code>.</li>\n</ul>\n\n<p>These are just one linear descriptions of each and can be used as per need, for further detail and examples one can look at the documentation of Boost.</p>\n\n<p>Additionally, the C++ standard library provides three smart pointers; <code>std::unique_ptr</code> for unique ownership, <code>std::shared_ptr</code> for shared ownership and <code>std::weak_ptr</code>. <code>std::auto_ptr</code> existed in C++03 but is now deprecated.</p>\n"
},
{
"answer_id": 22245665,
"author": "Santosh",
"author_id": 3240133,
"author_profile": "https://Stackoverflow.com/users/3240133",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the Link for similar answers : <a href=\"http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html\">http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html</a></p>\n\n<p>A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.</p>\n\n<p><strong>Example:</strong> </p>\n\n<pre><code>template <class X>\nclass smart_pointer\n{\n public:\n smart_pointer(); // makes a null pointer\n smart_pointer(const X& x) // makes pointer to copy of x\n\n X& operator *( );\n const X& operator*( ) const;\n X* operator->() const;\n\n smart_pointer(const smart_pointer <X> &);\n const smart_pointer <X> & operator =(const smart_pointer<X>&);\n ~smart_pointer();\n private:\n //...\n};\n</code></pre>\n\n<p>This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:</p>\n\n<pre><code>smart_pointer <employee> p= employee(\"Harris\",1333);\n</code></pre>\n\n<p>Like other overloaded operators, p will behave like a regular pointer,</p>\n\n<pre><code>cout<<*p;\np->raise_salary(0.5);\n</code></pre>\n"
},
{
"answer_id": 30143936,
"author": "einpoklum",
"author_id": 1593077,
"author_profile": "https://Stackoverflow.com/users/1593077",
"pm_score": 9,
"selected": false,
"text": "<p>Here's a simple answer for these days of modern C++ (C++11 and later):</p>\n<ul>\n<li><strong>"What is a smart pointer?"</strong> <br>\nIt's a type whose values can be used like pointers, but which provides the additional feature of automatic memory management: When a smart pointer is no longer in use, the memory it points to is deallocated (see also <a href=\"http://en.wikipedia.org/wiki/Smart_pointer\" rel=\"noreferrer\">the more detailed definition on Wikipedia</a>).</li>\n<li><strong>"When should I use one?"</strong> <br>\nIn code which involves tracking the ownership of a piece of memory, allocating or de-allocating; the smart pointer often saves you the need to do these things explicitly.</li>\n<li><strong>"But which smart pointer should I use in which of those cases?"</strong>\n<ul>\n<li>Use <a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"noreferrer\"><code>std::unique_ptr</code></a> when you want your object to live just as long as a single owning reference to it lives. For example, use it for a pointer to memory which gets allocated on entering some scope and de-allocated on exiting the scope.</li>\n<li>Use <a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"noreferrer\"><code>std::shared_ptr</code></a> when you do want to refer to your object from multiple places - and do not want your object to be de-allocated until all these references are themselves gone.</li>\n<li>Use <a href=\"http://en.cppreference.com/w/cpp/memory/weak_ptr\" rel=\"noreferrer\"><code>std::weak_ptr</code></a> when you do want to refer to your object from multiple places - for those references for which it's ok to ignore and deallocate (so they'll just note the object is gone when you try to dereference).</li>\n<li>There is a <a href=\"https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2530r0.pdf\" rel=\"noreferrer\">proposal</a> to add <a href=\"https://en.wikipedia.org/wiki/Hazard_pointer\" rel=\"noreferrer\">hazard pointers</a> to C++26, but for now you don't have them.</li>\n<li>Don't use the <code>boost::</code> smart pointers or <code>std::auto_ptr</code> except in special cases which you can read up on if you must.</li>\n</ul>\n</li>\n<li><strong>"Hey, I didn't ask which one to use!"</strong> <br>\nAh, but you really wanted to, admit it.</li>\n<li><strong>"So when should I use regular pointers then?"</strong> <br>\nMostly in code that is oblivious to memory ownership. This would typically be in functions which get a pointer from someplace else and do not allocate nor de-allocate, and do not store a copy of the pointer which outlasts their execution.</li>\n</ul>\n"
},
{
"answer_id": 35761185,
"author": "nnrales",
"author_id": 4749396,
"author_profile": "https://Stackoverflow.com/users/4749396",
"pm_score": 4,
"selected": false,
"text": "<p>Let T be a class in this tutorial \nPointers in C++ can be divided into 3 types :</p>\n\n<p>1) <strong>Raw pointers</strong> :</p>\n\n<pre><code>T a; \nT * _ptr = &a; \n</code></pre>\n\n<p>They hold a memory address to a location in memory. Use with caution , as programs become complex hard to keep track. </p>\n\n<p>Pointers with const data or address { Read backwards } </p>\n\n<pre><code>T a ; \nconst T * ptr1 = &a ; \nT const * ptr1 = &a ;\n</code></pre>\n\n<p>Pointer to a data type T which is a const. Meaning you cannot change the data type using the pointer. ie <code>*ptr1 = 19</code> ; will not work. But you can move the pointer. ie <code>ptr1++ , ptr1--</code> ; etc will work.\nRead backwards : pointer to type T which is const </p>\n\n<pre><code> T * const ptr2 ;\n</code></pre>\n\n<p>A const pointer to a data type T . Meaning you cannot move the pointer but you can change the value pointed to by the pointer. ie <code>*ptr2 = 19</code> will work but <code>ptr2++ ; ptr2--</code> etc will not work. Read backwards : const pointer to a type T </p>\n\n<pre><code>const T * const ptr3 ; \n</code></pre>\n\n<p>A const pointer to a const data type T . Meaning you cannot either move the pointer nor can you change the data type pointer to be the pointer. ie . <code>ptr3-- ; ptr3++ ; *ptr3 = 19;</code> will not work </p>\n\n<p>3) <strong>Smart Pointers</strong> : { <code>#include <memory></code> } </p>\n\n<p><strong>Shared Pointer</strong>: </p>\n\n<pre><code> T a ; \n //shared_ptr<T> shptr(new T) ; not recommended but works \n shared_ptr<T> shptr = make_shared<T>(); // faster + exception safe\n\n std::cout << shptr.use_count() ; // 1 // gives the number of \" \nthings \" pointing to it. \n T * temp = shptr.get(); // gives a pointer to object\n\n // shared_pointer used like a regular pointer to call member functions\n shptr->memFn();\n (*shptr).memFn(); \n\n //\n shptr.reset() ; // frees the object pointed to be the ptr \n shptr = nullptr ; // frees the object \n shptr = make_shared<T>() ; // frees the original object and points to new object\n</code></pre>\n\n<p>Implemented using reference counting to keep track of how many \" things \" point to the object pointed to by the pointer. When this count goes to 0 , the object is automatically deleted , ie objected is deleted when all the share_ptr pointing to the object goes out of scope. \nThis gets rid of the headache of having to delete objects which you have allocated using new. </p>\n\n<p><strong>Weak Pointer :</strong> \n Helps deal with cyclic reference which arises when using Shared Pointer\n If you have two objects pointed to by two shared pointers and there is an internal shared pointer pointing to each others shared pointer then there will be a cyclic reference and the object will not be deleted when shared pointers go out of scope. To solve this , change the internal member from a shared_ptr to weak_ptr. Note : To access the element pointed to by a weak pointer use lock() , this returns a weak_ptr. </p>\n\n<pre><code>T a ; \nshared_ptr<T> shr = make_shared<T>() ; \nweak_ptr<T> wk = shr ; // initialize a weak_ptr from a shared_ptr \nwk.lock()->memFn() ; // use lock to get a shared_ptr \n// ^^^ Can lead to exception if the shared ptr has gone out of scope\nif(!wk.expired()) wk.lock()->memFn() ;\n// Check if shared ptr has gone out of scope before access\n</code></pre>\n\n<p>See : <a href=\"https://stackoverflow.com/questions/12030650/when-is-stdweak-ptr-useful\">When is std::weak_ptr useful?</a></p>\n\n<p><strong>Unique Pointer :</strong> \n Light weight smart pointer with exclusive ownership. Use when pointer points to unique objects without sharing the objects between the pointers.</p>\n\n<pre><code>unique_ptr<T> uptr(new T);\nuptr->memFn(); \n\n//T * ptr = uptr.release(); // uptr becomes null and object is pointed to by ptr\nuptr.reset() ; // deletes the object pointed to by uptr \n</code></pre>\n\n<p>To change the object pointed to by the unique ptr , use move semantics</p>\n\n<pre><code>unique_ptr<T> uptr1(new T);\nunique_ptr<T> uptr2(new T);\nuptr2 = std::move(uptr1); \n// object pointed by uptr2 is deleted and \n// object pointed by uptr1 is pointed to by uptr2\n// uptr1 becomes null \n</code></pre>\n\n<p>References : \n They can essentially be though of as const pointers, ie a pointer which is const and cannot be moved with better syntax.</p>\n\n<p>See : <a href=\"https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in\">What are the differences between a pointer variable and a reference variable in C++?</a> </p>\n\n<pre><code>r-value reference : reference to a temporary object \nl-value reference : reference to an object whose address can be obtained\nconst reference : reference to a data type which is const and cannot be modified \n</code></pre>\n\n<p>Reference : \n<a href=\"https://www.youtube.com/channel/UCEOGtxYTB6vo6MQ-WQ9W_nQ\" rel=\"noreferrer\">https://www.youtube.com/channel/UCEOGtxYTB6vo6MQ-WQ9W_nQ</a> \nThanks to Andre for pointing out this question.</p>\n"
},
{
"answer_id": 40457705,
"author": "Daksh Gupta",
"author_id": 5662469,
"author_profile": "https://Stackoverflow.com/users/5662469",
"pm_score": 2,
"selected": false,
"text": "<p>Smart Pointers are those where you don't have to worry about Memory De-Allocation, Resource Sharing and Transfer. </p>\n\n<p>You can very well use these pointer in the similar way as any allocation works in Java. In java Garbage Collector does the trick, while in Smart Pointers, the trick is done by Destructors.</p>\n"
},
{
"answer_id": 44510089,
"author": "Trombe",
"author_id": 7304166,
"author_profile": "https://Stackoverflow.com/users/7304166",
"pm_score": 3,
"selected": false,
"text": "<p>A smart pointer is a class, a wrapper of a normal pointer. Unlike normal pointers, smart point’s life circle is based on a reference count (how many time the smart pointer object is assigned). So whenever a smart pointer is assigned to another one, the internal reference count plus plus. And whenever the object goes out of scope, the reference count minus minus.</p>\n\n<p>Automatic pointer, though looks similar, is totally different from smart pointer. It is a convenient class that deallocates the resource whenever an automatic pointer object goes out of variable scope. To some extent, it makes a pointer (to dynamically allocated memory) works similar to a stack variable (statically allocated in compiling time).</p>\n"
},
{
"answer_id": 48455270,
"author": "da77a",
"author_id": 4472066,
"author_profile": "https://Stackoverflow.com/users/4472066",
"pm_score": 2,
"selected": false,
"text": "<p>The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.</p>\n\n<p>Among other things (explained well in other answers) using a smart pointer is a possible solution to <a href=\"https://stackoverflow.com/questions/48454208/how-do-we-use-a-abstract-class-as-a-function-return-type\">How do we use a abstract class as a function return type?</a> which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is \"what do you really mean?\". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the <a href=\"http://www.boost.org/doc/libs/1_66_0/libs/ptr_container/doc/guidelines.html#recommended-practice-for-object-oriented-programming\" rel=\"nofollow noreferrer\">boost pointer container library</a>. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a <em>value</em> to some form of <em>reference</em>. If you really needed copy you may need to add more boilerplate \"idiom\" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like <a href=\"http://stlab.adobe.com/group__poly__related.html\" rel=\"nofollow noreferrer\">Adobe Poly</a> or <a href=\"http://www.boost.org/doc/libs/1_66_0/doc/html/boost_typeerasure.html\" rel=\"nofollow noreferrer\">Boost.TypeErasure</a>.</p>\n"
},
{
"answer_id": 63325001,
"author": "lbsweek",
"author_id": 2482283,
"author_profile": "https://Stackoverflow.com/users/2482283",
"pm_score": 3,
"selected": false,
"text": "<p>What is a smart pointer.</p>\n<p>Long version, In principle:</p>\n<p><a href=\"https://web.stanford.edu/class/archive/cs/cs106l/cs106l.1192/lectures/lecture15/15_RAII.pdf\" rel=\"noreferrer\">https://web.stanford.edu/class/archive/cs/cs106l/cs106l.1192/lectures/lecture15/15_RAII.pdf</a></p>\n<p>A modern C++ idiom:</p>\n<pre><code>RAII: Resource Acquisition Is Initialization.\n\n● When you initialize an object, it should already have \n acquired any resources it needs (in the constructor).\n\n\n● When an object goes out of scope, it should release every \n resource it is using (using the destructor).\n</code></pre>\n<p>key point:</p>\n<pre><code>● There should never be a half-ready or half-dead object.\n● When an object is created, it should be in a ready state.\n● When an object goes out of scope, it should release its resources. \n● The user shouldn’t have to do anything more. \n</code></pre>\n<p><strong>Raw Pointers violate RAII</strong>: It need user to delete manually when the pointers go out of scope.</p>\n<p>RAII solution is:</p>\n<pre><code>Have a smart pointer class:\n● Allocates the memory when initialized\n● Frees the memory when destructor is called\n● Allows access to underlying pointer\n</code></pre>\n<p>For smart pointer need copy and share, use shared_ptr:</p>\n<pre><code>● use another memory to store Reference counting and shared.\n● increment when copy, decrement when destructor.\n● delete memory when Reference counting is 0. \n also delete memory that store Reference counting.\n</code></pre>\n<p>for smart pointer not own the raw pointer, use weak_ptr:</p>\n<pre><code>● not change Reference counting.\n</code></pre>\n<p>shared_ptr usage:</p>\n<pre><code>correct way:\nstd::shared_ptr<T> t1 = std::make_shared<T>(TArgs);\nstd::shared_ptr<T> t2 = std::shared_ptr<T>(new T(Targs));\n\nwrong way:\nT* pt = new T(TArgs); // never exposure the raw pointer\nshared_ptr<T> t1 = shared_ptr<T>(pt);\nshared_ptr<T> t2 = shared_ptr<T>(pt);\n</code></pre>\n<p>Always avoid using raw pointer.</p>\n<p>For scenario that have to use raw pointer:</p>\n<p><a href=\"https://stackoverflow.com/a/19432062/2482283\">https://stackoverflow.com/a/19432062/2482283</a></p>\n<p>For raw pointer that not nullptr, use reference instead.</p>\n<pre><code>not use T*\nuse T& \n</code></pre>\n<p>For optional reference which maybe nullptr, use raw pointer, and which means:</p>\n<pre><code>T* pt; is optional reference and maybe nullptr.\nNot own the raw pointer, \nRaw pointer is managed by some one else.\nI only know that the caller is sure it is not released now.\n</code></pre>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19410/"
]
| What is a smart pointer and when should I use one? | **UPDATE**
This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr), [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr) and [`std::weak_ptr`](http://en.cppreference.com/w/cpp/memory/weak_ptr).
There was also [`std::auto_ptr`](http://en.cppreference.com/w/cpp/memory/auto_ptr). It was very much like a scoped pointer, except that it also had the "special" dangerous ability to be copied — which also unexpectedly transfers ownership.
**It was deprecated in C++11 and removed in C++17**, so you shouldn't use it.
```
std::auto_ptr<MyObject> p1 (new MyObject());
std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership.
// p1 gets set to empty!
p2->DoSomething(); // Works.
p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.
```
---
**OLD ANSWER**
A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.
Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you *really* do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.
With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful.
```
// Need to create the object to achieve some goal
MyObject* ptr = new MyObject();
ptr->DoSomething(); // Use the object in some way
delete ptr; // Destroy the object. Done with it.
// Wait, what if DoSomething() raises an exception...?
```
A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.
```
SomeSmartPtr<MyObject> ptr(new MyObject());
ptr->DoSomething(); // Use the object in some way.
// Destruction of the object happens, depending
// on the policy the smart pointer class uses.
// Destruction would happen even if DoSomething()
// raises an exception
```
The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by [`boost::scoped_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_ptr.htm) or [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr).
```
void f()
{
{
std::unique_ptr<MyObject> ptr(new MyObject());
ptr->DoSomethingUseful();
} // ptr goes out of scope --
// the MyObject is automatically destroyed.
// ptr->Oops(); // Compile error: "ptr" not defined
// since it is no longer in scope.
}
```
Note that `std::unique_ptr` instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.
`std::unique_ptr`s are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.
A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by [`boost::shared_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm) and [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr).
```
void f()
{
typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias
MyObjectPtr p1; // Empty
{
MyObjectPtr p2(new MyObject());
// There is now one "reference" to the created object
p1 = p2; // Copy the pointer.
// There are now two references to the object.
} // p2 is destroyed, leaving one reference to the object.
} // p1 is destroyed, leaving a reference count of zero.
// The object is deleted.
```
Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object.
There is one drawback to reference counted pointers — the possibility of creating a dangling reference:
```
// Create the smart pointer on the heap
MyObjectPtr* pp = new MyObjectPtr(new MyObject())
// Hmm, we forgot to destroy the smart pointer,
// because of that, the object is never destroyed!
```
Another possibility is creating circular references:
```
struct Owner {
std::shared_ptr<Owner> other;
};
std::shared_ptr<Owner> p1 (new Owner());
std::shared_ptr<Owner> p2 (new Owner());
p1->other = p2; // p1 references p2
p2->other = p1; // p2 references p1
// Oops, the reference count of of p1 and p2 never goes to zero!
// The objects are never destroyed!
```
To work around this problem, both Boost and C++11 have defined a `weak_ptr` to define a weak (uncounted) reference to a `shared_ptr`. |
106,509 | <p>I have a button that I would like to disable when the form submits to prevent the user submitting multiple times.</p>
<p>I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled.</p>
<p>How do I disable the button when the form successfully submits not just when the user clicks?</p>
<p>This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.</p>
| [
{
"answer_id": 106522,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>Disable the button at the very end of your submit handler. If the validation fails, it should return false before that.</p>\n\n<p>However, the JavaScript approach is not something that can be relied upon, so you should have something to detect duplicates on the server as well.</p>\n"
},
{
"answer_id": 106525,
"author": "ChRoss",
"author_id": 10802,
"author_profile": "https://Stackoverflow.com/users/10802",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this will help, but there's onsubmit event in form. You can use this event whenever the form submit (from any button or controls).\nFor reference: <a href=\"http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html\" rel=\"nofollow noreferrer\">http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html</a></p>\n"
},
{
"answer_id": 106840,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 3,
"selected": false,
"text": "<p>The following function is useful without needing the disabling part which tends to be unreliable. Just use \"return check_submit();\" as part of the onclick handler of the submit buttons.</p>\n\n<p>There should also be a hidden field to hold the form_submitted initial value of 0;</p>\n\n<pre><code><input type=\"hidden\" name=\"form_submitted\" value=\"0\">\n\nfunction check_submit (){\n if (document.Form1.form_submitted.value == 1){\n alert(\"Don't submit twice. Please wait.\");\n return false;\n }\n else{\n document.Form1.form_submitted.value = 1;\n return true;\n }\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 106845,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": "<p>A solution will be to set a hidden field when the button is clicked, with the number 1. </p>\n\n<p>On the button click handler first thing is to check that number if it is something other than 1 just return out of the function.</p>\n"
},
{
"answer_id": 106891,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 0,
"selected": false,
"text": "<p>You may also be able to take advantage of the onsubmit() javascript event that is available on forms. This event fires when the form is actually submit and shouldn't trap until after the validation is complete.</p>\n"
},
{
"answer_id": 106958,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 5,
"selected": true,
"text": "<p>Give this a whirl:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Threading;\n\npublic partial class _Default : System.Web.UI.Page \n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n // Identify button as a \"disabled-when-clicked\" button...\n WebHelpers.DisableButtonOnClick( buttonTest, \"showPleaseWait\" ); \n }\n\n protected void buttonTest_Click( object sender, EventArgs e )\n {\n // Emulate a server-side process to demo the disabled button during\n // postback.\n Thread.Sleep( 5000 );\n }\n}\n\n\n\nusing System;\nusing System.Web;\nusing System.Web.UI.WebControls;\nusing System.Text;\n\npublic class WebHelpers\n{\n //\n // Disable button with no secondary JavaScript function call.\n //\n public static void DisableButtonOnClick( Button ButtonControl )\n {\n DisableButtonOnClick( ButtonControl, string.Empty ); \n }\n\n //\n // Disable button with a JavaScript function call.\n //\n public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction )\n { \n StringBuilder sb = new StringBuilder( 128 );\n\n // If the page has ASP.NET validators on it, this code ensures the\n // page validates before continuing.\n sb.Append( \"if ( typeof( Page_ClientValidate ) == 'function' ) { \" );\n sb.Append( \"if ( ! Page_ClientValidate() ) { return false; } } \" );\n\n // Disable this button.\n sb.Append( \"this.disabled = true;\" ); \n\n // If a secondary JavaScript function has been provided, and if it can be found,\n // call it. Note the name of the JavaScript function to call should be passed without\n // parens.\n if ( ! String.IsNullOrEmpty( ClientFunction ) ) \n {\n sb.AppendFormat( \"if ( typeof( {0} ) == 'function' ) {{ {0}() }};\", ClientFunction ); \n }\n\n // GetPostBackEventReference() obtains a reference to a client-side script function \n // that causes the server to post back to the page (ie this causes the server-side part \n // of the \"click\" to be performed).\n sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + \";\" );\n\n // Add the JavaScript created a code to be executed when the button is clicked.\n ButtonControl.Attributes.Add( \"onclick\", sb.ToString() );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 107394,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>if the validation is successful, then disable the button. if it's not, then don't.</p>\n\n<pre><code>function validate(form) {\n // perform validation here\n if (isValid) {\n form.mySubmitButton.disabled = true;\n return true;\n } else {\n return false;\n }\n}\n\n<form onsubmit=\"return validate(this);\">...</form>\n</code></pre>\n"
},
{
"answer_id": 108330,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 0,
"selected": false,
"text": "<p>This is an easier but similar method than what <a href=\"https://stackoverflow.com/questions/106509/disable-button-on-form-submission#106958\">rp</a> has suggested:</p>\n\n<pre><code>function submit(button) {\n Page_ClientValidate(); \n if(Page_IsValid)\n {\n button.disabled = true;\n }\n}\n\n <asp:Button runat=\"server\" ID=\"btnSubmit\" OnClick=\"btnSubmit_OnClick\" OnClientClick=\"submit(this)\" Text=\"Submit Me\" />\n</code></pre>\n"
},
{
"answer_id": 108701,
"author": "Kyle B.",
"author_id": 6158,
"author_profile": "https://Stackoverflow.com/users/6158",
"pm_score": 1,
"selected": false,
"text": "<p>Set the visibility on the button to 'none';</p>\n\n<pre><code>\nbtnSubmit.Attributes(\"onClick\") = document.getElementById('btnName').style.display = 'none';</code></pre>\n\n<p>Not only does it prevent the double submission, but it is a clear indicator to the user that you don't want the button pressed more than once.</p>\n"
},
{
"answer_id": 612630,
"author": "Adam Nofsinger",
"author_id": 18524,
"author_profile": "https://Stackoverflow.com/users/18524",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not a huge fan of writing all that javascript in the code-behind. Here is what my final solution looks like.</p>\n\n<p>Button:</p>\n\n<pre><code><asp:Button ID=\"btnSubmit\" runat=\"server\" Text=\"Submit\" OnClick=\"btnSubmit_Click\" OnClientClick=\"doSubmit(this)\" />\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code><script type=\"text/javascript\"><!--\nfunction doSubmit(btnSubmit) {\n if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) { \n return false;\n } \n btnSubmit.disabled = 'disabled';\n btnSubmit.value = 'Processing. This may take several minutes...';\n <%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>; \n}\n//-->\n</script>\n</code></pre>\n"
},
{
"answer_id": 937262,
"author": "Steve J",
"author_id": 50568,
"author_profile": "https://Stackoverflow.com/users/50568",
"pm_score": 0,
"selected": false,
"text": "<p>Just heard about the \"DisableOnSubmit\" property of an <asp:Button>, like so:</p>\n\n<pre><code><asp:Button ID=\"submit\" runat=\"server\" Text=\"Save\"\n OnClick=\"yourClickEvent\" DisableOnSubmit=\"true\" />\n</code></pre>\n\n<p>When rendered, the button's onclick attribute looks like so:</p>\n\n<pre><code>onclick=\"this.disabled=true; setTimeout('enableBack()', 3000);\n WebForm_DoPostBackWithOptions(new\n WebForm_PostBackOptions('yourControlsName', '', true, '', '', false, true))\n</code></pre>\n\n<p>And the \"enableBack()' javascript function looks like this:</p>\n\n<pre><code>function enableBack()\n{\n document.getElementById('yourControlsName').disabled=false;\n}\n</code></pre>\n\n<p>So when the button is clicked, it becomes disabled for 3 seconds. If the form posts successfully then you never see the button re-enable. If, however, any validators fail then the button becomes enabled again after 3 seconds.</p>\n\n<p>All this just by setting an attribute on the button--no javascript code needs to be written by hand.</p>\n"
},
{
"answer_id": 955148,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Note that rp's approach will double submit your form if you are using buttons with <code>UseSubmitBehavior=\"false\"</code>.</p>\n\n<p>I use the following variation of rp's code:</p>\n\n<pre><code>public static void DisableButtonOnClick(Button button, string clientFunction)\n{\n // If the page has ASP.NET validators on it, this code ensures the\n // page validates before continuing.\n string script = \"if (typeof(Page_ClientValidate) == 'function') { \"\n + \"if (!Page_ClientValidate()) { return false; } } \";\n\n // disable the button\n script += \"this.disabled = true; \";\n\n // If a secondary JavaScript function has been provided, and if it can be found, call it.\n // Note the name of the JavaScript function to call should be passed without parens.\n if (!string.IsNullOrEmpty(clientFunction))\n script += string.Format(\"if (typeof({0}) == 'function') {{ {0}() }} \", clientFunction);\n\n // only need to post back if button is using submit behaviour\n if (button.UseSubmitBehavior)\n script += button.Page.GetPostBackEventReference(button) + \"; \";\n\n button.Attributes.Add(\"onclick\", script);\n}\n</code></pre>\n"
},
{
"answer_id": 955252,
"author": "HalliHax",
"author_id": 78292,
"author_profile": "https://Stackoverflow.com/users/78292",
"pm_score": 0,
"selected": false,
"text": "<p>The correct (as far as user-friendliness is concerned, at least) way would be to disable the button using the OnClientClick attribute, perform the client-side validation, and then use the result of that to continue or re-enable the button.</p>\n\n<p>Of course, you should ALSO write server-side code for this, as you cannot rely on the validation even being carried out due to a lack, or particular implementation, of JavaScript. However, if you rely on the server controlling the button's enabled / disabled state, then you basically have no way of blocking the user submitting the form multiple times anyway. For this reason you should have some kind of logic to detect multiple submissions from the same user in a short time period (identical values from the same Session, for example).</p>\n"
},
{
"answer_id": 1073332,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>one of my solution is as follow:</p>\n\n<p>add the script in the page_load of your aspx file</p>\n\n<pre><code> HtmlGenericControl includeMyJava = new HtmlGenericControl(\"script\");\n includeMyJava.Attributes.Add(\"type\", \"text/javascript\");\n includeMyJava.InnerHtml = \"\\nfunction dsbButton(button) {\";\n includeMyJava.InnerHtml += \"\\nPage_ClientValidate();\";\n includeMyJava.InnerHtml += \"\\nif(Page_IsValid)\";\n includeMyJava.InnerHtml += \"\\n{\";\n includeMyJava.InnerHtml += \"\\nbutton.disabled = true;\";\n includeMyJava.InnerHtml += \"}\";\n includeMyJava.InnerHtml += \"\\n}\";\n this.Page.Header.Controls.Add(includeMyJava);\n</code></pre>\n\n<p>and then set your aspx button parameters as follow:</p>\n\n<pre><code><asp:Button ID=\"send\" runat=\"server\" UseSubmitBehavior=\"false\" OnClientClick=\"dsbButton(this);\" Text=\"Send\" OnClick=\"send_Click\" />\n</code></pre>\n\n<p>Note that \"onClientClick\" helps to disable to button and \"UseSubmitBehaviour\" disables the traditional submitting behaviour of page and allows asp.net to render the submit behaviour upon user script.</p>\n\n<p>good luck</p>\n\n<p>-Waqas Aslam</p>\n"
},
{
"answer_id": 9008614,
"author": "joelmdev",
"author_id": 663246,
"author_profile": "https://Stackoverflow.com/users/663246",
"pm_score": 0,
"selected": false,
"text": "<p>So simply disabling the button via javascript is not a cross-browser compatible option. Chrome will not submit the form if you just use <code>OnClientClick=\"this.disabled=true;\"</code><br>\nBelow is a solution that I have tested in Firefox 9, Internet Explorer 9, and Chrome 16:</p>\n\n<pre><code><script type=\"text/javascript\">\nvar buttonToDisable;\nfunction disableButton(sender)\n{\n buttonToDisable=sender;\n setTimeout('if(Page_IsValid==true)buttonToDisable.disabled=true;', 10);\n}\n</script>\n</code></pre>\n\n<p>Then register 'disableButton' with the click event of your form submission button, one way being:</p>\n\n<pre><code><asp:Button runat=\"server\" ID=\"btnSubmit\" Text=\"Submit\" OnClientClick=\"disableButton(this);\" />\n</code></pre>\n\n<p>Worth noting that this gets around your issue of the button being disabled if client side validation fails. Also requires no server side processing.</p>\n"
},
{
"answer_id": 23803541,
"author": "Techek",
"author_id": 231144,
"author_profile": "https://Stackoverflow.com/users/231144",
"pm_score": 0,
"selected": false,
"text": "<p>Building on @rp.'s answer, I modified it to invoke the custom function and either submit and disable on success or \"halt\" on error:</p>\n\n<pre><code>public static void DisableButtonOnClick(Button ButtonControl, string ClientFunction)\n{\n StringBuilder sb = new StringBuilder(128);\n\n if (!String.IsNullOrEmpty(ClientFunction))\n {\n sb.AppendFormat(\"if (typeof({0}) == 'function') {{ if ({0}()) {{ {1}; this.disabled=true; return true; }} else {{ return false; }} }};\", ClientFunction, ButtonControl.Page.ClientScript.GetPostBackEventReference(ButtonControl, null));\n }\n else\n {\n sb.Append(\"return true;\");\n }\n\n ButtonControl.Attributes.Add(\"onclick\", sb.ToString());\n}\n</code></pre>\n"
},
{
"answer_id": 59095461,
"author": "Andy Smith",
"author_id": 3790293,
"author_profile": "https://Stackoverflow.com/users/3790293",
"pm_score": 0,
"selected": false,
"text": "<p>Came across rp's code in a legacy app of ours which was struggling with some crazy behaviour. </p>\n\n<p>Tracked it down to a strange combination of event firing - when DisableButtonOnClick() was being used on an asp button inside an UpdatePanel, the POST would be sent twice (once by the doPostBack added by DisableButtonOnClick(), and once by the UpdatePanel). However, this only happened with some browsers (early versions of Edge, but not recent ones, and IE11 did this, Chrome and FireFox did not (at least the versions I tested with)). I presume Chrome and newer versions of Edge are dealing with this scenario internally in some way. Tracking the issue with F12 devtools in IE - the two POSTs happen so closely together that the first one gets immediately ABORTED, but under some conditions (network latency, user machine load, etc) the request does get through to the server before the browser can abort. So this results in a seemingly random double-post coming from button presses throughout the system, and it was a pain to trace back. The fix is to add a \"return false;\" after the doPostBack to prevent the UpdatePanel from getting involved when older browsers are in play.</p>\n\n<p>TLDR - beware of this code on buttons in updatepanels. It's a good approach and nice method but has a potential issue in my (likely edge) case.</p>\n\n<p>ps - I would have commented on rp's post but I don't have the rep. Thought it might be useful for future travelers.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600/"
]
| I have a button that I would like to disable when the form submits to prevent the user submitting multiple times.
I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled.
How do I disable the button when the form successfully submits not just when the user clicks?
This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible. | Give this a whirl:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Identify button as a "disabled-when-clicked" button...
WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" );
}
protected void buttonTest_Click( object sender, EventArgs e )
{
// Emulate a server-side process to demo the disabled button during
// postback.
Thread.Sleep( 5000 );
}
}
using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;
public class WebHelpers
{
//
// Disable button with no secondary JavaScript function call.
//
public static void DisableButtonOnClick( Button ButtonControl )
{
DisableButtonOnClick( ButtonControl, string.Empty );
}
//
// Disable button with a JavaScript function call.
//
public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction )
{
StringBuilder sb = new StringBuilder( 128 );
// If the page has ASP.NET validators on it, this code ensures the
// page validates before continuing.
sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " );
sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " );
// Disable this button.
sb.Append( "this.disabled = true;" );
// If a secondary JavaScript function has been provided, and if it can be found,
// call it. Note the name of the JavaScript function to call should be passed without
// parens.
if ( ! String.IsNullOrEmpty( ClientFunction ) )
{
sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction );
}
// GetPostBackEventReference() obtains a reference to a client-side script function
// that causes the server to post back to the page (ie this causes the server-side part
// of the "click" to be performed).
sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" );
// Add the JavaScript created a code to be executed when the button is clicked.
ButtonControl.Attributes.Add( "onclick", sb.ToString() );
}
}
``` |
106,534 | <p>The default rails XML builder escapes all HTML, so something like:</p>
<pre class="lang-ruby prettyprint-override"><code>atom_feed do |feed|
@stories.each do |story|
feed.entry story do |entry|
entry.title story.title
entry.content "<b>foo</b>"
end
end
end
</code></pre>
<p>will produce the text:</p>
<pre class="lang-html prettyprint-override"><code><b>foo</b>
</code></pre>
<p>instead of: <strong>foo</strong></p>
<p>Is there any way to instruct the XML builder to not escape the XML?</p>
| [
{
"answer_id": 106616,
"author": "Shalmanese",
"author_id": 14559,
"author_profile": "https://Stackoverflow.com/users/14559",
"pm_score": 4,
"selected": true,
"text": "<p>turns out you need to do </p>\n\n<pre><code>entry.content \"<b>foo</b>\", :type => \"html\"\n</code></pre>\n\n<p>althought wrapping it in a CDATA stops it working.</p>\n"
},
{
"answer_id": 400280,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://builder.rubyforge.org/classes/Builder/XmlMarkup.html\" rel=\"nofollow noreferrer\">http://builder.rubyforge.org/classes/Builder/XmlMarkup.html</a></p>\n\n<blockquote>\n <p>The special XML characters <, >, and & are converted to <, > and & automatically. Use the << operation to insert text without modification.</p>\n</blockquote>\n"
},
{
"answer_id": 5706949,
"author": "Rodrigo",
"author_id": 713910,
"author_profile": "https://Stackoverflow.com/users/713910",
"pm_score": 3,
"selected": false,
"text": "<pre><code>entry.content \"type\" => \"html\" do\n entry.cdata!(post.content)\nend\n</code></pre>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14559/"
]
| The default rails XML builder escapes all HTML, so something like:
```ruby
atom_feed do |feed|
@stories.each do |story|
feed.entry story do |entry|
entry.title story.title
entry.content "<b>foo</b>"
end
end
end
```
will produce the text:
```html
<b>foo</b>
```
instead of: **foo**
Is there any way to instruct the XML builder to not escape the XML? | turns out you need to do
```
entry.content "<b>foo</b>", :type => "html"
```
althought wrapping it in a CDATA stops it working. |
106,544 | <p>I get the following error when trying to run the latest Cygwin version of rsync in Windows XP SP2. The error occurs for attempts at both local syncs (that is: source and destination on the local harddisk only) and remote syncs (using "-e ssh" from the openssh package). Any advice on how to fix/workaround it?</p>
<pre>
bash-3.2$ rsync -a dir1 dir2
rsync: Failed to dup/close: Socket operation on non-socket (108)
rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/pipe.c(143) [receiver=2.6.9]
rsync: read error: Connection reset by peer (104)
rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/io.c(604) [sender=2.6.9]
</pre>
| [
{
"answer_id": 106736,
"author": "Niall",
"author_id": 6049,
"author_profile": "https://Stackoverflow.com/users/6049",
"pm_score": 1,
"selected": true,
"text": "<p>Not really an answer to your question, but I've found <a href=\"http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp\" rel=\"nofollow noreferrer\">Delta Copy</a> to be a much better option than messing around with Cygwin. It connects to regular rsync daemons too.</p>\n"
},
{
"answer_id": 289858,
"author": "akaihola",
"author_id": 15770,
"author_profile": "https://Stackoverflow.com/users/15770",
"pm_score": 1,
"selected": false,
"text": "<p>Be aware that a long-standing pipe implementation bug in Cygwin causes rsync to hang if it's used through an SSH connection.</p>\n\n<p>As of Cygwin v. 1.7 it seems that the only reliable way to transfer lots of data with rsync is to connect to an rsync daemon using the rsync protocol. DeltaCopy is just a pretty wrapper around this method.</p>\n\n<p>Some users apparently have had success on top of SSH pushing data from Windows to Unix instead of pulling from Windows on the Unix side. In our experience that's unreliable too, though.</p>\n\n<p>Google for cygwin, rsync, ssh and pipe/hang/stall and you'll find more information about this problem.</p>\n"
},
{
"answer_id": 1154757,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have found this to be a winsock error. I confirmed the problem starts with the installation of the ATT Communcations Manager (version 6.12.0046.0) for the Sierra Wireless Aircard (875U). Uninstall the Communications Manager and the rsync error goes away.</p>\n"
},
{
"answer_id": 2507539,
"author": "DH4",
"author_id": 267429,
"author_profile": "https://Stackoverflow.com/users/267429",
"pm_score": 2,
"selected": false,
"text": "<p>You probably have something blocking rsync. In my case it's NOD32 antivirus. You can check this by running rsync in 'gdb' as follows:</p>\n\n<pre><code>$ gdb --args /usr/bin/rsync -a somedir/ anotherdir\nGNU gdb 6.8.0.20080328-cvs (cygwin-special)\n.....\n(no debugging symbols found)\n(gdb) run \n</code></pre>\n\n<p>note the \"run\" command after gdb has started. You will see some output like this:</p>\n\n<pre><code>Starting program: /usr/bin/rsync -a somedir/ anotherdir\n.....\n(no debugging symbols found)\nwarning: NOD32 protected [MSAFD Tcpip [TCP/IP]]\nwarning: NOD32 protected [MSAFD Tcpip [UDP/IP]]\nwarning: NOD32 protected [MSAFD Tcpip [RAW/IP]]\nwarning: NOD32 protected [RSVP UDP Service Provider]\nwarning: NOD32 protected [RSVP TCP Service Provider]\n(no debugging symbols found)\n(no debugging symbols found)\n---Type <return> to continue, or q <return> to quit---\n(no debugging symbols found)\n[New thread 1508.0x720]\n[New thread 1508.0xeb0]\n[New thread 1508.0x54c]\nrsync: Failed to dup/close: Socket operation on non-socket\n(108)\nrsync error: error in IPC code (code 14) at\n/home/lapo/packaging/rsync-3.0.4-1/src/rsync-3.0.4/pipe.c(147)\n[receiver=3.0.4] \n</code></pre>\n\n<p>So you will have to add rsync to your exclude list in that virus scanner (NOD32):</p>\n\n<p>c:\\cygwin\\bin\\rsync.exe</p>\n"
},
{
"answer_id": 23960010,
"author": "tvl",
"author_id": 1692965,
"author_profile": "https://Stackoverflow.com/users/1692965",
"pm_score": 0,
"selected": false,
"text": "<p>After following @akaihola ’s advice I found <a href=\"http://marc-abramowitz.com/archives/2007/10/14/solving-rsync-hangs-with-cygwin/comment-page-1/\" rel=\"nofollow\">this</a> blog post with the solution to the same problem.\nI post the solution here, but the credits go to <a href=\"http://marc-abramowitz.com/\" rel=\"nofollow\">Marc Abramowitz</a></p>\n\n<pre><code>cygrunsrv --install \"rsyncd\" --path /usr/bin/rsync --args \"--daemon --no-detach\" --desc \"Starts a rsync daemon for accepting incoming rsync connections\" --disp \"Rsync Daemon\" --type auto\n</code></pre>\n\n<p>Of course you need Cygwin with rsync.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19417/"
]
| I get the following error when trying to run the latest Cygwin version of rsync in Windows XP SP2. The error occurs for attempts at both local syncs (that is: source and destination on the local harddisk only) and remote syncs (using "-e ssh" from the openssh package). Any advice on how to fix/workaround it?
```
bash-3.2$ rsync -a dir1 dir2
rsync: Failed to dup/close: Socket operation on non-socket (108)
rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/pipe.c(143) [receiver=2.6.9]
rsync: read error: Connection reset by peer (104)
rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/io.c(604) [sender=2.6.9]
``` | Not really an answer to your question, but I've found [Delta Copy](http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp) to be a much better option than messing around with Cygwin. It connects to regular rsync daemons too. |
106,554 | <p>I use this code in my Windows Service to be notified of USB disk drives being inserted and removed:</p>
<pre><code>WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent",
"TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2");
query.WithinInterval = TimeSpan.FromSeconds(1);
_deviceWatcher = new ManagementEventWatcher(query);
_deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived);
_deviceWatcher.Start();
</code></pre>
<p>It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect?</p>
| [
{
"answer_id": 106775,
"author": "Andrew Queisser",
"author_id": 18321,
"author_profile": "https://Stackoverflow.com/users/18321",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I can't post here) to detect when USB devices are plugged in. There's a handful of native functions you have to import but it generally works well. Easiest to make it work in C++ first and then see what you have to move up into C#.</p>\n\n<p>There's some stuff on koders Code search that appears to be a whole C# device management module that might help:</p>\n\n<p><a href=\"http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx\" rel=\"nofollow noreferrer\">http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx</a></p>\n"
},
{
"answer_id": 328999,
"author": "Don Jones",
"author_id": 40405,
"author_profile": "https://Stackoverflow.com/users/40405",
"pm_score": 1,
"selected": false,
"text": "<p>Try looking for the InstanceCreationEvent, which will signal the creation of a new Win32_LogicalDisk instance. Right now you're querying for instance operations, not creations. You should know that the query interval on those events is pretty long - it's possible to pop a USB in and out faster that you'll detect.</p>\n"
},
{
"answer_id": 52615754,
"author": "Mujtaba",
"author_id": 6880486,
"author_profile": "https://Stackoverflow.com/users/6880486",
"pm_score": 1,
"selected": false,
"text": "<p>try this</p>\n\n<pre><code>using System;\nusing System.Management;\n\nnamespace MonitorDrives\n{\nclass Program\n{\n public enum EventType\n {\n Inserted = 2,\n Removed = 3\n }\n\n static void Main(string[] args)\n {\n ManagementEventWatcher watcher = new ManagementEventWatcher();\n WqlEventQuery query = new WqlEventQuery(\"SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3\");\n\n watcher.EventArrived += (s, e) =>\n {\n string driveName = e.NewEvent.Properties[\"DriveName\"].Value.ToString();\n EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties[\"EventType\"].Value));\n\n string eventName = Enum.GetName(typeof(EventType), eventType);\n\n Console.WriteLine(\"{0}: {1} {2}\", DateTime.Now, driveName, eventName);\n };\n\n watcher.Query = query;\n watcher.Start();\n\n Console.ReadKey();\n }\n}\n}\n</code></pre>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14842/"
]
| I use this code in my Windows Service to be notified of USB disk drives being inserted and removed:
```
WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent",
"TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2");
query.WithinInterval = TimeSpan.FromSeconds(1);
_deviceWatcher = new ManagementEventWatcher(query);
_deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived);
_deviceWatcher.Start();
```
It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect? | Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I can't post here) to detect when USB devices are plugged in. There's a handful of native functions you have to import but it generally works well. Easiest to make it work in C++ first and then see what you have to move up into C#.
There's some stuff on koders Code search that appears to be a whole C# device management module that might help:
<http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx> |
106,555 | <p>I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing. </p>
<p>I can do a check on the number of keys-value pairs:</p>
<pre><code>if (scalar keys %cache > $maxSize)
{
%cache = ();
}
</code></pre>
<p>But is it possible to check the actual memory occupied by the hash?</p>
| [
{
"answer_id": 106565,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 4,
"selected": false,
"text": "<p>You're looking for <a href=\"http://search.cpan.org/perldoc?Devel::Size\" rel=\"nofollow noreferrer\">Devel::Size</a></p>\n\n<h1>NAME</h1>\n\n<p>Devel::Size - Perl extension for finding the memory usage of Perl variables</p>\n\n<h1>SYNOPSIS</h1>\n\n<pre><code>use Devel::Size qw(size total_size);\n\nmy $size = size(\"A string\");\nmy @foo = (1, 2, 3, 4, 5);\nmy $other_size = size(\\@foo);\nmy $foo = {a => [1, 2, 3],\n b => {a => [1, 3, 4]}\n };\nmy $total_size = total_size($foo);\n</code></pre>\n"
},
{
"answer_id": 106587,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://search.cpan.org/perldoc?Devel::Size\" rel=\"nofollow noreferrer\">Devel::Size</a> to determine the memory used, but you can't generally give return memory to the OS. It sounds like you're just trying to clear and reuse, though, which should work fine.</p>\n\n<p>If the cache is for a function, consider using the <a href=\"http://search.cpan.org/perldoc?Memoize\" rel=\"nofollow noreferrer\">Memoize</a> module instead of maintaining the cache yourself. It supports cache expiration (via Memoize::Expire) so you can limit the size of the cache without destroying it entirely.</p>\n"
},
{
"answer_id": 106588,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 3,
"selected": false,
"text": "<p>You can install <a href=\"http://search.cpan.org/perldoc?Devel::Size\" rel=\"nofollow noreferrer\">Devel::Size</a> to find out the memory taken by any construct in Perl. However do be aware that it will take a large amount of intermediate memory, so I would not use it against a large data structure. I would certainly not do it if you think you may be about to run out of memory.</p>\n\n<p>BTW there are a number of good modules on CPAN to do caching in memory and otherwise. Rather than roll your own I would suggest using one of them instead. For instance try <a href=\"http://search.cpan.org/perldoc?Tie::Cache::LRU\" rel=\"nofollow noreferrer\">Tie::Cache::LRU</a> for an in-memory cache that will only go up to a specified number of keys.</p>\n"
},
{
"answer_id": 106642,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://search.cpan.org/perldoc?Devel::Size\" rel=\"noreferrer\">Devel::Size</a> is the answer to your question. (Note that Devel::Size will temporarily allocate a significant amount of memory when processing a large data structure, so it's not really well suited to this purpose.)</p>\n\n<p>However, <a href=\"http://search.cpan.org/perldoc?Cache::SizeAwareMemoryCache\" rel=\"noreferrer\">Cache::SizeAwareMemoryCache</a> and <a href=\"http://search.cpan.org/perldoc?Tie::Cache\" rel=\"noreferrer\">Tie::Cache</a> already implement what you're looking for (with somewhat different interfaces), and could save you from reinventing the wheel.</p>\n\n<p><a href=\"http://search.cpan.org/perldoc?Memoize\" rel=\"noreferrer\">Memoize</a> is a module that makes it simple to cache the return value from a function. It doesn't implement a size-based cache limit, but it should be possible to use Tie::Cache as a backend for Memoize.</p>\n"
},
{
"answer_id": 106707,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 1,
"selected": false,
"text": "<h3><a href=\"http://search.cpan.org/perldoc?Cache::Memory\" rel=\"nofollow noreferrer\">Cache::Memory</a></h3>\n<pre><code>use Cache::Memory;\n\nmy $cache = Cache::Memory->new(\n namespace => 'MyNamespace',\n default_expires => '600 sec'\n);\n\nmy $size = $cache->size()\nmy $limit = $cache->size_limit();\n</code></pre>\n"
},
{
"answer_id": 112709,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 1,
"selected": false,
"text": "<p>If you're worrying about managing the amount of memory that Perl is using, you should probably look at an alternative approach. Why do you need that much in RAM all at once? Should you be using some sort of persistence system?</p>\n"
},
{
"answer_id": 350109,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 0,
"selected": false,
"text": "<p>As others have said, caching is not a wheel you need to re-invent, there's plenty of simple caching solutions on CPAN which will do the job nicely for you.</p>\n\n<p><a href=\"http://search.cpan.org/perldoc?Cache::SizeAwareMemoryCache\" rel=\"nofollow noreferrer\">Cache::SizeAwareMemoryCache</a> can be told the maximum size you want it to use, then you can leave it to care about the cache for you.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5734/"
]
| I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing.
I can do a check on the number of keys-value pairs:
```
if (scalar keys %cache > $maxSize)
{
%cache = ();
}
```
But is it possible to check the actual memory occupied by the hash? | [Devel::Size](http://search.cpan.org/perldoc?Devel::Size) is the answer to your question. (Note that Devel::Size will temporarily allocate a significant amount of memory when processing a large data structure, so it's not really well suited to this purpose.)
However, [Cache::SizeAwareMemoryCache](http://search.cpan.org/perldoc?Cache::SizeAwareMemoryCache) and [Tie::Cache](http://search.cpan.org/perldoc?Tie::Cache) already implement what you're looking for (with somewhat different interfaces), and could save you from reinventing the wheel.
[Memoize](http://search.cpan.org/perldoc?Memoize) is a module that makes it simple to cache the return value from a function. It doesn't implement a size-based cache limit, but it should be possible to use Tie::Cache as a backend for Memoize. |
106,563 | <p>I'd like to log the output of a command to <code>stdout</code> as well as to a log file. I've got Cygwin installed and I'm trying to use the <code>tee</code> command to accomplish this.</p>
<pre><code>devenv mysolution.sln /build myproject "Release|Win32" | tee build.log
</code></pre>
<p>Trouble is that <code>tee</code> seems to insist on waiting for the end of file before outputting anything to either <code>stdout</code> or the log file. This takes away the point of it all, which is to have a log file for future reference, but also some <code>stdout</code> logging so I can easily see the build progress.</p>
<p><code>tee</code>'s options appear to be limited to <code>--append</code>, <code>--ignore-interrupts</code>, <code>--help</code>, and <code>--version</code>. So is there another method to get to what I'm trying to do?</p>
| [
{
"answer_id": 106575,
"author": "Sam Reynolds",
"author_id": 9192,
"author_profile": "https://Stackoverflow.com/users/9192",
"pm_score": 2,
"selected": false,
"text": "<p>You can output to the file and tail -f the file.</p>\n\n<p>devenv mysolution.sln /build myproject \"Release|Win32\" > build.log &</p>\n\n<p>tail -f build.log</p>\n"
},
{
"answer_id": 106579,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>Write your own! (The point here is that the autoflush (<code>$|</code>) setting is turned on, so every line seen is flushed straight away. This may perhaps be what the real <code>tee</code> command lacked.)</p>\n\n<pre><code>#!/usr/bin/perl -w\nuse strict;\nuse IO::File;\n$| = 1;\nmy @fhs = map IO::File->new(\">$_\"), @ARGV;\nwhile (my $line = <STDIN>) {\n print $line;\n $_->print($line) for @fhs;\n}\n$_->close for @fhs;\n</code></pre>\n\n<p>You can call the script anything you want. I call it <code>perlmilktee</code>! :-P</p>\n"
},
{
"answer_id": 108370,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>tee seems to insist on waiting for the\n end of file before outputting anything\n to either stdout or the log file.</p>\n</blockquote>\n\n<p>This should definitely not be happening - it would render tee nearly useless. Here's a simple test that I wrote that puts this to the test, and it's definitely not waiting for eof. </p>\n\n<pre><code>$ cat test\n#!/bin/sh\necho \"hello\"\nsleep 5\necho \"goodbye\"\n\n$ ./test | tee test.log\nhello\n<pause>\ngoodbye\n</code></pre>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
]
| I'd like to log the output of a command to `stdout` as well as to a log file. I've got Cygwin installed and I'm trying to use the `tee` command to accomplish this.
```
devenv mysolution.sln /build myproject "Release|Win32" | tee build.log
```
Trouble is that `tee` seems to insist on waiting for the end of file before outputting anything to either `stdout` or the log file. This takes away the point of it all, which is to have a log file for future reference, but also some `stdout` logging so I can easily see the build progress.
`tee`'s options appear to be limited to `--append`, `--ignore-interrupts`, `--help`, and `--version`. So is there another method to get to what I'm trying to do? | >
> tee seems to insist on waiting for the
> end of file before outputting anything
> to either stdout or the log file.
>
>
>
This should definitely not be happening - it would render tee nearly useless. Here's a simple test that I wrote that puts this to the test, and it's definitely not waiting for eof.
```
$ cat test
#!/bin/sh
echo "hello"
sleep 5
echo "goodbye"
$ ./test | tee test.log
hello
<pause>
goodbye
``` |
106,622 | <p>I'm trying to run the Tomcat with JBoss Embedded jpa booking example. I run the build and deploy the war. I then get the following error:</p>
<pre>
ERROR [catalina.core.ContainerBase.[Catalina].[localhost].[/jboss-seam-jpa]] Error configuring application listener of class com.sun.faces.config.ConfigureListener
java.lang.NoClassDefFoundError: javax/el/CompositeELResolver
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3618)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4104
</pre>
<p>I find this class exists in el-api.jar which is not in the classpath. So I add el-api.jar to the WEB-INF/lib directory. I then get the following error:</p>
<pre>
INFO: JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed.
Sep 19, 2008 5:37:50 PM com.sun.faces.config.ConfigureListener installExpressionFactory
SEVERE: Error Instantiating ExpressionFactory
java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at com.sun.faces.config.ConfigureListener.installExpressionFactory(ConfigureListener.java:1521)
</pre>
<p>This library appears to be in el-ri.jar or JSP 2.1 jar. Am I doing something wrong? Is there a place that explains how to run seam applications on tomcat 5.5.x? Any help is greatly appreciated!</p>
| [
{
"answer_id": 107003,
"author": "user17163",
"author_id": 17163,
"author_profile": "https://Stackoverflow.com/users/17163",
"pm_score": 0,
"selected": false,
"text": "<p>have you looked at the docs, there's also some pretty good info on the forums at www.seamframework.org and also the old forums at www.jboss.org.</p>\n"
},
{
"answer_id": 122155,
"author": "Joe Dean",
"author_id": 5917,
"author_profile": "https://Stackoverflow.com/users/5917",
"pm_score": 2,
"selected": true,
"text": "<p>I got this to work. I ran ant tomcat55 under the seam/examples/jpa example. This included the el-<em>.jars needed. I then ran 'ant clean' and 'ant jboss-embeded' and manually copied in all of the el-</em>.jars from the tomcat55 make. This got past my problem above. Now I'm able to start tomcat 5.5.9 with embedded JBoss. I can run the booking example now with no problems. </p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917/"
]
| I'm trying to run the Tomcat with JBoss Embedded jpa booking example. I run the build and deploy the war. I then get the following error:
```
ERROR [catalina.core.ContainerBase.[Catalina].[localhost].[/jboss-seam-jpa]] Error configuring application listener of class com.sun.faces.config.ConfigureListener
java.lang.NoClassDefFoundError: javax/el/CompositeELResolver
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3618)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4104
```
I find this class exists in el-api.jar which is not in the classpath. So I add el-api.jar to the WEB-INF/lib directory. I then get the following error:
```
INFO: JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed.
Sep 19, 2008 5:37:50 PM com.sun.faces.config.ConfigureListener installExpressionFactory
SEVERE: Error Instantiating ExpressionFactory
java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at com.sun.faces.config.ConfigureListener.installExpressionFactory(ConfigureListener.java:1521)
```
This library appears to be in el-ri.jar or JSP 2.1 jar. Am I doing something wrong? Is there a place that explains how to run seam applications on tomcat 5.5.x? Any help is greatly appreciated! | I got this to work. I ran ant tomcat55 under the seam/examples/jpa example. This included the el-*.jars needed. I then ran 'ant clean' and 'ant jboss-embeded' and manually copied in all of the el-*.jars from the tomcat55 make. This got past my problem above. Now I'm able to start tomcat 5.5.9 with embedded JBoss. I can run the booking example now with no problems. |
106,630 | <p>I start by creating a string variable with some <strong>non-ascii</strong> <em>utf-8</em> encoded data on it:</p>
<pre><code>>>> text = 'á'
>>> text
'\xc3\xa1'
>>> text.decode('utf-8')
u'\xe1'
</code></pre>
<p>Using <code>unicode()</code> on it raises errors...</p>
<pre><code>>>> unicode(text)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
</code></pre>
<p>...but if I know the encoding I can use it as second parameter:</p>
<pre><code>>>> unicode(text, 'utf-8')
u'\xe1'
>>> unicode(text, 'utf-8') == text.decode('utf-8')
True
</code></pre>
<p>Now if I have a class that returns this text in the <code>__str__()</code> method:</p>
<pre><code>>>> class ReturnsEncoded(object):
... def __str__(self):
... return text
...
>>> r = ReturnsEncoded()
>>> str(r)
'\xc3\xa1'
</code></pre>
<p><code>unicode(r)</code> seems to use <code>str()</code> on it, since it raises the same error as <code>unicode(text)</code> above:</p>
<pre><code>>>> unicode(r)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
</code></pre>
<p>Until now everything is as planned!</p>
<p><strong>But as no one would ever expect, <code>unicode(r, 'utf-8')</code> won't even try:</strong></p>
<pre><code>>>> unicode(r, 'utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, ReturnsEncoded found
</code></pre>
<p>Why? Why this inconsistent behavior? Is it a bug? is it intended? Very awkward.</p>
| [
{
"answer_id": 106640,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p><code>unicode</code> does not guess the encoding of your text. If your object can print itself as <code>unicode</code>, define the <code>__unicode__()</code> method that returns a Unicode string.</p>\n\n<hr>\n\n<p>The secret is that <code>unicode(r)</code> is not actually calling <code>__str__()</code> itself. Instead, it's looking for a <code>__unicode__()</code> method. The default implementation of <code>__unicode__()</code> will call <code>__str__()</code> and then attempt to decode it using the <code>ascii</code> charset. When you pass the encoding, <code>unicode()</code> expects the first object to be something that can be decoded -- that is, an instance of <code>basestring</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>Behavior is weird because it tries to decode as ascii if I don't pass 'utf-8'. But if I pass 'utf-8' it gives a different error...</p>\n</blockquote>\n\n<p>That's because when you specify \"utf-8\", it treats the first parameter as a string-like object to be decoded. Without it, it treats the parameter as an object to be coerced to unicode.</p>\n\n<p>I do not understand the confusion. If you know that the object's <code>text</code> attribute will always be UTF-8 encoded, just define <code>__unicode__()</code> and then everything will work fine.</p>\n"
},
{
"answer_id": 106709,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": true,
"text": "<p>The behaviour does seem confusing, but intensional. I reproduce here the entirety of the unicode documentation from the <a href=\"http://docs.python.org/lib/built-in-funcs.html\" rel=\"noreferrer\">Python Built-In Functions documentation</a> (for version 2.5.2, as I write this):</p>\n\n<blockquote>\n <p><strong>unicode([object[, encoding [, errors]]])</strong></p>\n \n <p>Return the Unicode string version of object using one of the following modes:</p>\n \n <p>If encoding and/or errors are given, unicode() will decode the\n object which can either be an 8-bit string or a character buffer\n using the codec for encoding. The encoding parameter is a string\n giving the name of an encoding; if the encoding is not known,\n LookupError is raised. Error handling is done according to\n errors; this specifies the treatment of characters which are\n invalid in the input encoding. If errors is 'strict' (the\n default), a ValueError is raised on errors, while a value of\n 'ignore' causes errors to be silently ignored, and a value of\n 'replace' causes the official Unicode replacement character,\n U+FFFD, to be used to replace input characters which cannot be\n decoded. See also the <a href=\"http://docs.python.org/lib/module-codecs.html\" rel=\"noreferrer\">codecs</a> module.</p>\n \n <p>If no optional parameters are given, unicode() will mimic the\n behaviour of str() except that it returns Unicode strings\n instead of 8-bit strings. More precisely, if object is a Unicode\n string or subclass it will return that Unicode string without\n any additional decoding applied.</p>\n \n <p>For objects which provide a __unicode__() method, it will call\n this method without arguments to create a Unicode string. For\n all other objects, the 8-bit string version or representation is\n requested and then converted to a Unicode string using the codec\n for the default encoding in 'strict' mode.</p>\n \n <p>New in version 2.0. Changed in version 2.2: Support for __unicode__() added. </p>\n</blockquote>\n\n<p>So, when you call <code>unicode(r, 'utf-8')</code>, it requires an 8-bit string or a character buffer as the first argument, so it coerces your object using the <code>__str__()</code> method, and attempts to decode that using the <code>utf-8</code> codec. Without the <code>utf-8</code>, the <code>unicode()</code> function looks for a for a <code>__unicode__()</code> method on your object, and not finding it, calls the <code>__str__()</code> method, as you suggested, attempting to use the default codec to convert to unicode.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17160/"
]
| I start by creating a string variable with some **non-ascii** *utf-8* encoded data on it:
```
>>> text = 'á'
>>> text
'\xc3\xa1'
>>> text.decode('utf-8')
u'\xe1'
```
Using `unicode()` on it raises errors...
```
>>> unicode(text)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
```
...but if I know the encoding I can use it as second parameter:
```
>>> unicode(text, 'utf-8')
u'\xe1'
>>> unicode(text, 'utf-8') == text.decode('utf-8')
True
```
Now if I have a class that returns this text in the `__str__()` method:
```
>>> class ReturnsEncoded(object):
... def __str__(self):
... return text
...
>>> r = ReturnsEncoded()
>>> str(r)
'\xc3\xa1'
```
`unicode(r)` seems to use `str()` on it, since it raises the same error as `unicode(text)` above:
```
>>> unicode(r)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
```
Until now everything is as planned!
**But as no one would ever expect, `unicode(r, 'utf-8')` won't even try:**
```
>>> unicode(r, 'utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, ReturnsEncoded found
```
Why? Why this inconsistent behavior? Is it a bug? is it intended? Very awkward. | The behaviour does seem confusing, but intensional. I reproduce here the entirety of the unicode documentation from the [Python Built-In Functions documentation](http://docs.python.org/lib/built-in-funcs.html) (for version 2.5.2, as I write this):
>
> **unicode([object[, encoding [, errors]]])**
>
>
> Return the Unicode string version of object using one of the following modes:
>
>
> If encoding and/or errors are given, unicode() will decode the
> object which can either be an 8-bit string or a character buffer
> using the codec for encoding. The encoding parameter is a string
> giving the name of an encoding; if the encoding is not known,
> LookupError is raised. Error handling is done according to
> errors; this specifies the treatment of characters which are
> invalid in the input encoding. If errors is 'strict' (the
> default), a ValueError is raised on errors, while a value of
> 'ignore' causes errors to be silently ignored, and a value of
> 'replace' causes the official Unicode replacement character,
> U+FFFD, to be used to replace input characters which cannot be
> decoded. See also the [codecs](http://docs.python.org/lib/module-codecs.html) module.
>
>
> If no optional parameters are given, unicode() will mimic the
> behaviour of str() except that it returns Unicode strings
> instead of 8-bit strings. More precisely, if object is a Unicode
> string or subclass it will return that Unicode string without
> any additional decoding applied.
>
>
> For objects which provide a \_\_unicode\_\_() method, it will call
> this method without arguments to create a Unicode string. For
> all other objects, the 8-bit string version or representation is
> requested and then converted to a Unicode string using the codec
> for the default encoding in 'strict' mode.
>
>
> New in version 2.0. Changed in version 2.2: Support for \_\_unicode\_\_() added.
>
>
>
So, when you call `unicode(r, 'utf-8')`, it requires an 8-bit string or a character buffer as the first argument, so it coerces your object using the `__str__()` method, and attempts to decode that using the `utf-8` codec. Without the `utf-8`, the `unicode()` function looks for a for a `__unicode__()` method on your object, and not finding it, calls the `__str__()` method, as you suggested, attempting to use the default codec to convert to unicode. |
106,646 | <p>I am looking for a CSS-based web page template where the main content <code>div</code> occupies the full height of the view port (minus header and footer heights) when its content has few lines. The footer should be at the bottom of the viewport, rather than right below content, where it's more in the middle of the viewport. Content area needs to expand vertically to be joined with the top of footer.</p>
<p>If the content requires more space than the viewport, then footer can be at the bottom of the web page (instead of the bottom of view-port) as standard web design. </p>
<p>A link to a specific link or sample code appreciated. Don't mention a template site and tell me to do a search there. Must work at least in IE 6 and FF. If JavaScript is required, it's OK as long as if browser doesn't support JS, it defaults to putting the footer at the bottom of the content area without breaking the layout.</p>
<p>Sketch for case #1:</p>
<pre><code>-------------- <-----
header area | |
-------------| |
small content| |
| view-port
| |
| |
-------------| |
footer area | |
-------------- <-----
all other cases:
-------------- <-----
header area | |
-------------| |
big content | |
| view-port
| |
| |
| |
| |
| <----
|
-------------|
footer area |
--------------
</code></pre>
| [
{
"answer_id": 106689,
"author": "Ross Martin",
"author_id": 19433,
"author_profile": "https://Stackoverflow.com/users/19433",
"pm_score": 3,
"selected": true,
"text": "<p>Example here:\n<a href=\"http://www.rossdmartin.com/aitp/index.htm\" rel=\"nofollow noreferrer\">http://www.rossdmartin.com/aitp/index.htm</a></p>\n\n<p>More in-depth resources:</p>\n\n<ul>\n<li><a href=\"http://www.themaninblue.com/experiment/footerStickAlt/\" rel=\"nofollow noreferrer\">http://www.themaninblue.com/experiment/footerStickAlt/</a></li>\n<li><a href=\"http://ryanfait.com/sticky-footer/\" rel=\"nofollow noreferrer\">http://ryanfait.com/sticky-footer/</a></li>\n</ul>\n"
},
{
"answer_id": 106704,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p>Look for \"Footer Stick Alt\"... there was a long blog write up on how to make this work.</p>\n\n<p><a href=\"http://www.themaninblue.com/writing/perspective/2005/08/29/\" rel=\"nofollow noreferrer\">Done by Cameron Adams a.k.a. \"The Man in Blue\"</a>.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
]
| I am looking for a CSS-based web page template where the main content `div` occupies the full height of the view port (minus header and footer heights) when its content has few lines. The footer should be at the bottom of the viewport, rather than right below content, where it's more in the middle of the viewport. Content area needs to expand vertically to be joined with the top of footer.
If the content requires more space than the viewport, then footer can be at the bottom of the web page (instead of the bottom of view-port) as standard web design.
A link to a specific link or sample code appreciated. Don't mention a template site and tell me to do a search there. Must work at least in IE 6 and FF. If JavaScript is required, it's OK as long as if browser doesn't support JS, it defaults to putting the footer at the bottom of the content area without breaking the layout.
Sketch for case #1:
```
-------------- <-----
header area | |
-------------| |
small content| |
| view-port
| |
| |
-------------| |
footer area | |
-------------- <-----
all other cases:
-------------- <-----
header area | |
-------------| |
big content | |
| view-port
| |
| |
| |
| |
| <----
|
-------------|
footer area |
--------------
``` | Example here:
<http://www.rossdmartin.com/aitp/index.htm>
More in-depth resources:
* <http://www.themaninblue.com/experiment/footerStickAlt/>
* <http://ryanfait.com/sticky-footer/> |
106,711 | <p>Here's a simplified version of what I'm trying to do :</p>
<ol>
<li>Before any other actions are performed, present the user with a form to retrieve a string.</li>
<li>Input the string, and then redirect to the default controller action (e.g. index). The string only needs to exist, no other validations are necessary.</li>
<li>The string must be available (as an instance variable?) to all the actions in this controller.</li>
</ol>
<p>I'm very new with Rails, but this doesn't seem like it ought to be exceedingly hard, so I'm feeling kind of dumb.</p>
<p>What I've tried :
I have a <code>before_filter</code> redirecting to a private method that looks like</p>
<pre><code>def check_string
if @string
return true
else
get_string
end
end
</code></pre>
<p>the <code>get_string</code> method looks like </p>
<pre><code>def get_string
if params[:string]
respond_to do |format|
format.html {redirect_to(accounts_url)} # authenticate.html.erb
end
end
respond_to do |format|
format.html {render :action =>"get_string"} # get_string.html.erb
end
end
</code></pre>
<p>This fails because i have two render or redirect calls in the same action. I can take out that first <code>respond_to</code>, of course, but what happens is that the controller gets trapped in the <code>get_string</code> method. I can more or less see why that's happening, but I don't know how to fix it and break out. I need to be able to show one form (View), get and then do something with the input string, and then proceed as normal.</p>
<p>The <code>get_string.html.erb</code> file looks like </p>
<pre><code><h1>Enter a string</h1>
<% form_tag('/accounts/get_string') do %>
<%= password_field_tag(:string, params[:string])%>
<%= submit_tag('Ok')%>
<% end %>
</code></pre>
<p>I'll be thankful for any help!</p>
<h2>EDIT</h2>
<p>Thanks for the replies...<br>
@Laurie Young : You are right, I was misunderstanding. For some reason I had it in my head that the instance of any given controller invoked by a user would persist throughout their session, and that some of the Rails magic was in tracking objects associated with each user session. I can see why that doesn't make a whole lot of sense in retrospect, and why my attempt to use an instance variable (which I'd thought would persist) won't work. Thanks to you as well :)</p>
| [
{
"answer_id": 106757,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 3,
"selected": true,
"text": "<p>Part of the problem is that you aren't setting @string. You don't really need the before_filter for this at all, and should just be able to use:</p>\n\n<pre><code>def get_string\n @string = params[:string] || session[:string] \n respond_to do |format|\n if @string \n format.html {redirect_to(accounts_url)} # authenticate.html.erb\n else \n format.html {render :action =>\"get_string\"} # get_string.html.erb\n end\n end\nend\n</code></pre>\n\n<p>If you want the @string variable to be available for all actions, you will need to store it in the session.</p>\n"
},
{
"answer_id": 108563,
"author": "Laurie Young",
"author_id": 7473,
"author_profile": "https://Stackoverflow.com/users/7473",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like me like your missing a rails concept. Every single page the user sees is a different request. </p>\n\n<p>I might have missunderstood what you are trying to do. But it seems to me you want the user to see two pages, </p>\n\n<ol>\n<li>In the first page they set a string variable </li>\n<li>In the second page they see a page that is somehow dependent on the variable set </li>\n</ol>\n\n<p>The best way to do this would be to have to a before filter that checks for the existance of the varibale, and if its not set, redirects to them to the form, and otherwise continues</p>\n\n<pre><code>class MyController < ApplicationController::Base\n before_filter :require_string\n\n def require_string\n return true if @string #return early if called multiple times in one request\n if params['string'] or session['string'] #depending on if you set it as a URL or session var\n @string = (params['string'] or session['string'])\n return true\n end\n\n #We now know that string is not set\n redirect_to string_setting_url and return false #the return false prevents any futher processing in this request\n end\nend\n</code></pre>\n\n<p>This is the basic idea behind how plugins like RestfulAuthentication work. In that case \"string\" is a login token (the user ID i think), is is stored in the session. </p>\n\n<p>If you take a look at the <code>login_required' action in</code>authenticated_system.rb` from ResultfulAuth: it does basically this, though it has a few more error corrections, other stuff added in</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17046/"
]
| Here's a simplified version of what I'm trying to do :
1. Before any other actions are performed, present the user with a form to retrieve a string.
2. Input the string, and then redirect to the default controller action (e.g. index). The string only needs to exist, no other validations are necessary.
3. The string must be available (as an instance variable?) to all the actions in this controller.
I'm very new with Rails, but this doesn't seem like it ought to be exceedingly hard, so I'm feeling kind of dumb.
What I've tried :
I have a `before_filter` redirecting to a private method that looks like
```
def check_string
if @string
return true
else
get_string
end
end
```
the `get_string` method looks like
```
def get_string
if params[:string]
respond_to do |format|
format.html {redirect_to(accounts_url)} # authenticate.html.erb
end
end
respond_to do |format|
format.html {render :action =>"get_string"} # get_string.html.erb
end
end
```
This fails because i have two render or redirect calls in the same action. I can take out that first `respond_to`, of course, but what happens is that the controller gets trapped in the `get_string` method. I can more or less see why that's happening, but I don't know how to fix it and break out. I need to be able to show one form (View), get and then do something with the input string, and then proceed as normal.
The `get_string.html.erb` file looks like
```
<h1>Enter a string</h1>
<% form_tag('/accounts/get_string') do %>
<%= password_field_tag(:string, params[:string])%>
<%= submit_tag('Ok')%>
<% end %>
```
I'll be thankful for any help!
EDIT
----
Thanks for the replies...
@Laurie Young : You are right, I was misunderstanding. For some reason I had it in my head that the instance of any given controller invoked by a user would persist throughout their session, and that some of the Rails magic was in tracking objects associated with each user session. I can see why that doesn't make a whole lot of sense in retrospect, and why my attempt to use an instance variable (which I'd thought would persist) won't work. Thanks to you as well :) | Part of the problem is that you aren't setting @string. You don't really need the before\_filter for this at all, and should just be able to use:
```
def get_string
@string = params[:string] || session[:string]
respond_to do |format|
if @string
format.html {redirect_to(accounts_url)} # authenticate.html.erb
else
format.html {render :action =>"get_string"} # get_string.html.erb
end
end
end
```
If you want the @string variable to be available for all actions, you will need to store it in the session. |
106,712 | <p>I have a VB.NET Windows Forms project that at one point paints text directly to onto the form at runtime. Before I paint with the font though, I want to make sure that the font and font-size exists on the user's machine. If they don't, I'll try a few other similar fonts, eventually defaulting with Arial or something.</p>
<p>What's the best way to test and validate a font on a user's computer?</p>
| [
{
"answer_id": 106724,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": true,
"text": "<p>From an MSDN article titled \"How To: Enumerate Installed Fonts\", I found this code:</p>\n\n<pre>\n<code>\n\nInstalledFontCollection installedFontCollection = new InstalledFontCollection();\n\n// Get the array of FontFamily objects.\nFontFamily[] fontFamilies = installedFontCollection.Families;\n\n</code>\n</pre>\n"
},
{
"answer_id": 106728,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 2,
"selected": false,
"text": "<p>Here is one solution, in c#:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n SetFontFinal();\n InitializeComponent();\n }\n\n /// <summary>\n /// This method attempts to set the font in the form to Cambria, which\n /// will only work in some scenarios. If Cambria is not available, it will\n /// fall back to Times New Roman, so the font is good on almost all systems.\n /// </summary>\n private void SetFontFinal()\n {\n string fontName = \"Cambria\";\n Font testFont = new Font(fontName, 16.0f, FontStyle.Regular,\n GraphicsUnit.Pixel);\n\n if (testFont.Name == fontName)\n {\n // The font exists, so use it.\n this.Font = testFont;\n }\n else\n {\n // The font we tested doesn't exist, so fallback to Times.\n this.Font = new Font(\"Times New Roman\", 16.0f,\n FontStyle.Regular, GraphicsUnit.Pixel);\n }\n }\n}\n</code></pre>\n\n<p>And here is one method in VB:</p>\n\n<pre><code>Public Function FontExists(FontName As String) As Boolean\n\n Dim oFont As New StdFont\n Dim bAns As Boolean\n\n oFont.Name = FontName\n bAns = StrComp(FontName, oFont.Name, vbTextCompare) = 0\n FontExists = bAns\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 253741,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 1,
"selected": false,
"text": "<p>See also this <a href=\"https://stackoverflow.com/questions/113989/test-if-a-font-is-installed\">same question</a> that results in this code:</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": 3868486,
"author": "panoone",
"author_id": 259776,
"author_profile": "https://Stackoverflow.com/users/259776",
"pm_score": 0,
"selected": false,
"text": "<p>Arial Bold Italic is unlikely to be a font. It's a subclass of the Arial family.</p>\n\n<p>Try keeping it simple and test for 'Arial'.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
]
| I have a VB.NET Windows Forms project that at one point paints text directly to onto the form at runtime. Before I paint with the font though, I want to make sure that the font and font-size exists on the user's machine. If they don't, I'll try a few other similar fonts, eventually defaulting with Arial or something.
What's the best way to test and validate a font on a user's computer? | From an MSDN article titled "How To: Enumerate Installed Fonts", I found this code:
```
InstalledFontCollection installedFontCollection = new InstalledFontCollection();
// Get the array of FontFamily objects.
FontFamily[] fontFamilies = installedFontCollection.Families;
``` |
106,800 | <p>Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example):</p>
<ul>
<li>Should tests be in the same project as application logic?</li>
<li>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</li>
<li>How should I name my test classes, methods, and projects (if they go in different projects)</li>
<li>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</li>
<li>Should unit and integration tests be separated?</li>
<li>Is there a <strong>good</strong> reason not to have 100% test coverage?</li>
</ul>
<p>What am I not asking about that I should be?</p>
<p>An online resource would be best.</p>
| [
{
"answer_id": 106806,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>I insistently recommend you to read <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321146530\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Test Driven Development: By Example</a> and <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131016490\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Test-Driven Development: A Practical Guide</a> It's too much questions for single topic</p>\n"
},
{
"answer_id": 106813,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 5,
"selected": true,
"text": "<p>I would recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321146530\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Kent Beck's</a> book on TDD.</p>\n\n<p>Also, you need to go to <a href=\"http://martinfowler.com/articles/mocksArentStubs.html\" rel=\"noreferrer\">Martin Fowler's</a> site. He has a lot of good information about testing as well.</p>\n\n<p>We are pretty big on TDD so I will answer the questions in that light.</p>\n\n<blockquote>\n <p>Should tests be in the same project as application logic?</p>\n</blockquote>\n\n<p>Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests</p>\n\n<blockquote>\n <p>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</p>\n</blockquote>\n\n<p>Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution.</p>\n\n<blockquote>\n <p>How should I name my test classes, methods, and projects (if they go in different projects)</p>\n</blockquote>\n\n<p>I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so:</p>\n\n<pre><code>public class UserBehavior\n</code></pre>\n\n<p>Methods should be named to describe the behavior that you expect.</p>\n\n<pre><code>public void ShouldBeAbleToSetUserFirstName()\n</code></pre>\n\n<p>Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization.</p>\n\n<blockquote>\n <p>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</p>\n</blockquote>\n\n<p>Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change.</p>\n\n<blockquote>\n <p>Should unit and integration tests be separated?</p>\n</blockquote>\n\n<p>Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well.</p>\n\n<blockquote>\n <p>Is there a good reason not to have 100% test coverage?</p>\n</blockquote>\n\n<p>I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point.</p>\n\n<p>In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well.</p>\n"
},
{
"answer_id": 106821,
"author": "Tom Carr",
"author_id": 14954,
"author_profile": "https://Stackoverflow.com/users/14954",
"pm_score": 2,
"selected": false,
"text": "<p>It's a good question. We grew our own organically, and I suspect the best way is just that. There's a bit \"It depends...\" in there.</p>\n\n<p>We put out tests in the same project, in a sub-namespace called \"UnitTes\"</p>\n\n<p>Our test classes mirror the logic class, in order to simplify keeping track of where the tests are in relation to what they are testing</p>\n\n<p>Classes are named like the logic class they are testing, methods are named for the scenario they are testing.</p>\n\n<p>We only write tests for the public and internal methods (test are in the same project), and aim for 95% coverage of the class.</p>\n\n<p>I prefer not to distinguish between \"unit\" and \"intergation\". To much time will be spent trying to figure out which is which...bag that! A test is a test.</p>\n\n<p>100% is too difficult to achieve all the time. We aim for 95%. There's also diminishing returns on how much time it will take to get that final 5% and what it will actually catch.</p>\n\n<p>That's us and what suited out environment and pace. You're milage may vary. Think about your envivonment nad the personalities that are involved. </p>\n\n<p>I look forward to seeing what others have to say on this one!</p>\n"
},
{
"answer_id": 106822,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 1,
"selected": false,
"text": "<p>In order:</p>\n\n<ul>\n<li>No, it's usually best to include them in a seperate project; unless you want to be able to run diagnostics at runtime.</li>\n<li>The ideal is 100% code coverage, which means every line of code in every routine in every class.</li>\n<li>I go with ClassnameTest, ClassnameTest.MethodNameTestnumber</li>\n<li>Everything.</li>\n<li>I'd say yes, as integration tests don't need to be run if unit tests fail.</li>\n<li>Simple properties that just set and get a field don't need to be tested.</li>\n</ul>\n"
},
{
"answer_id": 106827,
"author": "Fhoxh",
"author_id": 14785,
"author_profile": "https://Stackoverflow.com/users/14785",
"pm_score": 1,
"selected": false,
"text": "<p>With respect to your last question, in my experience, the \"good\" reason for not insisting upon 100% test coverage is that it takes a disproportionate amount of effort to get the last few percentage points, particularly in larger code bases. As such, it's a matter of deciding whether or not it's worth your time once you reach that point of diminishing returns.</p>\n"
},
{
"answer_id": 107452,
"author": "aridlehoover",
"author_id": 19317,
"author_profile": "https://Stackoverflow.com/users/19317",
"pm_score": 2,
"selected": false,
"text": "<p>Josh's answer is right on - just one point of clarification:</p>\n\n<p>The reason I separate unit tests from integration and acceptance tests is speed. I use TDD. I need close to instant feedback about the line of code I just created/modified. I cannot get that if I'm running full suites of integration and/or acceptance tests - tests that hit real disks, real networks, and really slow and unpredictable external systems.</p>\n\n<p>Don't cross the beams. Bad things will happen if you do.</p>\n"
},
{
"answer_id": 143888,
"author": "spiv",
"author_id": 22701,
"author_profile": "https://Stackoverflow.com/users/22701",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Should tests be in the same project as application logic?</strong></p>\n\n<p>It depends. There are trade-offs either way.</p>\n\n<p>Keeping it in one project requires extra bandwidth to distribute your project, extra build time and increases the installation footprint, and makes it easier to make the mistake of having production logic that depends on test code.</p>\n\n<p>On the other hand, keeping separate projects can make it harder to write tests involving private methods/classes (depending on programming language), and causes minor administration hassles, such as making setting up a new development environment (e.g. when a new developer joins the project) harder.</p>\n\n<p>How much these different costs matter varies by project, so there's no universal answer.</p>\n\n<p><strong>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</strong></p>\n\n<p>No.</p>\n\n<p>You should have test classes that allow for well-factored test code (i.e. minimal duplication, clear intent, etc).</p>\n\n<p>The obvious advantage of directly mirroring the logic classes in your test classes is that it makes it easy to find the tests corresponding to a particular piece of code. There are other ways solve this problem without restricting the flexibility of the test code. Simple naming conventions for test modules and classes is usually enough.</p>\n\n<p><strong>How should I name my test classes, methods, and projects (if they go in different projects)</strong></p>\n\n<p>You should name them so that:</p>\n\n<ul>\n<li>each test class and test method has a clear purpose, and</li>\n<li>so that someone looking for a particular test (or for tests about a particular unit) can find it easily.</li>\n</ul>\n\n<p><strong>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</strong></p>\n\n<p>Often non-public methods should be tested. It depends on if you get enough confidence from just testing the public interface, or if the unit you really want to be testing is not publically accessible.</p>\n\n<p><strong>Should unit and integration tests be separated?</strong></p>\n\n<p>This depends on your choice of testing framework(s). Do whichever works best with your testing framework(s) and makes it so that:</p>\n\n<ul>\n<li>both the unit and integration tests relating to a piece of code are easy to find,</li>\n<li>it is easy to run just the unit tests,</li>\n<li>it is easy to run just the integration tests,</li>\n<li>it is easy to run all tests.</li>\n</ul>\n\n<p><strong>Is there a good reason not to have 100% test coverage?</strong></p>\n\n<p>Yes, there is a good reason. Strictly speaking “100% test coverage” means every possible situation in your code is exercised and tested. This is simply impractical for almost any project to achieve.</p>\n\n<p>If you simply take “100% test coverage” to mean that every line of source code is exercised by the test suite at some point, then this is a good goal, but sometimes there are just a couple of lines in awkward places that are hard to reach with automated tests. If the cost of manually verifying that functionality periodically is less than the cost of going through contortions to reach those last five lines, then that is a good reason not to have 100% line coverage.</p>\n\n<p>Rather than a simple rule that you should have 100% line coverage, encourage your developers to discover <em>any</em> gaps in your testing, and find ways to fix those gaps, whether or the number of lines “covered” improves. In other words, if you measure lines covered, then you will improve your line coverge — but what you actually want is improved quality. So don't forget that line coverage is just a very crude approximation of quality.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19421/"
]
| Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example):
* Should tests be in the same project as application logic?
* Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?
* How should I name my test classes, methods, and projects (if they go in different projects)
* Should private, protected, and internal methods be tested, or just those that are publicly accessible?
* Should unit and integration tests be separated?
* Is there a **good** reason not to have 100% test coverage?
What am I not asking about that I should be?
An online resource would be best. | I would recommend [Kent Beck's](https://rads.stackoverflow.com/amzn/click/com/0321146530) book on TDD.
Also, you need to go to [Martin Fowler's](http://martinfowler.com/articles/mocksArentStubs.html) site. He has a lot of good information about testing as well.
We are pretty big on TDD so I will answer the questions in that light.
>
> Should tests be in the same project as application logic?
>
>
>
Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests
>
> Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?
>
>
>
Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution.
>
> How should I name my test classes, methods, and projects (if they go in different projects)
>
>
>
I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so:
```
public class UserBehavior
```
Methods should be named to describe the behavior that you expect.
```
public void ShouldBeAbleToSetUserFirstName()
```
Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization.
>
> Should private, protected, and internal methods be tested, or just those that are publicly accessible?
>
>
>
Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change.
>
> Should unit and integration tests be separated?
>
>
>
Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well.
>
> Is there a good reason not to have 100% test coverage?
>
>
>
I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point.
In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well. |
106,828 | <p>I need to display a bunch of images on a web page using AJAX. All of them have different dimensions, so I want to adjust their size before displaying them. Is there any way to do this in JavaScript?</p>
<p>Using PHP's <code>getimagesize()</code> for each image causes an unnecessary performance hit since there will be many images.</p>
| [
{
"answer_id": 106833,
"author": "Dori",
"author_id": 10936,
"author_profile": "https://Stackoverflow.com/users/10936",
"pm_score": 0,
"selected": false,
"text": "<p>Do you want to adjust the images themselves, or just the way they display? If the former, you want something on the server side. If the latter, you just need to change image.height and image.width.</p>\n"
},
{
"answer_id": 106842,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": "<p>...but... wouldn't it be better to adjust the image size on the server side rather than transmitting the bytes to the browser and doing it there? </p>\n\n<p>When I say adjust the image size, I don't mean set the height and width in the HTML image tag. If you do that, you are still shipping a large number of bytes from server to client. I mean, actually manipulate the image itself server side.</p>\n\n<p>I have .NET C# code here that takes that approach, but there must be a php way to do it too: <a href=\"http://ifdefined.com/www/gallery.html\" rel=\"nofollow noreferrer\">http://ifdefined.com/www/gallery.html</a></p>\n\n<p>Also, by doing it server side, that opens up the possibility of doing the adjustment just once and then saving the adjusted image, which would be very fast.</p>\n"
},
{
"answer_id": 106843,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well...there are several ways to interpret this question.</p>\n\n<p>The first way and the way I think you mean is to simply alter the display size so all images display the same size. For this, I would actually use CSS and not JavaScript. Simply create a class that has the appropriate width and height values set, and make all <code><img></code> tags use this class.</p>\n\n<p>A second way is that you want to preserve the aspect ration of all the images, but scale the display size to a sane value. There is a way to access this in JavaScript, but I'll need a bit to write up a quick code sample.</p>\n\n<p>The third way, and I hope you don't mean this way, is to alter the actual size of the image. This is something you'd have to do on the server side, as not only is JavaScript unable to create images, but it wouldn't make any sense, as the full sized image has already been sent.</p>\n"
},
{
"answer_id": 106844,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 4,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>var curHeight;\nvar curWidth;\n\nfunction getImgSize(imgSrc)\n{\nvar newImg = new Image();\nnewImg.src = imgSrc;\ncurHeight = newImg.height;\ncurWidth = newImg.width;\n\n}\n</code></pre>\n"
},
{
"answer_id": 106861,
"author": "bhollis",
"author_id": 11284,
"author_profile": "https://Stackoverflow.com/users/11284",
"pm_score": 0,
"selected": false,
"text": "<p>It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.</p>\n"
},
{
"answer_id": 110786,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<p>My preferred solution for this would be to do the resizing server-side, so you are transmitting less unnecessary data.</p>\n\n<p>If you have to do it client-side though, and need to keep the image ratio, you could use the below:</p>\n\n<pre><code>var image_from_ajax = new Image();\nimage_from_ajax.src = fetch_image_from_ajax(); // Downloaded via ajax call?\n\nimage_from_ajax = rescaleImage(image_from_ajax);\n\n// Rescale the given image to a max of max_height and max_width\nfunction rescaleImage(image_name)\n{\n var max_height = 100;\n var max_width = 100;\n\n var height = image_name.height;\n var width = image_name.width;\n var ratio = height/width;\n\n // If height or width are too large, they need to be scaled down\n // Multiply height and width by the same value to keep ratio constant\n if(height > max_height)\n {\n ratio = max_height / height;\n height = height * ratio;\n width = width * ratio;\n }\n\n if(width > max_width)\n {\n ratio = max_width / width;\n height = height * ratio;\n width = width * ratio;\n }\n\n image_name.width = width;\n image_name.height = height;\n return image_name;\n}\n</code></pre>\n"
},
{
"answer_id": 952185,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache.</p>\n\n<p>Finally I found a solution to get the image height and width even if the image does not exist in the browser cache:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n var imgHeight;\n var imgWidth;\n\n function findHHandWW() {\n imgHeight = this.height;\n imgWidth = this.width;\n return true;\n }\n\n function showImage(imgPath) {\n var myImage = new Image();\n myImage.name = imgPath;\n myImage.onload = findHHandWW;\n myImage.src = imgPath;\n }\n</script>\n</code></pre>\n\n<p>Thanks,</p>\n\n<p>Binod Suman</p>\n\n<p><a href=\"http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html\" rel=\"noreferrer\">http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html</a></p>\n"
},
{
"answer_id": 9718666,
"author": "Hoan Huynh",
"author_id": 1046168,
"author_profile": "https://Stackoverflow.com/users/1046168",
"pm_score": 2,
"selected": false,
"text": "<p>Try with JQuery:</p>\n\n<pre><code><script type=\"text/javascript\">\nfunction jquery_get_width_height()\n{\n var imgWidth = $(\"#img\").width();\n var imgHeight = $(\"#img\").height();\n alert(\"JQuery -- \" + \"imgWidth: \" + imgWidth + \" - imgHeight: \" + imgHeight);\n}\n</script>\n</code></pre>\n\n<p>or</p>\n\n<pre><code><script type=\"text/javascript\">\nfunction javascript_get_width_height()\n{\n var img = document.getElementById('img');\n alert(\"JavaSript -- \" + \"imgWidth: \" + img.width + \" - imgHeight: \" + img.height);\n}\n</script>\n</code></pre>\n"
},
{
"answer_id": 16193510,
"author": "Ray",
"author_id": 2209094,
"author_profile": "https://Stackoverflow.com/users/2209094",
"pm_score": 0,
"selected": false,
"text": "<p>Just load the image in a hidden <code><img></code> tag (<code>style = \"display none\"</code>), listen to the load event firing with jQuery, create a new <code>Image()</code> with JavaScript, set the source to the invisible image, and get the size like above.</p>\n"
},
{
"answer_id": 56649435,
"author": "moto",
"author_id": 7435898,
"author_profile": "https://Stackoverflow.com/users/7435898",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>img.naturalWidth</code> and <code>img.naturalHeight</code> to get real dimension of image in pixels</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I need to display a bunch of images on a web page using AJAX. All of them have different dimensions, so I want to adjust their size before displaying them. Is there any way to do this in JavaScript?
Using PHP's `getimagesize()` for each image causes an unnecessary performance hit since there will be many images. | I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache.
Finally I found a solution to get the image height and width even if the image does not exist in the browser cache:
```
<script type="text/javascript">
var imgHeight;
var imgWidth;
function findHHandWW() {
imgHeight = this.height;
imgWidth = this.width;
return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
}
</script>
```
Thanks,
Binod Suman
<http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html> |
106,880 | <p>I am trying to use the <code>InternalsVisibleTo</code> assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reason, I keep getting an error message that says:</p>
<blockquote>
<p>'MyClassName' is inaccessible due to its protection level</p>
</blockquote>
<p>Both assemblies are signed and I have the correct key listed in the attribute declaration. Any ideas?</p>
| [
{
"answer_id": 106921,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 2,
"selected": false,
"text": "<p>You need to use the /out: compiler switch when compiling the friend assembly (the assembly that\ndoes not contain the InternalsVisibleTo attribute). </p>\n\n<p>The compiler needs to know the name of the assembly being compiled in order to determine if the resulting assembly should be considered a friend assembly. </p>\n"
},
{
"answer_id": 107958,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 8,
"selected": true,
"text": "<p>Are you absolutely sure you have the correct public key specified in the attribute?\nNote that you need to specify the full public key, not just the public key token. It looks something like:</p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"MyFriendAssembly,\nPublicKey=0024000004800000940000000602000000240000525341310004000001000100F73\nF4DDC11F0CA6209BC63EFCBBAC3DACB04B612E04FA07F01D919FB5A1579D20283DC12901C8B66\nA08FB8A9CB6A5E81989007B3AA43CD7442BED6D21F4D33FB590A46420FB75265C889D536A9519\n674440C3C2FB06C5924360243CACD4B641BE574C31A434CE845323395842FAAF106B234C2C140\n6E2F553073FF557D2DB6C5\")]\n</code></pre>\n\n<p>It's 320 or so hex digits. Not sure why you need to specify the full public key - possibly with just the public key token that is used in other assembly references it would be easier for someone to spoof the friend assembly's identity.</p>\n"
},
{
"answer_id": 770404,
"author": "Colin Desmond",
"author_id": 93399,
"author_profile": "https://Stackoverflow.com/users/93399",
"pm_score": 4,
"selected": false,
"text": "<p>It is worth noting that if the "friend" (tests) assembly is written in C++/CLI rather than C#/VB.NET, you need to use the following:</p>\n<pre><code>#using "AssemblyUnderTest.dll" as_friend\n</code></pre>\n<p>instead of a project reference or the usual <code>#using</code> statement. For some reason, there is no way to do this in the project reference UI.</p>\n"
},
{
"answer_id": 2799863,
"author": "Vadim",
"author_id": 82005,
"author_profile": "https://Stackoverflow.com/users/82005",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"http://vkreynin.wordpress.com/2007/12/09/testing-internals-members-with-internalsvisibleto-attribute/\" rel=\"nofollow noreferrer\">AssemblyHelper tool</a> that will generate InternalsVisibleTo syntax for you. Here's <a href=\"http://vkreynin.wordpress.com/2010/05/09/assemblyhelpers-now-works-net-4-assemblies/\" rel=\"nofollow noreferrer\">the link to the latest version</a>. Just note that it only works for strongly-named assemblies.</p>\n"
},
{
"answer_id": 3594856,
"author": "Skimedic",
"author_id": 365309,
"author_profile": "https://Stackoverflow.com/users/365309",
"pm_score": 5,
"selected": false,
"text": "<p>If your assemblies aren't signed, but you are still getting the same error, check your AssemblyInfo.cs file for either of the following lines:</p>\n\n<pre><code>[assembly: AssemblyKeyFile(\"\")]\n[assembly: AssemblyKeyName(\"\")]\n</code></pre>\n\n<p>The properties tab will still show your assembly as unsigned if either (or both) of these lines are present, but the InternalsVisibleTo attribute treats an assembly with these lines as strongly signed. Simply delete (or comment out) these lines, and it should work fine for you.</p>\n"
},
{
"answer_id": 9827552,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a macro I use to quickly generate this attribute. Its a bit hacky, but it works. On my machine. When the latest signed binary is in <code>/bin/debug</code>. Etc equivocation etc. Anyhow, you can see how it gets the key, so that'll give you a hint. Fix/improve as your time permits.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub GetInternalsVisibleToForCurrentProject()\n Dim temp = \"[assembly: global::System.Runtime.CompilerServices.\" + _\n \"InternalsVisibleTo(\"\"{0}, publickey={1}\"\")]\"\n Dim projs As System.Array\n Dim proj As Project\n projs = DTE.ActiveSolutionProjects()\n If projs.Length < 1 Then\n Return\n End If\n\n proj = CType(projs.GetValue(0), EnvDTE.Project)\n Dim path, dir, filename As String\n path = proj.FullName\n dir = System.IO.Path.GetDirectoryName(path)\n filename = System.IO.Path.GetFileNameWithoutExtension(path)\n filename = System.IO.Path.ChangeExtension(filename, \"dll\")\n dir += \"\\bin\\debug\\\"\n filename = System.IO.Path.Combine(dir, filename)\n If Not System.IO.File.Exists(filename) Then\n MsgBox(\"Cannot load file \" + filename)\n Return\n End If\n Dim assy As System.Reflection.Assembly\n assy = System.Reflection.Assembly.Load(filename)\n Dim pk As Byte() = assy.GetName().GetPublicKey()\n Dim hex As String = BitConverter.ToString(pk).Replace(\"-\", \"\")\n System.Windows.Forms.Clipboard.SetText(String.Format(temp, assy.GetName().Name, hex))\n MsgBox(\"InternalsVisibleTo attribute copied to the clipboard.\")\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 10339243,
"author": "Bill W",
"author_id": 2220591,
"author_profile": "https://Stackoverflow.com/users/2220591",
"pm_score": 0,
"selected": false,
"text": "<p>As a side note, if you want to easily get the public key without having to use sn and figure out its options you can download the handy program <a href=\"http://www.davidarno.org/2008/01/15/c-and-friend-assemblies-made-easy/\" rel=\"nofollow\">here</a>. It not only determines the public key but also creates the \"assembly: InternalsVisibleTo...\" line ready to be copied to the clipboard and pasted into your code.</p>\n"
},
{
"answer_id": 15085309,
"author": "Keysharpener",
"author_id": 1314858,
"author_profile": "https://Stackoverflow.com/users/1314858",
"pm_score": 0,
"selected": false,
"text": "<p>I just resolved a similar problem with the <code>InternalsVisibleTo</code> Attribute. Everything seemed right and I couldn't figure out why the internal class I was aiming still wasn't accessible.</p>\n\n<p>Changing the case of the key from upper to lower case fixed the problem. </p>\n"
},
{
"answer_id": 17887998,
"author": "John Beyer",
"author_id": 1575257,
"author_profile": "https://Stackoverflow.com/users/1575257",
"pm_score": 5,
"selected": false,
"text": "<p>Another possible \"gotcha\": The name of the friend assembly that you specify in the <code>InternalsVisibleToAttribute</code> must <strong>exactly</strong> match the name of your friend assembly as shown in the friend's project properties (in the Application tab).</p>\n\n<p>In my case, I had a project <code>Thingamajig</code> and a companion project <code>ThingamajigAutoTests</code> (names changed to protect the guilty) that both produced unsigned assemblies. I duly added the attribute <code>[assembly: InternalsVisibleTo( \"ThingamajigAutoTests\" )]</code> to the Thingamajig\\AssemblyInfo.cs file, and commented out the <code>AssemblyKeyFile</code> and <code>AssemblyKeyName</code> attributes as noted above. The <code>Thingamajig</code> project built just fine, but its internal members stubbornly refused to show up in the autotest project.</p>\n\n<p>After much head scratching, I rechecked the <code>ThingamajigAutoTests</code> project properties, and discovered that the assembly name was specified as \"ThingamajigAutoTests.dll\". Bingo - I added the \".dll\" extension to the assembly name in the <code>InternalsVisibleTo</code> attribute, and the pieces fell into place.</p>\n\n<p>Sometimes it's the littlest things...</p>\n"
},
{
"answer_id": 25890081,
"author": "Alex J",
"author_id": 27667,
"author_profile": "https://Stackoverflow.com/users/27667",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to all of the above, when everything seems to be correct, but the friend assembly stubbornly refuses to see any internals, <strong>reloading the solution or restarting Visual Studio</strong> can solve the problem.</p>\n"
},
{
"answer_id": 33130126,
"author": "Micaël",
"author_id": 2312731,
"author_profile": "https://Stackoverflow.com/users/2312731",
"pm_score": 2,
"selected": false,
"text": "<p>Previous answers with PublicKey worked: (Visual Studio 2015: NEED to be on one line, otherwise it complains that the assembly reference is invalid or cannot referenced. PublicKeyToken didn't worked)</p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"NameSpace.MyFriendAssembly, PublicKey=0024000004800000940000000602000000240000525341310004000001000100F73F4DDC11F0CA6209BC63EFCBBAC3DACB04B612E04FA07F01D919FB5A1579D20283DC12901C8B66A08FB8A9CB6A5E81989007B3AA43CD7442BED6D21F4D33FB590A46420FB75265C889D536A9519674440C3C2FB06C5924360243CACD4B641BE574C31A434CE845323395842FAAF106B234C2C1406E2F553073FF557D2DB6C5\")]\n</code></pre>\n\n<p>Thanks to @Joe</p>\n\n<p>To get the public key of the friend assembly:</p>\n\n<pre><code>sn -Tp path\\to\\assembly\\MyFriendAssembly.dll\n</code></pre>\n\n<p>Inside a Developper command prompt (Startup > Programs > Visual Studio 2015 > Visual Studio Tools > Developer Command Prompt for VS2015).\nThanks to @Ian G.</p>\n\n<p>Although, the final touch that made it work for me after the above was to sign my friend library project the same way the project of the library to share is signed. Since it was a new Test library, it wasn't signed yet.</p>\n"
},
{
"answer_id": 33201501,
"author": "Murugan Sivananantha Perumal",
"author_id": 4856270,
"author_profile": "https://Stackoverflow.com/users/4856270",
"pm_score": 2,
"selected": false,
"text": "<p>You are required to generate an new full public key for the assembly and then specify the attribute to assembly.</p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"assemblyname,\nPublicKey=\"Full Public Key\")]\n</code></pre>\n\n<p>Follow the below <a href=\"https://msdn.microsoft.com/en-us/library/office/ee539398(v=office.14).aspx\" rel=\"nofollow\">MSDN</a> steps to generate new full public key for the assembly from visual studio.</p>\n\n\n\n<p><strong>To add a Get Assembly Public Key item to the Tools menu</strong></p>\n\n<p>In Visual Studio, click <strong>External Tools</strong> on the Tools menu.</p>\n\n<p>In the External Tools dialog box, click <strong>Add</strong> and enter Get Assembly Public Key in the Title box.</p>\n\n<p>Fill the Command box by browsing to sn.exe. It is typically installed at the following location: <strong>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0a\\Bin\\x64\\sn.exe</strong>.</p>\n\n<p>In the Arguments box, type the following (case sensitive): <strong>-Tp $(TargetPath)</strong>.\nSelect the Use Output window check box.</p>\n\n<p>Click <strong>OK</strong>. The new command is added to the Tools menu.</p>\n\n<p>Whenever you need the Public Key Token of the assembly you are developing, click the Get Assembly Public Key command on the Tools menu, and the public key token appears in the Output window.</p>\n"
},
{
"answer_id": 33914495,
"author": "Jochen",
"author_id": 628755,
"author_profile": "https://Stackoverflow.com/users/628755",
"pm_score": 2,
"selected": false,
"text": "<p>In my case using VS.Net 2015, I needed to sign <strong>BOTH</strong> assemblies (if at least 1 assembly shall be signed or you want to reference on the public key of your assembly).</p>\n\n<p>My project didn't use signing at all. So I started adding a sign key to my test library and useing the InternalsVisibleTo-Attribute at my project's base library. But VS.Net always explained it couldn't access the friend methods.</p>\n\n<p>When I started to sign the base library (it can be the same or another sign key - as long as you do sign the base library), VS.Net was immediately able to work as expected.</p>\n"
},
{
"answer_id": 33915479,
"author": "Jochen",
"author_id": 628755,
"author_profile": "https://Stackoverflow.com/users/628755",
"pm_score": 1,
"selected": false,
"text": "<p>Applies only if you like to keep unsigned assemblies as unsigned assembly (and don't want to sign it for several reasons):</p>\n\n<p>There is still another point: if you compile your base library from VS.Net to a local directory, it may work as expected.</p>\n\n<p>BUT: As soon as you compile your base library to a network drive, security policies apply and the assembly can't be successfully loaded. This again causes VS.NET or the compiler to fail when checking for the PublicKey match.</p>\n\n<p>FINALLY, it's possible to use unsigned assemblies:\n<a href=\"https://msdn.microsoft.com/en-us/library/bb384966.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/bb384966.aspx</a>\nYou must ensure that BOTH assemblies are NOT SIGNED\nAnd the Assembly attribute must be without PublicKey information: </p>\n\n<p><code><Assembly: InternalsVisibleTo(\"friend_unsigned_B\")></code></p>\n"
},
{
"answer_id": 39927370,
"author": "Tatiana Racheva",
"author_id": 132042,
"author_profile": "https://Stackoverflow.com/users/132042",
"pm_score": 2,
"selected": false,
"text": "<p>Another possibility that may be tricky to track down, depending on how your code is written.</p>\n\n<ol>\n<li>You're invoking an internal method defined in X from another assembly Y</li>\n<li>The method signature uses internal types defined in Z</li>\n<li>You then have to add [InternalsVisibleTo] in X AND in Z</li>\n</ol>\n\n<p>For example:</p>\n\n<pre><code>// In X\ninternal static class XType\n{\n internal static ZType GetZ() { ... }\n}\n\n// In Y:\nobject someUntypedValue = XType.GetZ();\n\n// In Z:\ninternal class ZType { ... }\n</code></pre>\n\n<p>If you have it written like above, where you're not referring to ZType directly in Y, after having added Y as a friend of X, you may be mystified why your code still doesn't compile.</p>\n\n<p>The compilation error could definitely be more helpful in this case.</p>\n"
},
{
"answer_id": 46821179,
"author": "Kameron Kincade",
"author_id": 2074351,
"author_profile": "https://Stackoverflow.com/users/2074351",
"pm_score": 2,
"selected": false,
"text": "<p>I'm writing this out of frustration. Make sure the assembly you are granting access to is named as you expect.</p>\n\n<p>I renamed my project but this does not automatically update the Assembly Name. Right click your project and click <em>Properties</em>. Under <em>Application</em>, ensure that the <strong>Assembly Name</strong> and <strong>Default Namespace</strong> are what you expect.</p>\n"
},
{
"answer_id": 49558091,
"author": "VladExL",
"author_id": 2571841,
"author_profile": "https://Stackoverflow.com/users/2571841",
"pm_score": 2,
"selected": false,
"text": "<p>If you have more than 1 referenced assembly - check that all necessary assemblies have InternalsVisibleTo attribute. Sometimes it's not obviously, and no message that you have to add this attribute into else one assembly.</p>\n"
},
{
"answer_id": 49560265,
"author": "Sentinel",
"author_id": 442396,
"author_profile": "https://Stackoverflow.com/users/442396",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem. None of the solutions worked.</p>\n\n<p>Eventually discovered the issue was due to class X explicitly implementing interface Y, which is internal.</p>\n\n<p>the method X.InterfaceMethod was unavailable, though I have no idea why.</p>\n\n<p>The solution was to cast (X as YourInterface).InterfaceMethod in the test library, and then things worked. </p>\n"
},
{
"answer_id": 53593271,
"author": "karr",
"author_id": 3029066,
"author_profile": "https://Stackoverflow.com/users/3029066",
"pm_score": 1,
"selected": false,
"text": "<p><strong>1- Sign the test project:</strong> In Visual Studio go to the properties window of <strong>the test project</strong> and <strong>Sign the assembly</strong> by checking the checkbox with the same phrase in the <strong>Signing</strong> tab.</p>\n\n<p><strong>2- Create a PublicKey for the test project:</strong> Open Visual Studio Command Prompt (e.g. Developer Command Prompt for VS 2017). Go to the folder where the .dll file of <strong>the test project</strong> exists. Create a Public Key via sn.exe:</p>\n\n<p>sn -Tp TestProject.dll</p>\n\n<p>Note that the argument is -Tp, but not -tp.</p>\n\n<p><strong>3- Introduce the PublicKey to the project to be tested:</strong> Go to the AssemblyInfo.cs file in <strong>the project to be tested</strong> and add this line with the PublicKey created in the previous step:</p>\n\n<p>[assembly: InternalsVisibleTo(\"<strong>TestProjectAssemblyName</strong>, <strong>PublicKey</strong>=2066212d128683a85f31645c60719617ba512c0bfdba6791612ed56350368f6cc40a17b4942ff16cda9e760684658fa3f357c137a1005b04cb002400000480000094000000060200000024000052534131000400000100010065fe67a14eb30ffcdd99880e9d725f04e5c720dffc561b23e2953c34db8b7c5d4643f476408ad1b1e28d6bde7d64279b0f51bf0e60be2d383a6c497bf27307447506b746bd2075\")]</p>\n\n<p>Don't forget to replace the above PublicKey with yours.</p>\n\n<p><strong>4- Make the private method internal:</strong> In the project to be tested change the access modifier of the method to internal.</p>\n\n<p><strong>internal static</strong> void DoSomething(){...}</p>\n"
},
{
"answer_id": 70007000,
"author": "Alexander Høst",
"author_id": 2149075,
"author_profile": "https://Stackoverflow.com/users/2149075",
"pm_score": 2,
"selected": false,
"text": "<p>Although using an <code>AssemblyInfo</code> file and adding <code>InternalsVisibleTo</code> still works, the preferred approach now (as far as I can tell) is to use an <code>ItemGroup</code> in your Project's <code>csproj</code> file, like so:</p>\n<pre><code> <ItemGroup>\n <InternalsVisibleTo Include="My.Project.Tests" />\n </ItemGroup>\n</code></pre>\n<p>If a PublicKey is required, this attribute may also be added.</p>\n"
},
{
"answer_id": 72241838,
"author": "Alexander Høst",
"author_id": 2149075,
"author_profile": "https://Stackoverflow.com/users/2149075",
"pm_score": 0,
"selected": false,
"text": "<p><code>InternalsVisibleTo</code> is often used in the context of testing. If you're using a mocking framework such as <code>Moq</code>, you will need to expose the internals of your project to <code>Moq</code> as well. In the particular case of that framework, I also needed to add <br><code>[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]</code>to my <code>AssemblyInfo</code>.</p>\n"
},
{
"answer_id": 74610374,
"author": "DevDave",
"author_id": 896631,
"author_profile": "https://Stackoverflow.com/users/896631",
"pm_score": 0,
"selected": false,
"text": "<p>For what it's worth, I found that the property that was inaccessible due to it's protection level:</p>\n<pre><code>MyField field;\n</code></pre>\n<p>had to be changed to:</p>\n<pre><code>internal MyField field;\n</code></pre>\n<p>And it then compiled. I thought that <code>internal</code> was the default access modifier?</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
]
| I am trying to use the `InternalsVisibleTo` assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reason, I keep getting an error message that says:
>
> 'MyClassName' is inaccessible due to its protection level
>
>
>
Both assemblies are signed and I have the correct key listed in the attribute declaration. Any ideas? | Are you absolutely sure you have the correct public key specified in the attribute?
Note that you need to specify the full public key, not just the public key token. It looks something like:
```
[assembly: InternalsVisibleTo("MyFriendAssembly,
PublicKey=0024000004800000940000000602000000240000525341310004000001000100F73
F4DDC11F0CA6209BC63EFCBBAC3DACB04B612E04FA07F01D919FB5A1579D20283DC12901C8B66
A08FB8A9CB6A5E81989007B3AA43CD7442BED6D21F4D33FB590A46420FB75265C889D536A9519
674440C3C2FB06C5924360243CACD4B641BE574C31A434CE845323395842FAAF106B234C2C140
6E2F553073FF557D2DB6C5")]
```
It's 320 or so hex digits. Not sure why you need to specify the full public key - possibly with just the public key token that is used in other assembly references it would be easier for someone to spoof the friend assembly's identity. |
106,896 | <p>I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.</p>
| [
{
"answer_id": 106903,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>I would say to put as many classes as can be logically grouped in that file without making it too big and complex.</p>\n"
},
{
"answer_id": 106909,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 5,
"selected": false,
"text": "<p>Since there is no artificial limit, it really depends on what's comprehensible. If you have a bunch of fairly short, simple classes that are logically grouped together, toss in a bunch of 'em. If you have big, complex classes or classes that don't make sense as a group, go one file per class. Or pick something in between. Refactor as things change.</p>\n"
},
{
"answer_id": 107836,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 9,
"selected": true,
"text": "<p>A Python file is called a \"module\" and it's one way to organize your software so that it makes \"sense\". Another is a directory, called a \"package\".</p>\n\n<p>A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software.</p>\n\n<p>The rule is this: <strong>a module is the unit of reuse</strong>. </p>\n\n<p>You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules.</p>\n\n<p>For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like?</p>\n\n<pre><code>from ssReader import Reader\nfrom theCalcs import ACalc, AnotherCalc\nfrom theDB import Loader\n\ndef main( sourceFileName ):\n rdr= Reader( sourceFileName )\n c1= ACalc( options )\n c2= AnotherCalc( options )\n ldr= Loader( parameters )\n for myObj in rdr.readAll():\n c1.thisOp( myObj )\n c2.thatOp( myObj )\n ldr.laod( myObj )\n</code></pre>\n\n<p>Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your <code>import</code> statements.</p>\n"
},
{
"answer_id": 328563,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": false,
"text": "<p>It entirely depends on how big the project is, how long the classes are, if they will be used from other files and so on.</p>\n\n<p>For example I quite often use a series of classes for data-abstraction - so I may have 4 or 5 classes that may only be 1 line long (<code>class SomeData: pass</code>).</p>\n\n<p>It would be stupid to split each of these into separate files - but since they may be used from different files, putting all these in a separate <code>data_model.py</code> file would make sense, so I can do <code>from mypackage.data_model import SomeData, SomeSubData</code></p>\n\n<p>If you have a class with lots of code in it, maybe with some functions only it uses, it would be a good idea to split this class and the helper-functions into a separate file.</p>\n\n<p>You should structure them so you do <code>from mypackage.database.schema import MyModel</code>, not <code>from mypackage.email.errors import MyDatabaseModel</code> - if where you are importing things from make sense, and the files aren't tens of thousands of lines long, you have organised it correctly.</p>\n\n<p>The <a href=\"http://www.python.org/doc/2.5.2/tut/node8.html#SECTION008400000000000000000\" rel=\"noreferrer\">Python Modules documentation</a> has some useful information on organising packages.</p>\n"
},
{
"answer_id": 7879007,
"author": "Raffi Khatchadourian",
"author_id": 405326,
"author_profile": "https://Stackoverflow.com/users/405326",
"pm_score": 5,
"selected": false,
"text": "<p>I happen to like the Java model for the following reason. Placing each class in an individual file promotes reuse by making classes easier to see when browsing the source code. If you have a bunch of classes grouped into a single file, it may not be obvious to other developers that there are classes there that can be reused simply by browsing the project's <em>directory structure</em>. Thus, if you think that your class can possibly be reused, I would put it in its own file.</p>\n"
},
{
"answer_id": 8098533,
"author": "mike rodent",
"author_id": 595305,
"author_profile": "https://Stackoverflow.com/users/595305",
"pm_score": 3,
"selected": false,
"text": "<p>I find myself splitting things up when I get annoyed with the bigness of files and when the desirable structure of relatedness starts to emerge naturally. Often these two stages seem to coincide.</p>\n\n<p>It can be very annoying if you split things up too early, because you start to realise that a totally different ordering of structure is required.</p>\n\n<p>On the other hand, when any .java or .py file is getting to more than about 700 lines I start to get annoyed constantly trying to remember where \"that particular bit\" is.</p>\n\n<p>With Python/Jython circular dependency of import statements also seems to play a role: if you try to split too many cooperating basic building blocks into separate files this \"restriction\"/\"imperfection\" of the language seems to force you to group things, perhaps in rather a sensible way.</p>\n\n<p>As to splitting into packages, I don't really know, but I'd say probably the same rule of annoyance and emergence of happy structure works at all levels of modularity.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14139/"
]
| I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes. | A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package".
A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software.
The rule is this: **a module is the unit of reuse**.
You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules.
For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like?
```
from ssReader import Reader
from theCalcs import ACalc, AnotherCalc
from theDB import Loader
def main( sourceFileName ):
rdr= Reader( sourceFileName )
c1= ACalc( options )
c2= AnotherCalc( options )
ldr= Loader( parameters )
for myObj in rdr.readAll():
c1.thisOp( myObj )
c2.thatOp( myObj )
ldr.laod( myObj )
```
Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your `import` statements. |
106,907 | <p>We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed?</p>
| [
{
"answer_id": 106933,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": -1,
"selected": false,
"text": "<p>Classes can be both public AND sealed.</p>\n\n<p>But, don't do that.</p>\n\n<p>You can create a tool to reflect over internal classes, and emit a new class that accesses everything via reflection. MSTest does that.</p>\n\n<p>Edit: I mean, if you don't want to include -any- testing stuff in your original assembly; this also works if the members are private.</p>\n"
},
{
"answer_id": 106944,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 3,
"selected": false,
"text": "<p>If it is an internal class then it must not be getting used in isolation. Therefore you shouldn't really be testing it apart from testing some other class that makes use of that object internally.</p>\n\n<p>Just as you shouldn't test private members of a class, you shouldn't be testing internal classes of a DLL. Those classes are implementation details of some publicly accessible class, and therefore should be well exercised through other unit tests.</p>\n\n<p>The idea is that you only want to test the behavior of a class because if you test internal implementation details then your tests will be brittle. You should be able to change the implementation details of any class without breaking all your tests.</p>\n\n<p>If you find that you really need to test that class, then you might want to reexamine why that class is internal in the first place.</p>\n"
},
{
"answer_id": 106948,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using .NET, the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"noreferrer\">InternalsVisibleTo</a> assembly attribute allows you to create \"friend\" assemblies. These are specific strongly named assemblies that are allowed to access internal classes and members of the other assembly.</p>\n\n<p>Note, this should be used with discretion as it tightly couples the involved assemblies. A common use for InternalsVisibleTo is for unit testing projects. It's probably not a good choice for use in your actual application assemblies, for the reason stated above.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"NameAssemblyYouWantToPermitAccess\")]\nnamespace NameOfYourNameSpace\n{\n</code></pre>\n"
},
{
"answer_id": 11167226,
"author": "ktutnik",
"author_id": 212706,
"author_profile": "https://Stackoverflow.com/users/212706",
"pm_score": 2,
"selected": false,
"text": "<p>for documentation purposes</p>\n\n<p>alternatively you can instantiate internal class by using <code>Type.GetType</code> method</p>\n\n<p>example</p>\n\n<pre><code>//IServiceWrapper is public class which is \n//the same assembly with the internal class \nvar asm = typeof(IServiceWrapper).Assembly;\n//Namespace.ServiceWrapper is internal\nvar type = asm.GetType(\"Namespace.ServiceWrapper\");\nreturn (IServiceWrapper<T>)Activator\n .CreateInstance(type, new object[1] { /*constructor parameter*/ });\n</code></pre>\n\n<p>for generic type there are different process as bellow:</p>\n\n<pre><code>var asm = typeof(IServiceWrapper).Assembly;\n//note the name Namespace.ServiceWrapper`1\n//this is for calling Namespace.ServiceWrapper<>\nvar type = asm.GetType(\"Namespace.ServiceWrapper`1\");\nvar genType = type.MakeGenericType(new Type[1] { typeof(T) });\nreturn (IServiceWrapper<T>)Activator\n .CreateInstance(genType, new object[1] { /*constructor parameter*/});\n</code></pre>\n"
},
{
"answer_id": 67281561,
"author": "babula pradhan",
"author_id": 8704435,
"author_profile": "https://Stackoverflow.com/users/8704435",
"pm_score": 3,
"selected": false,
"text": "<p>Below are ways to use in <strong>.NET Core</strong> applications.</p>\n<ol>\n<li>Add <strong>AssemblyInfo.cs</strong> file and add <code>[assembly: InternalsVisibleTo("AssemblytoVisible")]</code></li>\n<li>Add this in <strong>.csproj</strong> file <em>(the project which contains the Internal classes)</em></li>\n</ol>\n<pre class=\"lang-xml prettyprint-override\"><code><ItemGroup>\n <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">\n <_Parameter1>Test_Project_Name</_Parameter1> <!-- The name of the project that you want the Internal class to be visible To it -->\n </AssemblyAttribute>\n</ItemGroup>\n</code></pre>\n<p>For more information please follow <a href=\"https://improveandrepeat.com/2019/12/how-to-test-your-internal-classes-in-c/\" rel=\"noreferrer\">https://improveandrepeat.com/2019/12/how-to-test-your-internal-classes-in-c/</a></p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
]
| We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed? | If you're using .NET, the [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) assembly attribute allows you to create "friend" assemblies. These are specific strongly named assemblies that are allowed to access internal classes and members of the other assembly.
Note, this should be used with discretion as it tightly couples the involved assemblies. A common use for InternalsVisibleTo is for unit testing projects. It's probably not a good choice for use in your actual application assemblies, for the reason stated above.
**Example:**
```
[assembly: InternalsVisibleTo("NameAssemblyYouWantToPermitAccess")]
namespace NameOfYourNameSpace
{
``` |
106,912 | <p>How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form?</p>
<p>I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right.</p>
<p>Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista?</p>
| [
{
"answer_id": 107195,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "<p>Drawing seems to be the easy part, the following will do that:</p>\n\n<p>[Edit: Code removed, see my other answer]</p>\n\n<p>The real problem is changing the state and detecting clicks on the button... for that you'll need to hook into the global message handler for the program, .NET seems to hide the mouse events for a form while not in the actual container areas (ie. mouse moves and clicks on the title bar). I'm looking for info on that, found it now, I'm working on it, shouldn't be too hard... If we can figure out what these messages are actually passing.</p>\n"
},
{
"answer_id": 107437,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 4,
"selected": true,
"text": "<p>The following will work in XP, I have no Vista machine handy to test it, but I think your issues are steming from an incorrect hWnd somehow. Anyway, on with the poorly commented code.</p>\n\n<pre><code>// The state of our little button\nButtonState _buttState = ButtonState.Normal;\nRectangle _buttPosition = new Rectangle();\n\n[DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetWindowDC(IntPtr hWnd);\n[DllImport(\"user32.dll\")]\nprivate static extern int GetWindowRect(IntPtr hWnd, \n ref Rectangle lpRect);\n[DllImport(\"user32.dll\")]\nprivate static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);\nprotected override void WndProc(ref Message m)\n{\n int x, y;\n Rectangle windowRect = new Rectangle();\n GetWindowRect(m.HWnd, ref windowRect);\n\n switch (m.Msg)\n {\n // WM_NCPAINT\n case 0x85:\n // WM_PAINT\n case 0x0A:\n base.WndProc(ref m);\n\n DrawButton(m.HWnd);\n\n m.Result = IntPtr.Zero;\n\n break;\n\n // WM_ACTIVATE\n case 0x86:\n base.WndProc(ref m);\n DrawButton(m.HWnd);\n\n break;\n\n // WM_NCMOUSEMOVE\n case 0xA0:\n // Extract the least significant 16 bits\n x = ((int)m.LParam << 16) >> 16;\n // Extract the most significant 16 bits\n y = (int)m.LParam >> 16;\n\n x -= windowRect.Left;\n y -= windowRect.Top;\n\n base.WndProc(ref m);\n\n if (!_buttPosition.Contains(new Point(x, y)) && \n _buttState == ButtonState.Pushed)\n {\n _buttState = ButtonState.Normal;\n DrawButton(m.HWnd);\n }\n\n break;\n\n // WM_NCLBUTTONDOWN\n case 0xA1:\n // Extract the least significant 16 bits\n x = ((int)m.LParam << 16) >> 16;\n // Extract the most significant 16 bits\n y = (int)m.LParam >> 16;\n\n x -= windowRect.Left;\n y -= windowRect.Top;\n\n if (_buttPosition.Contains(new Point(x, y)))\n {\n _buttState = ButtonState.Pushed;\n DrawButton(m.HWnd);\n }\n else\n base.WndProc(ref m);\n\n break;\n\n // WM_NCLBUTTONUP\n case 0xA2:\n // Extract the least significant 16 bits\n x = ((int)m.LParam << 16) >> 16;\n // Extract the most significant 16 bits\n y = (int)m.LParam >> 16;\n\n x -= windowRect.Left;\n y -= windowRect.Top;\n\n if (_buttPosition.Contains(new Point(x, y)) &&\n _buttState == ButtonState.Pushed)\n {\n _buttState = ButtonState.Normal;\n // [[TODO]]: Fire a click event for your button \n // however you want to do it.\n DrawButton(m.HWnd);\n }\n else\n base.WndProc(ref m);\n\n break;\n\n // WM_NCHITTEST\n case 0x84:\n // Extract the least significant 16 bits\n x = ((int)m.LParam << 16) >> 16;\n // Extract the most significant 16 bits\n y = (int)m.LParam >> 16;\n\n x -= windowRect.Left;\n y -= windowRect.Top;\n\n if (_buttPosition.Contains(new Point(x, y)))\n m.Result = (IntPtr)18; // HTBORDER\n else\n base.WndProc(ref m);\n\n break;\n\n default:\n base.WndProc(ref m);\n break;\n }\n}\n\nprivate void DrawButton(IntPtr hwnd)\n{\n IntPtr hDC = GetWindowDC(hwnd);\n int x, y;\n\n using (Graphics g = Graphics.FromHdc(hDC))\n {\n // Work out size and positioning\n int CaptionHeight = Bounds.Height - ClientRectangle.Height;\n Size ButtonSize = SystemInformation.CaptionButtonSize;\n x = Bounds.Width - 4 * ButtonSize.Width;\n y = (CaptionHeight - ButtonSize.Height) / 2;\n _buttPosition.Location = new Point(x, y);\n\n // Work out color\n Brush color;\n if (_buttState == ButtonState.Pushed)\n color = Brushes.LightGreen;\n else\n color = Brushes.Red;\n\n // Draw our \"button\"\n g.FillRectangle(color, x, y, ButtonSize.Width, ButtonSize.Height);\n }\n\n ReleaseDC(hwnd, hDC);\n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n _buttPosition.Size = SystemInformation.CaptionButtonSize;\n}\n</code></pre>\n"
},
{
"answer_id": 862532,
"author": "AlexDrenea",
"author_id": 39624,
"author_profile": "https://Stackoverflow.com/users/39624",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's been long since the last answer but this really helped me recently and I like to update the code provided by Chris with my comments and modifications.\nThe version runs perfectly on Win XP and Win 2003. On Win 2008 ot has a small bug that I was not able to identify, when resizing windows. Works on Vista too (no-Aero) but note that the title bar buttons are not square and button dimensions should take that into account.</p>\n\n<pre><code> switch (m.Msg)\n {\n // WM_NCPAINT / WM_PAINT \n case 0x85:\n case 0x0A:\n //Call base method\n base.WndProc(ref m);\n //we have 3 buttons in the corner of the window. So first's new button left coord is offseted by 4 widths\n int crt = 4;\n //navigate trough all titlebar buttons on the form\n foreach (TitleBarImageButton crtBtn in titleBarButtons.Values)\n {\n //Calculate button coordinates\n p.X = (Bounds.Width - crt * crtBtn.Size.Width);\n p.Y = (Bounds.Height - ClientRectangle.Height - crtBtn.Size.Height) / 2;\n //Initialize button and draw\n crtBtn.Location = p;\n crtBtn.ButtonState = ImageButtonState.NORMAL;\n crtBtn.DrawButton(m.HWnd);\n //increment button left coord location offset\n crt++;\n }\n m.Result = IntPtr.Zero;\n break;\n // WM_ACTIVATE \n case 0x86:\n //Call base method\n base.WndProc(ref m);\n //Draw each button\n foreach (TitleBarImageButton crtBtn in titleBarButtons.Values)\n {\n crtBtn.ButtonState = ImageButtonState.NORMAL;\n crtBtn.DrawButton(m.HWnd);\n }\n break;\n // WM_NCMOUSEMOVE \n case 0xA0:\n //Get current mouse position\n p.X = ((int)m.LParam << 16) >> 16;// Extract the least significant 16 bits \n p.Y = (int)m.LParam >> 16; // Extract the most significant 16 bits \n p.X -= windowRect.Left;\n p.Y -= windowRect.Top;\n\n //Call base method\n base.WndProc(ref m);\n\n ImageButtonState newButtonState;\n foreach (TitleBarImageButton crtBtn in titleBarButtons.Values)\n {\n if (crtBtn.HitTest(p))\n {//mouse is over the current button\n if (crtBtn.MouseButtonState == MouseButtonState.PRESSED)\n //button is pressed - set pressed state\n newButtonState = ImageButtonState.PRESSED;\n else\n //button not pressed - set hoover state\n newButtonState = ImageButtonState.HOOVER;\n }\n else\n {\n //mouse not over the current button - set normal state\n newButtonState = ImageButtonState.NORMAL;\n }\n\n //if button state not modified, do not repaint it.\n if (newButtonState != crtBtn.ButtonState)\n {\n crtBtn.ButtonState = newButtonState;\n crtBtn.DrawButton(m.HWnd);\n }\n }\n break;\n // WM_NCLBUTTONDOWN \n case 0xA1:\n //Get current mouse position\n p.X = ((int)m.LParam << 16) >> 16;// Extract the least significant 16 bits\n p.Y = (int)m.LParam >> 16; // Extract the most significant 16 bits \n p.X -= windowRect.Left;\n p.Y -= windowRect.Top;\n\n //Call base method\n base.WndProc(ref m);\n\n foreach (TitleBarImageButton crtBtn in titleBarButtons.Values)\n {\n if (crtBtn.HitTest(p))\n {\n crtBtn.MouseButtonState = MouseButtonState.PRESSED;\n crtBtn.ButtonState = ImageButtonState.PRESSED;\n crtBtn.DrawButton(m.HWnd);\n }\n }\n break;\n // WM_NCLBUTTONUP \n case 0xA2:\n case 0x202:\n //Get current mouse position\n p.X = ((int)m.LParam << 16) >> 16;// Extract the least significant 16 bits \n p.Y = (int)m.LParam >> 16; // Extract the most significant 16 bits \n p.X -= windowRect.Left;\n p.Y -= windowRect.Top;\n\n //Call base method\n base.WndProc(ref m);\n foreach (TitleBarImageButton crtBtn in titleBarButtons.Values)\n {\n //if button is press\n if (crtBtn.ButtonState == ImageButtonState.PRESSED)\n {\n //Rasie button's click event\n crtBtn.OnClick(EventArgs.Empty);\n\n if (crtBtn.HitTest(p))\n crtBtn.ButtonState = ImageButtonState.HOOVER;\n else\n crtBtn.ButtonState = ImageButtonState.NORMAL;\n }\n\n crtBtn.MouseButtonState = MouseButtonState.NOTPESSED;\n crtBtn.DrawButton(m.HWnd);\n }\n break;\n // WM_NCHITTEST \n case 0x84:\n //Get current mouse position\n p.X = ((int)m.LParam << 16) >> 16;// Extract the least significant 16 bits\n p.Y = (int)m.LParam >> 16; // Extract the most significant 16 bits\n p.X -= windowRect.Left;\n p.Y -= windowRect.Top;\n\n bool isAnyButtonHit = false;\n foreach (TitleBarImageButton crtBtn in titleBarButtons.Values)\n {\n //if mouse is over the button, or mouse is pressed \n //(do not process messages when mouse was pressed on a button)\n if (crtBtn.HitTest(p) || crtBtn.MouseButtonState == MouseButtonState.PRESSED)\n {\n //return 18 (do not process further)\n m.Result = (IntPtr)18;\n //we have a hit\n isAnyButtonHit = true;\n //return \n break;\n }\n else\n {//mouse is not pressed and not over the button, redraw button if needed \n if (crtBtn.ButtonState != ImageButtonState.NORMAL)\n {\n crtBtn.ButtonState = ImageButtonState.NORMAL;\n crtBtn.DrawButton(m.HWnd);\n }\n }\n }\n //if we have a hit, do not process further\n if (!isAnyButtonHit)\n //Call base method\n base.WndProc(ref m);\n break;\n default:\n //Call base method\n base.WndProc(ref m);\n //Console.WriteLine(m.Msg + \"(0x\" + m.Msg.ToString(\"x\") + \")\");\n break;\n }\n</code></pre>\n\n<p>The code demonstrates the messages that heve to be treated and how to treat them.\nThe code uses a collection of custom TitleBarButton objets. That class is too big to be included here but I can provide it if needed along with an example.</p>\n"
}
]
| 2008/09/20 | [
"https://Stackoverflow.com/questions/106912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
]
| How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form?
I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right.
Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista? | The following will work in XP, I have no Vista machine handy to test it, but I think your issues are steming from an incorrect hWnd somehow. Anyway, on with the poorly commented code.
```
// The state of our little button
ButtonState _buttState = ButtonState.Normal;
Rectangle _buttPosition = new Rectangle();
[DllImport("user32.dll")]
private static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetWindowRect(IntPtr hWnd,
ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
protected override void WndProc(ref Message m)
{
int x, y;
Rectangle windowRect = new Rectangle();
GetWindowRect(m.HWnd, ref windowRect);
switch (m.Msg)
{
// WM_NCPAINT
case 0x85:
// WM_PAINT
case 0x0A:
base.WndProc(ref m);
DrawButton(m.HWnd);
m.Result = IntPtr.Zero;
break;
// WM_ACTIVATE
case 0x86:
base.WndProc(ref m);
DrawButton(m.HWnd);
break;
// WM_NCMOUSEMOVE
case 0xA0:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
base.WndProc(ref m);
if (!_buttPosition.Contains(new Point(x, y)) &&
_buttState == ButtonState.Pushed)
{
_buttState = ButtonState.Normal;
DrawButton(m.HWnd);
}
break;
// WM_NCLBUTTONDOWN
case 0xA1:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
if (_buttPosition.Contains(new Point(x, y)))
{
_buttState = ButtonState.Pushed;
DrawButton(m.HWnd);
}
else
base.WndProc(ref m);
break;
// WM_NCLBUTTONUP
case 0xA2:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
if (_buttPosition.Contains(new Point(x, y)) &&
_buttState == ButtonState.Pushed)
{
_buttState = ButtonState.Normal;
// [[TODO]]: Fire a click event for your button
// however you want to do it.
DrawButton(m.HWnd);
}
else
base.WndProc(ref m);
break;
// WM_NCHITTEST
case 0x84:
// Extract the least significant 16 bits
x = ((int)m.LParam << 16) >> 16;
// Extract the most significant 16 bits
y = (int)m.LParam >> 16;
x -= windowRect.Left;
y -= windowRect.Top;
if (_buttPosition.Contains(new Point(x, y)))
m.Result = (IntPtr)18; // HTBORDER
else
base.WndProc(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
private void DrawButton(IntPtr hwnd)
{
IntPtr hDC = GetWindowDC(hwnd);
int x, y;
using (Graphics g = Graphics.FromHdc(hDC))
{
// Work out size and positioning
int CaptionHeight = Bounds.Height - ClientRectangle.Height;
Size ButtonSize = SystemInformation.CaptionButtonSize;
x = Bounds.Width - 4 * ButtonSize.Width;
y = (CaptionHeight - ButtonSize.Height) / 2;
_buttPosition.Location = new Point(x, y);
// Work out color
Brush color;
if (_buttState == ButtonState.Pushed)
color = Brushes.LightGreen;
else
color = Brushes.Red;
// Draw our "button"
g.FillRectangle(color, x, y, ButtonSize.Width, ButtonSize.Height);
}
ReleaseDC(hwnd, hDC);
}
private void Form1_Load(object sender, EventArgs e)
{
_buttPosition.Size = SystemInformation.CaptionButtonSize;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.