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
246,162
<p>can we output a .jpg image or .gif image in C? <p>I mean can we print a picture as output with the help of a C program?<p>Aslo can we write a script in C language for HTML pages as can be written in JavaScript? <p>Can the browsers operate on it?<p>If not possible is there any plugin for any of the browsers? <p>Any example code or links please?</p>
[ { "answer_id": 246165, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>That's a lot of questions!</p>\n\n<p>You can generate JPEG and PNG files from C using <a href=\"http://www.ijg.org/\" rel=\"nofollow noreferrer\">libjpeg</a> and <a href=\"http://www.libpng.org/pub/png/libpng.html\" rel=\"nofollow noreferrer\">libpng</a>, respectively. (Yes, I'm dodging your GIF question on purpose. You don't need to do that; PNG is well-supported by mainstream browsers now and <a href=\"http://burnallgifs.org/archives/\" rel=\"nofollow noreferrer\">should be preferred</a>. :-P)</p>\n\n<p>Browsers generally only support JavaScript for client-side scripting. Using anything else will only destroy the portability of your webpages. Yes, like you say you can use plugins, but some people are averse to installing plugins, and others are behind corporate policies that don't allow such things.</p>\n" }, { "answer_id": 246174, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": true, "text": "<p>You can generate a web page from a C program by using the <a href=\"http://hoohoo.ncsa.uiuc.edu/cgi/\" rel=\"nofollow noreferrer\">Common Gateway Interface</a> (CGI). The C program is compiled and runs on the server, this is different from Javascript which runs on the browser.</p>\n\n<p>You can also generate images via CGI too. Just set the content type appropriately, eg. image/jpeg for a JPEG image. You can use <a href=\"http://en.wikipedia.org/wiki/Libjpeg\" rel=\"nofollow noreferrer\">libjpeg</a> to generate the actual image.</p>\n\n<hr>\n\n<p>Here is an example C program to generate a page with a JPEG image:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nmain()\n{\n char *pageTitle = \"Look, a JPEG!\";\n char *urlImage = \"/myimage.jpeg\";\n\n// Send HTTP header.\n printf(\"Content-type: text/html\\r\\n\\r\\n\");\n\n// Send the generated HTML.\n printf(\"&lt;html&gt;&lt;head&gt;&lt;title&gt;%s&lt;/title&gt;&lt;/head&gt;\\r\\n\"\n \"&lt;body&gt;\\r\\n\"\n \"&lt;h1&gt;%s&lt;/h1&gt;\\r\\n\"\n \"&lt;img src=\\\"%s\\\"&gt;\\r\\n\"\n \"&lt;/body&gt;&lt;/html&gt;\\r\\n\",\n pageTitle, pageTitle, urlImage);\n}\n</code></pre>\n" }, { "answer_id": 246347, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 1, "selected": false, "text": "<ul>\n<li>To save jpeg files, you will need <a href=\"http://www.ijg.org/\" rel=\"nofollow noreferrer\">libjpeg</a>. I am sure that there is a similar library for GIFs too.</li>\n<li>C is <strong>not</strong> a scripting language. You cannot write scripts in C like in Javascript. You can write server-side code in with CGI if you dare but this is really not a good idea. There are a couple of better tools to write server side components, including C#/ASP.NET, Java, Python, Perl, Ruby (with Rails) or PHP. Even Coldfusion is better for webpages than C.</li>\n<li>C is not an interpreted language. There is no browser that going to run your C code and I doubt there ever will be one, for millions of reasons. Also, there is no plugin for that. This is something really unfeasable. C is a great language for a lot of stuff, but the web is one of the areas where it's rarely used (except if you want to write a browser or a http server in C. But even for those tasks, C++ is usually better.) If you want client-side scripting in webpages, use Javascript. Some browsers will interpret VBScript too, but Javascript is the preferred browser scripting language.</li>\n</ul>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
can we output a .jpg image or .gif image in C? I mean can we print a picture as output with the help of a C program?Aslo can we write a script in C language for HTML pages as can be written in JavaScript? Can the browsers operate on it?If not possible is there any plugin for any of the browsers? Any example code or links please?
You can generate a web page from a C program by using the [Common Gateway Interface](http://hoohoo.ncsa.uiuc.edu/cgi/) (CGI). The C program is compiled and runs on the server, this is different from Javascript which runs on the browser. You can also generate images via CGI too. Just set the content type appropriately, eg. image/jpeg for a JPEG image. You can use [libjpeg](http://en.wikipedia.org/wiki/Libjpeg) to generate the actual image. --- Here is an example C program to generate a page with a JPEG image: ``` #include <stdio.h> main() { char *pageTitle = "Look, a JPEG!"; char *urlImage = "/myimage.jpeg"; // Send HTTP header. printf("Content-type: text/html\r\n\r\n"); // Send the generated HTML. printf("<html><head><title>%s</title></head>\r\n" "<body>\r\n" "<h1>%s</h1>\r\n" "<img src=\"%s\">\r\n" "</body></html>\r\n", pageTitle, pageTitle, urlImage); } ```
246,192
<p>Instead of hardcoding the default @author template I would like Eclipse to use user's real name taken from account information (in Linux - but Windows solution is also welcome). Entering it somewhere into Eclipse configuration would be acceptable, too, alas I can't find the right place.</p>
[ { "answer_id": 246264, "author": "Davide Inglima", "author_id": 32041, "author_profile": "https://Stackoverflow.com/users/32041", "pm_score": 9, "selected": true, "text": "<p>It seems that your best bet is to redefine the java <code>user.name</code> variable either at your command line, or using the <code>eclipse.ini</code> file in your eclipse install root directory.</p>\n<p>This seems to work fine for me:</p>\n<pre><code>-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256M\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Duser.name=Davide Inglima\n-Xms40m\n-Xmx512m \n</code></pre>\n<hr />\n<h3>Update:</h3>\n<p><a href=\"http://morlhon.net/blog/2005/09/07/eclipse-username/\" rel=\"noreferrer\">http://morlhon.net/blog/2005/09/07/eclipse-username/</a> is a dead link...</p>\n<p>Here's a new one: <a href=\"https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/\" rel=\"noreferrer\">https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/</a></p>\n" }, { "answer_id": 6583577, "author": "singletony", "author_id": 641936, "author_profile": "https://Stackoverflow.com/users/641936", "pm_score": 7, "selected": false, "text": "<p>Open Eclipse, navigate to\nWindow -> Preferences -> Java -> Code Style -> Code Templates -> Comments -> Types and then press the 'Edit' button. There you can change your name in the generated comment from @Author ${user} to @Author Rajish. </p>\n" }, { "answer_id": 9303226, "author": "Łukasz Siwiński", "author_id": 235973, "author_profile": "https://Stackoverflow.com/users/235973", "pm_score": 2, "selected": false, "text": "<p>dovescrywolf gave tip as a comment on <a href=\"http://morlhon.net/blog/2005/09/07/eclipse-username/\" rel=\"nofollow noreferrer\">article</a> linked by Davide Inglima</p>\n\n<p>It was was very useful for me on MacOS. </p>\n\n<ul>\n<li>Close Eclipse if it's opened.</li>\n<li><p>Open Termnal (bash console) and do below things: </p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ pwd /Users/You/YourEclipseInstalationDirectory \n$ cd Eclipse.app/Contents/MacOS/ \n$ echo \"-Duser.name=Your Name\" &gt;&gt; eclipse.ini \n$ cat eclipse.ini\n</code></pre></li>\n<li><p>Close Terminal and start/open Eclipse again. </p></li>\n</ul>\n" }, { "answer_id": 11439997, "author": "OJVM", "author_id": 317772, "author_profile": "https://Stackoverflow.com/users/317772", "pm_score": -1, "selected": false, "text": "<p>just other option. goto <strong><em>PREFERENCES >> JAVA >> EDITOR >> TEMPLATES</em></strong>, Select @author and change the variable ${user}.</p>\n" }, { "answer_id": 13206097, "author": "Anuj Balan", "author_id": 818557, "author_profile": "https://Stackoverflow.com/users/818557", "pm_score": 4, "selected": false, "text": "<p>Rather than changing <code>${user}</code> in eclipse, it is advisable to introduce </p>\n\n<p><code>-Duser.name=Whateverpleaseyou</code></p>\n\n<p>in <code>eclipse.ini</code> which is present in your eclipse folder.</p>\n" }, { "answer_id": 19357053, "author": "FranMowinckel", "author_id": 2077216, "author_profile": "https://Stackoverflow.com/users/2077216", "pm_score": 1, "selected": false, "text": "<p>This is the file we're all looking for (inside your Eclipse workspace):</p>\n\n<blockquote>\n <p>.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs</p>\n</blockquote>\n\n<p>You will find an @author tag with the name you want to change. Restart Eclipse and it will work.</p>\n\n<p>For accents you have to use the Unicode format (e.g. '\\u00E1' for á).</p>\n\n<p>You can also modify the 'ini' file as prior answers suggest or set the user name var for a global solution. Or override the @author tag in the Preferences menu for a local solution. Those are both valid solutions to this problem.</p>\n\n<p>But if you're looking for 'that' author name that is bothering most of us, is in that file.</p>\n" }, { "answer_id": 23194284, "author": "Sumit Singh", "author_id": 942391, "author_profile": "https://Stackoverflow.com/users/942391", "pm_score": 5, "selected": false, "text": "<pre><code>Windows &gt; Preferences &gt; Java &gt; Code Style &gt; Code Templates &gt; Comments\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/Q5Zja.png\" alt=\"enter image description here\"></p>\n\n<p>Or Open <code>eclipse.ini</code> file and add following.</p>\n\n<pre><code>-Duser.name=Sumit Singh // Your Name\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/gaeX8.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 34661765, "author": "parasrish", "author_id": 4361073, "author_profile": "https://Stackoverflow.com/users/4361073", "pm_score": 0, "selected": false, "text": "<p>edit the file <code>/etc/eclipse.ini</code>, so as to contain entry as;</p>\n\n<p><code>-Duser.name=myname</code></p>\n\n<p>Restart the \"eclipse\" and now, on creation of any new file, with wizard (c/c++/java), it will use \"myname\" in place of ${user}.</p>\n" }, { "answer_id": 41412349, "author": "Frelling", "author_id": 3304238, "author_profile": "https://Stackoverflow.com/users/3304238", "pm_score": 4, "selected": false, "text": "<h2>EGit Solution</h2>\n\n<p>One would expect creating or changing template variables on a project-, workspace-, or environment-basis is a standard Eclipse feature. Sadly, it is not. More so, given that Eclipse plugins can define new variables and templates, there should be plugins out there providing a solution. If they are, they must be hard to find. <a href=\"https://marketplace.eclipse.org/content/mmm-templatevariables\" rel=\"noreferrer\">mmm-TemplateVariable</a>, which is available in the Eclipse Marketplace, is a step in the right direction for Maven users, giving the ability to include version, artifactId, etc. in templates.</p>\n\n<p>Fortunately, <a href=\"http://www.eclipse.org/egit/\" rel=\"noreferrer\">EGit</a>, which is an Eclipse tool for Git, provides very flexible means for including many different variables in code templates. The only requirement is that your project uses Git. If you don’t use Git, but are serious about software development, now is the time to learn (<a href=\"https://git-scm.com/book/en/v2\" rel=\"noreferrer\">Pro Git book</a>). If you are forced to use a legacy version control system, try changing some minds.</p>\n\n<p>Thanks to the efforts of <a href=\"https://github.com/harmsk\" rel=\"noreferrer\">harmsk</a>, EGit 4.0 and above includes the ability to use Git configuration key values in templates. This allows setting template values based on repository settings (project), user settings (account), and/or global settings (workstation).</p>\n\n<p>The following example shows how to set up Eclipse and Git for a multi-user development workstation and use a custom Git configuration key in lieu of <code>${user}</code> to provide more flexibility. Although the example is based on a Windows 10 installation of Eclipse Mars and Git for Windows, the example is applicable to Linux and OSX running Eclipse and Git using their respective command line tools.</p>\n\n<p>To avoid possible confusion between Git’s <code>user.name</code> configuration key and Java’s <code>user.name</code> system property, a custom Git configuration key – <code>user.author</code> – will be used to provide an author’s name and/or credentials.</p>\n\n<h2>Configuring Templates</h2>\n\n<p>The format of a Git template variable is as follows</p>\n\n<p><code>${&lt;name&gt;:git_config(&lt;key&gt;)}</code></p>\n\n<p>where <code>&lt;name&gt;</code> is any arbitrary variable name and <code>&lt;key&gt;</code> is the Git configuration key whose value should be used. Given that, changing the <strong>Comments→Types</strong> template to</p>\n\n<pre><code>/**\n * @author ${author:git_config(user.author)}\n *\n * ${tags}\n */\n</code></pre>\n\n<p>will now attempt to resolve the author’s name from Git’s <code>user.author</code> configuration key. Without any further configuration, any newly created comments will not include a name after <code>@author</code>, since none has been defined yet.</p>\n\n<h2>Configuring Git</h2>\n\n<h1>From the command line</h1>\n\n<p><strong>Git System Configuration</strong> - This configuration step makes changes to Git’s system-wide configuration applicable to all accounts on the workstation unless overridden by user or repository settings. Because system-wide configurations are part the underlying Git application (e.g. Git for Windows), changes will require Administrator privileges. Run Git Bash, cmd, or PowerShell as Administrator. The following command will set the system-wide author.</p>\n\n<pre><code>git config --system user.author “SET ME IN GLOBAL(USER) or REPOSITORY(LOCAL) SETTINGS”\n</code></pre>\n\n<p>The purpose of this “author” is to serve as a reminder that it should be set elsewhere. This is particularly useful when new user accounts are being used on the workstation.</p>\n\n<p>To verify this setting, create an empty Java project that uses Git or open an existing Git-based project. Create a class and use <strong>Source→Generate Element Comment</strong> from the context menu, <strong>ALT-SHIFT-J</strong>, or start a JavaDoc comment. The resulting <code>@author</code> tag should be followed by the warning.</p>\n\n<p>The remaining configuration changes can be performed without Administrator privileges.</p>\n\n<p><strong>Git Global(User) Configuration</strong> - Global, or user, configurations are those associated with a specific user and will override system-wide configurations. These settings apply to all Git-based projects unless overridden by repository settings. If the author name is different due to various project types such as for work, open source contributions, or personal, set the most frequently used here.</p>\n\n<pre><code>git config --global user.author “Mr. John Smith”\n</code></pre>\n\n<p>Having configured the global value, return to the test project used early and apply a class comment. The<code>@author</code> tag should now show the global setting.</p>\n\n<p><strong>Git Repository(Local) Configuration</strong> - Lastly, a repository or local configuration can be used to configure an author for a specific project. Unlike the previous configurations, a repository configuration must be done from within the repository. Using Git Bash, PowerShell, etc. navigate into the test project’s repository.</p>\n\n<pre><code>git config --local user.author “smithy”\n</code></pre>\n\n<p>Given this, new comments in the test project will use the locally defined author name. Other Git-based projects, will still use the global author name.</p>\n\n<h1>From Within Eclipse</h1>\n\n<p>The configuration changes above can also be set from within Eclipse through its <strong>Preferences: Team→Git-Configuration</strong>. Eclipse must be run as Administrator to change system-wide Git configurations.</p>\n\n<h2>In Sum</h2>\n\n<p>Although this example dealt specifically with the most common issue, that of changing <code>${user}</code>, this approach can be used for more. <strong><em>However, caution should be exercised not to use Git-defined configuration keys, unless it is specifically intended.</em></strong></p>\n" }, { "answer_id": 55655586, "author": "Waqas Ahmed", "author_id": 5679543, "author_profile": "https://Stackoverflow.com/users/5679543", "pm_score": -1, "selected": false, "text": "<p>Window -> Preferences -> Java -> Code Style -> Code Templates -> Comments -> Types\nChnage the tage infront ${user} to your name.</p>\n\n<p>Before</p>\n\n<pre><code>/**\n * @author ${user}\n *\n * ${tags}\n */\n</code></pre>\n\n<p>After </p>\n\n<pre><code>/**\n * @author Waqas Ahmed\n *\n * ${tags}\n */\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/hUqt9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hUqt9.png\" alt=\"enter image description here\"></a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29576/" ]
Instead of hardcoding the default @author template I would like Eclipse to use user's real name taken from account information (in Linux - but Windows solution is also welcome). Entering it somewhere into Eclipse configuration would be acceptable, too, alas I can't find the right place.
It seems that your best bet is to redefine the java `user.name` variable either at your command line, or using the `eclipse.ini` file in your eclipse install root directory. This seems to work fine for me: ``` -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256M -vmargs -Dosgi.requiredJavaVersion=1.5 -Duser.name=Davide Inglima -Xms40m -Xmx512m ``` --- ### Update: <http://morlhon.net/blog/2005/09/07/eclipse-username/> is a dead link... Here's a new one: <https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/>
246,193
<p>While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of</p> <pre><code>Name : Value Name2 : Value2 </code></pre> <p>etc.</p> <p>The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form <code>2.20011E+17</code>. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?</p>
[ { "answer_id": 246203, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 4, "selected": false, "text": "<p>You can use <a href=\"http://www.w3schools.com/js/js_obj_math.asp\" rel=\"noreferrer\">Math.round()</a> for rounding numbers to the nearest integer.</p>\n\n<pre><code>Math.round(532.24) =&gt; 532\n</code></pre>\n\n<p>Also, you can use <a href=\"http://www.w3schools.com/jsref/jsref_parseInt.asp\" rel=\"noreferrer\">parseInt()</a> and <a href=\"http://www.w3schools.com/jsref/jsref_parseFloat.asp\" rel=\"noreferrer\">parseFloat()</a> to cast a variable to a certain type, in this case integer and floating point.</p>\n" }, { "answer_id": 246379, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 5, "selected": false, "text": "<p>According to the <a href=\"http://bclary.com/2004/11/07/#a-4.3.20\" rel=\"noreferrer\">ECMAScript specification</a>, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.</p>\n\n<p>Regarding the rounding of these numbers, there are a number of ways you can achieve this. The <a href=\"http://bclary.com/2004/11/07/#a-15.8\" rel=\"noreferrer\">Math</a> object gives us three rounding methods wich we can use:</p>\n\n<p>The <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/round\" rel=\"noreferrer\">Math.round()</a> is most commonly used, it returns the value rounded to the nearest integer. Then there is the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/floor\" rel=\"noreferrer\">Math.floor()</a> wich returns the largest integer less than or equal to a number. Lastly we have the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/ceil\" rel=\"noreferrer\">Math.ceil()</a> function that returns the smallest integer greater than or equal to a number.</p>\n\n<p>There is also the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number/toFixed\" rel=\"noreferrer\">toFixed()</a> that returns a string representing the number using fixed-point notation.</p>\n\n<p>Ps.: There is <strong>no 2nd argument</strong> in the <em>Math.round()</em> method. The <em>toFixed()</em> is <strong>not IE specific</strong>, its <a href=\"http://bclary.com/2004/11/07/#a-15.7.4\" rel=\"noreferrer\">within</a> the ECMAScript specification aswell</p>\n" }, { "answer_id": 246447, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 7, "selected": true, "text": "<p>You hav to convert your input into a number and then round them:</p>\n\n<pre><code>function toInteger(number){ \n return Math.round( // round to nearest integer\n Number(number) // type cast your input\n ); \n};\n</code></pre>\n\n<p>Or as a one liner:</p>\n\n<pre><code>function toInt(n){ return Math.round(Number(n)); };\n</code></pre>\n\n<p>Testing with different values:</p>\n\n<pre><code>toInteger(2.5); // 3\ntoInteger(1000); // 1000\ntoInteger(\"12345.12345\"); // 12345\ntoInteger(\"2.20011E+17\"); // 220011000000000000\n</code></pre>\n" }, { "answer_id": 478445, "author": "Raj Rao", "author_id": 44815, "author_profile": "https://Stackoverflow.com/users/44815", "pm_score": 7, "selected": false, "text": "<p>If you need to round to a certain number of digits use the following function</p>\n\n<pre><code>function roundNumber(number, digits) {\n var multiple = Math.pow(10, digits);\n var rndedNum = Math.round(number * multiple) / multiple;\n return rndedNum;\n }\n</code></pre>\n" }, { "answer_id": 10453009, "author": "Maxime Pacary", "author_id": 488666, "author_profile": "https://Stackoverflow.com/users/488666", "pm_score": 5, "selected": false, "text": "<p>Here is a way to be able to use <code>Math.round()</code> with a second argument (number of decimals for rounding):</p>\n\n<pre><code>// 'improve' Math.round() to support a second argument\nvar _round = Math.round;\nMath.round = function(number, decimals /* optional, default 0 */)\n{\n if (arguments.length == 1)\n return _round(number);\n\n var multiplier = Math.pow(10, decimals);\n return _round(number * multiplier) / multiplier;\n}\n\n// examples\nMath.round('123.4567', 2); // =&gt; 123.46\nMath.round('123.4567'); // =&gt; 123\n</code></pre>\n" }, { "answer_id": 10480103, "author": "irfandar", "author_id": 1379441, "author_profile": "https://Stackoverflow.com/users/1379441", "pm_score": 4, "selected": false, "text": "<p>You can also use <code>toFixed(x)</code> or <code>toPrecision(x)</code> where <em>x</em> is the number of digits.</p>\n\n<p>Both these methods are supported in all major browsers</p>\n" }, { "answer_id": 18741520, "author": "user2768720", "author_id": 2768720, "author_profile": "https://Stackoverflow.com/users/2768720", "pm_score": 0, "selected": false, "text": "<p>A very good approximation for rounding:</p>\n\n<pre><code>function Rounding (number, precision){\n\nvar newNumber;\nvar sNumber = number.toString();\n\nvar increase = precision + sNumber.length - sNumber.indexOf('.') + 1;\n\nif (number &lt; 0)\n newNumber = (number - 5 * Math.pow(10,-increase));\nelse\n newNumber = (number + 5 * Math.pow(10,-increase));\n\nvar multiple = Math.pow(10,precision);\n\nreturn Math.round(newNumber * multiple)/multiple;\n}\n</code></pre>\n\n<p>Only in some cases when the length of the decimal part of the number is very long will it be incorrect.</p>\n" }, { "answer_id": 23690054, "author": "Praveen", "author_id": 554860, "author_profile": "https://Stackoverflow.com/users/554860", "pm_score": -1, "selected": false, "text": "<p>Math.floor(19.5) = 19 should also work.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18673/" ]
While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of ``` Name : Value Name2 : Value2 ``` etc. The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form `2.20011E+17`. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?
You hav to convert your input into a number and then round them: ``` function toInteger(number){ return Math.round( // round to nearest integer Number(number) // type cast your input ); }; ``` Or as a one liner: ``` function toInt(n){ return Math.round(Number(n)); }; ``` Testing with different values: ``` toInteger(2.5); // 3 toInteger(1000); // 1000 toInteger("12345.12345"); // 12345 toInteger("2.20011E+17"); // 220011000000000000 ```
246,215
<p>I am writing a shell script that takes file paths as input.</p> <p>For this reason, I need to generate recursive file listings with full paths. For example, the file <code>bar</code> has the path:</p> <pre><code>/home/ken/foo/bar </code></pre> <p>but, as far as I can see, both <code>ls</code> and <code>find</code> only give relative path listings:</p> <pre><code>./foo/bar (from the folder ken) </code></pre> <p>It seems like an obvious requirement, but I can't see anything in the <code>find</code> or <code>ls</code> man pages.</p> <p>How can I generate a list of files in the shell including their absolute paths?</p>
[ { "answer_id": 246220, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 10, "selected": true, "text": "<p>If you give <code>find</code> an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:</p>\n\n<pre><code>find \"$(pwd)\" -name .htaccess\n</code></pre>\n\n<p>or if your shell expands <code>$PWD</code> to the current directory:</p>\n\n<pre><code>find \"$PWD\" -name .htaccess\n</code></pre>\n\n<p><code>find</code> simply prepends the path it was given to a relative path to the file from that path. </p>\n\n<p><a href=\"https://stackoverflow.com/users/893/greg-hewgill\">Greg Hewgill</a> also suggested using <code>pwd -P</code> if you want to resolve symlinks in your current directory.</p>\n" }, { "answer_id": 246221, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": -1, "selected": false, "text": "<p><code>find / -print</code> will do this</p>\n" }, { "answer_id": 246224, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": false, "text": "<p>You can use </p>\n\n<pre><code>find $PWD \n</code></pre>\n\n<p>in bash</p>\n" }, { "answer_id": 1427114, "author": "didi", "author_id": 53094, "author_profile": "https://Stackoverflow.com/users/53094", "pm_score": 5, "selected": false, "text": "<pre><code>ls -d \"$PWD/\"*\n</code></pre>\n\n<p>This looks only in the <em>current</em> directory. It quotes \"$PWD\" in case it contains spaces.</p>\n" }, { "answer_id": 2162261, "author": "Trudius", "author_id": 261847, "author_profile": "https://Stackoverflow.com/users/261847", "pm_score": 3, "selected": false, "text": "<p>If you give the find command an absolute path, it will spit the results out with an absolute path. So, from the Ken directory if you were to type:</p>\n\n<pre><code>find /home/ken/foo/ -name bar -print \n</code></pre>\n\n<p>(instead of the relative path <code>find . -name bar -print</code>)</p>\n\n<p>You should get:</p>\n\n<pre><code>/home/ken/foo/bar\n</code></pre>\n\n<p>Therefore, if you want an <code>ls -l</code> and have it return the absolute path, you can just tell the find command to execute an <code>ls -l</code> on whatever it finds.</p>\n\n<pre><code>find /home/ken/foo -name bar -exec ls -l {} ;\\ \n</code></pre>\n\n<p>NOTE: There is a space between <code>{}</code> and <code>;</code></p>\n\n<p>You'll get something like this:</p>\n\n<pre><code>-rw-r--r-- 1 ken admin 181 Jan 27 15:49 /home/ken/foo/bar\n</code></pre>\n\n<p>If you aren't sure where the file is, you can always change the search location. As long as the search path starts with \"/\", you will get an absolute path in return. If you are searching a location (like /) where you are going to get a lot of permission denied errors, then I would recommend redirecting standard error so you can actually see the find results:</p>\n\n<pre><code>find / -name bar -exec ls -l {} ;\\ 2&gt; /dev/null\n</code></pre>\n\n<p>(<code>2&gt;</code> is the syntax for the Borne and Bash shells, but will not work with the C shell. It may work in other shells too, but I only know for sure that it works in Bourne and Bash).</p>\n" }, { "answer_id": 3105345, "author": "Albert", "author_id": 374636, "author_profile": "https://Stackoverflow.com/users/374636", "pm_score": -1, "selected": false, "text": "<pre><code>ls -1 | awk -vpath=$PWD/ '{print path$1}'\n</code></pre>\n" }, { "answer_id": 3572628, "author": "user431529", "author_id": 431529, "author_profile": "https://Stackoverflow.com/users/431529", "pm_score": 7, "selected": false, "text": "<p>Use this for dirs (the <code>/</code> after <code>**</code> is needed in bash to limit it to directories):</p>\n\n<pre><code>ls -d -1 \"$PWD/\"**/\n</code></pre>\n\n<p>this for files and directories directly under the current directory, whose names contain a <code>.</code>:</p>\n\n<pre><code>ls -d -1 \"$PWD/\"*.*\n</code></pre>\n\n<p>this for everything:</p>\n\n<pre><code>ls -d -1 \"$PWD/\"**/*\n</code></pre>\n\n<p>Taken from here\n <a href=\"http://www.zsh.org/mla/users/2002/msg00033.html\" rel=\"noreferrer\">http://www.zsh.org/mla/users/2002/msg00033.html</a></p>\n\n<p>In bash, <code>**</code> is recursive if you enable <code>shopt -s globstar</code>.</p>\n" }, { "answer_id": 4577170, "author": "balki", "author_id": 463758, "author_profile": "https://Stackoverflow.com/users/463758", "pm_score": 8, "selected": false, "text": "<pre><code>readlink -f filename \n</code></pre>\n\n<p>gives the full absolute path. but if the file is a symlink, u'll get the final resolved name.</p>\n" }, { "answer_id": 5493917, "author": "rxw", "author_id": 220472, "author_profile": "https://Stackoverflow.com/users/220472", "pm_score": 1, "selected": false, "text": "<pre><code>lspwd() { for i in $@; do ls -d -1 $PWD/$i; done }\n</code></pre>\n" }, { "answer_id": 7000260, "author": "Gurpreet", "author_id": 365358, "author_profile": "https://Stackoverflow.com/users/365358", "pm_score": 3, "selected": false, "text": "<p>The <code>$PWD</code> is a good option by Matthew above. If you want find to only print files then you can also add the -type f option to search only normal files. Other options are \"d\" for directories only etc. So in your case it would be (if i want to search only for files with .c ext):</p>\n\n<pre><code>find $PWD -type f -name \"*.c\" \n</code></pre>\n\n<p>or if you want all files:</p>\n\n<pre><code>find $PWD -type f\n</code></pre>\n\n<p>Note: You can't make an alias for the above command, because $PWD gets auto-completed to your home directory when the alias is being set by bash. </p>\n" }, { "answer_id": 54975344, "author": "Mike Behr", "author_id": 10860023, "author_profile": "https://Stackoverflow.com/users/10860023", "pm_score": 1, "selected": false, "text": "<p>Here's an example that prints out a list without an extra period and that also demonstrates how to search for a file match. Hope this helps:</p>\n\n<pre><code>find . -type f -name \"extr*\" -exec echo `pwd`/{} \\; | sed \"s|\\./||\"\n</code></pre>\n" }, { "answer_id": 55251492, "author": "GSM", "author_id": 2714227, "author_profile": "https://Stackoverflow.com/users/2714227", "pm_score": 4, "selected": false, "text": "<p><strong>Command:</strong> <code>ls -1 -d \"$PWD/\"*</code></p>\n\n<p>This will give the absolute paths of the file like below.</p>\n\n<pre><code>[root@kubenode1 ssl]# ls -1 -d \"$PWD/\"*\n/etc/kubernetes/folder/file-test-config.txt\n/etc/kubernetes/folder/file-test.txt\n/etc/kubernetes/folder/file-client.txt\n</code></pre>\n" }, { "answer_id": 58537748, "author": "Raveen Kumar", "author_id": 7914647, "author_profile": "https://Stackoverflow.com/users/7914647", "pm_score": 1, "selected": false, "text": "<p>This worked for me. But it didn't list in alphabetical order.</p>\n\n<pre><code>find \"$(pwd)\" -maxdepth 1\n</code></pre>\n\n<p>This command lists alphabetically as well as lists hidden files too.</p>\n\n<pre><code>ls -d -1 \"$PWD/\".*; ls -d -1 \"$PWD/\"*;\n</code></pre>\n" }, { "answer_id": 58540753, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 1, "selected": false, "text": "<h3><code>stat</code></h3>\n\n<p>Absolute path of a single file:</p>\n\n<pre><code>stat -c %n \"$PWD\"/foo/bar\n</code></pre>\n" }, { "answer_id": 58540801, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "<h3><a href=\"https://github.com/sharkdp/fd\" rel=\"noreferrer\"><code>fd</code></a></h3>\n\n<p>Using <code>fd</code> (alternative to <code>find</code>), use the following syntax:</p>\n\n<pre><code>fd . foo -a\n</code></pre>\n\n<p>Where <code>.</code> is the search pattern and <code>foo</code> is the root directory.</p>\n\n<p>E.g. to list all files in <code>etc</code> recursively, run: <code>fd . /etc -a</code>.</p>\n\n<blockquote>\n <p><code>-a</code>, <code>--absolute-path</code> Show absolute instead of relative paths</p>\n</blockquote>\n" }, { "answer_id": 59637390, "author": "Marisha", "author_id": 12005509, "author_profile": "https://Stackoverflow.com/users/12005509", "pm_score": 3, "selected": false, "text": "<p>Just an alternative to </p>\n\n<pre><code>ls -d \"$PWD/\"* \n</code></pre>\n\n<p>to pinpoint that <code>*</code> is shell expansion, so </p>\n\n<pre><code>echo \"$PWD/\"*\n</code></pre>\n\n<p>would do the same (the drawback you cannot use <code>-1</code> to separate by new lines, not spaces).</p>\n" }, { "answer_id": 60597033, "author": "fangxlmr", "author_id": 11372883, "author_profile": "https://Stackoverflow.com/users/11372883", "pm_score": 2, "selected": false, "text": "<p>You might want to try this.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>for name in /home/ken/foo/bar/*\ndo\n echo $name\ndone\n</code></pre>\n\n<p>You can get abs path using <code>for</code> loop and <code>echo</code> simply without <code>find</code>.</p>\n" }, { "answer_id": 61906980, "author": "Thyag", "author_id": 1338875, "author_profile": "https://Stackoverflow.com/users/1338875", "pm_score": 3, "selected": false, "text": "<p>If you need list of all files in current as well as sub-directories</p>\n\n<pre><code>find $PWD -type f\n</code></pre>\n\n<p>If you need list of all files only in current directory</p>\n\n<pre><code>find $PWD -maxdepth 1 -type f\n</code></pre>\n" }, { "answer_id": 62272135, "author": "JGurtz", "author_id": 287746, "author_profile": "https://Stackoverflow.com/users/287746", "pm_score": 1, "selected": false, "text": "<p>This will give the canonical path (will resolve symlinks): <code>realpath FILENAME</code></p>\n\n<p>If you want canonical path to the symlink itself, then: <code>realpath -s FILENAME</code></p>\n" }, { "answer_id": 62365350, "author": "Adam", "author_id": 13741548, "author_profile": "https://Stackoverflow.com/users/13741548", "pm_score": 1, "selected": false, "text": "<p>Most if not all of the suggested methods result in paths that cannot be used directly in some other terminal command if the path contains spaces. Ideally the results will have slashes prepended.\nThis works for me on macOS:</p>\n\n<pre><code>find / -iname \"*SEARCH TERM spaces are okay*\" -print 2&gt;&amp;1 | grep -v denied |grep -v permitted |sed -E 's/\\ /\\\\ /g'\n</code></pre>\n" }, { "answer_id": 63319024, "author": "linux.cnf", "author_id": 10000566, "author_profile": "https://Stackoverflow.com/users/10000566", "pm_score": 0, "selected": false, "text": "<p>Recursive files can be listed by many ways in Linux. Here I am sharing one liner script to clear all logs of files(only files) from <code>/var/log/</code> directory and second check recently which logs file has made an entry.</p>\n<p>First:</p>\n<pre><code>find /var/log/ -type f #listing file recursively \n</code></pre>\n<p>Second:</p>\n<pre><code>for i in $(find $PWD -type f) ; do cat /dev/null &gt; &quot;$i&quot; ; done #empty files recursively \n</code></pre>\n<p>Third use:</p>\n<pre><code>ls -ltr $(find /var/log/ -type f ) # listing file used in recent\n</code></pre>\n<p>Note: for directory location you can also pass <code>$PWD</code> instead of <code>/var/log</code>.</p>\n" }, { "answer_id": 66028792, "author": "Michael Yan", "author_id": 10330832, "author_profile": "https://Stackoverflow.com/users/10330832", "pm_score": 0, "selected": false, "text": "<p>If you don't have symbolic links, you could try</p>\n<pre class=\"lang-sh prettyprint-override\"><code>tree -iFL 1 [DIR]\n</code></pre>\n<p><code>-i</code> makes tree print filenames in each line, without the tree structure.</p>\n<p><code>-f</code> makes tree print the full path of each file.</p>\n<p><code>-L 1</code> avoids tree from recursion.</p>\n" }, { "answer_id": 66289574, "author": "Jabir Ali", "author_id": 4594212, "author_profile": "https://Stackoverflow.com/users/4594212", "pm_score": 3, "selected": false, "text": "<p>You can do</p>\n<pre><code>ls -1 |xargs realpath\n</code></pre>\n<p>If you need to specify an absolute path or relative path You can do that as well</p>\n<pre><code> ls -1 $FILEPATH |xargs realpath\n</code></pre>\n" }, { "answer_id": 67534394, "author": "Koder95", "author_id": 12581888, "author_profile": "https://Stackoverflow.com/users/12581888", "pm_score": 4, "selected": false, "text": "<p>Try this:</p>\n<pre><code>find &quot;$PWD&quot;/\n</code></pre>\n<p>You get <strong>list of absolute paths</strong> in working directory.</p>\n" }, { "answer_id": 67995568, "author": "geosmart", "author_id": 3480359, "author_profile": "https://Stackoverflow.com/users/3480359", "pm_score": 2, "selected": false, "text": "<p>find jar file recursely and print absolute path</p>\n<pre><code>`ls -R |grep &quot;\\.jar$&quot; | xargs readlink -f` \n</code></pre>\n<pre class=\"lang-sh prettyprint-override\"><code>/opt/tool/dev/maven_repo/com/oracle/ojdbc/ojdbc8-19.3.0.0.jar\n/opt/tool/dev/maven_repo/com/oracle/ojdbc/ons-19.3.0.0.jar\n/opt/tool/dev/maven_repo/com/oracle/ojdbc/oraclepki-19.3.0.0.jar\n/opt/tool/dev/maven_repo/com/oracle/ojdbc/osdt_cert-19.3.0.0.jar\n/opt/tool/dev/maven_repo/com/oracle/ojdbc/osdt_core-19.3.0.0.jar\n/opt/tool/dev/maven_repo/com/oracle/ojdbc/simplefan-19.3.0.0.jar\n/opt/tool/dev/maven_repo/com/oracle/ojdbc/ucp-19.3.0.0.jar\n\n</code></pre>\n" }, { "answer_id": 69397542, "author": "Daniel Kobe", "author_id": 4885784, "author_profile": "https://Stackoverflow.com/users/4885784", "pm_score": 2, "selected": false, "text": "<p>This works best if you want a dynamic solution that works well in a function</p>\n<pre><code>lfp ()\n{\n ls -1 $1 | xargs -I{} echo $(realpath $1)/{}\n}\n\n</code></pre>\n" }, { "answer_id": 73065141, "author": "Renju Ashokan", "author_id": 6531633, "author_profile": "https://Stackoverflow.com/users/6531633", "pm_score": 0, "selected": false, "text": "<p>Write one small function</p>\n<pre><code>lsf() {\nls `pwd`/$1\n}\n</code></pre>\n<p>Then you can use like</p>\n<pre><code>lsf test.sh \n</code></pre>\n<p>it gives full path like</p>\n<pre><code>/home/testuser/Downloads/test.sh\n</code></pre>\n" }, { "answer_id": 73781205, "author": "YouJiacheng", "author_id": 16613821, "author_profile": "https://Stackoverflow.com/users/16613821", "pm_score": 1, "selected": false, "text": "<pre class=\"lang-bash prettyprint-override\"><code>for p in &lt;either relative of absolute path of the directory&gt;/*; do\n echo $(realpath -s $p)\ndone\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
I am writing a shell script that takes file paths as input. For this reason, I need to generate recursive file listings with full paths. For example, the file `bar` has the path: ``` /home/ken/foo/bar ``` but, as far as I can see, both `ls` and `find` only give relative path listings: ``` ./foo/bar (from the folder ken) ``` It seems like an obvious requirement, but I can't see anything in the `find` or `ls` man pages. How can I generate a list of files in the shell including their absolute paths?
If you give `find` an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory: ``` find "$(pwd)" -name .htaccess ``` or if your shell expands `$PWD` to the current directory: ``` find "$PWD" -name .htaccess ``` `find` simply prepends the path it was given to a relative path to the file from that path. [Greg Hewgill](https://stackoverflow.com/users/893/greg-hewgill) also suggested using `pwd -P` if you want to resolve symlinks in your current directory.
246,223
<p>Is there any way to export data (not necessarily schema) to an access database via asp.net?</p> <p>The server has no office components installed and the process must occur via a webpage (like an excel export).</p>
[ { "answer_id": 246265, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>Here is a very detailed article. It is something I stumbled upon, not an approach I am familiar with:</p>\n\n<p><a href=\"http://www.stardeveloper.com/articles/display.html?article=2003031201&amp;page=1\" rel=\"nofollow noreferrer\">File Uploading to Access Database using ASP.NET\nby Faisal Khan.</a></p>\n" }, { "answer_id": 246959, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 3, "selected": true, "text": "<p>You have to do it programatically.</p>\n\n<ol>\n<li>Open the source table</li>\n<li>Create a new AccessDB using ADO Extensions (as shown above)</li>\n<li>Create the table in the AccessDB by reading the source schema (CREATE TABLE X ...)</li>\n<li>Iterate thought the source table inserting the records in the Access table</li>\n</ol>\n\n<p>Note: Code from <a href=\"http://www.freevbcode.com/ShowCode.asp?ID=5797\" rel=\"nofollow noreferrer\">http://www.freevbcode.com/ShowCode.asp?ID=5797</a> posted here in case the link cease to exists in the future</p>\n\n<pre><code> 'select References from the Project Menu, choose the COM tab, \n 'and add a reference to Microsoft ADO Ext. 2.7 for DDL and Security\n\n Public Function CreateAccessDatabase( ByVal DatabaseFullPath As String) As Boolean\n Dim bAns As Boolean\n Dim cat As New ADOX.Catalog()\n Try\n\n\n 'Make sure the folder\n 'provided in the path exists. If file name w/o path \n 'is specified, the database will be created in your\n 'application folder.\n\n Dim sCreateString As String\n sCreateString = _\n \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" &amp; _\n DatabaseFullPath\n cat.Create(sCreateString)\n\n bAns = True\n\n Catch Excep As System.Runtime.InteropServices.COMException\n bAns = False\n 'do whatever else you need to do here, log, \n 'msgbox etc.\n Finally\n cat = Nothing\n End Try\n Return bAns\n End Function\n\n\n DEMO\n ====\n\n\n ' If CreateAccessDatabase(\"F:\\test.mdb\") = True Then\n ' MsgBox(\"Database Created\")\n ' Else\n ' MsgBox(\"Database Creation Failed\")\n ' End If\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23230/" ]
Is there any way to export data (not necessarily schema) to an access database via asp.net? The server has no office components installed and the process must occur via a webpage (like an excel export).
You have to do it programatically. 1. Open the source table 2. Create a new AccessDB using ADO Extensions (as shown above) 3. Create the table in the AccessDB by reading the source schema (CREATE TABLE X ...) 4. Iterate thought the source table inserting the records in the Access table Note: Code from <http://www.freevbcode.com/ShowCode.asp?ID=5797> posted here in case the link cease to exists in the future ``` 'select References from the Project Menu, choose the COM tab, 'and add a reference to Microsoft ADO Ext. 2.7 for DDL and Security Public Function CreateAccessDatabase( ByVal DatabaseFullPath As String) As Boolean Dim bAns As Boolean Dim cat As New ADOX.Catalog() Try 'Make sure the folder 'provided in the path exists. If file name w/o path 'is specified, the database will be created in your 'application folder. Dim sCreateString As String sCreateString = _ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ DatabaseFullPath cat.Create(sCreateString) bAns = True Catch Excep As System.Runtime.InteropServices.COMException bAns = False 'do whatever else you need to do here, log, 'msgbox etc. Finally cat = Nothing End Try Return bAns End Function DEMO ==== ' If CreateAccessDatabase("F:\test.mdb") = True Then ' MsgBox("Database Created") ' Else ' MsgBox("Database Creation Failed") ' End If ```
246,225
<p>I need to create a midnight DateTime</p> <p>I've just done this:</p> <pre><code>DateTime endTime = DateTime.Now; endTime.Subtract(endTime.TimeOfDay); </code></pre> <p>Haven't test it yet, I'm assuming it works but is there a better/cleaner way?</p>
[ { "answer_id": 246229, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 9, "selected": true, "text": "<p>Just use <code>foo.Date</code>, or <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetime.today\" rel=\"noreferrer\"><code>DateTime.Today</code></a> for today's date</p>\n" }, { "answer_id": 246231, "author": "mmiika", "author_id": 6846, "author_profile": "https://Stackoverflow.com/users/6846", "pm_score": 4, "selected": false, "text": "<p>DateTime.Today</p>\n" }, { "answer_id": 246237, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetime.now\" rel=\"noreferrer\"><code>DateTime.Now</code></a> . <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetime.adddays\" rel=\"noreferrer\"><code>AddDays(1)</code></a> . <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date\" rel=\"noreferrer\"><code>Date</code></a></p>\n" }, { "answer_id": 246253, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 5, "selected": false, "text": "<pre><code>DateTime endTime = DateTime.Now.Date;\n</code></pre>\n\n<p>Now <code>endTime.TimeOfDay.ToString()</code> returns <code>\"00:00:00\"</code></p>\n" }, { "answer_id": 40780390, "author": "Aruna", "author_id": 2047527, "author_profile": "https://Stackoverflow.com/users/2047527", "pm_score": 4, "selected": false, "text": "<p>You can use <code>DateTime.Today</code> with exact seconds of the midnight. </p>\n\n<pre><code> DateTime today = DateTime.Today;\n DateTime mid = today.AddDays(1).AddSeconds(-1);\n Console.WriteLine(string.Format(\"Today: {0} , Mid Night: {1}\", today.ToString(), mid.ToString()));\n\n Console.ReadLine();\n</code></pre>\n\n<p>This should print :</p>\n\n<pre><code>Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM\n</code></pre>\n" }, { "answer_id": 41837573, "author": "David Petersen", "author_id": 7322542, "author_profile": "https://Stackoverflow.com/users/7322542", "pm_score": -1, "selected": false, "text": "<pre><code> private bool IsServiceDatabaseProcessReadyToStart()\n {\n bool isGoodParms = true;\n DateTime currentTime = DateTime.Now;\n //24 Hour Clock\n string[] timeSpan = currentTime.ToString(\"HH:mm:ss\").Split(':');\n //Default to Noon\n int hr = 12;\n int mn = 0;\n int sc = 0;\n\n if (!string.IsNullOrEmpty(timeSpan[0]))\n {\n hr = Convert.ToInt32(timeSpan[0]);\n }\n else\n {\n isGoodParms = false;\n }\n\n if (!string.IsNullOrEmpty(timeSpan[1]))\n {\n mn = Convert.ToInt32(timeSpan[1]);\n }\n else\n {\n isGoodParms = false;\n }\n\n if (!string.IsNullOrEmpty(timeSpan[2]))\n {\n sc = Convert.ToInt32(timeSpan[2]);\n }\n else\n {\n isGoodParms = false;\n }\n\n if (isGoodParms == true )\n {\n TimeSpan currentTimeSpan = new TimeSpan(hr, mn, sc);\n TimeSpan minTimeSpan = new TimeSpan(0, 0, 0);\n TimeSpan maxTimeSpan = new TimeSpan(0, 04, 59);\n if (currentTimeSpan &gt;= minTimeSpan &amp;&amp; currentTimeSpan &lt;= maxTimeSpan)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n</code></pre>\n" }, { "answer_id": 54315961, "author": "Peter", "author_id": 9221484, "author_profile": "https://Stackoverflow.com/users/9221484", "pm_score": 1, "selected": false, "text": "<pre><code>var dateMidnight = DateTime.ParseExact(DateTime.Now.ToString(\"yyyyMMdd\"), \"yyyyMMdd\", CultureInfo.InvariantCulture);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25462/" ]
I need to create a midnight DateTime I've just done this: ``` DateTime endTime = DateTime.Now; endTime.Subtract(endTime.TimeOfDay); ``` Haven't test it yet, I'm assuming it works but is there a better/cleaner way?
Just use `foo.Date`, or [`DateTime.Today`](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.today) for today's date
246,227
<p>There's an option to hide the version so it will display only nginx, but is there a way to hide that too so it will not show anything or change the header?</p>
[ { "answer_id": 246260, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": -1, "selected": false, "text": "<p>Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work. <a href=\"http://wiki.codemongers.com/NginxHttpHeadersModule\" rel=\"nofollow noreferrer\">http://wiki.codemongers.com/NginxHttpHeadersModule</a></p>\n" }, { "answer_id": 246294, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 7, "selected": true, "text": "<p>Like Apache, this is a quick edit to the source and recompile. From <a href=\"https://calomel.org/nginx.html\" rel=\"noreferrer\">Calomel.org</a>:</p>\n\n<blockquote>\n <p>The Server: string is the header which\n is sent back to the client to tell\n them what type of http server you are\n running and possibly what version.\n This string is used by places like\n Alexia and Netcraft to collect\n statistics about how many and of what\n type of web server are live on the\n Internet. To support the author and\n statistics for Nginx we recommend\n keeping this string as is. But, for\n security you may not want people to\n know what you are running and you can\n change this in the source code. Edit\n the source file\n <code>src/http/ngx_http_header_filter_module.c</code>\n at look at lines 48 and 49. You can\n change the String to anything you\n want.</p>\n</blockquote>\n\n<pre><code>## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)\nstatic char ngx_http_server_string[] = \"Server: MyDomain.com\" CRLF;\nstatic char ngx_http_server_full_string[] = \"Server: MyDomain.com\" CRLF;\n</code></pre>\n\n<p><strong>March 2011 edit:</strong> Props to Flavius below for pointing out a new option, replacing Nginx's standard <a href=\"http://wiki.nginx.org/HttpHeadersModule\" rel=\"noreferrer\">HttpHeadersModule</a> with the forked <a href=\"http://wiki.nginx.org/HttpHeadersMoreModule\" rel=\"noreferrer\">HttpHeadersMoreModule</a>. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.</p>\n" }, { "answer_id": 729553, "author": "Jauder Ho", "author_id": 26366, "author_profile": "https://Stackoverflow.com/users/26366", "pm_score": 2, "selected": false, "text": "<p>The only way is to modify the file src/http/ngx_http_header_filter_module.c . I changed nginx on line 48 to a different string.</p>\n\n<p>What you can do in the nginx config file is to set <em>server_tokens</em> to off. This will prevent nginx from printing the version number.</p>\n\n<p>To check things out, try <em>curl -I <a href=\"http://vurbu.com/\" rel=\"nofollow noreferrer\">http://vurbu.com/</a> | grep Server</em></p>\n\n<p>It should return</p>\n\n<pre><code>Server: Hai\n</code></pre>\n" }, { "answer_id": 2280486, "author": "Flavius", "author_id": 88054, "author_profile": "https://Stackoverflow.com/users/88054", "pm_score": 5, "selected": false, "text": "<p>There is a special module: <a href=\"http://wiki.nginx.org/NginxHttpHeadersMoreModule\" rel=\"nofollow noreferrer\">http://wiki.nginx.org/NginxHttpHeadersMoreModule</a></p>\n\n<blockquote>\n <p>This module allows you to add, set, or clear any output or input header that you specify.</p>\n \n <p>This is an enhanced version of the standard <a href=\"https://web.archive.org/web/20100209015711/http://wiki.nginx.org/NginxHttpHeadersModule\" rel=\"nofollow noreferrer\">headers</a> module because it provides more utilities like resetting or clearing \"builtin headers\" like <code>Content-Type</code>, <code>Content-Length</code>, and <code>Server</code>.</p>\n \n <p>It also allows you to specify an optional HTTP status code criteria using the <code>-s</code> option and an optional content type criteria using the <code>-t</code> option while modifying the output headers with the <a href=\"https://web.archive.org/web/20100209015711/http://wiki.nginx.org/NginxHttpHeadersMoreModule#more_set_headers\" rel=\"nofollow noreferrer\">more_set_headers</a> and <a href=\"https://web.archive.org/web/20100209015711/http://wiki.nginx.org/NginxHttpHeadersMoreModule#more_clear_headers\" rel=\"nofollow noreferrer\">more_clear_headers</a> directives...</p>\n</blockquote>\n" }, { "answer_id": 8139116, "author": "Rui Marques", "author_id": 379556, "author_profile": "https://Stackoverflow.com/users/379556", "pm_score": 5, "selected": false, "text": "<p>Simple, edit /etc/nginx/nginx.conf and remove comment from</p>\n\n<pre><code>#server_tokens off;\n</code></pre>\n\n<p>Search for <em>http</em> section.</p>\n" }, { "answer_id": 9253190, "author": "Brandon Rhodes", "author_id": 85360, "author_profile": "https://Stackoverflow.com/users/85360", "pm_score": 7, "selected": false, "text": "<p>If you are using nginx to proxy a back-end application and want the back-end to advertise its own <code>Server:</code> header without nginx overwriting it, then you can go inside of your <code>server {…}</code> stanza and set:</p>\n\n<pre><code>proxy_pass_header Server;\n</code></pre>\n\n<p>That will convince nginx to leave that header alone and not rewrite the value set by the back-end.</p>\n" }, { "answer_id": 23589719, "author": "Farshid Ashouri", "author_id": 895659, "author_profile": "https://Stackoverflow.com/users/895659", "pm_score": 5, "selected": false, "text": "<p>It’s very simple: Add these lines to server section:</p>\n\n<pre><code>server_tokens off;\nmore_set_headers 'Server: My Very Own Server';\n</code></pre>\n" }, { "answer_id": 29881550, "author": "Parthian Shot", "author_id": 3680301, "author_profile": "https://Stackoverflow.com/users/3680301", "pm_score": 4, "selected": false, "text": "<p>If you're okay with just changing the header to another string five letters or fewer, you can simply patch the binary.</p>\n\n<pre><code>sed -i 's/nginx\\r/thing\\r/' `which nginx`\n</code></pre>\n\n<p>Which, as a solution, has a few notable advantages. Namely, that you can allow your nginx versioning to be handled by the package manager (so, no compiling from source) even if nginx-extras isn't available for your distro, and you don't need to worry about any of the additional code of something like nginx-extras being vulnerable.</p>\n\n<p>Of course, you'll also want to set the option <code>server_tokens off</code>, to hide the version number, or patch that format string as well.</p>\n\n<p>I say \"five letters or fewer\" because of course you can always replace:</p>\n\n<blockquote>\n <p>nginx\\r\\0</p>\n</blockquote>\n\n<p>with</p>\n\n<blockquote>\n <p>bob\\r\\0\\r\\0</p>\n</blockquote>\n\n<p>leaving the last two bytes unchanged.</p>\n\n<p>If you actually want more than five characters, you'll want to leave server_tokens on, and replace the (slightly longer) format string, although again there's an upper limit on that length imposed by the length of the format string - 1 (for the carriage return).</p>\n\n<p>...If none of the above makes sense to you, or you've never patched a binary before, you may want to stay away from this approach, though.</p>\n" }, { "answer_id": 33513698, "author": "james-see", "author_id": 1215344, "author_profile": "https://Stackoverflow.com/users/1215344", "pm_score": 7, "selected": false, "text": "<p>The last update was a while ago, so here is what worked for me on Ubuntu:</p>\n\n<pre><code>sudo apt-get update\nsudo apt-get install nginx-extras\n</code></pre>\n\n<p>Then add the following two lines to the <code>http</code> section of <code>nginx.conf</code>, which is usually located at /etc/nginx/nginx.conf:</p>\n\n<pre><code>sudo nano /etc/nginx/nginx.conf\nserver_tokens off; # removed pound sign\nmore_set_headers 'Server: Eff_You_Script_Kiddies!';\n</code></pre>\n\n<p>Also, don't forget to restart nginx with <code>sudo service nginx restart</code>.</p>\n" }, { "answer_id": 44325540, "author": "Aamish Baloch", "author_id": 4776650, "author_profile": "https://Stackoverflow.com/users/4776650", "pm_score": 5, "selected": false, "text": "<p>Install Nginx Extras</p>\n\n<pre><code>sudo apt-get update\nsudo apt-get install nginx-extras\n</code></pre>\n\n<p>Server details can be removed from response by adding following two lines in the nginx.conf (under http section)</p>\n\n<pre><code>more_clear_headers Server;\nserver_tokens off;\n</code></pre>\n" }, { "answer_id": 51746866, "author": "Afrig Aminuddin", "author_id": 1124942, "author_profile": "https://Stackoverflow.com/users/1124942", "pm_score": 2, "selected": false, "text": "<p>After I read Parthian Shot's answer, I dig into <code>/usr/sbin/nginx</code> binary file. Then I found out that the file contains these three lines. </p>\n\n<pre><code>Server: nginx/1.12.2\nServer: nginx/1.12.2\nServer: nginx\n</code></pre>\n\n<p>Basically first two of them are meant for <code>server_tokens on;</code> directive (Server version included).\nThen I change the search criteria to match those lines within the binary file.</p>\n\n<pre><code>sed -i 's/Server: nginx/Server: thing/' `which nginx`\n</code></pre>\n\n<p>After I dig farther I found out that the error message produced by nginx is also included in this file.</p>\n\n<pre><code>&lt;hr&gt;&lt;center&gt;nginx&lt;/center&gt;\n</code></pre>\n\n<p>There are three of them, one without the version, two of them included the version. So I run the following command to replace nginx string within the error message.</p>\n\n<pre><code>sed -i 's/center&gt;nginx/center&gt;thing/' `which nginx`\n</code></pre>\n" }, { "answer_id": 55952210, "author": "Adrian", "author_id": 4681265, "author_profile": "https://Stackoverflow.com/users/4681265", "pm_score": 3, "selected": false, "text": "<p>According to nginx <a href=\"http://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens\" rel=\"noreferrer\">documentation</a> it supports custom values or even the exclusion: </p>\n\n<pre><code>Syntax: server_tokens on | off | build | string;\n</code></pre>\n\n<p>but sadly only with a <em>commercial subscription</em>: </p>\n\n<blockquote>\n <p>Additionally, as part of our commercial subscription, starting from\n version 1.9.13 the signature on error pages and the “Server” response\n header field value can be set explicitly using the string with\n variables. An empty string disables the emission of the “Server”\n field.</p>\n</blockquote>\n" }, { "answer_id": 56704160, "author": "creekorful", "author_id": 3042802, "author_profile": "https://Stackoverflow.com/users/3042802", "pm_score": 2, "selected": false, "text": "<p>I know the post is kinda old, but I have found a solution easy that works on Debian based distribution without compiling nginx from source.</p>\n\n<p>First install nginx-extras package</p>\n\n<blockquote>\n <p>sudo apt install nginx-extras</p>\n</blockquote>\n\n<p>Then load the nginx http headers more module by editing nginx.conf and adding the following line inside the server block</p>\n\n<blockquote>\n <p>load_module modules/ngx_http_headers_more_filter_module.so;</p>\n</blockquote>\n\n<p>Once it's done you'll have access to both more_set_headers and more_clear_headers directives.</p>\n" }, { "answer_id": 61628484, "author": "LazyDeveloper", "author_id": 10012744, "author_profile": "https://Stackoverflow.com/users/10012744", "pm_score": 0, "selected": false, "text": "<p>Nginx-extra package is deprecated now.</p>\n\n<p>The following therefore did now work for me as i tried installing various packages\nmore_set_headers 'Server: My Very Own Server';</p>\n\n<p>You can just do the following and no server or version information will be sent back</p>\n\n<pre><code> server_tokens '';\n</code></pre>\n\n<p>if you just want to remove the version number this works</p>\n\n<pre><code> server_tokens off;\n</code></pre>\n" }, { "answer_id": 73401209, "author": "Kristofer", "author_id": 1398417, "author_profile": "https://Stackoverflow.com/users/1398417", "pm_score": 0, "selected": false, "text": "<p>Expanding on Parthian Shot's answer, you can actually replace the whole header and not only the value as long as the total length is the same:</p>\n<pre><code>sed -i 's/Server: nginx/My-Header: hi/' `which nginx`\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
There's an option to hide the version so it will display only nginx, but is there a way to hide that too so it will not show anything or change the header?
Like Apache, this is a quick edit to the source and recompile. From [Calomel.org](https://calomel.org/nginx.html): > > The Server: string is the header which > is sent back to the client to tell > them what type of http server you are > running and possibly what version. > This string is used by places like > Alexia and Netcraft to collect > statistics about how many and of what > type of web server are live on the > Internet. To support the author and > statistics for Nginx we recommend > keeping this string as is. But, for > security you may not want people to > know what you are running and you can > change this in the source code. Edit > the source file > `src/http/ngx_http_header_filter_module.c` > at look at lines 48 and 49. You can > change the String to anything you > want. > > > ``` ## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49) static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF; static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF; ``` **March 2011 edit:** Props to Flavius below for pointing out a new option, replacing Nginx's standard [HttpHeadersModule](http://wiki.nginx.org/HttpHeadersModule) with the forked [HttpHeadersMoreModule](http://wiki.nginx.org/HttpHeadersMoreModule). Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.
246,228
<p>If I make a JFrame like this</p> <pre><code>public static void main(String[] args) { new JFrame().setVisible(true); } </code></pre> <p>then after closing the window the appication doesn't stop (I need to kill it).</p> <p>What is the proper way of showing application's main windows ?</p> <p>I'd also like to know a reason of a proposed solution.</p> <p>Thanks in advance.</p>
[ { "answer_id": 246234, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 6, "selected": true, "text": "<p>You should call the <code>setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</code> in your JFrame.</p>\n\n<p>Example code:</p>\n\n<pre><code>public static void main(String[] args) {\n Runnable guiCreator = new Runnable() {\n public void run() {\n JFrame fenster = new JFrame(\"Hallo Welt mit Swing\");\n fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n fenster.setVisible(true);\n }\n };\n SwingUtilities.invokeLater(guiCreator);\n}\n</code></pre>\n" }, { "answer_id": 246250, "author": "Yuval", "author_id": 2819, "author_profile": "https://Stackoverflow.com/users/2819", "pm_score": 2, "selected": false, "text": "<p>There's a difference between the application window and the application itself... The window runs in its own thread, and finishing <code>main()</code> will not end the application if other threads are still active. When closing the window you should also make sure to close the application, possibly by calling <code>System.exit(0);</code></p>\n\n<p>Yuval =8-)</p>\n" }, { "answer_id": 246279, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 2, "selected": false, "text": "<p>You must dispose the frame, invoking the dispose method in your window listener or using setDefaultCloseOperation. For the argument of the last one, you can use two options: </p>\n\n<p><code>DISPOSE_ON_CLOSE</code> or <code>EXIT_ON_CLOSE</code>. </p>\n\n<p><code>DISPOSE_ON_CLOSE</code> only dispose the frame resources. </p>\n\n<p><code>EXIT_ON_CLOSE</code> disposes the frame resources and then invokes <code>System.exit</code>.</p>\n\n<p>There is no real difference between the two unless you have non daemon threads.\nI prefer to use <code>DISPOSE_ON_CLOSE</code> because this way I'm able to notice if I forgot to terminate a thread, because the JVM will stop if there are no more threads running. That's also the reason closing a Frame without disposing will not terminate the application, since Swing creates a thread to handle events that is terminated only when dispose is invoked.</p>\n" }, { "answer_id": 8660157, "author": "giannis christofakis", "author_id": 839554, "author_profile": "https://Stackoverflow.com/users/839554", "pm_score": 0, "selected": false, "text": "<p>You can set a <em>window listener</em> to the frame so the program terminates after you close it.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>frame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent e) {\n System.exit(0);\n }\n}\n</code></pre>\n" }, { "answer_id": 43114906, "author": "Steve Smith", "author_id": 1551685, "author_profile": "https://Stackoverflow.com/users/1551685", "pm_score": 0, "selected": false, "text": "<p>The correct way to do this (unless you're writing a very trivial single-window app, i.e. no other windows or threads etc..) is to catch the <code>windowClosing()</code> event, and then call the <code>dispose();</code> method of the form.</p>\n\n<p>If your program doesn't completely exit after this, it means you have other non-deamon threads running, and you must stop these as best you see fit depending on your program.</p>\n\n<p>Calling <code>System.exit()</code> or <code>setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</code> will force stop any other threads (and the whole program), meaning your code is less portable, and force-stopping threads is obviously dangerous (in a programming kind of way).</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24028/" ]
If I make a JFrame like this ``` public static void main(String[] args) { new JFrame().setVisible(true); } ``` then after closing the window the appication doesn't stop (I need to kill it). What is the proper way of showing application's main windows ? I'd also like to know a reason of a proposed solution. Thanks in advance.
You should call the `setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);` in your JFrame. Example code: ``` public static void main(String[] args) { Runnable guiCreator = new Runnable() { public void run() { JFrame fenster = new JFrame("Hallo Welt mit Swing"); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fenster.setVisible(true); } }; SwingUtilities.invokeLater(guiCreator); } ```
246,232
<p>I have the following text</p> <pre><code>tooooooooooooon </code></pre> <p>According to this book I'm reading, when the <code>?</code> follows after any quantifier, it becomes non greedy.</p> <p>My regex <code>to*?n</code> is still returning <code>tooooooooooooon</code>.</p> <p>It should return <code>ton</code> shouldn't it?</p> <p>Any idea why?</p>
[ { "answer_id": 246236, "author": "Hank", "author_id": 7610, "author_profile": "https://Stackoverflow.com/users/7610", "pm_score": 2, "selected": false, "text": "<p>The string you are searching in (the haystack as it were) does not contain the substring \"ton\".</p>\n\n<p>It does however contain the substring \"tooooooooooooon\".</p>\n" }, { "answer_id": 246239, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 7, "selected": true, "text": "<p>A regular expression can only match a fragment of text that actually exists.</p>\n\n<p>Because the substring 'ton' doesn't exist anywhere in your string, it can't be the result of a match. A match will only return a substring of the original string</p>\n\n<p>EDIT: To be clear, if you were using the string below, with an extra 'n'</p>\n\n<pre><code>toooooooonoooooon\n</code></pre>\n\n<p>this regular expression (which doesn't specify 'o's)</p>\n\n<pre><code>t.*n\n</code></pre>\n\n<p>would match the following (as many characters as possible before an 'n')</p>\n\n<pre><code>toooooooonoooooon\n</code></pre>\n\n<p>but the regular expression</p>\n\n<pre><code>t.*?n\n</code></pre>\n\n<p>would only match the following (as few characters as possible before an 'n')</p>\n\n<pre><code>toooooooon\n</code></pre>\n" }, { "answer_id": 246244, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Regexps try to match everything in them. Because there are no less 'o's to match than every o in toooon to match the n, everything is matched. Also, because you are using o*? instead of o+? you are not requiring an o to be present.</p>\n\n<p>Example, in Perl</p>\n\n<pre><code>$a = \"toooooo\";\n$b = \"toooooon\";\n\nif ($a =~ m/(to*?)/) {\n print $1,\"\\n\";\n}\nif ($b =~ m/(to*?n)/) {\n print $1,\"\\n\";\n}\n\n~&gt;perl ex.pl\nt\ntoooooon\n</code></pre>\n" }, { "answer_id": 246255, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>A regular expression es always eager to match. </p>\n\n<p>Your expression says this:</p>\n\n<pre>\nA 't', followed by *as few as possible* 'o's, followed by a 'n'.\n</pre>\n\n<p>That means any o's necessary will be matched, because there is an 'n' at the end, which the expression is eager to reach. Matching all the o's is it's only possibility to succeed.</p>\n" }, { "answer_id": 249069, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "<p>The Regex always does its best to match. The only thing you are doing in this case would be slowing your parser down, by having it backtrack into the <code>/o*?/</code> node. Once for every single <code>'o'</code> in <code>&quot;tooooon&quot;</code>. Whereas with normal matching, it would take as many <code>'o'</code>s, as it can, the first time through. Since the next element to match against is <code>'n'</code>, which won't be matched by <code>'o'</code>, there is little point in trying to use minimal matching. Actually, when the normal matching fails, it would take quite a while for it to fail. It has to backtrack through every <code>'o'</code>, until there is none left to backtrack through. In this case I would actually use maximal matching <code>/to*+n/</code>. The <code>'o'</code> would take all it could, and never give any of it back. This would make it so that when it fails it fails quickly.</p>\n<h3>Minimal RE succeeding:</h3>\n<pre>\n'toooooon' ~~ /to*?n/\n\n t o o o o o o n \n{t} match [t]\n[t] match [o] 0 times\n[t]&lt;n&gt; fail to match [n] -> retry [o]\n[t]{o} match [o] 1 times\n[t][o]&lt;n&gt; fail to match [n] -> retry [o]\n[t][o]{o} match [o] 2 times\n[t][o][o]&lt;n&gt; fail to match [n] -> retry [o]\n\n. . . .\n\n[t][o][o][o][o]{o} match [o] 5 times\n[t][o][o][o][o][o]&lt;n&gt; fail to match [n] -> retry [o]\n[t][o][o][o][o][o]{o} match [o] 6 times\n[t][o][o][o][o][o][o]{n} match [n]\n</pre>\n<h3>Normal RE succeeding:</h3>\n<p><em>(NOTE: Similar for Maximal RE)</em></p>\n<pre>\n'toooooon' ~~ /to*n/\n\n t o o o o o o n \n{t} match [t]\n[t]{o}{o}{o}{o}{o}{o} match [o] 6 times\n[t][o][o][o][o][o][o]{n} match [n]\n\n</pre>\n<h3>Failure of Minimal RE:</h3>\n<pre>\n'toooooo' ~~ /to*?n/\n\n t o o o o o o\n\n. . . .\n\n. . . .\n\n[t][o][o][o][o]{o} match [o] 5 times\n[t][o][o][o][o][o]&lt;n&gt; fail to match [n] -> retry [o]\n[t][o][o][o][o][o]{o} match [o] 6 times\n[t][o][o][o][o][o][o]&lt;n&gt; fail to match [n] -> retry [o]\n[t][o][o][o][o][o][o]&lt;o&gt; fail to match [o] 7 times -> match failed\n</pre>\n<h3>Failure of Normal RE:</h3>\n<pre>\n'toooooo' ~~ /to*n/\n\n t o o o o o o \n{t} match [t]\n[t]{o}{o}{o}{o}{o}{o} match [o] 6 times\n[t][o][o][o][o][o][o]&lt;n&gt; fail to match [n] -> retry [o]\n[t][o][o][o][o][o] match [o] 5 times\n[t][o][o][o][o][o]&lt;n&gt; fail to match [n] -> retry [o]\n\n. . . .\n\n[t][o] match [o] 1 times\n[t][o]&lt;o&gt; fail to match [n] -> retry [o]\n[t] match [o] 0 times\n[t]&lt;n&gt; fail to match [n] -> match failed\n</pre>\n<h3>Failure of Maximal RE:</h3>\n<pre>\n'toooooo' ~~ /to*+n/\n\n t o o o o o o\n{t} match [t]\n[t]{o}{o}{o}{o}{o}{o} match [o] 6 times\n[t][o][o][o][o][o][o]&lt;n&gt; fail to match [n] -> match failed\n</pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
I have the following text ``` tooooooooooooon ``` According to this book I'm reading, when the `?` follows after any quantifier, it becomes non greedy. My regex `to*?n` is still returning `tooooooooooooon`. It should return `ton` shouldn't it? Any idea why?
A regular expression can only match a fragment of text that actually exists. Because the substring 'ton' doesn't exist anywhere in your string, it can't be the result of a match. A match will only return a substring of the original string EDIT: To be clear, if you were using the string below, with an extra 'n' ``` toooooooonoooooon ``` this regular expression (which doesn't specify 'o's) ``` t.*n ``` would match the following (as many characters as possible before an 'n') ``` toooooooonoooooon ``` but the regular expression ``` t.*?n ``` would only match the following (as few characters as possible before an 'n') ``` toooooooon ```
246,249
<p>Is there any way to add iCal event to the iPhone Calendar from the custom App?</p>
[ { "answer_id": 249141, "author": "keremk", "author_id": 29475, "author_profile": "https://Stackoverflow.com/users/29475", "pm_score": 4, "selected": false, "text": "<p>Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.</p>\n\n<p><a href=\"https://developer.apple.com/bugreporter/\" rel=\"nofollow noreferrer\">https://developer.apple.com/bugreporter/</a></p>\n" }, { "answer_id": 2108508, "author": "xgretsch", "author_id": 217953, "author_profile": "https://Stackoverflow.com/users/217953", "pm_score": 0, "selected": false, "text": "<p>The Google idea is a nice one, but has problems.</p>\n\n<p>I can successfully open a Google calendar event screen - but only on the main desktop version, and it doesn't display properly on iPhone Safari. The Google mobile calendar, which does display properly on Safari, doesn't seem to work with the API to add events.</p>\n\n<p>For the moment, I can't see a good way out of this one.</p>\n" }, { "answer_id": 2856933, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://developer.apple.com/technologies/iphone/whats-new.html\" rel=\"noreferrer\">Calendar access is being added in iPhone OS 4.0</a>:</p>\n\n<blockquote>\n <p><strong>Calendar Access</strong><br>\n Apps can now create and edit events directly in the\n Calendar app with Event Kit.<br>\n Create recurring events, set up start and end\n times and assign them to any calendar\n on the device.</p>\n</blockquote>\n" }, { "answer_id": 3177284, "author": "WoodenKitty", "author_id": 2684342, "author_profile": "https://Stackoverflow.com/users/2684342", "pm_score": 7, "selected": false, "text": "<p>You can do this using the Event Kit framework in OS 4.0.</p>\n\n<p>Right click on the FrameWorks group in the Groups and Files Navigator on the left of the window. Select 'Add' then 'Existing FrameWorks' then 'EventKit.Framework'. </p>\n\n<p>Then you should be able to add events with code like this:</p>\n\n<pre><code>#import \"EventTestViewController.h\"\n#import &lt;EventKit/EventKit.h&gt;\n\n@implementation EventTestViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n\n EKEventStore *eventStore = [[EKEventStore alloc] init];\n\n EKEvent *event = [EKEvent eventWithEventStore:eventStore];\n event.title = @\"EVENT TITLE\";\n\n event.startDate = [[NSDate alloc] init];\n event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];\n\n [event setCalendar:[eventStore defaultCalendarForNewEvents]];\n NSError *err;\n [eventStore saveEvent:event span:EKSpanThisEvent error:&amp;err]; \n}\n\n@end\n</code></pre>\n" }, { "answer_id": 11397272, "author": "Iggy", "author_id": 216354, "author_profile": "https://Stackoverflow.com/users/216354", "pm_score": 3, "selected": false, "text": "<p>You can add the event using the Event API like Tristan outlined and you can also add a Google Calendar event which shows up in the iOS calendar.</p>\n\n<p>using <a href=\"http://code.google.com/p/google-api-objectivec-client/source/browse/trunk/Examples/CalendarSample/CalendarSampleWindowController.m\" rel=\"noreferrer\">Google's API Objective-C Client</a> </p>\n\n<pre><code> - (void)addAnEvent {\n // Make a new event, and show it to the user to edit\n GTLCalendarEvent *newEvent = [GTLCalendarEvent object];\n newEvent.summary = @\"Sample Added Event\";\n newEvent.descriptionProperty = @\"Description of sample added event\";\n\n // We'll set the start time to now, and the end time to an hour from now,\n // with a reminder 10 minutes before\n NSDate *anHourFromNow = [NSDate dateWithTimeIntervalSinceNow:60*60];\n GTLDateTime *startDateTime = [GTLDateTime dateTimeWithDate:[NSDate date]\n timeZone:[NSTimeZone systemTimeZone]];\n GTLDateTime *endDateTime = [GTLDateTime dateTimeWithDate:anHourFromNow\n timeZone:[NSTimeZone systemTimeZone]];\n\n newEvent.start = [GTLCalendarEventDateTime object];\n newEvent.start.dateTime = startDateTime;\n\n newEvent.end = [GTLCalendarEventDateTime object];\n newEvent.end.dateTime = endDateTime;\n\n GTLCalendarEventReminder *reminder = [GTLCalendarEventReminder object];\n reminder.minutes = [NSNumber numberWithInteger:10];\n reminder.method = @\"email\";\n\n newEvent.reminders = [GTLCalendarEventReminders object];\n newEvent.reminders.overrides = [NSArray arrayWithObject:reminder];\n newEvent.reminders.useDefault = [NSNumber numberWithBool:NO];\n\n // Display the event edit dialog\n EditEventWindowController *controller = [[[EditEventWindowController alloc] init] autorelease];\n [controller runModalForWindow:[self window]\n event:newEvent\n completionHandler:^(NSInteger returnCode, GTLCalendarEvent *event) {\n // Callback\n if (returnCode == NSOKButton) {\n [self addEvent:event];\n }\n }];\n}\n</code></pre>\n" }, { "answer_id": 12153705, "author": "Rajesh_Bangalore", "author_id": 911831, "author_profile": "https://Stackoverflow.com/users/911831", "pm_score": 0, "selected": false, "text": "<p>Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....</p>\n" }, { "answer_id": 17331677, "author": "William T.", "author_id": 1807644, "author_profile": "https://Stackoverflow.com/users/1807644", "pm_score": 8, "selected": true, "text": "<p>Based on <a href=\"https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/EventKitProgGuide/ReadingAndWritingEvents.html#//apple_ref/doc/uid/TP40004775-SW1\" rel=\"noreferrer\">Apple Documentation</a>, this has changed a bit as of iOS 6.0.</p>\n\n<p>1) You should request access to the user's calendar via \"requestAccessToEntityType:completion:\" and execute the event handling inside of a block.</p>\n\n<p>2) You need to commit your event now or pass the \"commit\" param to your save/remove call</p>\n\n<p>Everything else stays the same...</p>\n\n<p>Add the EventKit framework and <code>#import &lt;EventKit/EventKit.h&gt;</code> to your code.</p>\n\n<p>In my example, I have a NSString *savedEventId instance property.</p>\n\n<p>To add an event:</p>\n\n<pre><code> EKEventStore *store = [EKEventStore new];\n [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {\n if (!granted) { return; }\n EKEvent *event = [EKEvent eventWithEventStore:store];\n event.title = @\"Event Title\";\n event.startDate = [NSDate date]; //today\n event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting\n event.calendar = [store defaultCalendarForNewEvents];\n NSError *err = nil;\n [store saveEvent:event span:EKSpanThisEvent commit:YES error:&amp;err];\n self.savedEventId = event.eventIdentifier; //save the event id if you want to access this later\n }];\n</code></pre>\n\n<p>Remove the event:</p>\n\n<pre><code> EKEventStore* store = [EKEventStore new];\n [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {\n if (!granted) { return; }\n EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId];\n if (eventToRemove) {\n NSError* error = nil;\n [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&amp;error];\n }\n }];\n</code></pre>\n\n<p>This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is</p>\n\n<p><em>Swift version</em></p>\n\n<p>You need to import the EventKit framework</p>\n\n<pre><code>import EventKit\n</code></pre>\n\n<p>Add event</p>\n\n<pre><code>let store = EKEventStore()\nstore.requestAccessToEntityType(.Event) {(granted, error) in\n if !granted { return }\n var event = EKEvent(eventStore: store)\n event.title = \"Event Title\"\n event.startDate = NSDate() //today\n event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting\n event.calendar = store.defaultCalendarForNewEvents\n do {\n try store.saveEvent(event, span: .ThisEvent, commit: true)\n self.savedEventId = event.eventIdentifier //save event id to access this particular event later\n } catch {\n // Display error to user\n }\n}\n</code></pre>\n\n<p>Remove event</p>\n\n<pre><code>let store = EKEventStore()\nstore.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in\n if !granted { return }\n let eventToRemove = store.eventWithIdentifier(self.savedEventId)\n if eventToRemove != nil {\n do {\n try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true)\n } catch {\n // Display error to user\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 34790334, "author": "Dashrath", "author_id": 1510544, "author_profile": "https://Stackoverflow.com/users/1510544", "pm_score": 3, "selected": false, "text": "<p>Swift 4.0 implementation :</p>\n\n<p>use import in top of page by <code>import EventKit</code></p>\n\n<p>then </p>\n\n<pre><code>@IBAction func addtoCalendarClicked(sender: AnyObject) {\n\n let eventStore = EKEventStore()\n\n eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in\n\n if (granted) &amp;&amp; (error == nil) {\n print(\"granted \\(granted)\")\n print(\"error \\(error)\")\n\n let event = EKEvent(eventStore: eventStore)\n\n event.title = \"Event Title\"\n event.startDate = Date()\n event.endDate = Date()\n event.notes = \"Event Details Here\"\n event.calendar = eventStore.defaultCalendarForNewEvents\n\n var event_id = \"\"\n do {\n try eventStore.save(event, span: .thisEvent)\n event_id = event.eventIdentifier\n }\n catch let error as NSError {\n print(\"json error: \\(error.localizedDescription)\")\n }\n\n if(event_id != \"\"){\n print(\"event added !\")\n }\n }\n })\n}\n</code></pre>\n" }, { "answer_id": 38269271, "author": "halbano", "author_id": 677210, "author_profile": "https://Stackoverflow.com/users/677210", "pm_score": 1, "selected": false, "text": "<p>Remember to set the endDate to the created event, it is mandatory. </p>\n\n<p>Otherwise it will fail (almost silently) with this error: </p>\n\n<pre><code>\"Error Domain=EKErrorDomain Code=3 \"No end date has been set.\" UserInfo={NSLocalizedDescription=No end date has been set.}\"\n</code></pre>\n\n<p>The complete working code for me is: </p>\n\n<pre><code>EKEventStore *store = [EKEventStore new];\n[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {\n if (!granted) { return; }\n EKEvent *calendarEvent = [EKEvent eventWithEventStore:store];\n calendarEvent.title = [NSString stringWithFormat:@\"CEmprendedor: %@\", _event.name];\n calendarEvent.startDate = _event.date;\n // 5 hours of duration, we must add the duration of the event to the API\n NSDate *endDate = [_event.date dateByAddingTimeInterval:60*60*5];\n calendarEvent.endDate = endDate;\n calendarEvent.calendar = [store defaultCalendarForNewEvents];\n NSError *err = nil;\n [store saveEvent:calendarEvent span:EKSpanThisEvent commit:YES error:&amp;err];\n self.savedEventId = calendarEvent.eventIdentifier; //saving the calendar event id to possibly deleted them\n}];\n</code></pre>\n" }, { "answer_id": 46721030, "author": "luhuiya", "author_id": 932672, "author_profile": "https://Stackoverflow.com/users/932672", "pm_score": 2, "selected": false, "text": "<p>Update for swift 4 for Dashrath answer</p>\n\n<pre><code>import UIKit\nimport EventKit\n\nclass ViewController: UIViewController {\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n let eventStore = EKEventStore()\n\n eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in\n\n if (granted) &amp;&amp; (error == nil) {\n\n\n let event = EKEvent(eventStore: eventStore)\n\n event.title = \"My Event\"\n event.startDate = Date(timeIntervalSinceNow: TimeInterval())\n event.endDate = Date(timeIntervalSinceNow: TimeInterval())\n event.notes = \"Yeah!!!\"\n event.calendar = eventStore.defaultCalendarForNewEvents\n\n var event_id = \"\"\n do{\n try eventStore.save(event, span: .thisEvent)\n event_id = event.eventIdentifier\n }\n catch let error as NSError {\n print(\"json error: \\(error.localizedDescription)\")\n }\n\n if(event_id != \"\"){\n print(\"event added !\")\n }\n }\n })\n }\n\n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n\n\n}\n</code></pre>\n\n<p>also don't forget to add permission for calendar usage \n<a href=\"https://i.stack.imgur.com/4lQEN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4lQEN.png\" alt=\"image for privary setting\"></a></p>\n" }, { "answer_id": 52961768, "author": "Alok", "author_id": 3024579, "author_profile": "https://Stackoverflow.com/users/3024579", "pm_score": 2, "selected": false, "text": "<p>Working code in Swift-4.2</p>\n\n<pre><code>import UIKit\nimport EventKit\nimport EventKitUI\n\nclass yourViewController: UIViewController{\n\n let eventStore = EKEventStore()\n\n func addEventToCalendar() {\n\n eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in\n DispatchQueue.main.async {\n if (granted) &amp;&amp; (error == nil) {\n let event = EKEvent(eventStore: self.eventStore)\n event.title = self.headerDescription\n event.startDate = self.parse(self.requestDetails.value(forKey: \"session_time\") as? String ?? \"\")\n event.endDate = self.parse(self.requestDetails.value(forKey: \"session_end_time\") as? String ?? \"\")\n let eventController = EKEventEditViewController()\n eventController.event = event\n eventController.eventStore = self.eventStore\n eventController.editViewDelegate = self\n self.present(eventController, animated: true, completion: nil)\n\n }\n }\n\n\n })\n }\n\n}\n</code></pre>\n\n<p>Now we will get the event screen and here you can also modify your settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rGDdS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rGDdS.png\" alt=\"enter image description here\"></a></p>\n\n<p><em>Now add delegate method to handle Cancel and add the event button action of event screen:</em></p>\n\n<pre><code> extension viewController: EKEventEditViewDelegate {\n\n func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {\n controller.dismiss(animated: true, completion: nil)\n\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> Don't forget to add <strong>NSCalendarsUsageDescription</strong> key into info plist.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26980/" ]
Is there any way to add iCal event to the iPhone Calendar from the custom App?
Based on [Apple Documentation](https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/EventKitProgGuide/ReadingAndWritingEvents.html#//apple_ref/doc/uid/TP40004775-SW1), this has changed a bit as of iOS 6.0. 1) You should request access to the user's calendar via "requestAccessToEntityType:completion:" and execute the event handling inside of a block. 2) You need to commit your event now or pass the "commit" param to your save/remove call Everything else stays the same... Add the EventKit framework and `#import <EventKit/EventKit.h>` to your code. In my example, I have a NSString \*savedEventId instance property. To add an event: ``` EKEventStore *store = [EKEventStore new]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (!granted) { return; } EKEvent *event = [EKEvent eventWithEventStore:store]; event.title = @"Event Title"; event.startDate = [NSDate date]; //today event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting event.calendar = [store defaultCalendarForNewEvents]; NSError *err = nil; [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err]; self.savedEventId = event.eventIdentifier; //save the event id if you want to access this later }]; ``` Remove the event: ``` EKEventStore* store = [EKEventStore new]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (!granted) { return; } EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId]; if (eventToRemove) { NSError* error = nil; [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error]; } }]; ``` This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is *Swift version* You need to import the EventKit framework ``` import EventKit ``` Add event ``` let store = EKEventStore() store.requestAccessToEntityType(.Event) {(granted, error) in if !granted { return } var event = EKEvent(eventStore: store) event.title = "Event Title" event.startDate = NSDate() //today event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting event.calendar = store.defaultCalendarForNewEvents do { try store.saveEvent(event, span: .ThisEvent, commit: true) self.savedEventId = event.eventIdentifier //save event id to access this particular event later } catch { // Display error to user } } ``` Remove event ``` let store = EKEventStore() store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in if !granted { return } let eventToRemove = store.eventWithIdentifier(self.savedEventId) if eventToRemove != nil { do { try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true) } catch { // Display error to user } } } ```
246,272
<p>I have a problem with how ASP.Net generates the <strong>img</strong> tag. I have a server control like this: </p> <pre><code>&lt;asp:Image runat="server" ID="someWarning" ImageUrl="~/images/warning.gif" AlternateText="Warning" /&gt; </code></pre> <p>I expect it to generate this: </p> <pre><code>&lt;img id="ctl00_ContentPlaceHolder1_ctl00_someWarning" src="../images/warning.gif" /&gt; </code></pre> <p>but instead it generates this:</p> <pre><code>&lt;img alt="" src="/Image.ashx;img=%2fimages%2fwarning.gif"&lt;/img&gt; </code></pre> <p>This give me errors when I execute the following js:</p> <pre><code>document.getElementById('ctl00_ContentPlaceHolder1_someWarning') </code></pre> <p>Any idea why it won't generate the expected html?</p>
[ { "answer_id": 246282, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": true, "text": "<p>Looks like it's trying to use a custom handler (ashx) to deliver the image. Do you have any additional modules that may be overriding the default behaviour of the asp:Image?</p>\n\n<p>Your JavaScript won't work because the image tag has not been given an ID in the HTML that was generated.</p>\n" }, { "answer_id": 251353, "author": "AaronS", "author_id": 26932, "author_profile": "https://Stackoverflow.com/users/26932", "pm_score": 0, "selected": false, "text": "<p>You can get the actual ID that is generated by using ClientID. I use this to get the ID of a control for use in JavaScript using syntax similar to the following:</p>\n\n<pre><code>document.getElementById('&lt;%=ddlCountry.ClientID%&gt;').style.display = \"block\";\n</code></pre>\n\n<p>However you can also use it in your code-behind to get the same thing.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2099426/" ]
I have a problem with how ASP.Net generates the **img** tag. I have a server control like this: ``` <asp:Image runat="server" ID="someWarning" ImageUrl="~/images/warning.gif" AlternateText="Warning" /> ``` I expect it to generate this: ``` <img id="ctl00_ContentPlaceHolder1_ctl00_someWarning" src="../images/warning.gif" /> ``` but instead it generates this: ``` <img alt="" src="/Image.ashx;img=%2fimages%2fwarning.gif"</img> ``` This give me errors when I execute the following js: ``` document.getElementById('ctl00_ContentPlaceHolder1_someWarning') ``` Any idea why it won't generate the expected html?
Looks like it's trying to use a custom handler (ashx) to deliver the image. Do you have any additional modules that may be overriding the default behaviour of the asp:Image? Your JavaScript won't work because the image tag has not been given an ID in the HTML that was generated.
246,274
<p>I want to be able to run a function in my firefox sidebar js file when the selected tab in the main content window is reloaded or changed. So the sidebar can change depending on the site the user is looking at. </p> <p>Anyone able to point me in the right direction?</p>
[ { "answer_id": 301756, "author": "user11198", "author_id": 11198, "author_profile": "https://Stackoverflow.com/users/11198", "pm_score": 2, "selected": false, "text": "<p>My solution pilfered from somewhere but can't remember where: </p>\n\n<pre><code>//add the load eventListener to the window object\nwindow.addEventListener(\"load\", function() { functioname.init(); }, true);\n\n\nvar functionname = { \n //add the listener for the document load event\ninit: function() {\n var appcontent = document.getElementById(\"appcontent\"); // browser\n if(appcontent)\n appcontent.addEventListener(\"DOMContentLoaded\", functionname.onPageLoad, false);\n },\n //function called on document load\n onPageLoad: function(aEvent) {\n if(aEvent.originalTarget.nodeName == \"#document\"){\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 647832, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>@oly1234 - your answer helped me to find the source:<br>\n<a href=\"https://developer.mozilla.org/en/Code_snippets/On_page_load\" rel=\"nofollow noreferrer\">Mozilla Developer Center - On page load</a> </p>\n\n<p>(<a href=\"https://developer.mozilla.org/en/Code_snippets/On_page_load\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/Code_snippets/On_page_load</a>)</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11198/" ]
I want to be able to run a function in my firefox sidebar js file when the selected tab in the main content window is reloaded or changed. So the sidebar can change depending on the site the user is looking at. Anyone able to point me in the right direction?
My solution pilfered from somewhere but can't remember where: ``` //add the load eventListener to the window object window.addEventListener("load", function() { functioname.init(); }, true); var functionname = { //add the listener for the document load event init: function() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent) appcontent.addEventListener("DOMContentLoaded", functionname.onPageLoad, false); }, //function called on document load onPageLoad: function(aEvent) { if(aEvent.originalTarget.nodeName == "#document"){ } } } ```
246,275
<p>I am working on a git repository with a master branch and another the topic branch. I have switched to topic branch and modified a file. Now, if I switched to the master branch, that same file is shown as modified.</p> <p>For example:</p> <p>git status in git-build branch:</p> <pre><code># On branch git-build # Changes to be committed: # (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) # # modified: cvsup_current # </code></pre> <p>Switch to master branch</p> <pre><code>[root@redbull builder_scripts (git-build)]# git co master M builder_scripts/cvsup_current Switched to branch &quot;master&quot; </code></pre> <p>git status in master branch</p> <pre><code>[root@redbull builder_scripts (master)]# git status # On branch master # Changes to be committed: # (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) # # modified: cvsup_current # </code></pre> <p>Why is that the file is shown as modified in the master branch even though it was modified in git-build branch?</p> <p>My understanding was that the branches are independent of each other and when I change from one branch to another the changes do not &quot;spill over&quot; from one branch to another. So I am obviously missing something here.</p> <p>Has anyone got a clue stick?</p>
[ { "answer_id": 246285, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>The modified files are not put in the repository until you add <em>and</em> commit them. If you switch back to your topic branch and commit the file, then it won't appear on the master branch.</p>\n" }, { "answer_id": 246286, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 5, "selected": true, "text": "<p>This is the default behaviour of git.</p>\n\n<p>You can use <strong>-f</strong> flag to checkout to do \"clean checkout\" if you like.</p>\n" }, { "answer_id": 246298, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 6, "selected": false, "text": "<blockquote>\n <p>Why is that the file is shown as modified in master branch even though it was modified in git-build branch?</p>\n</blockquote>\n\n<p>The key to remember is that the file was <strong>not</strong> modified in the git-build branch. It was only modified in your working copy.</p>\n\n<p>Only when you commit are the changes put back into whichever branch you have checked out</p>\n" }, { "answer_id": 246343, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 5, "selected": false, "text": "<p>If you want to temporarily store your changes to one branch while you go off to do work on another, you can use the <code>git stash</code> command. It's one of the amazing little unsung perks of using git. Example workflow:</p>\n\n<pre><code>git stash #work saved\ngit checkout master\n#edit files\ngit commit\ngit checkout git-build\ngit stash apply #restore earlier work\n</code></pre>\n\n<p><code>git stash</code> stores a stack of changes, so you can safely store multiple checkpoints. You can also give them names/descriptions. Full usage info <a href=\"http://git-scm.com/docs/git-stash\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 30775199, "author": "Raviteja", "author_id": 2067448, "author_profile": "https://Stackoverflow.com/users/2067448", "pm_score": 2, "selected": false, "text": "<ul>\n<li>It is not like git branches are dependent on each other but also they\ndo not have a complete code base separately for each branch either.</li>\n<li>For each commit, Git stores an object that contains a pointer to the\nchanges. So each branch points to its own latest commit and HEAD points to the branch currently you are in.</li>\n<li>When you switch the branch, the HEAD pointer points to that\nparticular commit of the branch. So if there are modified files, the\ndefault behavior is to copy over them.</li>\n</ul>\n\n<p>You can do the following things to overcome this issue. </p>\n\n<ol>\n<li>Use <code>-f</code> option to ignore the changes.</li>\n</ol>\n\n<p>If you want to save the changes: </p>\n\n<ol start=\"2\">\n<li>Commit the changes locally in the same branch and then switch the\nbranch.</li>\n<li>Use <code>git stash</code>, switch the branch, do your work, switch back to the\noriginal branch and do <code>git stash apply</code>.</li>\n</ol>\n" }, { "answer_id": 74043944, "author": "mirekphd", "author_id": 9962007, "author_profile": "https://Stackoverflow.com/users/9962007", "pm_score": 0, "selected": false, "text": "<p>In my experience this &quot;spillover&quot; problem arises because <code>git</code> does not protect &quot;untracked&quot; files from <code>git checkout</code> (only tracked but uncommitted files would be protected, i.e. user would be forced to <code>git commit</code> them before a <code>git checkout</code> is allowed to another branch).</p>\n<p>If you switch back to the original branch that created these files (and &quot;untracks&quot; them), these files become &quot;untracked&quot; again and can be <code>git add</code>'ed or <code>git rm</code>'ed.</p>\n<p>For me it looks like a bug: even &quot;untracked&quot; files should be protected from <code>git checkout</code>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25453/" ]
I am working on a git repository with a master branch and another the topic branch. I have switched to topic branch and modified a file. Now, if I switched to the master branch, that same file is shown as modified. For example: git status in git-build branch: ``` # On branch git-build # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: cvsup_current # ``` Switch to master branch ``` [root@redbull builder_scripts (git-build)]# git co master M builder_scripts/cvsup_current Switched to branch "master" ``` git status in master branch ``` [root@redbull builder_scripts (master)]# git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: cvsup_current # ``` Why is that the file is shown as modified in the master branch even though it was modified in git-build branch? My understanding was that the branches are independent of each other and when I change from one branch to another the changes do not "spill over" from one branch to another. So I am obviously missing something here. Has anyone got a clue stick?
This is the default behaviour of git. You can use **-f** flag to checkout to do "clean checkout" if you like.
246,280
<p>I have seen a function whose prototype is:</p> <pre><code>int myfunc(void** ppt) </code></pre> <p>This function is called in a C file as a = myfunc(mystruct **var1);</p> <p>where mystruct is typedef for one of structure we have. </p> <p>This works without any compilation errors in MSVC6.0, But when I compile it with some other C compiler, it gives an error at the place where this function is called with error message:</p> <p><strong>Argument of type mystruct ** is incompatible with parameter of type void **</strong></p> <p>The argument of myfunc() is kept as void** because it seems to be a generic malloc kind of function to be called with various structure variable types for memory allocation </p> <ol> <li>Is there any type such as void ** allowed in C standard/any C compilers?</li> <li>How do I fix this? [I tried casting the function call argument to <code>mystruct**</code>, but it didn't work]</li> </ol> <p>-AD</p>
[ { "answer_id": 246288, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": true, "text": "<p><code>void**</code> <em>is</em> valid but, based on your error message, you probably have to explicitly cast the argument as follows:</p>\n\n<pre><code>mystruct **var1;\nx = myfunc ((void**) var1);\n</code></pre>\n\n<p>That's because the <code>myfunc</code> function is expecting the <code>void**</code> type. While <code>void*</code> can be implicitly cast to any other pointer, that is not so for the double pointer - you need to explicitly cast it.</p>\n" }, { "answer_id": 246291, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "<p>This question is slightly confusing. But yes, <code>void **</code> is certainly legal and valid C, and means \"pointer to pointer to <code>void</code>\" as expected.</p>\n\n<p>I'm not sure about your example of a call, the arguments (\"mystruct **var1\") don't make sense. If <code>var1</code> is of type <code>mystruct **</code>, the call should just read <code>a = func(var1);</code>, this might be a typo.</p>\n\n<p>Casting should work, but you need to cast to <code>void **</code>, since that is what the function expects.</p>\n" }, { "answer_id": 246292, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "<p>As dirty as it may look like: sometimes you can't solve a problem without using void **.</p>\n" }, { "answer_id": 246372, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>There is a reason the compiler cannot automatically cast from <code>mystruct**</code> to <code>void**</code>.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>void stupid(struct mystruct **a, struct myotherstruct **b)\n{\n void **x = (void **)a;\n *x = *b;\n}\n</code></pre>\n\n<p>The compiler will not complain about the implicit cast from <code>myotherstruct*</code> to <code>void*</code> in the <code>*x = *b</code> line, even though that line is trying to put a pointer to a <code>myotherstruct</code> in a place where only pointers to <code>mystruct</code> should be put.</p>\n\n<p>The mistake is in fact in the previous line, which is converting \"a pointer to a place where pointers to <code>mystruct</code> can be put\" to \"a pointer to a place where pointers to <em>anything</em> can be put\". <em>This</em> is the reason there is no implicit cast. Of course, when you use a explicit cast, the compiler assumes you know what you are doing.</p>\n" }, { "answer_id": 248215, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yes, <code>void **</code> is perfectly acceptable and quite useful in certain circumstances. Also consider that given the declaration <code>void **foo</code> and <code>void *bar</code>, the compiler will know the size of the object pointed to by foo (it points to a pointer, and all pointers are the same size except on a few ancient platforms you needn't worry about), but it will not know the size of the object pointed to by bar (it could point to an object of any size). You can therefore safely perform pointer arithmetic on <code>void **</code> pointers but <strong>not</strong> on <code>void *</code> pointers. You must cast them to something else first, like a <code>char *</code>. GCC will allow you to pretend that <code>void *</code> and <code>char *</code> are equivalent, each pointing to an object a single byte in size, but this is nonstandard and nonportable.</p>\n" }, { "answer_id": 250706, "author": "George Eadon", "author_id": 30530, "author_profile": "https://Stackoverflow.com/users/30530", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"http://c-faq.com/\" rel=\"noreferrer\">comp.lang.c FAQ</a> addresses this issue in detail in <a href=\"http://c-faq.com/ptrs/genericpp.html\" rel=\"noreferrer\">Question 4.9</a>. In short, they say <strong>it's not strictly portable</strong> to cast an arbitrary pointer-to-pointer to a <code>void **</code>; they go on to explain that \"code like this may work and is sometimes recommended, but it relies on all pointer types having the same internal representation (which is common, but not universal).\" They go on to explain that \"any <code>void **</code> value you play with must be the address of an actual <code>void *</code> value somewhere; casts like <code>(void **)&amp;dp</code>, though they may shut the compiler up, are nonportable (and may not even do what you want).\"</p>\n\n<p>So, you can safely/portably achieve the desired behavior with code like:</p>\n\n<pre><code>some_type *var1 = foo();\nvoid *tmp_void_ptr = (void *)var1;\nmyfunc(&amp;tmp_void_ptr);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
I have seen a function whose prototype is: ``` int myfunc(void** ppt) ``` This function is called in a C file as a = myfunc(mystruct \*\*var1); where mystruct is typedef for one of structure we have. This works without any compilation errors in MSVC6.0, But when I compile it with some other C compiler, it gives an error at the place where this function is called with error message: **Argument of type mystruct \*\* is incompatible with parameter of type void \*\*** The argument of myfunc() is kept as void\*\* because it seems to be a generic malloc kind of function to be called with various structure variable types for memory allocation 1. Is there any type such as void \*\* allowed in C standard/any C compilers? 2. How do I fix this? [I tried casting the function call argument to `mystruct**`, but it didn't work] -AD
`void**` *is* valid but, based on your error message, you probably have to explicitly cast the argument as follows: ``` mystruct **var1; x = myfunc ((void**) var1); ``` That's because the `myfunc` function is expecting the `void**` type. While `void*` can be implicitly cast to any other pointer, that is not so for the double pointer - you need to explicitly cast it.
246,293
<p>Is there any good practice related to dynamic_cast error handling (except not using it when you don't have to)? I'm wondering how should I go about NULL and bad_cast it can throw. Should I check for both? And if I catch bad_cast or detect NULL I probably can't recover anyway... For now, I'm using assert to check if dynamic_cast returned not NULL value. Would you accept this solution on a code review?</p>
[ { "answer_id": 246313, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 1, "selected": false, "text": "<p>It depends... ;-)</p>\n\n<p>If I really expected the <code>dynamic_cast</code> to give me something usable, for example if I and no one else added a polymorphic type to a container of pointers to a base class, then I would go with the reference cast and let the <code>std::bad_cast</code> kill my application - there wouldn't be much else to do, really.</p>\n\n<p>However, if I'm querying a polymorphic type for some capability exposed by an interface that it doesn't necessarily have to implement, then I'd go with the pointer cast and then a NULL wouldn't be an error (unless, of course, I expected the capability to <em>really</em> be there - but then I'd had gone for the reference cast in the first place...)</p>\n" }, { "answer_id": 246323, "author": "Magnus Hoff", "author_id": 2971, "author_profile": "https://Stackoverflow.com/users/2971", "pm_score": 6, "selected": true, "text": "<p>If the <code>dynamic_cast</code> <em>should</em> succeed, it would be good practice to use <code>boost::polymorphic_downcast</code> instead, which goes a little something like this:</p>\n\n<pre><code>assert(dynamic_cast&lt;T*&gt;(o) == static_cast&lt;T*&gt;(o));\nreturn static_cast&lt;T*&gt;(o);\n</code></pre>\n\n<p>This way, you will detect errors in the debug build while at the same time avoiding the runtime overhead in a release build.</p>\n\n<p>If you suspect the cast <em>might</em> fail and you want to detect it, use <code>dynamic_cast</code> and cast to a reference type. This cast will throw <code>bad_cast</code> in case of error, and will take down your program. (This is good if, as you say, you are not going to recover anyway)</p>\n\n<pre><code>T&amp; t = dynamic_cast&lt;T&amp;&gt;(o);\nt.func(); //&lt; Use t here, no extra check required\n</code></pre>\n\n<p>Use <code>dynamic_cast</code> to a pointer type only if the 0-pointer makes sense in the context. You might want to use it in an <code>if</code> like this:</p>\n\n<pre><code>if (T* t = dynamic_cast&lt;T*&gt;(o)) {\n t-&gt;func(); //&lt; Use t here, it is valid\n}\n// consider having an else-clause\n</code></pre>\n\n<p>With this last option you need to make sure that the execution path makes sense if the <code>dynamic_cast</code> returns 0.</p>\n\n<p>To answer your question directly: I would prefer one of the two first alternatives I have given to having an explicit <code>assert</code> in the code :)</p>\n" }, { "answer_id": 246328, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 5, "selected": false, "text": "<p>bad_cast is only thrown when casting references</p>\n\n<pre><code>dynamic_cast&lt; Derived &amp; &gt;(baseclass)\n</code></pre>\n\n<p>NULL is returned when casting pointers</p>\n\n<pre><code>dynamic_cast&lt; Derived * &gt;(&amp;baseclass)\n</code></pre>\n\n<p>So there's never a need to check both.</p>\n\n<p>Assert can be acceptable, but that greatly depends on the context, then again, that's true for pretty much every assert...</p>\n" }, { "answer_id": 246331, "author": "Dave", "author_id": 32300, "author_profile": "https://Stackoverflow.com/users/32300", "pm_score": 0, "selected": false, "text": "<p>I'd concur with the 'it depends' answer, and also add \"Graceful degradation\": just because a cast fails somewhere isn't enough reason to let the application fail (and the user lose his/her work, etc.). I'd recommend a combination of asserts and defensive programming:</p>\n\n<pre><code>ptr = dynamic_cast&lt;MyClass&gt;(obj);\nASSERT(ptr);\nif(ptr)\n{\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 292356, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 2, "selected": false, "text": "<p>Yes and no.</p>\n\n<p><code>boost::polymorphic_downcast&lt;&gt;</code> is surely a good option to handle errors of <code>dynamic_cast&lt;&gt;</code> during the debug phase. However it's worth to mention that <code>polymorphic_downcast&lt;&gt;</code> should be used only when <em>it's possible to predict the polymorphic type passed at compile time</em>, otherwise the <code>dynamic_cast&lt;&gt;</code> should be used in place of it.</p>\n\n<p>However a sequence of: </p>\n\n<pre><code>if (T1* t1 = dynamic_cast&lt;T1*&gt;(o)) \n{ }\nif (T2* t2 = dynamic_cast&lt;T2*&gt;(o)) \n{ }\nif (T3* t3 = dynamic_cast&lt;T3*&gt;(o)) \n{ }\n</code></pre>\n\n<p>denotes a very bad design that should be settle by <strong>polymorphism</strong> and <strong>virtual functions</strong>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3579/" ]
Is there any good practice related to dynamic\_cast error handling (except not using it when you don't have to)? I'm wondering how should I go about NULL and bad\_cast it can throw. Should I check for both? And if I catch bad\_cast or detect NULL I probably can't recover anyway... For now, I'm using assert to check if dynamic\_cast returned not NULL value. Would you accept this solution on a code review?
If the `dynamic_cast` *should* succeed, it would be good practice to use `boost::polymorphic_downcast` instead, which goes a little something like this: ``` assert(dynamic_cast<T*>(o) == static_cast<T*>(o)); return static_cast<T*>(o); ``` This way, you will detect errors in the debug build while at the same time avoiding the runtime overhead in a release build. If you suspect the cast *might* fail and you want to detect it, use `dynamic_cast` and cast to a reference type. This cast will throw `bad_cast` in case of error, and will take down your program. (This is good if, as you say, you are not going to recover anyway) ``` T& t = dynamic_cast<T&>(o); t.func(); //< Use t here, no extra check required ``` Use `dynamic_cast` to a pointer type only if the 0-pointer makes sense in the context. You might want to use it in an `if` like this: ``` if (T* t = dynamic_cast<T*>(o)) { t->func(); //< Use t here, it is valid } // consider having an else-clause ``` With this last option you need to make sure that the execution path makes sense if the `dynamic_cast` returns 0. To answer your question directly: I would prefer one of the two first alternatives I have given to having an explicit `assert` in the code :)
246,296
<p>What possible reasons could exist for MySQL giving the error <code>“Access denied for user 'xxx'@'yyy'”</code> when trying to access a database using PHP-mysqli and working fine when using the command-line mysql tool with exactly the same username, password, socket, database and host?<br> <strong>Update:</strong><br> There were indeed three users in the <code>mysql.user</code> table, each one with a different host (but with the same hashed password), one was set to localhost, one to 127.0.0.1 and one to the machine’s host name. Deleting two of them and changing the host of the third to “%” had only one effect: now the access is denied using the command-line tool also. I did do a</p> <pre><code> select user(); </code></pre> <p>before that in the command line and it yielded the same xxx@yyy that were denied in php.</p>
[ { "answer_id": 246312, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 3, "selected": false, "text": "<p>Sometimes in php/mysql there is a difference between localhost and 127.0.0.1</p>\n\n<p>In mysql you grant access based on the host name, for localusers this would be localhost.\nI have seen php trying to connect with 'myservername' instead of localhost allthough in the config 'localhost' was defined.</p>\n\n<p>Try to grant access in mysql for 127.0.0.1 and connect in php over 127.0.0.1 port 3306.</p>\n" }, { "answer_id": 253108, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 0, "selected": false, "text": "<p>After I read your update I would suspect an error in/with the password.\nAre you using \"strange\" characters in your PW (something likely to cause utf-8/iso encoding problems)?</p>\n\n<p>Using % in the Host field would allow the user to connect from any host. So the only thing that could be wrong would be the password.</p>\n\n<p>Can you create another user. whith the \"grant all on all for '...'@'%' identiefied by 'somesimplepw'\" syntax, and try to connect with that user?\nDon't forget to 'flush privelidges' </p>\n\n<p>For info on how to create a new user klick <a href=\"http://dev.mysql.com/doc/mysql/en/adding-users.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 13875969, "author": "Raphael Schweikert", "author_id": 11940, "author_profile": "https://Stackoverflow.com/users/11940", "pm_score": 3, "selected": true, "text": "<p>In case anyone’s still interested: I never did solve this particular problem. It really seems like the problem was with the hardware I was running MySQL on. I’ve never seen anything remotely like it since.</p>\n" }, { "answer_id": 21916299, "author": "ste.cape", "author_id": 2828042, "author_profile": "https://Stackoverflow.com/users/2828042", "pm_score": 0, "selected": false, "text": "<p>Today the FTP service of my web hosting provider is having some trouble, so I decide to realize a local virtual webserver for working on my website. I have installed EasyPHP 14.1 with phpMyAdmin and I have created my user and my database with tables.</p>\n\n<p>First attempt: failed. I realized that the table I was looking for didn't exist. -> I solved creating the missing table.</p>\n\n<p>Second attempt: failed. I realized that username that I set for my new user was diffrent from the username I used for my connection. -> I edited username.</p>\n\n<p>Third attempt: failed. I realized that new database name was diffrent from database name I use for connection in my site. -> I edited db name.</p>\n\n<p>Forth attempt: failed. I realized that between privileges of my new user there wasn't \"Grant\". I don't even know what \"Grant\" means, but let's try to enable it -> Added \"Grant\" privilege.</p>\n\n<p>Fifth attempt: I win!</p>\n\n<p>I hope my little adventure could help someone. =)</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11940/" ]
What possible reasons could exist for MySQL giving the error `“Access denied for user 'xxx'@'yyy'”` when trying to access a database using PHP-mysqli and working fine when using the command-line mysql tool with exactly the same username, password, socket, database and host? **Update:** There were indeed three users in the `mysql.user` table, each one with a different host (but with the same hashed password), one was set to localhost, one to 127.0.0.1 and one to the machine’s host name. Deleting two of them and changing the host of the third to “%” had only one effect: now the access is denied using the command-line tool also. I did do a ``` select user(); ``` before that in the command line and it yielded the same xxx@yyy that were denied in php.
In case anyone’s still interested: I never did solve this particular problem. It really seems like the problem was with the hardware I was running MySQL on. I’ve never seen anything remotely like it since.
246,306
<p>How do I convert a keycode to a keychar in .NET?</p>
[ { "answer_id": 246309, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 4, "selected": false, "text": "<p>In VB.NET:</p>\n\n<pre><code>ChrW(70)\n</code></pre>\n\n<p>In C# you can cast:</p>\n\n<pre><code>(char) 70\n</code></pre>\n" }, { "answer_id": 1142756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>String.fromCharCode(event.keyCode)</p>\n" }, { "answer_id": 3001690, "author": "DaveH", "author_id": 361851, "author_profile": "https://Stackoverflow.com/users/361851", "pm_score": 0, "selected": false, "text": "<p>Convert.ToChar(Keys.Enter);</p>\n" }, { "answer_id": 5629660, "author": "Yiu Korochko", "author_id": 325238, "author_profile": "https://Stackoverflow.com/users/325238", "pm_score": -1, "selected": false, "text": "<p>I can't seem to reply to DaveH, but if you do as he says, it works fine!</p>\n\n<pre><code> Private Declare Function GetAsyncKeyState Lib \"user32\" (ByVal vKey As Long) As Integer\n Public sub harry()\n For i = 1 to 255\n If Chr(i) = Convert.ToChar(Keys.Enter) Then\n Label1.Text &amp;= \" [Enter] \"\n ElseIf Chr(i) = Convert.ToChar(Keys.Delete) Then\n Label1.Text &amp;= \" [Delete] \"\n End If\n Next i\n End Sub\n</code></pre>\n" }, { "answer_id": 6670641, "author": "MRb", "author_id": 841511, "author_profile": "https://Stackoverflow.com/users/841511", "pm_score": 1, "selected": false, "text": "<p>I found this snippet to be rather helpful in detecting a keypress from the enter key:</p>\n\n<pre><code>Private Sub StartValue_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles StartValue.KeyPress\n If ChrW(13).ToString = e.KeyChar And StartValue.Text = \"\" Then\n StartValue.Text = \"0\"\n End If\nEnd Sub\n</code></pre>\n\n<p>I found this to be a decent solution to having people trying to submit a null value in a textbox. This just forces a 0, but it uses the \"detect enter being pressed\" to run.</p>\n" }, { "answer_id": 6957338, "author": "Pablo Rausch", "author_id": 880683, "author_profile": "https://Stackoverflow.com/users/880683", "pm_score": 3, "selected": false, "text": "<p>I solved this using a library class from user32.dll.\nI would prefer a Framework class, but couldn't find one so this worked for me.</p>\n\n<pre><code>Imports System.Runtime.InteropServices\n\nPublic Class KeyCodeToAscii\n\n &lt;DllImport(\"User32.dll\")&gt; _\n Public Shared Function ToAscii(ByVal uVirtKey As Integer, _\n ByVal uScanCode As Integer, _\n ByVal lpbKeyState As Byte(), _\n ByVal lpChar As Byte(), _\n ByVal uFlags As Integer) _\n As Integer\n End Function\n\n &lt;DllImport(\"User32.dll\")&gt; _\n Public Shared Function GetKeyboardState(ByVal pbKeyState As Byte()) _\n As Integer\n\n End Function\n\n Public Shared Function GetAsciiCharacter(ByVal uVirtKey As Integer) _\n As Char\n\n Dim lpKeyState As Byte() = New Byte(255) {}\n GetKeyboardState(lpKeyState)\n Dim lpChar As Byte() = New Byte(1) {}\n If ToAscii(uVirtKey, 0, lpKeyState, lpChar, 0) = 1 Then\n Return Convert.ToChar((lpChar(0)))\n Else\n Return New Char()\n End If\n End Function\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 12894492, "author": "Hasitha D", "author_id": 1576214, "author_profile": "https://Stackoverflow.com/users/1576214", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>Char.ConvertFromUtf32(e.KeyValue)\n</code></pre>\n" }, { "answer_id": 19838142, "author": "Nooa", "author_id": 2965149, "author_profile": "https://Stackoverflow.com/users/2965149", "pm_score": -1, "selected": false, "text": "<p>Here an example from my side :)</p>\n\n<pre><code>#region Just for fun :D\n\nprivate string _lastKeys = \"\";\n\nprivate readonly Dictionary&lt;string, string[]&gt; _keyChecker = _\n new Dictionary&lt;string, string[]&gt;\n {\n // Key code to press, msgbox header, msgbox text\n {\"iddqd\", new[] {\"Cheater! :-)\", \"Godmode activated!\"}},\n {\"idkfa\", new[] {\"Cheater! :-)\", \"All Weapons unlocked!\"}},\n {\"aAa\", new[] {\"Testing\", \"Test!\"}},\n {\"aaa\", new[] {\"function\", \"close\"}}\n };\n\nprivate void KeyChecker(KeyPressEventArgs e)\n{\n _lastKeys += e.KeyChar;\n\n foreach (var key in _keyChecker.Keys)\n if (_lastKeys.EndsWith(key))\n if (_keyChecker[key][0] != \"function\")\n MessageBox.Show(_keyChecker[key][1], _keyChecker[key][0]);\n else\n KeyCheckerFunction(_keyChecker[key][1]);\n\n while (_lastKeys.Length &gt; 100)\n _lastKeys = _lastKeys.Substring(1);\n}\n\nprivate void KeyCheckerFunction(string func)\n{\n switch (func)\n {\n case \"close\":\n Close();\n break;\n }\n}\n\nprivate void FormMain_KeyPress(object sender, KeyPressEventArgs e)\n{\n KeyChecker(e);\n}\n\n#endregion Just for fun :D\n</code></pre>\n" }, { "answer_id": 70236087, "author": "Philippe Hollmuller", "author_id": 17596014, "author_profile": "https://Stackoverflow.com/users/17596014", "pm_score": -1, "selected": false, "text": "<p>In VBA or Vb6:</p>\n<p>Accessing from a KeyPress on a Button or other element sending a KeyCode:</p>\n<pre><code>Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)\n Label1.Caption = &quot;&quot;&quot;&quot; &amp; KeyCodeToUnicodeString(CLng(KeyCode)) &amp; &quot;&quot;&quot;&quot;\nEnd Sub\n</code></pre>\n<p>In a module copy this code:</p>\n<pre><code>Option Explicit\n'VB6\nPrivate Declare Function ToUnicode Lib &quot;user32&quot; (ByVal wVirtKey As Long, ByVal wScanCode As Long, lpKeyState As Byte, ByVal pwszBuff As String, ByVal cchBuff As Long, ByVal wFlags As Long) As Long\nPrivate Declare Function GetKeyboardState Lib &quot;user32&quot; (pbKeyState As Byte) As Long\n\n''VBA\n'#If VBA7 And Win64 Then\n' 'VBA7 And Win64\n' Private Declare PtrSafe Function GetKeyboardState Lib &quot;user32&quot; (pbKeyState As Byte) As Long\n' 'must be tested, maybe Long has to be replaced by Integer for 64 bit:\n' Private Declare PtrSafe Function ToUnicode Lib &quot;user32&quot; (ByVal wVirtKey As Long, ByVal wScanCode As Long, lpKeyState As Byte, ByVal pwszBuff As String, ByVal cchBuff As Long, ByVal wFlags As Long) As Long\n'#Else\n' 'VBA 32 bit\n' Private Declare Function GetKeyboardState Lib &quot;user32&quot; (pbKeyState As Byte) As Long\n' Private Declare Function ToUnicode Lib &quot;user32&quot; (ByVal wVirtKey As Long, ByVal wScanCode As Long, lpKeyState As Byte, ByVal pwszBuff As String, ByVal cchBuff As Long, ByVal wFlags As Long) As Long\n'#End If\n\n'Returns the text of the KeyCode pressed depending of the Keyboard language\n'Does not work on Win98 (returns &quot;&quot;) but works well on winXP and onwards\nPublic Function KeyCodeToUnicodeString(KeyCode As Long) As String\n On Error GoTo KeyCodeToUnicodeString_End\n Dim ret As Long\n Dim keyBoardState(0 To 255) As Byte\n Dim buffer As String * 256\n ret = GetKeyboardState(keyBoardState(0))\n Dim i As Long\n \n 'Special: This portion of code is important for the function to work properly after compilation.\n 'Why I do not know, but if removed, the next call to ret = ToUnicode will make a OutOfMemory Error\n 'because the keyBoardState array is not yet in a correct state.\n 'Tried Sleep or Byte b = keyBoardState(i) within the loop,\n 'but the only way to make it work properlyIN vb6 is coded here.\n 'If used in VBA, this part of code may be removed\n Dim s As String\n For i = 0 To 255\n s = s &amp; CStr(keyBoardState(i)) &amp; &quot;-&quot;\n Next i\n 'end of special portion of code\n \n If ret &lt;&gt; 0 Then\n ret = ToUnicode(KeyCode, 0, keyBoardState(0), buffer, Len(buffer), 0)\n buffer = StrConv(buffer, vbFromUnicode)\n If ret &lt;&gt; 0 Then\n On Error Resume Next\n KeyCodeToUnicodeString = Left(buffer, InStr(buffer, vbNullChar) - 1)\n Else\n KeyCodeToUnicodeString = &quot;&quot;\n End If\n End If\nKeyCodeToUnicodeString_End:\nEnd Function\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I convert a keycode to a keychar in .NET?
In VB.NET: ``` ChrW(70) ``` In C# you can cast: ``` (char) 70 ```
246,315
<p>I'm trying to compile such code:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class CPosition { private: int itsX,itsY; public: void Show(); void Set(int,int); }; void CPosition::Set(int a, int b) { itsX=a; itsY=b; } void CPosition::Show() { cout &lt;&lt; "x:" &lt;&lt; itsX &lt;&lt; " y:" &lt;&lt; itsY &lt;&lt; endl; } class CCube { friend class CPosition; private: CPosition Position; }; main() { CCube cube1; cube1.Position.Show(); cube1.Position.Set(2,3); cube1.Position.Show(); } </code></pre> <p>but get 'CCube::Position' is not accessible in function main() 3 times. I want class CPosition to be declared outside CCube so that I can use it in future in new classes e.g. CBall :) but how can I make it work without using inheritance. Is it possible :)?</p> <p>Regards, PK</p>
[ { "answer_id": 246324, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": "<p>errr, no, Position isnt visible in the function \"main\"</p>\n\n<p>Make it public... or put a public getter function in</p>\n" }, { "answer_id": 246327, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 2, "selected": false, "text": "<p>The statement <code>friend class CPosition;</code> means that CPosition can now access the private members of the CCube class. To every other class the members are still as private as you declared them. To make the sample work you'd:</p>\n\n<pre><code>class CCube\n{\n public:\n CPosition Position;\n};\n</code></pre>\n" }, { "answer_id": 246340, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 0, "selected": false, "text": "<p>Well, you already got an answer for the error. One things though:\nDo you plan on having the cube access the private members of CPosition (itsX, itsY)? If not, it doesn't need to be declared as a friend. If it is, consider exposing public methods in CPosition to return X and Y, and you still don't need to declare it as a friend.</p>\n\n<p>What I'm saying is that you need to make sure that you need to use friends. Here's a <a href=\"https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c\">good place to start</a>.</p>\n" }, { "answer_id": 246341, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 1, "selected": false, "text": "<p>Your friend declaration would need to be</p>\n\n<pre><code>friend int main();\n</code></pre>\n\n<p>You are giving 'main' permission to access CCube's private member.</p>\n" }, { "answer_id": 246391, "author": "Moomin", "author_id": 32312, "author_profile": "https://Stackoverflow.com/users/32312", "pm_score": 0, "selected": false, "text": "<p>OK it works with:</p>\n\n<pre><code>class CCube\n{\n private:\n CPosition Position;\n public:\n CPosition&amp; getPosition() { return Position; }\n};\n\nmain()\n{\n CCube cube1;\n\n cube1.getPosition().Show();\n cube1.getPosition().Set(2,3);\n cube1.getPosition().Show();\n}\n</code></pre>\n\n<p>Thanks</p>\n" }, { "answer_id": 246429, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>You have 3 questions in one: </p>\n\n<ol>\n<li>reusability of <code>CPosition</code></li>\n<li>how to influence a shape's state (in this case includes a member of type <code>CPosition</code>, but may also include an <code>int radius</code> or something else)</li>\n<li>Usage of the <code>friend</code> keyword</li>\n</ol>\n\n<p>You clearly say you need the CPosition class to be accessible from other places. Well, it is class. Problem 1 is solved.</p>\n\n<p>If you want you <code>CCube</code> users to be able to change a <code>CCube</code>'s position, you need to provide a means for that:</p>\n\n<ol>\n<li>By making <code>CCube::Position</code> public</li>\n<li>By adding accessor methods - <code>CCube::MoveTo( const CPosition&amp; p )</code> and <code>CCube::GetPosition() const</code>.</li>\n</ol>\n\n<p>As @Firas said: don't play with <code>friend</code> until you're really sure you need it.</p>\n" }, { "answer_id": 246611, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": true, "text": "<p>In addition to the normal getter you should also have a const getter.<br>\nPlease note the return by reference. This allows you any call to SetXX() to affect the copy of Position inside CCube and not the copy that you have been updating.</p>\n\n<pre><code>class CCube\n{\n private:\n CPosition Position;\n public:\n CPosition&amp; getPosition() { return Position; }\n CPosition const&amp; getPosition() const { return Position; }\n};\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32312/" ]
I'm trying to compile such code: ``` #include <iostream> using namespace std; class CPosition { private: int itsX,itsY; public: void Show(); void Set(int,int); }; void CPosition::Set(int a, int b) { itsX=a; itsY=b; } void CPosition::Show() { cout << "x:" << itsX << " y:" << itsY << endl; } class CCube { friend class CPosition; private: CPosition Position; }; main() { CCube cube1; cube1.Position.Show(); cube1.Position.Set(2,3); cube1.Position.Show(); } ``` but get 'CCube::Position' is not accessible in function main() 3 times. I want class CPosition to be declared outside CCube so that I can use it in future in new classes e.g. CBall :) but how can I make it work without using inheritance. Is it possible :)? Regards, PK
In addition to the normal getter you should also have a const getter. Please note the return by reference. This allows you any call to SetXX() to affect the copy of Position inside CCube and not the copy that you have been updating. ``` class CCube { private: CPosition Position; public: CPosition& getPosition() { return Position; } CPosition const& getPosition() const { return Position; } }; ```
246,321
<p>Here's a very simple question. I have an SP that inserts a row into a table and at the end there's the statement RETURN @@IDENTITY. What I can't seem to find is a way to retrieve this value in C#. I'm using the Enterprise library and using the method:</p> <pre><code>db.ExecuteNonQuery(cmd); </code></pre> <p>I've tried <strong>cmd.Parameters[0].Value</strong> to get the value but that returns 0 all the time. Any ideas?</p>
[ { "answer_id": 246332, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": 3, "selected": true, "text": "<pre><code>Dim c as new sqlcommand(\"...\")\n\nDim d As New SqlParameter()\nd.Direction = ParameterDirection.ReturnValue\nc.parameters.add(d)\n\nc.executeNonQuery\n\n(@@IDENTITY) = d.value\n</code></pre>\n\n<p>It is more or less like this...either this or just return the value from a stored procedure as an output parameter.</p>\n" }, { "answer_id": 246346, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>BTW, in most circumstances, you should use SCOPE_IDENTITY() rather than @@IDENTITY. <a href=\"http://msdn.microsoft.com/en-us/library/aa259185.aspx\" rel=\"noreferrer\">Ref</a>.</p>\n" }, { "answer_id": 246351, "author": "Neil Albrock", "author_id": 32124, "author_profile": "https://Stackoverflow.com/users/32124", "pm_score": 2, "selected": false, "text": "<p>One point to mention. You should really use SCOPE_IDENTITY to return the identity value after INSERT. There is potential for @@IDENTITY to return the wrong value. Especially if TRIGGERS are in use, writing value to other tables after INSERT.</p>\n\n<p>See the <a href=\"http://msdn.microsoft.com/en-us/library/ms190315.aspx\" rel=\"nofollow noreferrer\">Books Online</a> page for more detail.</p>\n" }, { "answer_id": 246352, "author": "thmsn", "author_id": 28145, "author_profile": "https://Stackoverflow.com/users/28145", "pm_score": 0, "selected": false, "text": "<p>Sounds to me like you want to execute with a scalar value</p>\n\n<pre><code>SqlCommand.ExecuteScalar()\n</code></pre>\n\n<p>as others have mentioned I think using SCOPE_IDENTITY() is more secure than the @@IDENTITY variable</p>\n" }, { "answer_id": 283583, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Someone says use </p>\n\n<p>IDENT_CURRENT('TableName')</p>\n\n<p><a href=\"http://www.velocityreviews.com/forums/t303448-return-identity-after-sql-insert.html\" rel=\"nofollow noreferrer\">http://www.velocityreviews.com/forums/t303448-return-identity-after-sql-insert.html</a></p>\n\n<p>-Zubair\n<a href=\"http://zubairdotnet.blogspot.com\" rel=\"nofollow noreferrer\">http://zubairdotnet.blogspot.com</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
Here's a very simple question. I have an SP that inserts a row into a table and at the end there's the statement RETURN @@IDENTITY. What I can't seem to find is a way to retrieve this value in C#. I'm using the Enterprise library and using the method: ``` db.ExecuteNonQuery(cmd); ``` I've tried **cmd.Parameters[0].Value** to get the value but that returns 0 all the time. Any ideas?
``` Dim c as new sqlcommand("...") Dim d As New SqlParameter() d.Direction = ParameterDirection.ReturnValue c.parameters.add(d) c.executeNonQuery (@@IDENTITY) = d.value ``` It is more or less like this...either this or just return the value from a stored procedure as an output parameter.
246,329
<p>This might be a naive question. I have to manually edit a .WXS file to make it support select features from command line.</p> <p>For example, there are 3 features in .WXS file.</p> <pre><code>&lt;Feature Id="AllFeature" Level='1'&gt; &lt;Feature Id="Feature1" Level='1'&gt; &lt;/Feature&gt; &lt;Feature Id="Feature2" Level='1'&gt; &lt;/Feature&gt; &lt;Feature Id="Feature3" Level='1'&gt; &lt;/Feature&gt; &lt;/Feature&gt; </code></pre> <p>Now, I want to select features from command line. Say, if I type "msiexec /i install.msi FEATURE=A", then "Feature1" and "Feature2" is installed; if I type "msiexec/i install.msi FEATURE=B", then "Feature1" and "Feature3" is installed. In this case, "A" maps to Feature 1 and 2; "B" maps to Feature 1 and 3.</p> <p>How to accomplish this in WIX?</p>
[ { "answer_id": 246920, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 6, "selected": true, "text": "<p>I would change Feature1, Feature2 and Feature3 to Components, then would declare something like this:</p>\n\n<pre><code>&lt;Feature Id=\"FEATUREA\" Title=\"Super\" Level=\"1\" &gt;\n &lt;ComponentRef Id=\"Component1\" /&gt;\n &lt;ComponentRef Id=\"Component2\" /&gt;\n&lt;/Feature&gt;\n\n&lt;Feature Id=\"FEATUREB\" Title=\"Super1\" Level=\"1\" &gt;\n &lt;ComponentRef Id=\"Component1\" /&gt;\n &lt;ComponentRef Id=\"Component3\"/&gt;\n&lt;/Feature&gt;\n</code></pre>\n\n<p>Then to Install either FeatureA or FeatureB</p>\n\n<pre><code>msiexec /i install.msi ADDLOCAL=[FEATUREA | FEATUREB]\n</code></pre>\n" }, { "answer_id": 247282, "author": "Rob Mensching", "author_id": 23852, "author_profile": "https://Stackoverflow.com/users/23852", "pm_score": 4, "selected": false, "text": "<p>There are a number of properties that can control the install states of Features. Check out this MSI SDK documentation and the links from it: <a href=\"http://msdn.microsoft.com/en-us/library/aa367536(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa367536(VS.85).aspx</a></p>\n" }, { "answer_id": 463875, "author": "Wim Coenen", "author_id": 52626, "author_profile": "https://Stackoverflow.com/users/52626", "pm_score": 6, "selected": false, "text": "<p>The accepted answer already mentions the ADDLOCAL property, but seems to imply that you can select only one feature. You can actually select multiple features by seperating them by commas like this:</p>\n\n<pre><code>msiexec /i install.msi ADDLOCAL=Feature1,Feature2\n</code></pre>\n\n<p>or</p>\n\n<pre><code>msiexec /i install.msi ADDLOCAL=Feature2,Feature3\n</code></pre>\n\n<p>Another hint: you can discover these feature names by opening the msi with <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa370557(v=vs.85).aspx\" rel=\"noreferrer\">orca</a>. This is very useful when you want to use these tricks to create a bootstrapper that installs certain features of thirdparty msi packages.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
This might be a naive question. I have to manually edit a .WXS file to make it support select features from command line. For example, there are 3 features in .WXS file. ``` <Feature Id="AllFeature" Level='1'> <Feature Id="Feature1" Level='1'> </Feature> <Feature Id="Feature2" Level='1'> </Feature> <Feature Id="Feature3" Level='1'> </Feature> </Feature> ``` Now, I want to select features from command line. Say, if I type "msiexec /i install.msi FEATURE=A", then "Feature1" and "Feature2" is installed; if I type "msiexec/i install.msi FEATURE=B", then "Feature1" and "Feature3" is installed. In this case, "A" maps to Feature 1 and 2; "B" maps to Feature 1 and 3. How to accomplish this in WIX?
I would change Feature1, Feature2 and Feature3 to Components, then would declare something like this: ``` <Feature Id="FEATUREA" Title="Super" Level="1" > <ComponentRef Id="Component1" /> <ComponentRef Id="Component2" /> </Feature> <Feature Id="FEATUREB" Title="Super1" Level="1" > <ComponentRef Id="Component1" /> <ComponentRef Id="Component3"/> </Feature> ``` Then to Install either FeatureA or FeatureB ``` msiexec /i install.msi ADDLOCAL=[FEATUREA | FEATUREB] ```
246,357
<p>I am reading WIX script written by others. There are some code really confuses me. </p> <pre><code>&lt;Custom Action='UnLoadSchedulerPerfCounters' After='InstallInitialize'&gt; &lt;![CDATA[(Installed) AND (!Scheduler = 3)]]&gt; &lt;/Custom&gt; &lt;Custom Action='RollbackSchedulerPerfCounters' After='WriteRegistryValues'&gt; &lt;![CDATA[(&amp;Scheduler = 3)]]&gt; &lt;/Custom&gt; </code></pre> <p>So, what's the difference between <code>!Scheduler</code> and <code>&amp;Scheduler</code>? Is any special meaning when property is prefix-ed by <code>&amp;</code> or <code>!</code>?</p>
[ { "answer_id": 246411, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 4, "selected": true, "text": "<p>From <a href=\"http://www.tramontana.co.hu/wix/lesson5.php#5.3\" rel=\"nofollow noreferrer\">http://www.tramontana.co.hu/wix/lesson5.php#5.3</a>:</p>\n\n<blockquote>\n <p>Prepending some special characters to\n the names will give them extra\n meaning:</p>\n\n<pre><code>% environment variable (name is case insensitive)\n$ action state of component\n? installed state of component\n&amp; action state of feature\n! installed state of feature\n</code></pre>\n \n <p>The last four can return the following\n integer values:</p>\n\n<pre><code>-1 no action to be taken\n1 advertised (only for components)\n2 not present\n3 on the local computer\n4 run from the source\n</code></pre>\n</blockquote>\n" }, { "answer_id": 247290, "author": "Rob Mensching", "author_id": 23852, "author_profile": "https://Stackoverflow.com/users/23852", "pm_score": 3, "selected": false, "text": "<p>Those are operators on the Windows Installer condition syntax. See this MSI SDK documentation for a complete list: <a href=\"http://msdn.microsoft.com/en-us/library/aa368012.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa368012.aspx</a>. </p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
I am reading WIX script written by others. There are some code really confuses me. ``` <Custom Action='UnLoadSchedulerPerfCounters' After='InstallInitialize'> <![CDATA[(Installed) AND (!Scheduler = 3)]]> </Custom> <Custom Action='RollbackSchedulerPerfCounters' After='WriteRegistryValues'> <![CDATA[(&Scheduler = 3)]]> </Custom> ``` So, what's the difference between `!Scheduler` and `&Scheduler`? Is any special meaning when property is prefix-ed by `&` or `!`?
From <http://www.tramontana.co.hu/wix/lesson5.php#5.3>: > > Prepending some special characters to > the names will give them extra > meaning: > > > > ``` > % environment variable (name is case insensitive) > $ action state of component > ? installed state of component > & action state of feature > ! installed state of feature > > ``` > > The last four can return the following > integer values: > > > > ``` > -1 no action to be taken > 1 advertised (only for components) > 2 not present > 3 on the local computer > 4 run from the source > > ``` > >
246,364
<p>I'm working on a piece of library code around <code>IDisposable</code>. The managed path (via <code>using</code>) is easily testable. I'm wondering about the finalizer though: Is calling <a href="http://msdn.microsoft.com/en-us/library/xe0c2357.aspx" rel="noreferrer"><code>System.GC.Collect()</code></a> sufficient to force the finalizer to run?</p>
[ { "answer_id": 246366, "author": "brien", "author_id": 4219, "author_profile": "https://Stackoverflow.com/users/4219", "pm_score": 0, "selected": false, "text": "<p>Could you mock out an <code>IDisposable</code> interface and expect a call to <code>Dispose</code>? That would at least let you see when the object is actually disposed.</p>\n" }, { "answer_id": 246375, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 4, "selected": true, "text": "<p>No, the GC.Collect() call is asynchronous, you would also need to call this:</p>\n\n<pre><code>System.GC.WaitForPendingFinalizers();\n</code></pre>\n" }, { "answer_id": 248499, "author": "Ben Fulton", "author_id": 6902, "author_profile": "https://Stackoverflow.com/users/6902", "pm_score": 0, "selected": false, "text": "<p>I think I would lean towards making Finalize() call another method, and test that the other method does what you want. You wouldn't get 100% code coverage, but at least you'd know that the method releases the object's resources properly.</p>\n" }, { "answer_id": 538203, "author": "Rob McCready", "author_id": 47525, "author_profile": "https://Stackoverflow.com/users/47525", "pm_score": 2, "selected": false, "text": "<p>I would take a look at <a href=\"http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae\" rel=\"nofollow noreferrer\">Dispose, Finalization, and Resource Management\n</a> its the best reference on the subject I know of. Using their pattern:</p>\n\n<pre><code>~ComplexCleanupBase()\n{\n Dispose(false);\n}\n\npublic void Dispose()\n{\n Dispose(true);\n GC.SuppressFinalize(this);\n}\n\nprotected override void Dispose(bool disposing)\n{\n if (!disposed)\n {\n if (disposing)\n {\n // dispose-only, i.e. non-finalizable logic\n }\n\n // new shared cleanup logic\n disposed = true;\n }\n\n base.Dispose(disposing);\n}\n</code></pre>\n\n<p>You wind up with dead simple Finalizer/Dispose() methods and a testable Dispose(bool). No need to force Finalization or anything using the GC class.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
I'm working on a piece of library code around `IDisposable`. The managed path (via `using`) is easily testable. I'm wondering about the finalizer though: Is calling [`System.GC.Collect()`](http://msdn.microsoft.com/en-us/library/xe0c2357.aspx) sufficient to force the finalizer to run?
No, the GC.Collect() call is asynchronous, you would also need to call this: ``` System.GC.WaitForPendingFinalizers(); ```
246,367
<p>My programming environment includes scripts for setting up my autobuild on a clean machine.</p> <p>One step uses a vbscript to configure a website on IIS that is used to monitor the build.</p> <p>On a particular machine I will be running apache on port 80 for a separate task.</p> <p>I would like my vbscript to set the port to 8080 for the new site that it is adding.</p> <p>How can I do this?</p>
[ { "answer_id": 246366, "author": "brien", "author_id": 4219, "author_profile": "https://Stackoverflow.com/users/4219", "pm_score": 0, "selected": false, "text": "<p>Could you mock out an <code>IDisposable</code> interface and expect a call to <code>Dispose</code>? That would at least let you see when the object is actually disposed.</p>\n" }, { "answer_id": 246375, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 4, "selected": true, "text": "<p>No, the GC.Collect() call is asynchronous, you would also need to call this:</p>\n\n<pre><code>System.GC.WaitForPendingFinalizers();\n</code></pre>\n" }, { "answer_id": 248499, "author": "Ben Fulton", "author_id": 6902, "author_profile": "https://Stackoverflow.com/users/6902", "pm_score": 0, "selected": false, "text": "<p>I think I would lean towards making Finalize() call another method, and test that the other method does what you want. You wouldn't get 100% code coverage, but at least you'd know that the method releases the object's resources properly.</p>\n" }, { "answer_id": 538203, "author": "Rob McCready", "author_id": 47525, "author_profile": "https://Stackoverflow.com/users/47525", "pm_score": 2, "selected": false, "text": "<p>I would take a look at <a href=\"http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae\" rel=\"nofollow noreferrer\">Dispose, Finalization, and Resource Management\n</a> its the best reference on the subject I know of. Using their pattern:</p>\n\n<pre><code>~ComplexCleanupBase()\n{\n Dispose(false);\n}\n\npublic void Dispose()\n{\n Dispose(true);\n GC.SuppressFinalize(this);\n}\n\nprotected override void Dispose(bool disposing)\n{\n if (!disposed)\n {\n if (disposing)\n {\n // dispose-only, i.e. non-finalizable logic\n }\n\n // new shared cleanup logic\n disposed = true;\n }\n\n base.Dispose(disposing);\n}\n</code></pre>\n\n<p>You wind up with dead simple Finalizer/Dispose() methods and a testable Dispose(bool). No need to force Finalization or anything using the GC class.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5427/" ]
My programming environment includes scripts for setting up my autobuild on a clean machine. One step uses a vbscript to configure a website on IIS that is used to monitor the build. On a particular machine I will be running apache on port 80 for a separate task. I would like my vbscript to set the port to 8080 for the new site that it is adding. How can I do this?
No, the GC.Collect() call is asynchronous, you would also need to call this: ``` System.GC.WaitForPendingFinalizers(); ```
246,400
<p>What is the best way of working with calculated fields of Propel objects?</p> <p>Say I have an object "Customer" that has a corresponding table "customers" and each column corresponds to an attribute of my object. What I would like to do is: add a calculated attribute "Number of completed orders" to my object when using it on View A but not on Views B and C.</p> <p>The calculated attribute is a COUNT() of "Order" objects linked to my "Customer" object via ID.</p> <p>What I can do now is to first select all Customer objects, then iteratively count Orders for all of them, but I'd think doing it in a single query would improve performance. But I cannot properly "hydrate" my Propel object since it does not contain the definition of the calculated field(s).</p> <p>How would you approach it?</p>
[ { "answer_id": 246900, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Add an attribute \"orders_count\" to a Customer, and then write something like this:</p>\n\n<pre><code>class Order {\n...\n public function save($conn = null) {\n $customer = $this->getCustomer();\n $customer->setOrdersCount($customer->getOrdersCount() + 1);\n $custoner->save();\n parent::save();\n }\n...\n}</code></pre>\n\n<p>You can use not only the \"save\" method, but the idea stays the same. Unfortunately, Propel doesn't support any \"magic\" for such fields.</p>\n" }, { "answer_id": 247259, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": true, "text": "<p>There are several choices. First, is to create a view in your DB that will do the counts for you, similar to my answer <a href=\"https://stackoverflow.com/questions/234785/#235267\">here</a>. I do this for a current Symfony project I work on where the read-only attributes for a given table are actually much, much wider than the table itself. This is my recommendation since grouping columns (max(), count(), etc) are read-only anyway.</p>\n\n<p>The other options are to actually build this functionality into your model. You absolutely CAN do this hydration yourself, but it's a bit complicated. Here's the rough steps</p>\n\n<ol>\n<li>Add the columns to your <em>Table</em> class as protected data members.</li>\n<li>Write the appropriate getters and setters for these columns</li>\n<li>Override the hydrate method and within, populate your new columns with the data from other queries. Make sure to call parent::hydrate() as the first line</li>\n</ol>\n\n<p>However, this isn't much better than what you're talking about already. You'll still need <em>N</em> + 1 queries to retrieve a single record set. However, you can get creative in step #3 so that <em>N</em> is the number of calculated columns, not the number of rows returned.</p>\n\n<p>Another option is to create a custom selection method on your <em>Table</em>Peer class.</p>\n\n<ol>\n<li>Do steps 1 and 2 from above.</li>\n<li>Write custom SQL that you will query manually via the Propel::getConnection() process.</li>\n<li>Create the dataset manually by iterating over the result set, and handle custom hydration at this point as to not break hydration when use by the doSelect processes.</li>\n</ol>\n\n<p>Here's an example of this approach</p>\n\n<pre><code>&lt;?php\n\nclass TablePeer extends BaseTablePeer\n{\n public static function selectWithCalculatedColumns()\n {\n // Do our custom selection, still using propel's column data constants\n $sql = \"\n SELECT \" . implode( ', ', self::getFieldNames( BasePeer::TYPE_COLNAME ) ) . \"\n , count(\" . JoinedTablePeer::ID . \") AS calc_col\n FROM \" . self::TABLE_NAME . \"\n LEFT JOIN \" . JoinedTablePeer::TABLE_NAME . \"\n ON \" . JoinedTablePeer::ID . \" = \" . self::FKEY_COLUMN\n ;\n\n // Get the result set\n $conn = Propel::getConnection();\n $stmt = $conn-&gt;prepareStatement( $sql );\n $rs = $stmt-&gt;executeQuery( array(), ResultSet::FETCHMODE_NUM );\n\n // Create an empty rowset\n $rowset = array();\n\n // Iterate over the result set\n while ( $rs-&gt;next() )\n {\n // Create each row individually\n $row = new Table();\n $startcol = $row-&gt;hydrate( $rs );\n\n // Use our custom setter to populate the new column\n $row-&gt;setCalcCol( $row-&gt;get( $startcol ) );\n $rowset[] = $row;\n }\n return $rowset;\n }\n}\n</code></pre>\n\n<p>There may be other solutions to your problem, but they are beyond my knowledge. Best of luck!</p>\n" }, { "answer_id": 250928, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 0, "selected": false, "text": "<p>Propel actually builds an automatic function based on the name of the linked field. Let's say you have a schema like this:</p>\n\n<pre><code>customer:\n id:\n name:\n ...\n\norder:\n id:\n customer_id: # links to customer table automagically\n completed: { type: boolean, default false }\n ...\n</code></pre>\n\n<p>When you build your model, your Customer object will have a method getOrders() that will retrieve all orders associated with that customer. You can then simply use count($customer->getOrders()) to get the number of orders for that customer.</p>\n\n<p>The downside is this will also fetch and hydrate those Order objects. On most RDBMS, the only performance difference between pulling the records or using COUNT() is the bandwidth used to return the results set. If that bandwidth would be significant for your application, you might want to create a method in the Customer object that builds the COUNT() query manually using Creole:</p>\n\n<pre><code> // in lib/model/Customer.php\n class Customer extends BaseCustomer\n {\n public function CountOrders()\n {\n $connection = Propel::getConnection();\n $query = \"SELECT COUNT(*) AS count FROM %s WHERE customer_id='%s'\";\n $statement = $connection-&gt;prepareStatement(sprintf($query, CustomerPeer::TABLE_NAME, $this-&gt;getId());\n $resultset = $statement-&gt;executeQuery();\n $resultset-&gt;next();\n return $resultset-&gt;getInt('count');\n }\n ...\n }\n</code></pre>\n" }, { "answer_id": 675263, "author": "apinstein", "author_id": 72114, "author_profile": "https://Stackoverflow.com/users/72114", "pm_score": 1, "selected": false, "text": "<p>I am doing this in a project now by overriding hydrate() and Peer::addSelectColumns() for accessing postgis fields:</p>\n\n<pre><code>// in peer\npublic static function locationAsEWKTColumnIndex()\n{\n return GeographyPeer::NUM_COLUMNS - GeographyPeer::NUM_LAZY_LOAD_COLUMNS;\n}\n\npublic static function polygonAsEWKTColumnIndex()\n{\n return GeographyPeer::NUM_COLUMNS - GeographyPeer::NUM_LAZY_LOAD_COLUMNS + 1;\n}\n\npublic static function addSelectColumns(Criteria $criteria)\n{\n parent::addSelectColumns($criteria);\n $criteria-&gt;addAsColumn(\"locationAsEWKT\", \"AsEWKT(\" . GeographyPeer::LOCATION . \")\");\n $criteria-&gt;addAsColumn(\"polygonAsEWKT\", \"AsEWKT(\" . GeographyPeer::POLYGON . \")\");\n}\n// in object\npublic function hydrate($row, $startcol = 0, $rehydrate = false)\n{\n $r = parent::hydrate($row, $startcol, $rehydrate);\n if ($row[GeographyPeer::locationAsEWKTColumnIndex()]) // load GIS info from DB IFF the location field is populated. NOTE: These fields are either both NULL or both NOT NULL, so this IF is OK\n {\n $this-&gt;location_ = GeoPoint::PointFromEWKT($row[GeographyPeer::locationAsEWKTColumnIndex()]); // load gis data from extra select columns See GeographyPeer::addSelectColumns().\n $this-&gt;polygon_ = GeoMultiPolygon::MultiPolygonFromEWKT($row[GeographyPeer::polygonAsEWKTColumnIndex()]); // load gis data from extra select columns See GeographyPeer::addSelectColumns().\n } \n return $r;\n} \n</code></pre>\n\n<p>There's something goofy with AddAsColumn() but I can't remember at the moment, but this does work. You can <a href=\"http://propel.phpdb.org/trac/ticket/681\" rel=\"nofollow noreferrer\">read more about the AddAsColumn() issues</a>.</p>\n" }, { "answer_id": 2523488, "author": "Ashton King", "author_id": 302496, "author_profile": "https://Stackoverflow.com/users/302496", "pm_score": 1, "selected": false, "text": "<p>Here's what I did to solve this without any additional queries:</p>\n\n<p><strong>Problem</strong></p>\n\n<p>Needed to add a custom COUNT field to a typical result set used with the Symfony Pager. However, as we know, Propel doesn't support this out the box. So the easy solution is to just do something like this in the template: </p>\n\n<pre><code>foreach ($pager-&gt;getResults() as $project):\n\n echo $project-&gt;getName() . ' and ' . $project-&gt;getNumMembers()\n\nendforeach;\n</code></pre>\n\n<p>Where <code>getNumMembers()</code> runs a separate COUNT query for each <code>$project</code> object. Of course, we know this is grossly inefficient because you can do the COUNT on the fly by adding it as a column to the original SELECT query, saving a query for each result displayed.</p>\n\n<p>I had several different pages displaying this result set, all using different Criteria. So writing my own SQL query string with PDO directly would be way too much hassle as I'd have to get into the Criteria object and mess around trying to form a query string based on whatever was in it!</p>\n\n<p>So, what I did in the end avoids all that, letting Propel's native code work with the Criteria and create the SQL as usual.</p>\n\n<p>1 - First create the [get/set]NumMembers() equivalent accessor/mutator methods in the model object that gets returning by the doSelect(). Remember, the accessor doesn't do the COUNT query anymore, it just holds its value.</p>\n\n<p>2 - Go into the peer class and override the parent doSelect() method and copy all code from it exactly as it is</p>\n\n<p>3 - Remove this bit because getMixerPreSelectHook is a private method of the base peer (or copy it into your peer if you need it):</p>\n\n<pre><code>// symfony_behaviors behavior\nforeach (sfMixer::getCallables(self::getMixerPreSelectHook(__FUNCTION__)) as $sf_hook)\n{\n call_user_func($sf_hook, 'BaseTsProjectPeer', $criteria, $con);\n}\n</code></pre>\n\n<p>4 - Now add your custom COUNT field to the doSelect method in your peer class:</p>\n\n<pre><code>// copied into ProjectPeer - overrides BaseProjectPeer::doSelectJoinUser()\npublic static function doSelectJoinUser(Criteria $criteria, ...)\n{\n // copied from parent method, along with everything else\n ProjectPeer::addSelectColumns($criteria);\n $startcol = (ProjectPeer::NUM_COLUMNS - ProjectPeer::NUM_LAZY_LOAD_COLUMNS);\n UserPeer::addSelectColumns($criteria);\n\n // now add our custom COUNT column after all other columns have been added\n // so as to not screw up Propel's position matching system when hydrating\n // the Project and User objects.\n $criteria-&gt;addSelectColumn('COUNT(' . ProjectMemberPeer::ID . ')');\n\n // now add the GROUP BY clause to count members by project\n $criteria-&gt;addGroupByColumn(self::ID);\n\n // more parent code\n\n ...\n\n // until we get to this bit inside the hydrating loop:\n\n $obj1 = new $cls();\n $obj1-&gt;hydrate($row);\n\n // AND...hydrate our custom COUNT property (the last column)\n $obj1-&gt;setNumMembers($row[count($row) - 1]);\n\n // more code copied from parent\n\n ...\n\n return $results; \n}\n</code></pre>\n\n<p>That's it. Now you have the additional COUNT field added to your object without doing a separate query to get it as you spit out the results. The only drawback to this solution is that you've had to copy all the parent code because you need to add bits right in the middle of it. But in my situation, this seemed like a small compromise to save all those queries and not write my own SQL query string.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2706/" ]
What is the best way of working with calculated fields of Propel objects? Say I have an object "Customer" that has a corresponding table "customers" and each column corresponds to an attribute of my object. What I would like to do is: add a calculated attribute "Number of completed orders" to my object when using it on View A but not on Views B and C. The calculated attribute is a COUNT() of "Order" objects linked to my "Customer" object via ID. What I can do now is to first select all Customer objects, then iteratively count Orders for all of them, but I'd think doing it in a single query would improve performance. But I cannot properly "hydrate" my Propel object since it does not contain the definition of the calculated field(s). How would you approach it?
There are several choices. First, is to create a view in your DB that will do the counts for you, similar to my answer [here](https://stackoverflow.com/questions/234785/#235267). I do this for a current Symfony project I work on where the read-only attributes for a given table are actually much, much wider than the table itself. This is my recommendation since grouping columns (max(), count(), etc) are read-only anyway. The other options are to actually build this functionality into your model. You absolutely CAN do this hydration yourself, but it's a bit complicated. Here's the rough steps 1. Add the columns to your *Table* class as protected data members. 2. Write the appropriate getters and setters for these columns 3. Override the hydrate method and within, populate your new columns with the data from other queries. Make sure to call parent::hydrate() as the first line However, this isn't much better than what you're talking about already. You'll still need *N* + 1 queries to retrieve a single record set. However, you can get creative in step #3 so that *N* is the number of calculated columns, not the number of rows returned. Another option is to create a custom selection method on your *Table*Peer class. 1. Do steps 1 and 2 from above. 2. Write custom SQL that you will query manually via the Propel::getConnection() process. 3. Create the dataset manually by iterating over the result set, and handle custom hydration at this point as to not break hydration when use by the doSelect processes. Here's an example of this approach ``` <?php class TablePeer extends BaseTablePeer { public static function selectWithCalculatedColumns() { // Do our custom selection, still using propel's column data constants $sql = " SELECT " . implode( ', ', self::getFieldNames( BasePeer::TYPE_COLNAME ) ) . " , count(" . JoinedTablePeer::ID . ") AS calc_col FROM " . self::TABLE_NAME . " LEFT JOIN " . JoinedTablePeer::TABLE_NAME . " ON " . JoinedTablePeer::ID . " = " . self::FKEY_COLUMN ; // Get the result set $conn = Propel::getConnection(); $stmt = $conn->prepareStatement( $sql ); $rs = $stmt->executeQuery( array(), ResultSet::FETCHMODE_NUM ); // Create an empty rowset $rowset = array(); // Iterate over the result set while ( $rs->next() ) { // Create each row individually $row = new Table(); $startcol = $row->hydrate( $rs ); // Use our custom setter to populate the new column $row->setCalcCol( $row->get( $startcol ) ); $rowset[] = $row; } return $rowset; } } ``` There may be other solutions to your problem, but they are beyond my knowledge. Best of luck!
246,407
<p>Does anyone know how could I programatically disable/enable sleep mode on Windows Mobile?</p> <p>Thanks!</p>
[ { "answer_id": 246423, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>Probably by modifying the \"System Power States\" as <a href=\"http://www.codeproject.com/KB/mobile/WiMoPower1.aspx\" rel=\"nofollow noreferrer\">described here</a> (but in c#)</p>\n\n<p>That article also describes a way to prevent the mobile device to sleep (which is not exactly what you may want), by calling the native function SystemIdleTimerReset() periodically (to prevent the device from powering down).</p>\n" }, { "answer_id": 246794, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": false, "text": "<p>Modify <a href=\"http://msdn.microsoft.com/en-us/library/aa932196.aspx\" rel=\"nofollow noreferrer\">the Power Manager registry setting</a> that affects the specific sleep condition you want (timeout, batter, AC power, etc) and the SetEvent on a named system event called \"PowerManager/ReloadActivityTimeouts\" to tell the OS to reload the settings.</p>\n" }, { "answer_id": 248673, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 4, "selected": true, "text": "<p>If you want your program to not be put to sleep while it's running, the best way is to create a KeepAlive type function that calls SystemIdleTimerReset, SHIdleTimerReset and simulates a key touch. Then you need to call it a lot, basically everywhere.</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;commctrl.h&gt;\n\nextern \"C\"\n{\n void WINAPI SHIdleTimerReset();\n};\n\nvoid KeepAlive()\n{\n static DWORD LastCallTime = 0;\n DWORD TickCount = GetTickCount();\n if ((TickCount - LastCallTime) &gt; 1000 || TickCount &lt; LastCallTime) // watch for wraparound\n {\n SystemIdleTimerReset();\n SHIdleTimerReset();\n keybd_event(VK_LBUTTON, 0, KEYEVENTF_SILENT, 0);\n keybd_event(VK_LBUTTON, 0, KEYEVENTF_KEYUP | KEYEVENTF_SILENT, 0);\n LastCallTime = TickCount;\n }\n}\n</code></pre>\n\n<p>This method only works when the user starts the application manually.</p>\n\n<p>If your application is started by a notification (i.e. while the device is suspended), then you need to do more or else your application will be suspended after a very short period of time until the user powers the device out of suspended mode. To handle this you need to put the device into unattended power mode. </p>\n\n<pre><code>if(!::PowerPolicyNotify (PPN_UNATTENDEDMODE, TRUE))\n{\n // handle error\n}\n\n// do long running process\n\nif(!::PowerPolicyNotify (PPN_UNATTENDEDMODE, FALSE))\n{\n // handle error\n}\n</code></pre>\n\n<p>During unattended mode use, you still need to call the KeepAlive a lot, you can use a separate thread that sleeps for x milliseconds and calls the keep alive funcation. </p>\n\n<p>Please note that unattended mode does not bring it out of sleep mode, it puts the device in a weird half-awake state.</p>\n\n<p>So if you start a unattended mode while the device in suspended mode, it will not wake up the screen or anything. All unattended mode does is stop WM from suspending your application. Also the other problem is that it does not work on all devices, some devices power management is not very good and it will suspend you anyway no matter what you do.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
Does anyone know how could I programatically disable/enable sleep mode on Windows Mobile? Thanks!
If you want your program to not be put to sleep while it's running, the best way is to create a KeepAlive type function that calls SystemIdleTimerReset, SHIdleTimerReset and simulates a key touch. Then you need to call it a lot, basically everywhere. ``` #include <windows.h> #include <commctrl.h> extern "C" { void WINAPI SHIdleTimerReset(); }; void KeepAlive() { static DWORD LastCallTime = 0; DWORD TickCount = GetTickCount(); if ((TickCount - LastCallTime) > 1000 || TickCount < LastCallTime) // watch for wraparound { SystemIdleTimerReset(); SHIdleTimerReset(); keybd_event(VK_LBUTTON, 0, KEYEVENTF_SILENT, 0); keybd_event(VK_LBUTTON, 0, KEYEVENTF_KEYUP | KEYEVENTF_SILENT, 0); LastCallTime = TickCount; } } ``` This method only works when the user starts the application manually. If your application is started by a notification (i.e. while the device is suspended), then you need to do more or else your application will be suspended after a very short period of time until the user powers the device out of suspended mode. To handle this you need to put the device into unattended power mode. ``` if(!::PowerPolicyNotify (PPN_UNATTENDEDMODE, TRUE)) { // handle error } // do long running process if(!::PowerPolicyNotify (PPN_UNATTENDEDMODE, FALSE)) { // handle error } ``` During unattended mode use, you still need to call the KeepAlive a lot, you can use a separate thread that sleeps for x milliseconds and calls the keep alive funcation. Please note that unattended mode does not bring it out of sleep mode, it puts the device in a weird half-awake state. So if you start a unattended mode while the device in suspended mode, it will not wake up the screen or anything. All unattended mode does is stop WM from suspending your application. Also the other problem is that it does not work on all devices, some devices power management is not very good and it will suspend you anyway no matter what you do.
246,430
<p>0x34363932353433373538323038353135353439</p>
[ { "answer_id": 246437, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 2, "selected": false, "text": "<p>From the Unix / cygwin command line, you can use bc.</p>\n\n<pre><code>$ bc\nibase=16\n34363932353433373538323038353135353439\n1164362276596472215941024063897591129839055929\n</code></pre>\n\n<p>There is also <a href=\"http://sciencesoft.at/bc/?lang=en\" rel=\"nofollow noreferrer\">an online version</a>. If you want to do it in code you should use an arbitrary precision library facility, like Java's BigInteger, Perl's Math::BigInt, Tcl's math::bignum, or of the many multiple precision arithmetic libraries that are available for C, like <a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">GNU GMP</a>, or <a href=\"http://spinning-yarns.org/michael/mpi\" rel=\"nofollow noreferrer\">MPI</a>.</p>\n" }, { "answer_id": 246493, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>Looks like ASCII to me! On a big-endian system, you get the string \"4692543758208515549\". :-)</p>\n\n<p>Anyway, to actually answer your question, Ruby is useful for that purpose:</p>\n\n<pre><code>ruby -e 'p 0x34363932353433373538323038353135353439'\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
0x34363932353433373538323038353135353439
From the Unix / cygwin command line, you can use bc. ``` $ bc ibase=16 34363932353433373538323038353135353439 1164362276596472215941024063897591129839055929 ``` There is also [an online version](http://sciencesoft.at/bc/?lang=en). If you want to do it in code you should use an arbitrary precision library facility, like Java's BigInteger, Perl's Math::BigInt, Tcl's math::bignum, or of the many multiple precision arithmetic libraries that are available for C, like [GNU GMP](http://gmplib.org/), or [MPI](http://spinning-yarns.org/michael/mpi).
246,438
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/358874/how-can-i-use-a-carriage-return-in-a-html-tooltip">How can I use a carriage return in a HTML tooltip?</a> </p> </blockquote> <p>I'd like to know if it's possible to force a newline to show in the tooltip when using title property of a TD. something like </p> <pre><code>&lt;td title="lineone \n linetwo \n etc..."&gt; </code></pre> <p>Can this be done?</p>
[ { "answer_id": 246439, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "<p>This should be OK, but is Internet Explorer specific:</p>\n\n<pre><code>&lt;td title=\"lineone\nlinetwo \netc...\">\n</code></pre>\n\n<p>As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.</p>\n" }, { "answer_id": 246441, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 2, "selected": false, "text": "<p>If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples</p>\n" }, { "answer_id": 246451, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 9, "selected": true, "text": "<p>This should now work with Internet Explorer, Firefox v12+ and Chrome 28+</p>\n\n<pre><code>&lt;img src=\"'../images/foo.gif'\" \n alt=\"line 1&amp;#013;line 2\" title=\"line 1&amp;#013;line 2\"&gt;\n</code></pre>\n\n<p>Try a JavaScript tooltip library for a better result, something like <a href=\"https://github.com/overlib/overlib\" rel=\"noreferrer\">OverLib</a>.</p>\n" }, { "answer_id": 360221, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I use the jQuery <a href=\"http://plugins.learningjquery.com/cluetip/#\" rel=\"nofollow noreferrer\">clueTip</a> plugin for this.</p>\n" }, { "answer_id": 3316441, "author": "Stéphane Klein", "author_id": 261061, "author_profile": "https://Stackoverflow.com/users/261061", "pm_score": 5, "selected": false, "text": "<p>The Extensible Markup Language (XML) 1.1 W3C Recommendation say</p>\n\n<p>« All line breaks MUST have been normalized on input to #xA as described in 2.11 End-of-Line Handling, so the rest of this algorithm operates on text normalized in this way. »</p>\n\n<p>The link is <a href=\"http://www.w3.org/TR/2006/REC-xml11-20060816/#AVNormalize\" rel=\"noreferrer\">http://www.w3.org/TR/2006/REC-xml11-20060816/#AVNormalize</a></p>\n\n<p>Then you can write :</p>\n\n<pre><code>&lt;td title=\"lineone &amp;#xA; linetwo &amp;#xA; etc...\"&gt;\n</code></pre>\n" }, { "answer_id": 4555163, "author": "baik", "author_id": 533292, "author_profile": "https://Stackoverflow.com/users/533292", "pm_score": 1, "selected": false, "text": "<p>The jquery <a href=\"http://tutorialzine.com/2010/07/colortips-jquery-tooltip-plugin/\" rel=\"nofollow\">colortip</a> plugin also supports <code>&lt;br&gt;</code>\n tags in the title attribute, you might want to look into that one.</p>\n" }, { "answer_id": 8526097, "author": "Petr Tuma", "author_id": 345436, "author_profile": "https://Stackoverflow.com/users/345436", "pm_score": 5, "selected": false, "text": "<p>One way to achieve similar effect would be through CSS:</p>\n\n<pre><code>&lt;td&gt;Cell content.\n &lt;div class=\"popup\"&gt;\n This is the popup.\n &lt;br&gt;\n Another line of popup.\n &lt;/div&gt;\n&lt;/td&gt;\n</code></pre>\n\n<p>And then use the following in CSS:</p>\n\n<pre><code>td div.popup { display: none; }\ntd:hover div.popup { display: block; position: absolute; }\n</code></pre>\n\n<p>You will want to add some borders and background to make the popup look decent, but this should sketch the idea. It has some drawbacks though, for example the popup is not positioned relative to mouse but relative to the containing cell.</p>\n" }, { "answer_id": 10624123, "author": "Dave Van Meter", "author_id": 1399313, "author_profile": "https://Stackoverflow.com/users/1399313", "pm_score": 3, "selected": false, "text": "<p>Using <code>&amp;#xA;</code> Works in Chrome to create separate lines in a tooltip.</p>\n" }, { "answer_id": 12284082, "author": "Erez Cohen", "author_id": 145599, "author_profile": "https://Stackoverflow.com/users/145599", "pm_score": 2, "selected": false, "text": "<p>Using <code>&amp;#013;</code> didn't work in my fb app.\nHowever this did, beautifully (in Chrome FF and IE):</p>\n\n<pre><code>&lt;img src=\"'../images/foo.gif'\" title=\"line 1&amp;lt;br&amp;gt;line 2\"&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15616/" ]
> > **Possible Duplicate:** > > [How can I use a carriage return in a HTML tooltip?](https://stackoverflow.com/questions/358874/how-can-i-use-a-carriage-return-in-a-html-tooltip) > > > I'd like to know if it's possible to force a newline to show in the tooltip when using title property of a TD. something like ``` <td title="lineone \n linetwo \n etc..."> ``` Can this be done?
This should now work with Internet Explorer, Firefox v12+ and Chrome 28+ ``` <img src="'../images/foo.gif'" alt="line 1&#013;line 2" title="line 1&#013;line 2"> ``` Try a JavaScript tooltip library for a better result, something like [OverLib](https://github.com/overlib/overlib).
246,443
<p>I am experiencing some strange behavior of embedded audio (wav file) on HTML page. I've got a page <code>https://server.com/listen-to-sound</code>, and a Wav file embedded in it via <code>&lt;EMBED/&gt;</code> tag, like this:</p> <pre><code>&lt;embed src='https://server.com/path-to-sound' hidden="true" autostart="true" /&gt; </code></pre> <p>The page <code>https://server.com/listen-to-sound</code> is opened in IE 6 SP3 on machine#1 - the sound is played in the headphones. The same page is opened on another machine(#2), with <strong>exactly</strong> same IE 6 SP3 version, privacy and proxy settings - there's no sound.</p> <p>Totally, from 6 machines the sound is played on 2 and not played on 4. From these 4 machines, when the page <code>https://server.com/listen-to-sound</code> is opened in Opera, the sound is played.</p> <p>I've triple-checked headphone connections, volume settings and other possible hardware and software driver issues: the problem is definitely in IE settings.</p> <p>I've also checked <code>https://server.com/path.to.sound</code> URL - the 4 machnies that do not play sound fail to open this link, failing with an error like "Failed to download page".</p> <p>Cleaning IE caches, temporary internet files, SSL certificate caches did not solve the problem either.</p> <p>Googling gave me nothing special but old Flash trick to use <code>&lt;OBJECT&gt;</code> tag and <code>&lt;EMBED&gt;</code> tag to be written in Object's comments.</p> <p>What have I missed? Have you experienced similar or related problems? How were they solved? Do you have any suggestions on where the trick is? Do you know some IE "features" that might affect execution(playing, showing) of embedded objects?</p>
[ { "answer_id": 246553, "author": "netsuo", "author_id": 27911, "author_profile": "https://Stackoverflow.com/users/27911", "pm_score": 0, "selected": false, "text": "<p>I could'nt find any informations on this, but have you tried playing sound from Javascript ? I don't know if it's a viable workaround for you but this might be a solution.<br />\nYou can find different ways to do it here: <a href=\"http://www.phon.ucl.ac.uk/home/mark/audio/play.htm\" rel=\"nofollow noreferrer\">http://www.phon.ucl.ac.uk/home/mark/audio/play.htm</a></p>\n\n<p>Hope that will help you.</p>\n" }, { "answer_id": 246729, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>In regard to your comment to jamesh, I would advise to provide instead a link to the audio file: some computers (mine at work) have no sound, not everybody is using IE, embed isn't part of HTML (it is a hack supported by various browsers, it isn't defined in <a href=\"http://www.w3.org/TR/html401/sgml/loosedtd.html\" rel=\"nofollow noreferrer\" title=\"HTML 4.01 Transitional DTD\">HTML 4.01 Transitional DTD</a> for example) and chances are the visiting browser have no plug-in to play your sound.</p>\n\n<p>As your tests show, it is prone to problems...</p>\n\n<p>At worst, provide a <code>&lt;NOEMBED&gt;</code> tag to supply the said link. Or nest various methods, like <code>&lt;object&gt;</code>. At least, Flash is supported by nearly all browsers.</p>\n" }, { "answer_id": 821112, "author": "Travis", "author_id": 307338, "author_profile": "https://Stackoverflow.com/users/307338", "pm_score": 1, "selected": false, "text": "<p>I think the main reason is acting different on each computer/browser you're using is because it is a non-standard tag.</p>\n\n<p>Getting media to play inside a web page has always been a bit of a pain. You may try something like this:</p>\n\n<pre><code>&lt;object type=\"audio/x-wav\" data=\"data/test.wav\" width=\"200\" height=\"20\"&gt;\n &lt;param name=\"src\" value=\"data/test.wav\"&gt;\n &lt;param name=\"autoplay\" value=\"false\"&gt;\n &lt;param name=\"autoStart\" value=\"0\"&gt;\n alt : &lt;a href=\"data/test.wav\"&gt;test.wav&lt;/a&gt;\n&lt;/object&gt;\n</code></pre>\n\n<p>The above was taken from <a href=\"http://joliclic.free.fr/html/object-tag/en/\" rel=\"nofollow noreferrer\">this site</a> explaining how to use the object tag.</p>\n" }, { "answer_id": 3127553, "author": "Jason", "author_id": 377408, "author_profile": "https://Stackoverflow.com/users/377408", "pm_score": 1, "selected": false, "text": "<p>I have not found the solution, but I can confirm that the likely problem is the https:. I have found that windows media player does not play files with a full url/src leading to https. However, quicktime will. So, computers with quicktime will successfully play the file back while those with only WMP will fail.</p>\n\n<p>One \"solution\" is to link to the http: (non-secure) version of the file.</p>\n" }, { "answer_id": 73721854, "author": "Michael", "author_id": 19997715, "author_profile": "https://Stackoverflow.com/users/19997715", "pm_score": 0, "selected": false, "text": "<p>Somewhere along the way, browsers changed operations like using flash and playing audio. I have tried java, html embeded code none is exact.. the only thing i noticed is if you make a link on another page to the page that suppose to play the music it will work every time. but many times it wont play if you take and put your music page url in url box.. the link is reliable to the music page.. Don't know why?\nI have been working for a while on it. and of course there the difference between all the various browsers. The embedded code embed src='https://server.com/path-to-sound' hidden=&quot;true&quot; autostart=&quot;true&quot; /&gt;you showed before should work as long a sound file is there and if placed as first line after body statement.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17707/" ]
I am experiencing some strange behavior of embedded audio (wav file) on HTML page. I've got a page `https://server.com/listen-to-sound`, and a Wav file embedded in it via `<EMBED/>` tag, like this: ``` <embed src='https://server.com/path-to-sound' hidden="true" autostart="true" /> ``` The page `https://server.com/listen-to-sound` is opened in IE 6 SP3 on machine#1 - the sound is played in the headphones. The same page is opened on another machine(#2), with **exactly** same IE 6 SP3 version, privacy and proxy settings - there's no sound. Totally, from 6 machines the sound is played on 2 and not played on 4. From these 4 machines, when the page `https://server.com/listen-to-sound` is opened in Opera, the sound is played. I've triple-checked headphone connections, volume settings and other possible hardware and software driver issues: the problem is definitely in IE settings. I've also checked `https://server.com/path.to.sound` URL - the 4 machnies that do not play sound fail to open this link, failing with an error like "Failed to download page". Cleaning IE caches, temporary internet files, SSL certificate caches did not solve the problem either. Googling gave me nothing special but old Flash trick to use `<OBJECT>` tag and `<EMBED>` tag to be written in Object's comments. What have I missed? Have you experienced similar or related problems? How were they solved? Do you have any suggestions on where the trick is? Do you know some IE "features" that might affect execution(playing, showing) of embedded objects?
I think the main reason is acting different on each computer/browser you're using is because it is a non-standard tag. Getting media to play inside a web page has always been a bit of a pain. You may try something like this: ``` <object type="audio/x-wav" data="data/test.wav" width="200" height="20"> <param name="src" value="data/test.wav"> <param name="autoplay" value="false"> <param name="autoStart" value="0"> alt : <a href="data/test.wav">test.wav</a> </object> ``` The above was taken from [this site](http://joliclic.free.fr/html/object-tag/en/) explaining how to use the object tag.
246,445
<p>I have a <code>char* p</code>, which points to a <code>\0</code>-terminated string. How do I create a C++ <code>string</code> from it in an exception-safe way?</p> <p>Here is an unsafe version:</p> <pre><code>string foo() { char *p = get_string(); string str( p ); free( p ); return str; } </code></pre> <p>An obvious solution would be to try-catch - any easier ways? </p>
[ { "answer_id": 246457, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "<p>You can use <code>shared_ptr</code> from <a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"noreferrer\">C++11</a> or <a href=\"http://www.boost.org/libs/smart_ptr/\" rel=\"noreferrer\">Boost</a>:</p>\n\n<pre><code>string\nfoo()\n{\n shared_ptr&lt;char&gt; p(get_string(), &amp;free);\n string str(p.get());\n return str;\n}\n</code></pre>\n\n<p>This uses a very specific feature of <code>shared_ptr</code> not available in <code>auto_ptr</code> or anything else, namely the ability to specify a custom deleter; in this case, I'm using <code>free</code> as the deleter.</p>\n" }, { "answer_id": 246460, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>Yup - stack-based unwinding. Modern C++ Design has the general solution but in this case you can use</p>\n\n<pre><code>struct Cleanup {\n void* toFree;\n Cleanup(void* toFree) : toFree(toFree) {}\n ~Cleanup() { free(toFree); }\n private:\n Cleanup(Cleanup&amp;);\n void operator=(Cleanup&amp;);\n};\n</code></pre>\n\n<p>No matter what happens with your std::string, free(toFree) will be called when your Cleanup object goes out of scope.</p>\n" }, { "answer_id": 246853, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 1, "selected": false, "text": "<p>Well, <code>p</code> does not point to a 0-terminated string if <code>get_string()</code> returns NULL; that's the problem here, since the <code>std::string</code> constructors that take a pointer to 0-terminated C string cannot deal with NULL, which is as much a 0-terminated C string as two dozens of bananas are.</p>\n\n<p>So, if <code>get_string()</code> is your own function, as opposed to a library function, then maybe you should make sure that it cannot return NULL. You could for instance let it return the sought <code>std::string</code> itself, since it knows it's own state. Otherwise, I'd do this, using the <code>Cleanup</code> from <a href=\"https://stackoverflow.com/questions/246445/create-stdstring-from-char-in-a-safe-way#246460\">this answer</a> as a helper to guarantee that <code>p</code> cannot leak (as suggested by Martin York in a comment):</p>\n\n<pre><code>string foo()\n{\n const char* p = get_string();\n const Cleanup cleanup(p);\n const std::string str(p != NULL ? p : \"\");\n\n return str;\n}\n</code></pre>\n" }, { "answer_id": 246888, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "<p>We commonly use <a href=\"http://www.ddj.com/cpp/184403758\" rel=\"nofollow noreferrer\">ScopeGuard</a> for these cases:</p>\n\n<pre><code>string foo()\n{\n char *p = get_string();\n ScopeGuard sg = MakeGuard(&amp;free, p);\n string str( p );\n return str;\n}\n</code></pre>\n" }, { "answer_id": 246902, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 2, "selected": false, "text": "<p>Can I ask you what exception you are expecting in your example?</p>\n\n<p>On many platforms (Linux, AIX) new or malloc will never fail and your app will get killed by the os if you run out of memory.</p>\n\n<p>See this link: <a href=\"http://www.linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-memory.html\" rel=\"nofollow noreferrer\">What happens when Linux runs out of memory.</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23420/" ]
I have a `char* p`, which points to a `\0`-terminated string. How do I create a C++ `string` from it in an exception-safe way? Here is an unsafe version: ``` string foo() { char *p = get_string(); string str( p ); free( p ); return str; } ``` An obvious solution would be to try-catch - any easier ways?
You can use `shared_ptr` from [C++11](http://en.cppreference.com/w/cpp/memory/shared_ptr) or [Boost](http://www.boost.org/libs/smart_ptr/): ``` string foo() { shared_ptr<char> p(get_string(), &free); string str(p.get()); return str; } ``` This uses a very specific feature of `shared_ptr` not available in `auto_ptr` or anything else, namely the ability to specify a custom deleter; in this case, I'm using `free` as the deleter.
246,498
<p>I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected.</p> <p>In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where they are located.</p> <p>From what I can see from the DateTime constructor I can set the TimeZone to be either the local timezone, the UTC timezone or not specified.</p> <p>How do I create a DateTime with a specific timezone like PST?</p>
[ { "answer_id": 246512, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>You'll have to create a custom object for that. Your custom object will contain two values:</p>\n\n<ul>\n<li>a DateTime value</li>\n<li>a <a href=\"http://msdn.microsoft.com/en-us/library/system.timezone.aspx\" rel=\"nofollow noreferrer\">TimeZone</a> object</li>\n</ul>\n\n<p>Not sure if there already is a CLR-provided data type that has that, but at least the TimeZone component is already available.</p>\n" }, { "answer_id": 246529, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512\">Jon's answer</a> talks about <a href=\"http://msdn.microsoft.com/en-us/library/system.timezone.aspx\" rel=\"noreferrer\">TimeZone</a>, but I'd suggest using <a href=\"http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx\" rel=\"noreferrer\">TimeZoneInfo</a> instead.</p>\n\n<p>Personally I like keeping things in UTC where possible (at least for the past; <a href=\"https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/\" rel=\"noreferrer\">storing UTC for the <em>future</em> has potential issues</a>), so I'd suggest a structure like this:</p>\n\n<pre><code>public struct DateTimeWithZone\n{\n private readonly DateTime utcDateTime;\n private readonly TimeZoneInfo timeZone;\n\n public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)\n {\n var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);\n utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); \n this.timeZone = timeZone;\n }\n\n public DateTime UniversalTime { get { return utcDateTime; } }\n\n public TimeZoneInfo TimeZone { get { return timeZone; } }\n\n public DateTime LocalTime\n { \n get \n { \n return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); \n }\n } \n}\n</code></pre>\n\n<p>You may wish to change the \"TimeZone\" names to \"TimeZoneInfo\" to make things clearer - I prefer the briefer names myself.</p>\n" }, { "answer_id": 1281006, "author": "CleverPatrick", "author_id": 22399, "author_profile": "https://Stackoverflow.com/users/22399", "pm_score": 6, "selected": false, "text": "<p>The DateTimeOffset structure was created for exactly this type of use.</p>\n\n<p>See:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx</a></p>\n\n<p>Here's an example of creating a DateTimeOffset object with a specific time zone:</p>\n\n<p><code>DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));</code></p>\n" }, { "answer_id": 9027480, "author": "Chris Moschini", "author_id": 176877, "author_profile": "https://Stackoverflow.com/users/176877", "pm_score": 6, "selected": false, "text": "<p>The other answers here are useful but they don't cover how to access Pacific specifically - here you go:</p>\n\n<pre><code>public static DateTime GmtToPacific(DateTime dateTime)\n{\n return TimeZoneInfo.ConvertTimeFromUtc(dateTime,\n TimeZoneInfo.FindSystemTimeZoneById(\"Pacific Standard Time\"));\n}\n</code></pre>\n\n<p>Oddly enough, although \"Pacific Standard Time\" normally means something different from \"Pacific Daylight Time,\" in this case it refers to Pacific time in general. In fact, if you use <code>FindSystemTimeZoneById</code> to fetch it, one of the properties available is a bool telling you whether that timezone is currently in daylight savings or not.</p>\n\n<p>You can see more generalized examples of this in a library I ended up throwing together to deal with DateTimes I need in different TimeZones based on where the user is asking from, etc:</p>\n\n<p><a href=\"https://github.com/b9chris/TimeZoneInfoLib.Net\" rel=\"noreferrer\">https://github.com/b9chris/TimeZoneInfoLib.Net</a></p>\n\n<p>This won't work outside of Windows (for example Mono on Linux) since the list of times comes from the Windows Registry:\n<code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\</code></p>\n\n<p>Underneath that you'll find keys (folder icons in Registry Editor); the names of those keys are what you pass to <code>FindSystemTimeZoneById</code>. On Linux you have to use a separate Linux-standard set of timezone definitions, which I've not adequately explored.</p>\n" }, { "answer_id": 20504276, "author": "Gabe Halsmer", "author_id": 922258, "author_profile": "https://Stackoverflow.com/users/922258", "pm_score": 2, "selected": false, "text": "<p>I like Jon Skeet's answer, but would like to add one thing. I'm not sure if Jon was expecting the ctor to always be passed in the Local timezone. But I want to use it for cases where it's something other then local. </p>\n\n<p>I'm reading values from a database, and I know what timezone that database is in. So in the ctor, I'll pass in the timezone of the database. But then I would like the value in local time. Jon's LocalTime does not return the original date converted into a local timezone date. It returns the date converted into the original timezone (whatever you had passed into the ctor).</p>\n\n<p>I think these property names clear it up...</p>\n\n<pre><code>public DateTime TimeInOriginalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } }\npublic DateTime TimeInLocalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, TimeZoneInfo.Local); } }\npublic DateTime TimeInSpecificZone(TimeZoneInfo tz)\n{\n return TimeZoneInfo.ConvertTime(utcDateTime, tz);\n}\n</code></pre>\n" }, { "answer_id": 22829864, "author": "Jernej Novak", "author_id": 1063571, "author_profile": "https://Stackoverflow.com/users/1063571", "pm_score": 3, "selected": false, "text": "<p>I altered <a href=\"https://stackoverflow.com/a/246529/1063571\">Jon Skeet answer</a> a bit for the web with extension method. It also works on azure like a charm.</p>\n\n<pre><code>public static class DateTimeWithZone\n{\n\nprivate static readonly TimeZoneInfo timeZone;\n\nstatic DateTimeWithZone()\n{\n//I added web.config &lt;add key=\"CurrentTimeZoneId\" value=\"Central Europe Standard Time\" /&gt;\n//You can add value directly into function.\n timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings[\"CurrentTimeZoneId\"]);\n}\n\n\npublic static DateTime LocalTime(this DateTime t)\n{\n return TimeZoneInfo.ConvertTime(t, timeZone); \n}\n}\n</code></pre>\n" }, { "answer_id": 58189080, "author": "Meghs Dhameliya", "author_id": 2030126, "author_profile": "https://Stackoverflow.com/users/2030126", "pm_score": 1, "selected": false, "text": "<p>Using <strong>TimeZones</strong> class makes it easy to create timezone specific date.</p>\n\n<pre><code>TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));\n</code></pre>\n" }, { "answer_id": 69205190, "author": "Eugene Ihnatsyeu", "author_id": 8419483, "author_profile": "https://Stackoverflow.com/users/8419483", "pm_score": 2, "selected": false, "text": "<p>Try <code>TimeZoneInfo.ConvertTime(dateTime, sourceTimeZone, destinationTimeZone)</code></p>\n" }, { "answer_id": 69913523, "author": "Arthur", "author_id": 816351, "author_profile": "https://Stackoverflow.com/users/816351", "pm_score": 1, "selected": false, "text": "<p>For date/time with offset for a specific time zone (neither local, nor UTC) you can to use DateTimeOffset class:</p>\n<pre><code> var time = TimeSpan.Parse(&quot;9:00&quot;);\n var est = TimeZoneInfo.FindSystemTimeZoneById(&quot;Eastern Standard Time&quot;);\n var nationalDateTime = new DateTimeOffset(DateTime.Today.Ticks + time.Ticks, est.BaseUtcOffset);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42109/" ]
I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected. In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where they are located. From what I can see from the DateTime constructor I can set the TimeZone to be either the local timezone, the UTC timezone or not specified. How do I create a DateTime with a specific timezone like PST?
[Jon's answer](https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512) talks about [TimeZone](http://msdn.microsoft.com/en-us/library/system.timezone.aspx), but I'd suggest using [TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) instead. Personally I like keeping things in UTC where possible (at least for the past; [storing UTC for the *future* has potential issues](https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/)), so I'd suggest a structure like this: ``` public struct DateTimeWithZone { private readonly DateTime utcDateTime; private readonly TimeZoneInfo timeZone; public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone) { var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); this.timeZone = timeZone; } public DateTime UniversalTime { get { return utcDateTime; } } public TimeZoneInfo TimeZone { get { return timeZone; } } public DateTime LocalTime { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } } } ``` You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.
246,503
<p>OK, I am trying to generate the rDoc for paperclip, but the rake task is choking on another plugin before it gets to it, so this is out of the question:</p> <pre><code>rake doc:plugins </code></pre> <p>I could go and fix up the broken plugin, but I'm busy and lazy, so I just want to generate the docs for paperclip. Is there any way of doing this?</p>
[ { "answer_id": 246507, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 4, "selected": true, "text": "<p>Unbelievably, I've just figured it out!</p>\n\n<pre><code>rake doc:plugins:paperclip\n</code></pre>\n\n<p>That was simple.</p>\n" }, { "answer_id": 246511, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 0, "selected": false, "text": "<p>You can always just run rdoc from the plugin's individual directory. This wouldn't include it in your project's /doc folder, but it would create a /doc folder inside the plugin which you can browse</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
OK, I am trying to generate the rDoc for paperclip, but the rake task is choking on another plugin before it gets to it, so this is out of the question: ``` rake doc:plugins ``` I could go and fix up the broken plugin, but I'm busy and lazy, so I just want to generate the docs for paperclip. Is there any way of doing this?
Unbelievably, I've just figured it out! ``` rake doc:plugins:paperclip ``` That was simple.
246,520
<p>I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:</p> <pre><code> string login = User.Identity.Name.ToString(); </code></pre> <p>But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...</p> <p>Can I access my organisation's AD via a web application?</p>
[ { "answer_id": 246655, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "<p>See related question: <a href=\"https://stackoverflow.com/questions/132277/active-directory-retrieve-user-information\">Active Directory: Retrieve User information</a></p>\n\n<p>See also: <a href=\"http://www.codeproject.com/KB/system/everythingInAD.aspx\" rel=\"nofollow noreferrer\">Howto: (Almost) Everything In Active Directory via C#</a> and more specifically section \"<a href=\"http://www.codeproject.com/KB/system/everythingInAD.aspx#26\" rel=\"nofollow noreferrer\">Enumerate an object's properties</a>\".</p>\n\n<p>If you have a path to connect to a group in a domain, the following snippet may be helpful:</p>\n\n<pre><code>GetUserProperty(\"&lt;myaccount&gt;\", \"DisplayName\");\n\npublic static string GetUserProperty(string accountName, string propertyName)\n{\n DirectoryEntry entry = new DirectoryEntry();\n // \"LDAP://CN=&lt;group name&gt;, CN =&lt;Users&gt;, DC=&lt;domain component&gt;, DC=&lt;domain component&gt;,...\"\n entry.Path = \"LDAP://...\";\n entry.AuthenticationType = AuthenticationTypes.Secure;\n\n DirectorySearcher search = new DirectorySearcher(entry);\n search.Filter = \"(SAMAccountName=\" + accountName + \")\";\n search.PropertiesToLoad.Add(propertyName);\n\n SearchResultCollection results = search.FindAll();\n if (results != null &amp;&amp; results.Count &gt; 0)\n {\n return results[0].Properties[propertyName][0].ToString();\n }\n else\n {\n return \"Unknown User\";\n }\n}\n</code></pre>\n" }, { "answer_id": 246700, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>How about this:</p>\n\n<pre><code>private static string GetFullName()\n {\n try\n {\n DirectoryEntry de = new DirectoryEntry(\"WinNT://\" + Environment.UserDomainName + \"/\" + Environment.UserName);\n return de.Properties[\"displayName\"].Value.ToString();\n }\n catch { return null; }\n }\n</code></pre>\n" }, { "answer_id": 246757, "author": "GalacticCowboy", "author_id": 29638, "author_profile": "https://Stackoverflow.com/users/29638", "pm_score": 2, "selected": false, "text": "<p>There is a CodePlex project for <a href=\"http://www.codeplex.com/LINQtoAD\" rel=\"nofollow noreferrer\">Linq to AD</a>, if you're interested.</p>\n\n<p>It's also covered in the book <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/0672329832\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">LINQ Unleashed for C#</a></em> by Paul Kimmel - he uses the above project as his starting point.</p>\n\n<p><em>not affiliated with either source - I just read the book recently</em></p>\n" }, { "answer_id": 280812, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 2, "selected": false, "text": "<p>In case anyone cares I managed to crack this one:</p>\n\n<pre><code> /// This is some imaginary code to show you how to use it\n\n Session[\"USER\"] = User.Identity.Name.ToString();\n Session[\"LOGIN\"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D\n string ldappath = \"LDAP://your_ldap_path\";\n // \"LDAP://CN=&lt;group name&gt;, CN =&lt;Users&gt;, DC=&lt;domain component&gt;, DC=&lt;domain component&gt;,...\"\n\n\n Session[\"cn\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"cn\");\n Session[\"displayName\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"displayName\");\n Session[\"mail\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"mail\");\n Session[\"givenName\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"givenName\");\n Session[\"sn\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"sn\");\n\n\n/// working code\n\npublic static string GetAttribute(string ldappath, string sAMAccountName, string attribute)\n {\n string OUT = string.Empty;\n\n try\n {\n DirectoryEntry de = new DirectoryEntry(ldappath);\n DirectorySearcher ds = new DirectorySearcher(de);\n ds.Filter = \"(&amp;(objectClass=user)(objectCategory=person)(sAMAccountName=\" + sAMAccountName + \"))\";\n\n SearchResultCollection results = ds.FindAll();\n\n foreach (SearchResult result in results)\n {\n OUT = GetProperty(result, attribute);\n }\n }\n catch (Exception t)\n {\n // System.Diagnostics.Debug.WriteLine(t.Message);\n }\n\n return (OUT != null) ? OUT : string.Empty;\n }\n\npublic static string GetProperty(SearchResult searchResult, string PropertyName)\n {\n if (searchResult.Properties.Contains(PropertyName))\n {\n return searchResult.Properties[PropertyName][0].ToString();\n }\n else\n {\n return string.Empty;\n }\n }\n</code></pre>\n" }, { "answer_id": 15782876, "author": "user2239589", "author_id": 2239589, "author_profile": "https://Stackoverflow.com/users/2239589", "pm_score": 3, "selected": false, "text": "<p>Use this:</p>\n\n<p><code>string displayName = UserPrincipal.Current.DisplayName;</code></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31765/" ]
I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like: ``` string login = User.Identity.Name.ToString(); ``` But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now... Can I access my organisation's AD via a web application?
How about this: ``` private static string GetFullName() { try { DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName); return de.Properties["displayName"].Value.ToString(); } catch { return null; } } ```
246,525
<p>I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.</p>
[ { "answer_id": 246628, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 5, "selected": true, "text": "<p>A bezier curve isn't that hard to draw yourself. Given three points <code>A</code>, <code>B</code>, <code>C</code> you require three linear interpolations in order to draw the curve. We use the scalar <code>t</code> as the parameter for the linear interpolation:</p>\n\n<pre><code>P0 = A * t + (1 - t) * B\nP1 = B * t + (1 - t) * C\n</code></pre>\n\n<p>This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so:</p>\n\n<pre><code>Pfinal = P0 * t + (1 - t) * P1\n</code></pre>\n\n<p>There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some <code>dt</code> (delta t) and we need to be aware that <code>0 &lt;= t &lt;= 1</code>. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.</p>\n" }, { "answer_id": 246933, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 3, "selected": false, "text": "<p>You can use the <a href=\"http://effbot.org/zone/aggdraw-index.htm\" rel=\"noreferrer\">aggdraw</a> on top of PIL, bezier curves are <a href=\"http://effbot.org/zone/pythondoc-aggdraw.htm#aggdraw.Path-class\" rel=\"noreferrer\">supported</a>.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I made an example only to discover there is a bug in the <code>Path</code> class regarding <code>curveto</code> :(</p>\n\n<p>Here is the example anyway:</p>\n\n<pre><code>from PIL import Image\nimport aggdraw\n\nimg = Image.new(\"RGB\", (200, 200), \"white\")\ncanvas = aggdraw.Draw(img)\n\npen = aggdraw.Pen(\"black\")\npath = aggdraw.Path()\npath.moveto(0, 0)\npath.curveto(0, 60, 40, 100, 100, 100)\ncanvas.path(path.coords(), path, pen)\ncanvas.flush()\n\nimg.save(\"curve.png\", \"PNG\")\nimg.show()\n</code></pre>\n\n<p><a href=\"http://www.mail-archive.com/[email protected]/msg02108.html\" rel=\"noreferrer\">This</a> should fix the bug if you're up for recompiling the module...</p>\n" }, { "answer_id": 2292690, "author": "unutbu", "author_id": 190597, "author_profile": "https://Stackoverflow.com/users/190597", "pm_score": 5, "selected": false, "text": "<pre><code>def make_bezier(xys):\n # xys should be a sequence of 2-tuples (Bezier control points)\n n = len(xys)\n combinations = pascal_row(n-1)\n def bezier(ts):\n # This uses the generalized formula for bezier curves\n # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization\n result = []\n for t in ts:\n tpowers = (t**i for i in range(n))\n upowers = reversed([(1-t)**i for i in range(n)])\n coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)]\n result.append(\n tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys)))\n return result\n return bezier\n\ndef pascal_row(n, memo={}):\n # This returns the nth row of Pascal's Triangle\n if n in memo:\n return memo[n]\n result = [1]\n x, numerator = 1, n\n for denominator in range(1, n//2+1):\n # print(numerator,denominator,x)\n x *= numerator\n x /= denominator\n result.append(x)\n numerator -= 1\n if n&amp;1 == 0:\n # n is even\n result.extend(reversed(result[:-1]))\n else:\n result.extend(reversed(result))\n memo[n] = result\n return result\n</code></pre>\n\n<p>This, for example, draws a heart:</p>\n\n<pre><code>from PIL import Image\nfrom PIL import ImageDraw\n\nif __name__ == '__main__':\n im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) \n draw = ImageDraw.Draw(im)\n ts = [t/100.0 for t in range(101)]\n\n xys = [(50, 100), (80, 80), (100, 50)]\n bezier = make_bezier(xys)\n points = bezier(ts)\n\n xys = [(100, 50), (100, 0), (50, 0), (50, 35)]\n bezier = make_bezier(xys)\n points.extend(bezier(ts))\n\n xys = [(50, 35), (50, 0), (0, 0), (0, 50)]\n bezier = make_bezier(xys)\n points.extend(bezier(ts))\n\n xys = [(0, 50), (20, 80), (50, 100)]\n bezier = make_bezier(xys)\n points.extend(bezier(ts))\n\n draw.polygon(points, fill = 'red')\n im.save('out.png')\n</code></pre>\n" }, { "answer_id": 21416678, "author": "Karim Bahgat", "author_id": 2898490, "author_profile": "https://Stackoverflow.com/users/2898490", "pm_score": 3, "selected": false, "text": "<p>Although bezier curveto paths don't work with Aggdraw, as mentioned by @ToniRuža, there is another way to do this in Aggdraw. The benefit of using Aggdraw instead of PIL or your own bezier functions is that Aggdraw will antialias the image making it look smoother (see pic at bottom).</p>\n\n<p><strong>Aggdraw Symbols</strong></p>\n\n<p>Instead of using the aggdraw.Path() class to draw, you can use the <code>aggdraw.Symbol(pathstring)</code> class which is basically the same except you write the path as a string. According to the Aggdraw docs the way to write your path as a string is to use SVG path syntax (see: <a href=\"http://www.w3.org/TR/SVG/paths.html\" rel=\"noreferrer\">http://www.w3.org/TR/SVG/paths.html</a>). Basically, each addition (node) to the path normally starts with</p>\n\n<ul>\n<li>a letter representing the drawing action (uppercase for absolute path, lowercase for relative path), followed by (no spaces in between)</li>\n<li>the x coordinate (precede by a minus sign if it is a negative number or direction)</li>\n<li>a comma</li>\n<li>the y coordinate (precede by a minus sign if it is a negative number or direction)</li>\n</ul>\n\n<p>In your pathstring just separate your multiple nodes with a space. Once you have created your symbol, just remember to draw it by passing it as one of the arguments to <code>draw.symbol(args)</code>. </p>\n\n<p><strong>Bezier Curves in Aggdraw Symbols</strong></p>\n\n<p>Specifically for cubic bezier curves you write the letter \"C\" or \"c\" followed by 6 numbers (3 sets of xy coordinates x1,y1,x2,y2,x3,y3 with commas in between the numbers but not between the first number and the letter). According the docs there are also other bezier versions by using the letter \"S (smooth cubic bezier), Q (quadratic bezier), T (smooth quadratic bezier)\". Here is a complete example code (requires PIL and aggdraw):</p>\n\n<pre><code>print \"initializing script\"\n\n# imports\nfrom PIL import Image\nimport aggdraw\n\n# setup\nimg = Image.new(\"RGBA\", (1000,1000)) # last part is image dimensions\ndraw = aggdraw.Draw(img)\noutline = aggdraw.Pen(\"black\", 5) # 5 is the outlinewidth in pixels\nfill = aggdraw.Brush(\"yellow\")\n\n# the pathstring:\n#m for starting point\n#c for bezier curves\n#z for closing up the path, optional\n#(all lowercase letters for relative path)\npathstring = \" m0,0 c300,300,700,600,300,900 z\"\n\n# create symbol\nsymbol = aggdraw.Symbol(pathstring)\n\n# draw and save it\nxy = (20,20) # xy position to place symbol\ndraw.symbol(xy, symbol, outline, fill)\ndraw.flush()\nimg.save(\"testbeziercurves.png\") # this image gets saved to same folder as the script\n\nprint \"finished drawing and saved!\"\n</code></pre>\n\n<p>And the output is a smooth-looking curved bezier figure:\n<img src=\"https://i.stack.imgur.com/tqW5g.png\" alt=\"Result from script above using aggdraw bezier curve symbol\"></p>\n" }, { "answer_id": 45843865, "author": "Lucas VL", "author_id": 6189478, "author_profile": "https://Stackoverflow.com/users/6189478", "pm_score": 0, "selected": false, "text": "<p>I found a simpler way creating a bezier curve (without aggraw and without complex functions). </p>\n\n<pre><code>import math\nfrom PIL import Image\nfrom PIL import ImageDraw\n\nimage = Image.new('RGB',(1190,841),'white')\ndraw = ImageDraw.Draw(image)\ncurve_smoothness = 100\n\n#First, select start and end of curve (pixels)\ncurve_start = [(167,688)] \ncurve_end = [(678,128)]\n\n#Second, split the path into segments\ncurve = [] \nfor i in range(1,curve_smoothness,1):\n split = (curve_end[0][0] - curve_start[0][0])/curve_smoothness\n x = curve_start[0][0] + split * i \n curve.append((x, -7 * math.pow(10,-7) * math.pow(x,3) - 0.0011 * math.pow(x,2) + 0.235 * x + 682.68))\n\n#Third, edit any other corners of polygon\nother =[(1026,721), (167,688)]\n\n#Finally, combine all parts of polygon into one list\nxys = curve_start + curve + curve_end + other #putting all parts of the polygon together\ndraw.polygon(xys, fill = None, outline = 256)\n\nimage.show()\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498/" ]
I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
A bezier curve isn't that hard to draw yourself. Given three points `A`, `B`, `C` you require three linear interpolations in order to draw the curve. We use the scalar `t` as the parameter for the linear interpolation: ``` P0 = A * t + (1 - t) * B P1 = B * t + (1 - t) * C ``` This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so: ``` Pfinal = P0 * t + (1 - t) * P1 ``` There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some `dt` (delta t) and we need to be aware that `0 <= t <= 1`. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.
246,540
<p>This error has been driving me nuts. We have a server running Apache and Tomcat, serving multiple different sites. Normally the server runs fine, but sometimes an error happens where people are served the wrong page - <strong>the page that <em>somebody else</em> requested!</strong></p> <p>Clues:</p> <ul> <li>The pages being delivered are those that another user requested recently, and are otherwise delivered correctly. It's been known for two simultaneous requests to be swapped. As far as I can tell, none of the pages being incorrectly delivered are older than a few minutes.</li> <li>It only affects the files that are being served by Tomcat. Static files like images are unaffected.</li> <li>It doesn't happen all the time. When it does happen, it happens for everybody.</li> <li>It seems to happen at times of peak demand. However, the demand is not yet very high - it's certainly well within the bounds of what Apache can cope with.</li> <li>Restarting Tomcat fixed it, but only for a few minutes. Restarting Apache fixed it, but only for a few minutes.</li> <li>The server is running Apache 2 and Tomcat 6, using a Java 6 VM on Gentoo. The connection is with AJP13, and <code>JkMount</code> directives within <code>&lt;VirtualHost&gt;</code> blocks are correct.</li> <li>There's nothing of use in any of the log files.</li> </ul> <hr> <p><strong>Further information:</strong></p> <p>Apache does not have any form of caching turned on. All the caching-related entries in httpd.conf and related imports say, for example:</p> <pre><code>&lt;IfDefine CACHE&gt; LoadModule cache_module modules/mod_cache.so &lt;/IfDefine&gt; </code></pre> <p>While the options for Apache don't include that flag:</p> <pre><code>APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PHP5 -D JK" </code></pre> <p>Tomcat likewise has no caching options switched on, that I can find.</p> <p><a href="https://stackoverflow.com/questions/246540/apachetomcat-error-wrong-pages-being-delivered#246566">toolkit's suggestion</a> was good, but not appropriate in this case. What leads me to believe that the error can't be within my own code is that it isn't simply a few values that are being transferred - it's the entire request, including the URL, parameters, session cookies, the whole thing. People are getting pages back saying "You are logged in as John", when they clearly aren't.</p> <hr> <p><strong>Update:</strong></p> <p>Based on suggestions from several people, I'm going to add the following HTTP headers to Tomcat-served pages to disable all forms of caching:</p> <pre><code>Cache-Control: no-store Vary: * </code></pre> <p>Hopefully these headers will be respected not just by Apache, but also by any other caches or proxies that may be in the way. Unfortunately I have no way of deliberately reproducing this error, so I'm just going to have to wait and see if it turns up again.</p> <p>I notice that the following headers are being included - could they be related in any way?</p> <pre><code>Connection: Keep-Alive Keep-Alive: timeout=5, max=66 </code></pre> <hr> <p><strong>Update:</strong></p> <p>Apparently this happened again while I was asleep, but has stopped happening now I'm awake to see it. Again, there's nothing useful in the logs that I can see, so I have no clues to what was actually happening or how to prevent it.</p> <p>Is there any extra information I can put in Apache or Tomcat's logs to make this easier to diagnose?</p> <hr> <p><strong>Update:</strong></p> <p>Since this has happened again a couple of times, we've changed how Apache connects to Tomcat to see if it affects things. We were using <code>mod_jk</code> with a directive like this:</p> <pre><code>JkMount /portal ajp13 </code></pre> <p>We've switched now to using <code>mod_proxy_ajp</code>, like so:</p> <pre><code>ProxyPass /portal ajp://localhost:8009/portal </code></pre> <p>We'll see if it makes any difference. This error was always annoyingly unpredictable, so we can never definitively say if it's worked or not.</p> <hr> <p><strong>Update:</strong></p> <p>We just got the error briefly on a site that was left using <code>mod_jk</code>, while a sister site on the same server using <code>mod_proxy_ajp</code> didn't show the error. This doesn't prove anything, but it does provide evidence that swithing to <code>mod_proxy_ajp</code> may have helped.</p> <hr> <p><strong>Update:</strong></p> <p>We just got the error again last night on a site using <code>mod_proxy_ajp</code>, so clearly that hasn't solved it - <code>mod_jk</code> wasn't the source of the problem. I'm going to try the anonymous suggestion of turning off persistent connections:</p> <pre><code>KeepAlive Off </code></pre> <p>If that fails as well, I'm going to be desperate enough to start investigating GlassFish.</p> <hr> <p><strong>Update:</strong></p> <p>Dammit! The problem just came back. I hadn't seen it in a while, so I was starting to think we'd finally sorted it. I hate heisenbugs.</p>
[ { "answer_id": 246566, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 3, "selected": false, "text": "<p>Could it be the thread-safety of your servlets?</p>\n\n<p>Do your servlets store any information in instance members.</p>\n\n<p>For example, something as simple as the following may cause thread-related issues:</p>\n\n<pre><code>public class MyServlet ... {\n private String action;\n\n public void doGet(...) {\n action = request.getParameter(\"action\");\n processAction(response);\n }\n\n public void processAction(...) {\n if (action.equals(\"foo\")) {\n // send foo page\n } else if (action.equals(\"bar\")) {\n // send bar page\n }\n }\n}\n</code></pre>\n\n<p>Because the serlvet is accessed by multiple threads, there is no guarantee that the action instance member will not be clobbered by someone elses request, and end up sending the wrong page back.</p>\n\n<p>The simple solution to this issue is to use local variables insead of instance members:</p>\n\n<pre><code>public class MyServlet ... {\n public void doGet(...) {\n String action = request.getParameter(\"action\");\n processAction(action, response);\n }\n\n public void processAction(...) {\n if (action.equals(\"foo\")) {\n // send foo page\n } else if (action.equals(\"bar\")) {\n // send bar page\n }\n }\n}\n</code></pre>\n\n<p><strong>Note: this extends to JavaServer Pages too, if you were dispatching to them for your views?</strong></p>\n" }, { "answer_id": 247684, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "<p>I'm no expert, but could it be some weird <a href=\"http://en.wikipedia.org/wiki/Network_address_translation\" rel=\"nofollow noreferrer\">Network Address Translation</a> issue?</p>\n" }, { "answer_id": 248724, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>Check if your headers allow caching without the correct <code>Vary</code> HTTP header (if you use session cookies, for instance, and allow caching, you need an entry in the <code>Vary</code> HTTP header for the cookie header, or a cache/proxy might serve the cached version of a page intended for one user to another user).</p>\n\n<p>The problem might be not with caching on your web server, but on another layer of caching (either on a reverse proxy in front of your web server, or on a proxy near the users). If the clients are behing a NAT, they might also be behind a transparent proxy (and, to make things even harder to debug, the transparent proxy might be configured to not be visible in the headers).</p>\n" }, { "answer_id": 479020, "author": "user58941", "author_id": 58941, "author_profile": "https://Stackoverflow.com/users/58941", "pm_score": 1, "selected": false, "text": "<p>I had this problem and it really drove me nuts. I dont know why, but I solved it turning off the Keep Alive on the http.conf</p>\n\n<p>from</p>\n\n<p>KeepAlive On</p>\n\n<p>to </p>\n\n<p>KeepAlive Off</p>\n\n<p>My application doesn't use the keepalive feature, so it worked very well for me.</p>\n" }, { "answer_id": 764922, "author": "cherouvim", "author_id": 72478, "author_profile": "https://Stackoverflow.com/users/72478", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>response.setHeader(\"Cache-Control\", \"no-cache\"); //HTTP 1.1\nresponse.setHeader(\"Pragma\", \"no-cache\"); //HTTP 1.0\nresponse.setDateHeader(\"Expires\", 0); //prevents caching at the proxy server\n</code></pre>\n" }, { "answer_id": 764996, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 2, "selected": false, "text": "<p>8 updates of the question later one more issue to use to test/reproduce, albeit it might be difficult (or expensive) for public sites.</p>\n\n<p>You could enable https on the sites. This would at least wipe out any other proxies caches along the way. It'd be bad to see that there are some forgotten loadbalancers or company caches on the way that interfere with your traffic.</p>\n\n<p>For public sites this would imply trusted certificates on the keys, so some money will be involved. For testing self-signed keys might suffice. Also, check that there's no transparent proxy involved that decrypts and reencrypts the traffic. (they are easily detectable, as they can't use the same certificate/key as the original server)</p>\n" }, { "answer_id": 1004697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Have a look at this site, it describes an issue with mod_jk. I came accross your posting while looking at a very similar issue. Basically the fix is to upgrade to a newer version of mod_jk. I haven't had a chance to implement the change in our server yet, but I'm going to try this tomorrow and see if it helps. </p>\n\n<p><a href=\"http://securitytracker.com/alerts/2009/Apr/1022001.html\" rel=\"nofollow noreferrer\">http://securitytracker.com/alerts/2009/Apr/1022001.html</a></p>\n" }, { "answer_id": 1743757, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 1, "selected": true, "text": "<p>We switched Apache from proxying with AJP to proxying with HTTP. So far it appears to have solved the issue, or at least vastly reduced it - the problem hasn't been reported in months, and the app's use has increased since then.</p>\n\n<p>The change is in Apache's httpd.conf. Having started with <code>mod_jk</code>:</p>\n\n<pre><code>JkMount /portal ajp13\n</code></pre>\n\n<p>We switched to <code>mod_proxy_ajp</code>:</p>\n\n<pre><code>ProxyPass /portal ajp://localhost:8009/portal\n</code></pre>\n\n<p>Then finally to straight <code>mod_proxy</code>:</p>\n\n<pre><code>ProxyPass /portal http://localhost:8080/portal\n</code></pre>\n\n<p>You'll need to make sure Tomcat is set up to serve HTTP on port 8080. And remember that if you're serving <code>/</code>, you need to include <code>/</code> on both sides of the proxy or it starts crying:</p>\n\n<pre><code>ProxyPass / http://localhost:8080/\n</code></pre>\n" }, { "answer_id": 2526564, "author": "gazum", "author_id": 302851, "author_profile": "https://Stackoverflow.com/users/302851", "pm_score": 0, "selected": false, "text": "<p>It may be not a caching issue at all. Try to increase MaxClients parameter in apache2.conf. If it is too low (150 by default?), Apache starts to queue requests. When it decides to serve queued request via mod_proxy it pulls out a wrong page (or may be it is just stressed doing all the queuing).</p>\n" }, { "answer_id": 4786167, "author": "William Lee", "author_id": 588004, "author_profile": "https://Stackoverflow.com/users/588004", "pm_score": 2, "selected": false, "text": "<p>Although you did mention mod_cache was not enabled in your setup, for others who may have encountered the same issue with mod_cache enabled (even on static contents), the solution is to make sure the following directive is enabled on the Set-Cookie HTTP header:</p>\n\n<pre><code>CacheIgnoreHeaders Set-Cookie\n</code></pre>\n\n<p>The reason being mod_cache will cache the Set-Cookie header that may get served to other users. This would then leak session ID from the user who last filled the cache to another. </p>\n" }, { "answer_id": 11375693, "author": "Steven Lizarazo", "author_id": 589132, "author_profile": "https://Stackoverflow.com/users/589132", "pm_score": 0, "selected": false, "text": "<p>Are you sure that is the page that somebody else requested or a page without parameters?,\nyou could get weird errors if your connectionTimeout is too short at server.xml on the tomcat server behind apache, increase it to a bigger number:</p>\n\n<p>default configuration:</p>\n\n<pre><code> &lt;Connector port=\"8080\" protocol=\"HTTP/1.1\"\n connectionTimeout=\"20000\"\n redirectPort=\"8443\" /&gt;\n</code></pre>\n\n<p>changed:</p>\n\n<pre><code> &lt;Connector port=\"8080\" protocol=\"HTTP/1.1\"\n connectionTimeout=\"2000000\"\n redirectPort=\"8443\" /&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000/" ]
This error has been driving me nuts. We have a server running Apache and Tomcat, serving multiple different sites. Normally the server runs fine, but sometimes an error happens where people are served the wrong page - **the page that *somebody else* requested!** Clues: * The pages being delivered are those that another user requested recently, and are otherwise delivered correctly. It's been known for two simultaneous requests to be swapped. As far as I can tell, none of the pages being incorrectly delivered are older than a few minutes. * It only affects the files that are being served by Tomcat. Static files like images are unaffected. * It doesn't happen all the time. When it does happen, it happens for everybody. * It seems to happen at times of peak demand. However, the demand is not yet very high - it's certainly well within the bounds of what Apache can cope with. * Restarting Tomcat fixed it, but only for a few minutes. Restarting Apache fixed it, but only for a few minutes. * The server is running Apache 2 and Tomcat 6, using a Java 6 VM on Gentoo. The connection is with AJP13, and `JkMount` directives within `<VirtualHost>` blocks are correct. * There's nothing of use in any of the log files. --- **Further information:** Apache does not have any form of caching turned on. All the caching-related entries in httpd.conf and related imports say, for example: ``` <IfDefine CACHE> LoadModule cache_module modules/mod_cache.so </IfDefine> ``` While the options for Apache don't include that flag: ``` APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PHP5 -D JK" ``` Tomcat likewise has no caching options switched on, that I can find. [toolkit's suggestion](https://stackoverflow.com/questions/246540/apachetomcat-error-wrong-pages-being-delivered#246566) was good, but not appropriate in this case. What leads me to believe that the error can't be within my own code is that it isn't simply a few values that are being transferred - it's the entire request, including the URL, parameters, session cookies, the whole thing. People are getting pages back saying "You are logged in as John", when they clearly aren't. --- **Update:** Based on suggestions from several people, I'm going to add the following HTTP headers to Tomcat-served pages to disable all forms of caching: ``` Cache-Control: no-store Vary: * ``` Hopefully these headers will be respected not just by Apache, but also by any other caches or proxies that may be in the way. Unfortunately I have no way of deliberately reproducing this error, so I'm just going to have to wait and see if it turns up again. I notice that the following headers are being included - could they be related in any way? ``` Connection: Keep-Alive Keep-Alive: timeout=5, max=66 ``` --- **Update:** Apparently this happened again while I was asleep, but has stopped happening now I'm awake to see it. Again, there's nothing useful in the logs that I can see, so I have no clues to what was actually happening or how to prevent it. Is there any extra information I can put in Apache or Tomcat's logs to make this easier to diagnose? --- **Update:** Since this has happened again a couple of times, we've changed how Apache connects to Tomcat to see if it affects things. We were using `mod_jk` with a directive like this: ``` JkMount /portal ajp13 ``` We've switched now to using `mod_proxy_ajp`, like so: ``` ProxyPass /portal ajp://localhost:8009/portal ``` We'll see if it makes any difference. This error was always annoyingly unpredictable, so we can never definitively say if it's worked or not. --- **Update:** We just got the error briefly on a site that was left using `mod_jk`, while a sister site on the same server using `mod_proxy_ajp` didn't show the error. This doesn't prove anything, but it does provide evidence that swithing to `mod_proxy_ajp` may have helped. --- **Update:** We just got the error again last night on a site using `mod_proxy_ajp`, so clearly that hasn't solved it - `mod_jk` wasn't the source of the problem. I'm going to try the anonymous suggestion of turning off persistent connections: ``` KeepAlive Off ``` If that fails as well, I'm going to be desperate enough to start investigating GlassFish. --- **Update:** Dammit! The problem just came back. I hadn't seen it in a while, so I was starting to think we'd finally sorted it. I hate heisenbugs.
We switched Apache from proxying with AJP to proxying with HTTP. So far it appears to have solved the issue, or at least vastly reduced it - the problem hasn't been reported in months, and the app's use has increased since then. The change is in Apache's httpd.conf. Having started with `mod_jk`: ``` JkMount /portal ajp13 ``` We switched to `mod_proxy_ajp`: ``` ProxyPass /portal ajp://localhost:8009/portal ``` Then finally to straight `mod_proxy`: ``` ProxyPass /portal http://localhost:8080/portal ``` You'll need to make sure Tomcat is set up to serve HTTP on port 8080. And remember that if you're serving `/`, you need to include `/` on both sides of the proxy or it starts crying: ``` ProxyPass / http://localhost:8080/ ```
246,542
<p>There was no endpoint listening at http;//localhost:8080/xdxservice/xdsrepository that could accept the message. This is often caused by an incorrect address or SOAP action. </p>
[ { "answer_id": 246556, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "<p>the url should have a .svc extention, no? (answered in comments)</p>\n\n<p>Are you running the WCF in ASP.NET or the VS webserver?</p>\n" }, { "answer_id": 246625, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 1, "selected": false, "text": "<p>Probably a typo in the question, but your URL is invalid. </p>\n\n<pre><code>http;//localhost:8080/xdxservice/xdsrepository\n</code></pre>\n\n<p>should have a colon rather than a semi-colon</p>\n\n<pre><code>http://localhost:8080/xdxservice/xdsrepository\n</code></pre>\n\n<p>This may well not be your problem, but I thought it was worth pointing out.</p>\n" }, { "answer_id": 979898, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 0, "selected": false, "text": "<p>What service class is the .svc file pointing to? Is there a section for this class in the web.config or app.config file? Does this section have an element defined?</p>\n\n<p>If not running under IIS, does this element have an address defined? Or does the have a base address defined?</p>\n" }, { "answer_id": 2615018, "author": "John Saunders", "author_id": 76337, "author_profile": "https://Stackoverflow.com/users/76337", "pm_score": 0, "selected": false, "text": "<p>This usually just means that the service is not running, or is otherwise not able to listen to requests. It could be the mistyped URL, or the IIS application is not started, or you have the wrong port number.</p>\n\n<p>But basically, it means what the message says.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There was no endpoint listening at http;//localhost:8080/xdxservice/xdsrepository that could accept the message. This is often caused by an incorrect address or SOAP action.
Probably a typo in the question, but your URL is invalid. ``` http;//localhost:8080/xdxservice/xdsrepository ``` should have a colon rather than a semi-colon ``` http://localhost:8080/xdxservice/xdsrepository ``` This may well not be your problem, but I thought it was worth pointing out.
246,559
<p>I need to copy a set of DLL and PDB files from a set of folders recursively into another folder. I don't want to recreate the folder hierarchy in the target folder. I want to use built in Windows tools, e.g. DOS commands. </p>
[ { "answer_id": 246573, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": -1, "selected": false, "text": "<p>I'm not aware of any command line tools that do this directly, but you could create a batch script to loop through sub folders, and copy the files you need.</p>\n\n<p>However you may end up with files with duplicate filenames if you place them all in the same folder.</p>\n" }, { "answer_id": 246576, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 8, "selected": true, "text": "<pre><code>mkdir targetDir\nfor /r %x in (*.dll, *pdb) do copy \"%x\" targetDir\\\n</code></pre>\n\n<p>Use /Y at the end of the above command if you are copying multiple files and don't want to keep answering \"Yes\". </p>\n" }, { "answer_id": 5632706, "author": "Henrik Thomsen", "author_id": 703690, "author_profile": "https://Stackoverflow.com/users/703690", "pm_score": -1, "selected": false, "text": "<pre><code>@echo off\nif %1'==' goto usage\nif %2'==' goto usage\nif %3'==' goto usage\nfor /D %%F in (%1\\*) do xcopy %%F\\%2 %3 /D /Y\nfor /D %%F in (%1\\*.) do call TreeCopy %%F %2 %3\ngoto end\n:usage\n@echo Usage: TreeCopy [Source folder] [Search pattern] [Destination folder]\n@echo Example: TreeCopy C:\\Project\\UDI *.xsd C:\\Project\\UDI\\SOA\\Deploy\\Metadata\n:end\n</code></pre>\n" }, { "answer_id": 13681925, "author": "Bronek", "author_id": 769465, "author_profile": "https://Stackoverflow.com/users/769465", "pm_score": 5, "selected": false, "text": "<p><strong>command XCOPY</strong></p>\n\n<p>example of copying folder recursively:</p>\n\n<pre><code>mkdir DestFolder\nxcopy SrcFolder DestFolder /E\n</code></pre>\n\n<p>(as stated below in the comment following <a href=\"http://en.wikipedia.org/wiki/List_of_MS-DOS_commands#XCOPY\">WIKI</a> that command was made available since DOS 3.2)</p>\n" }, { "answer_id": 24206920, "author": "SteckDEV", "author_id": 1771899, "author_profile": "https://Stackoverflow.com/users/1771899", "pm_score": 0, "selected": false, "text": "<p>Make sure that you have the quotes right if you have spaces in your path.</p>\n\n<p>This is my postbuild event for my TFS build server (that is why there is \"%%\"). I needed all the test files to be copied over. </p>\n\n<pre><code>if not exist \"$(TargetDir)..\\SingleFolderOutput\" mkdir -p \"$(TargetDir)..\\SingleFolderOutput\"\n\nfor /r **%%x** in (*.dll, *.pdb, *.xml, *.xaml, *.exe, *.exe.config) do xcopy **\"%%x\"** \"$(TargetDir)..\\SingleFolderOutput\" /Y\n</code></pre>\n" }, { "answer_id": 60885062, "author": "uzrgm", "author_id": 936541, "author_profile": "https://Stackoverflow.com/users/936541", "pm_score": 0, "selected": false, "text": "<p>For gathering PBD files I end up with this:</p>\n\n<pre><code>cmd /q /c for /R \"&lt;your_source_folder&gt;\" %f in (*.pdb) do xcopy \"%f\" \"&lt;your_destination_folder&gt;\" /I /Y\n</code></pre>\n" }, { "answer_id": 74270686, "author": "Михаил Сухарев", "author_id": 6214542, "author_profile": "https://Stackoverflow.com/users/6214542", "pm_score": 0, "selected": false, "text": "<p>Note: must be two percent chars, if you use <em>for /r</em> from cmd-file:</p>\n<p>for /r <strong>%%x</strong> in (*.dll, *pdb) do copy <strong>&quot;%%x&quot;</strong> targetDir\\</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32333/" ]
I need to copy a set of DLL and PDB files from a set of folders recursively into another folder. I don't want to recreate the folder hierarchy in the target folder. I want to use built in Windows tools, e.g. DOS commands.
``` mkdir targetDir for /r %x in (*.dll, *pdb) do copy "%x" targetDir\ ``` Use /Y at the end of the above command if you are copying multiple files and don't want to keep answering "Yes".
246,564
<p>If a variable is declared as <code>static</code> in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?</p> <pre><code>void foo() { static string plonk = "When will I die?"; } </code></pre>
[ { "answer_id": 246568, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 9, "selected": true, "text": "<p>The lifetime of function <code>static</code> variables begins the first time<sup>[0]</sup> the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.</p>\n<p>Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction<sup>[1]</sup>, and the order of construction may depend on the specific program run, the order of construction must be taken into account.</p>\n<p><strong>Example</strong></p>\n<pre><code>struct emitter {\n string str;\n emitter(const string&amp; s) : str(s) { cout &lt;&lt; &quot;Created &quot; &lt;&lt; str &lt;&lt; endl; }\n ~emitter() { cout &lt;&lt; &quot;Destroyed &quot; &lt;&lt; str &lt;&lt; endl; }\n};\n\nvoid foo(bool skip_first) \n{\n if (!skip_first)\n static emitter a(&quot;in if&quot;);\n static emitter b(&quot;in foo&quot;);\n}\n\nint main(int argc, char*[])\n{\n foo(argc != 2);\n if (argc == 3)\n foo(false);\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<blockquote>\n<p>C:&gt;sample.exe<br />\nCreated in foo<br />\nDestroyed in foo</p>\n<p>C:&gt;sample.exe 1<br />\nCreated in if<br />\nCreated in foo<br />\nDestroyed in foo<br />\nDestroyed in if</p>\n<p>C:&gt;sample.exe 1 2<br />\nCreated in foo<br />\nCreated in if<br />\nDestroyed in if<br />\nDestroyed in foo</p>\n</blockquote>\n<p><code>[0]</code> Since <strong>C++98</strong><sup>[2]</sup> has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as <a href=\"https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function#246594\">Roddy</a> mentions.</p>\n<p><code>[1]</code> <strong>C++98</strong> section <code>3.6.3.1</code> <em>[basic.start.term]</em></p>\n<p><code>[2]</code> In C++11 statics are initialized in a thread safe way, this is also known as <a href=\"http://herbsutter.com/2013/09/09/visual-studio-2013-rc-is-now-available/\" rel=\"noreferrer\"><em>Magic Statics</em></a>.</p>\n" }, { "answer_id": 246594, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 7, "selected": false, "text": "<p>Motti is right about the order, but there are some other things to consider:</p>\n\n<p>Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.</p>\n\n<p>If you have a local static as above, and <code>foo</code> is called from multiple threads, you may have race conditions causing <code>plonk</code> to be initialized incorrectly or even multiple times. Also, in this case <code>plonk</code> may get destructed by a different thread than the one which constructed it.</p>\n\n<p>Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down. </p>\n" }, { "answer_id": 247470, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 3, "selected": false, "text": "<p>FWIW, Codegear C++Builder doesn't destruct in the expected order according to the standard.</p>\n\n<pre><code>C:\\&gt; sample.exe 1 2\nCreated in foo\nCreated in if\nDestroyed in foo\nDestroyed in if\n</code></pre>\n\n<p>... which is another reason not to rely on the destruction order!</p>\n" }, { "answer_id": 25796970, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 3, "selected": false, "text": "<p>The existing explanations aren't really complete without the actual rule from the Standard, found in 6.7:</p>\n\n<blockquote>\n <p>The zero-initialization of all block-scope variables with static storage duration or thread storage duration is performed before any other initialization takes place. Constant initialization of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope. Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization\n is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.</p>\n</blockquote>\n" }, { "answer_id": 56588508, "author": "Chandra Shekhar", "author_id": 7497038, "author_profile": "https://Stackoverflow.com/users/7497038", "pm_score": 0, "selected": false, "text": "<p>The <em>Static variables</em> are come into play once the <em>program execution starts</em> and it remain available till the program execution ends.</p>\n\n<p>The Static variables are created in the <strong>Data Segment of the Memory</strong>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
If a variable is declared as `static` in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called? ``` void foo() { static string plonk = "When will I die?"; } ```
The lifetime of function `static` variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed. Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account. **Example** ``` struct emitter { string str; emitter(const string& s) : str(s) { cout << "Created " << str << endl; } ~emitter() { cout << "Destroyed " << str << endl; } }; void foo(bool skip_first) { if (!skip_first) static emitter a("in if"); static emitter b("in foo"); } int main(int argc, char*[]) { foo(argc != 2); if (argc == 3) foo(false); } ``` **Output:** > > C:>sample.exe > > Created in foo > > Destroyed in foo > > > C:>sample.exe 1 > > Created in if > > Created in foo > > Destroyed in foo > > Destroyed in if > > > C:>sample.exe 1 2 > > Created in foo > > Created in if > > Destroyed in if > > Destroyed in foo > > > `[0]` Since **C++98**[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as [Roddy](https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function#246594) mentions. `[1]` **C++98** section `3.6.3.1` *[basic.start.term]* `[2]` In C++11 statics are initialized in a thread safe way, this is also known as [*Magic Statics*](http://herbsutter.com/2013/09/09/visual-studio-2013-rc-is-now-available/).
246,577
<p>I am writing an RSS feed (for fun) and was looking at the spec <a href="http://cyber.law.harvard.edu/rss/rss.html" rel="noreferrer">here</a>.</p> <blockquote> <p>RSS is a dialect of XML. All RSS files must conform to the XML 1.0 specification, as published on the World Wide Web Consortium (W3C) website.</p> </blockquote> <p>Obviously this means that I am not serving 'pure' RSS if I choose the JSON option. That said, if I conform to the rest of the spec, is it likely that (customised) readers will be able to parse it?</p> <p>To put it another way, if I conform to the spec, but using JSON instead of XML is it a usable RSS feed?</p> <p><em>edit</em> I am not sure I made myself clear. There is no XML involved. I want to write something akin to RSS (which is XML) using JSON instead. Obviously the readers of such a feed would need to be written to understand the JSON format. I was wondering if this had been done already. Are there services that serve a feed this way? Are there programs that can aggregate/understand this format. Is the RSS spec (sans the XML part) a useful spec to conform to in this case?</p> <p>rg </p> <pre><code>{ "title":"example.com", "link":"http://www.example.com/", "description":"Awesome news about junk", "items":[ { "title":"An article", "link":"http://www.example.com/an-article", "descrition":"Some sample text here", "pubDate":"2008-10-27 11:06 EST", "author":"example author", }, { "title":"Second", "link":"http://www.example.com/Seond", "descrition":"Some sample text here", "pubDate":"2008-10-25 23:20 EST", "author":"author mcauthor", }, { "title":"third article", "link":"http://www.example.com/third-article", "descrition":"Some sample text here", "pubDate":"2008-10-25 23:18 EST", "author":"some other author", } ] } </code></pre>
[ { "answer_id": 246593, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 5, "selected": false, "text": "<p>No, RSS is an XML-based format, and JSON is an different language rather than some kind of dialect. RSS readers won't understand JSON.</p>\n\n<p>Your question is akin to asking 'Can I speak French in Chinese?'</p>\n" }, { "answer_id": 248133, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>There are a bunch of different ways to serialize RSS into JSON. All of them work pretty much the same way: the elements and attributes become property names, the values become property values, etc. See <a href=\"http://blogs.msdn.com/shahpiyush/archive/2007/04/12/2103116.aspx\" rel=\"nofollow noreferrer\">Piyush Shah's</a> technique, for example, which is a .NET implementation. </p>\n\n<p>Transforming arbitrary XML to JSON using XSLT is simple enough that you can find a half-dozen examples of it on Google.</p>\n\n<p>As long as this is done consistently, JavaScript that can process an object model designed to replicate the data structure of the RSS specification should be able to handle the object model that the JSON deserializes into. </p>\n\n<p>Who are you planning to send this JSON to? That's the real question.</p>\n" }, { "answer_id": 251764, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 4, "selected": false, "text": "<p>I believe this has been done already. </p>\n\n<p>Take a look at this jQuery extension: <a href=\"https://github.com/jfhovinne/jFeed\" rel=\"nofollow noreferrer\">jFeed - RSS/ATOM feed parser</a></p>\n\n<pre><code>jQuery.getFeed(options);\n</code></pre>\n\n<p><strong>Options:</strong></p>\n\n<ul>\n<li>url: </li>\n<li>data:</li>\n<li>success:</li>\n</ul>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>jQuery.getFeed({\n url: 'rss.xml',\n success: function(feed) {\n alert(feed.title);\n }\n });\n</code></pre>\n\n<p>Note that in this case, 'feed' would be a javascript object. If you wanted to pass this using JSON, you can just use the <a href=\"http://www.json.org/js.html\" rel=\"nofollow noreferrer\">javascript JSON utility</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>var myJSONText = JSON.stringify(feed);\n</code></pre>\n" }, { "answer_id": 251780, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 2, "selected": false, "text": "<p>Json.NET - <a href=\"http://james.newtonking.com/projects/json-net.aspx\" rel=\"nofollow noreferrer\">http://james.newtonking.com/projects/json-net.aspx</a> - has support to convert any XML document to JSON.</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\n\ndoc.LoadXml(@\"&lt;?xml version=\"\"1.0\"\" standalone=\"\"no\"\"?&gt;\n&lt;root&gt;\n &lt;person id=\"\"1\"\"&gt;\n &lt;name&gt;Alan&lt;/name&gt;\n &lt;url&gt;http://www.google.com&lt;/url&gt;\n &lt;/person&gt;\n &lt;person id=\"\"2\"\"&gt;\n &lt;name&gt;Louis&lt;/name&gt;\n &lt;url&gt;http://www.yahoo.com&lt;/url&gt;\n &lt;/person&gt;\n&lt;/root&gt;\");\n\n\nstring jsonText = JavaScriptConvert.SerializeXmlNode(doc);\n//{\n// \"?xml\": {\n// \"@version\": \"1.0\",\n// \"@standalone\": \"no\"\n// },\n// \"root\": {\n// \"person\": [\n// {\n// \"@id\": \"1\",\n// \"name\": \"Alan\",\n// \"url\": \"http://www.google.com\"\n// },\n// {\n// \"@id\": \"2\",\n// \"name\": \"Louis\",\n// \"url\": \"http://www.yahoo.com\"\n// }\n// ]\n// }\n//}\n\nXmlDocument newDoc = (XmlDocument)JavaScriptConvert.DeerializeXmlNode(jsonText);\n\nAssert.AreEqual(doc.InnerXml, newDoc.InnerXml);\n</code></pre>\n" }, { "answer_id": 322500, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Is the RSS spec (sans the XML part) a useful spec to conform to in this case?</p>\n</blockquote>\n\n<p>If you want to invent yet another syndication format, I recommend using Atom as a base. IMHO it has much cleaner, more consistent design, and has useful features like reliable updates of past items, makes distinction between summaries and full content, etc.</p>\n\n<blockquote>\n <p>I was wondering if this had been done already.</p>\n</blockquote>\n\n<p>Flickr has <a href=\"http://api.flickr.com/services/feeds/photos_public.gne?id=36998705@N00&amp;lang=en-us&amp;format=json\" rel=\"noreferrer\">JSON output format</a>. They even have <a href=\"http://api.flickr.com/services/feeds/photos_public.gne?id=36998705@N00&amp;lang=en-us&amp;format=lolcode\" rel=\"noreferrer\">lolcode feed</a>.</p>\n" }, { "answer_id": 1692951, "author": "Uzbekjon", "author_id": 52317, "author_profile": "https://Stackoverflow.com/users/52317", "pm_score": 1, "selected": false, "text": "<p>Well, if you are developing some javascript app you might want to get any RSS feeds as JSON to overcome cross-domain querying issue. There is a reliable Google provided solution that converts about any RSS to JSON. For jQuery lover's there is a <a href=\"http://jquery-howto.blogspot.com/2009/11/cross-domain-rss-to-json-converter.html\" rel=\"nofollow noreferrer\">universal RSS to JSON converter plugin</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>$.jGFeed('http://twitter.com/statuses/user_timeline/26767000.rss',\n function(feeds){\n\n // feeds is a javascript object with RSS content\n\n }, 10);\n</code></pre>\n" }, { "answer_id": 44185624, "author": "jlbang", "author_id": 602769, "author_profile": "https://Stackoverflow.com/users/602769", "pm_score": 4, "selected": true, "text": "<p>You're right that the client <em>reading</em> the feed would have to have custom support for whatever the particulars of your JSON were. So you'd either need to make a custom feed reader to consume that information, or someone would have to propose a JSON feed standard, and it'd have to be widely adopted.</p>\n\n<p>Well, I think your desires have finally been met, friend! </p>\n\n<p>Take a look at <a href=\"https://jsonfeed.org/\" rel=\"noreferrer\">JSON Feed</a>. As of this writing it's only about a week old, but it's already picking up steam, having been supported now by <a href=\"https://twitter.com/feedly/status/875046109651116034\" rel=\"noreferrer\">Feedly</a>, <a href=\"https://feedbin.com/blog/2017/05/22/feedbin-supports-json-feed/\" rel=\"noreferrer\">Feedbin</a>, <a href=\"https://betamagic.nl/blog.html\" rel=\"noreferrer\">News Explorer</a>, <a href=\"http://blog.newsblur.com/post/160982162270/newsblur-now-supports-the-new-json-feed-spec\" rel=\"noreferrer\">NewsBlur</a>, and more being added all the time.</p>\n\n<p>If I had to pick a standard to use when generating a JSON version of RSS, I'd pick JSON Feed for sure.</p>\n" }, { "answer_id": 44808394, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 1, "selected": false, "text": "<p>I know this is a fairly old question, and maybe irrelevant now.</p>\n\n<p>However. I would suggest anyone looking to publish a RSS-like feed in JSON should use a new format that is rapidly gaining adoption; JSONFeed (<a href=\"https://jsonfeed.org\" rel=\"nofollow noreferrer\">https://jsonfeed.org</a>).</p>\n" }, { "answer_id": 54882328, "author": "vhs", "author_id": 712334, "author_profile": "https://Stackoverflow.com/users/712334", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>Are there programs that can aggregate/understand this format.</p>\n</blockquote>\n\n<p>You can use <a href=\"https://www.w3.org/TR/xslt-30/\" rel=\"nofollow noreferrer\">XSLT 3.0</a> to transform XML to JSON and back to XML again. More info on how to accomplish the transforms to JSON here: </p>\n\n<p><a href=\"https://www.xml.com/articles/2017/02/14/why-you-should-be-using-xslt-30/\" rel=\"nofollow noreferrer\">https://www.xml.com/articles/2017/02/14/why-you-should-be-using-xslt-30/</a>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431280/" ]
I am writing an RSS feed (for fun) and was looking at the spec [here](http://cyber.law.harvard.edu/rss/rss.html). > > RSS is a dialect of XML. All RSS files must conform to the XML 1.0 specification, as published on the World Wide Web Consortium (W3C) website. > > > Obviously this means that I am not serving 'pure' RSS if I choose the JSON option. That said, if I conform to the rest of the spec, is it likely that (customised) readers will be able to parse it? To put it another way, if I conform to the spec, but using JSON instead of XML is it a usable RSS feed? *edit* I am not sure I made myself clear. There is no XML involved. I want to write something akin to RSS (which is XML) using JSON instead. Obviously the readers of such a feed would need to be written to understand the JSON format. I was wondering if this had been done already. Are there services that serve a feed this way? Are there programs that can aggregate/understand this format. Is the RSS spec (sans the XML part) a useful spec to conform to in this case? rg ``` { "title":"example.com", "link":"http://www.example.com/", "description":"Awesome news about junk", "items":[ { "title":"An article", "link":"http://www.example.com/an-article", "descrition":"Some sample text here", "pubDate":"2008-10-27 11:06 EST", "author":"example author", }, { "title":"Second", "link":"http://www.example.com/Seond", "descrition":"Some sample text here", "pubDate":"2008-10-25 23:20 EST", "author":"author mcauthor", }, { "title":"third article", "link":"http://www.example.com/third-article", "descrition":"Some sample text here", "pubDate":"2008-10-25 23:18 EST", "author":"some other author", } ] } ```
You're right that the client *reading* the feed would have to have custom support for whatever the particulars of your JSON were. So you'd either need to make a custom feed reader to consume that information, or someone would have to propose a JSON feed standard, and it'd have to be widely adopted. Well, I think your desires have finally been met, friend! Take a look at [JSON Feed](https://jsonfeed.org/). As of this writing it's only about a week old, but it's already picking up steam, having been supported now by [Feedly](https://twitter.com/feedly/status/875046109651116034), [Feedbin](https://feedbin.com/blog/2017/05/22/feedbin-supports-json-feed/), [News Explorer](https://betamagic.nl/blog.html), [NewsBlur](http://blog.newsblur.com/post/160982162270/newsblur-now-supports-the-new-json-feed-spec), and more being added all the time. If I had to pick a standard to use when generating a JSON version of RSS, I'd pick JSON Feed for sure.
246,623
<p>I want do something like this:</p> <pre><code>Result = 'MyString' in [string1, string2, string3, string4]; </code></pre> <p>This can't be used with strings and I don't want to do something like this:</p> <pre><code>Result = (('MyString' = string1) or ('MyString' = string2)); </code></pre> <p>Also I think that creating a StringList to do just this is too complex.</p> <p>Is there some other way to achieve this?</p> <p>Thanks.</p>
[ { "answer_id": 246660, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 2, "selected": false, "text": "<p>Here is a function that does the job:</p>\n\n<pre><code>function StringInArray(Value: string; Strings: array of string): Boolean;\nvar I: Integer;\nbegin\n Result := False;\n for I := Low(Strings) to High(Strings) do\n Result := Result or (Value = Strings[I]);\nend;\n</code></pre>\n\n<p>In fact, you do compare MyString with each string in Strings. As soon as you find one matching you can exit the for loop.</p>\n" }, { "answer_id": 246730, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "<p>The code by Burkhard works, but iterates needlessly over the list even if a match is found.</p>\n\n<p>Better approach:</p>\n\n<pre><code>function StringInArray(const Value: string; Strings: array of string): Boolean;\nvar I: Integer;\nbegin\n Result := True;\n for I := Low(Strings) to High(Strings) do\n if Strings[i] = Value then Exit;\n Result := False;\nend;\n</code></pre>\n" }, { "answer_id": 246753, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 7, "selected": true, "text": "<p>You could use <code>AnsiIndexText(const AnsiString AText, const array of string AValues):integer</code> or <code>MatchStr(const AText: string; const AValues: array of string): Boolean;</code> (Both from <code>StrUtils</code> unit)</p>\n<p>Something like:</p>\n<pre><code>Result := (AnsiIndexText('Hi',['Hello','Hi','Foo','Bar']) &gt; -1);\n</code></pre>\n<p>or</p>\n<pre><code>Result := MatchStr('Hi', ['foo', 'Bar']); \n</code></pre>\n<blockquote>\n<p>AnsiIndexText returns the 0-offset\nindex of the first string it finds in\nAValues that matches AText\n<strong>case-insensitively</strong>. If the string\nspecified by AText does not have a\n(possibly case-insensitive) match in\nAValues, AnsiIndexText returns –1.\nComparisons are based on the current\nsystem locale.</p>\n<p>MatchStr determines if any of the\nstrings in the array AValues match the\nstring specified by AText using a <strong>case\nsensitive comparison</strong>. It returns true\nif at least one of the strings in the\narray match, or false if none of the\nstrings match.</p>\n</blockquote>\n<p>Note <code>AnsiIndexText</code> has case-insensitively and <code>MatchStr</code> is case sensitive so I guess it depends on your use</p>\n<p><strong>EDIT: 2011-09-3</strong>: Just found this answer and thought I would add a note that, in Delphi 2010 there is also a <code>MatchText</code> function which is the same as <code>MatchStr</code> but case insenstive. -- Larry</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
I want do something like this: ``` Result = 'MyString' in [string1, string2, string3, string4]; ``` This can't be used with strings and I don't want to do something like this: ``` Result = (('MyString' = string1) or ('MyString' = string2)); ``` Also I think that creating a StringList to do just this is too complex. Is there some other way to achieve this? Thanks.
You could use `AnsiIndexText(const AnsiString AText, const array of string AValues):integer` or `MatchStr(const AText: string; const AValues: array of string): Boolean;` (Both from `StrUtils` unit) Something like: ``` Result := (AnsiIndexText('Hi',['Hello','Hi','Foo','Bar']) > -1); ``` or ``` Result := MatchStr('Hi', ['foo', 'Bar']); ``` > > AnsiIndexText returns the 0-offset > index of the first string it finds in > AValues that matches AText > **case-insensitively**. If the string > specified by AText does not have a > (possibly case-insensitive) match in > AValues, AnsiIndexText returns –1. > Comparisons are based on the current > system locale. > > > MatchStr determines if any of the > strings in the array AValues match the > string specified by AText using a **case > sensitive comparison**. It returns true > if at least one of the strings in the > array match, or false if none of the > strings match. > > > Note `AnsiIndexText` has case-insensitively and `MatchStr` is case sensitive so I guess it depends on your use **EDIT: 2011-09-3**: Just found this answer and thought I would add a note that, in Delphi 2010 there is also a `MatchText` function which is the same as `MatchStr` but case insenstive. -- Larry
246,636
<p>My WCF Service uses wsHttpBinding and works fine from the client when the service is gerenated by the client using the default options as follows:</p> <pre><code>RServiceClient R = new RServiceClient(); </code></pre> <p>However, at some point I'll need to be able to specify the location of the service, presumably by changing the endpoint address as follows:</p> <pre><code>RServiceClient R = new RServiceClient(); R.Endpoint.Address = new EndpointAddress(new Uri "http://xxx.xxxx.xxx:80/RServer/RService.svc")); </code></pre> <p>However, when I do specify the exact endpoint, I get a SecurityNegotiationException: System.ServiceModel.Security.SecurityNegotiationException was unhandled Message="The caller was not authenticated by the service." Source="mscorlib"....</p> <p>The WCF service runs on IIS and has anonymous access enabled under IIS admin. Also, this error occurs when the client is run from the same machine as the service under an admin account - I havn't got to the scary part of running it over the net yet!</p> <p>Any Ideas?</p>
[ { "answer_id": 246646, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<p>Are you using MessageSecurity with certificates? this could be a certificate issue (wrong hostname, self-signed certificate not installed, etc..)</p>\n" }, { "answer_id": 246694, "author": "Calanus", "author_id": 445, "author_profile": "https://Stackoverflow.com/users/445", "pm_score": 0, "selected": false, "text": "<p>Here is my Service configuration information, i'm using wshttpbinding:</p>\n\n<pre><code>&lt;system.serviceModel&gt;\n &lt;services&gt;\n &lt;service behaviorConfiguration=\"ServiceBehavior\" name=\"RService\"&gt;\n&lt;endpoint address=\"\" binding=\"wsHttpBinding\" bindingConfiguration=\"\"\n name=\"RService\" contract=\"IRService\"&gt;\n &lt;identity&gt;\n &lt;dns value=\"localhost\" /&gt;\n &lt;/identity&gt;\n&lt;/endpoint&gt;\n&lt;endpoint address=\"mex\" binding=\"mexHttpBinding\" name=\"MetadataExchange\"\n contract=\"IMetadataExchange\" /&gt;\n &lt;/service&gt;\n&lt;/services&gt;\n &lt;behaviors&gt;\n &lt;serviceBehaviors&gt;\n &lt;behavior name=\"ServiceBehavior\"&gt;\n &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt;\n &lt;serviceMetadata httpGetEnabled=\"true\"/&gt;\n &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt;\n &lt;serviceDebug includeExceptionDetailInFaults=\"true\"/&gt;\n &lt;/behavior&gt;\n &lt;/serviceBehaviors&gt;\n &lt;/behaviors&gt;\n&lt;/system.serviceModel&gt;\n</code></pre>\n" }, { "answer_id": 246754, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 2, "selected": false, "text": "<p>check this from your config :</p>\n\n<pre><code>... \n &lt;identity&gt;\n &lt;dns value=\"localhost\" /&gt;\n &lt;/identity&gt;\n...\n</code></pre>\n\n<p>afaik wsHttpBinding has <strong>message security turned on by default</strong>.\nand when it checks against the dns value \"localhost\" it fails.</p>\n" }, { "answer_id": 246858, "author": "Calanus", "author_id": 445, "author_profile": "https://Stackoverflow.com/users/445", "pm_score": 0, "selected": false, "text": "<p>Deleting the identity block didn't work, although did give me an idea:\nIf I change the endpoint address from:</p>\n\n<pre><code> R.Endpoint.Address = new EndpointAddress(new Uri(\"http://bigpuss.homeip.net/RServer/RService.svc\"));\n</code></pre>\n\n<p>to</p>\n\n<pre><code> R.Endpoint.Address = new EndpointAddress(new Uri(\"http://localhost/RServer/RService.svc\"));\n</code></pre>\n\n<p>then everything works fine! Soo, its obviously upset about the nonlocal url address. Are there any other areas in the configuration where security is set up?</p>\n" }, { "answer_id": 246862, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 4, "selected": true, "text": "<p>By default, wsHttpBinding uses Windows authentication. I'm not sure how hosting in IIS affects that scenario. </p>\n\n<p>If you don't want security turned on, you can add an element for security and set the mode element to \"None\" to the config on both ends to turn off the default setting.</p>\n\n<p>I think this may do the trick -- I've added the section for wsHttpBinding and set the bindingConfiguration of your service to point to the newly added binding properties:</p>\n\n<pre><code>&lt;system.serviceModel&gt;\n &lt;bindings&gt;\n &lt;wsHttpBinding&gt;\n &lt;binding name=\"wsHttpBind\"&gt;\n &lt;security mode=\"None\"&gt;\n &lt;transport clientCredentialType=\"None\" protectionLevel=\"EncryptAndSign\" /&gt;\n &lt;message clientCredentialType=\"None\" algorithmSuite=\"Default\" /&gt;\n &lt;/security&gt;\n &lt;/binding&gt;\n &lt;/wsHttpBinding&gt;\n &lt;/bindings&gt;\n &lt;services&gt;\n &lt;service behaviorConfiguration=\"ServiceBehavior\" \n name=\"RService\"&gt;\n &lt;endpoint address=\"\" \n binding=\"wsHttpBinding\" \n bindingConfiguration=\"wsHttpBind\" \n name=\"RService\" \n contract=\"IRService\"&gt; \n &lt;identity&gt;\n &lt;dns value=\"localhost\" /&gt;\n &lt;/identity&gt;\n &lt;/endpoint&gt;\n &lt;endpoint address=\"mex\" \n binding=\"mexHttpBinding\" \n name=\"MetadataExchange\" \n contract=\"IMetadataExchange\" /&gt;\n &lt;/service&gt;\n &lt;/services&gt;\n &lt;behaviors&gt;\n &lt;serviceBehaviors&gt;\n &lt;behavior name=\"ServiceBehavior\"&gt;\n &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt;\n &lt;serviceMetadata httpGetEnabled=\"true\"/&gt;\n &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt;\n &lt;serviceDebug includeExceptionDetailInFaults=\"true\"/&gt;\n &lt;/behavior&gt;\n &lt;/serviceBehaviors&gt;\n &lt;/behaviors&gt;\n&lt;/system.serviceModel&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445/" ]
My WCF Service uses wsHttpBinding and works fine from the client when the service is gerenated by the client using the default options as follows: ``` RServiceClient R = new RServiceClient(); ``` However, at some point I'll need to be able to specify the location of the service, presumably by changing the endpoint address as follows: ``` RServiceClient R = new RServiceClient(); R.Endpoint.Address = new EndpointAddress(new Uri "http://xxx.xxxx.xxx:80/RServer/RService.svc")); ``` However, when I do specify the exact endpoint, I get a SecurityNegotiationException: System.ServiceModel.Security.SecurityNegotiationException was unhandled Message="The caller was not authenticated by the service." Source="mscorlib".... The WCF service runs on IIS and has anonymous access enabled under IIS admin. Also, this error occurs when the client is run from the same machine as the service under an admin account - I havn't got to the scary part of running it over the net yet! Any Ideas?
By default, wsHttpBinding uses Windows authentication. I'm not sure how hosting in IIS affects that scenario. If you don't want security turned on, you can add an element for security and set the mode element to "None" to the config on both ends to turn off the default setting. I think this may do the trick -- I've added the section for wsHttpBinding and set the bindingConfiguration of your service to point to the newly added binding properties: ``` <system.serviceModel> <bindings> <wsHttpBinding> <binding name="wsHttpBind"> <security mode="None"> <transport clientCredentialType="None" protectionLevel="EncryptAndSign" /> <message clientCredentialType="None" algorithmSuite="Default" /> </security> </binding> </wsHttpBinding> </bindings> <services> <service behaviorConfiguration="ServiceBehavior" name="RService"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBind" name="RService" contract="IRService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" name="MetadataExchange" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> ```
246,644
<p>Here is a simplified version of my database model. I have two tables: "Image", and "HostingProvider" which look like this:</p> <p><strong>[Image]</strong></p> <ul> <li>id</li> <li>filename</li> <li>hostingprovider_id</li> </ul> <p><strong>[HostingProvider]</strong></p> <ul> <li>id</li> <li>base_url</li> </ul> <p>Image HostingproviderId is a many-to-one foreign key relationship to the HostingProvider table. (Each image has one hosting provider). </p> <p>Essentially I want to be able to have my Image class look like this:</p> <p><strong>[Image]</strong></p> <ul> <li>Id</li> <li>base_url</li> <li>filename</li> </ul> <p>In NHibernate, how can I create a mapping file that will combine the base_url from the HostingProvider table, into the Image class?</p>
[ { "answer_id": 246769, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<pre><code>public class Image {\n public virtual HostingProvider HostingProvider { get; set; } // NHibernate takes care of this\n public virtual string BaseUrl { get { return HostingProvider.BaseUrl; } }\n}\n</code></pre>\n" }, { "answer_id": 246782, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": true, "text": "<p>What you're looking for is this:</p>\n\n<p><a href=\"http://ayende.com/Blog/archive/2007/04/24/Multi-Table-Entities-in-NHibernate.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2007/04/24/Multi-Table-Entities-in-NHibernate.aspx</a></p>\n\n<p>Here's a peek of what it looks like:</p>\n\n<pre><code>&lt;class name=\"Person\"&gt;\n\n &lt;id name=\"Id\" column=\"person_id\" unsaved-value=\"0\"&gt;\n\n &lt;generator class=\"native\"/&gt;\n\n &lt;/id&gt;\n\n\n\n &lt;property name=\"Name\"/&gt;\n\n &lt;property name=\"Sex\"/&gt;\n\n\n\n &lt;join table=\"address\"&gt;\n\n &lt;key column=\"address_id\"/&gt;\n\n &lt;property name=\"Address\"/&gt;\n\n &lt;property name=\"Zip\"/&gt;\n\n &lt;property name=\"Country\"/&gt;\n\n &lt;property name=\"HomePhone\"/&gt;\n\n &lt;property name=\"BusinessPhone\"/&gt;\n\n &lt;/join&gt;\n\n&lt;/class&gt; \n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13145/" ]
Here is a simplified version of my database model. I have two tables: "Image", and "HostingProvider" which look like this: **[Image]** * id * filename * hostingprovider\_id **[HostingProvider]** * id * base\_url Image HostingproviderId is a many-to-one foreign key relationship to the HostingProvider table. (Each image has one hosting provider). Essentially I want to be able to have my Image class look like this: **[Image]** * Id * base\_url * filename In NHibernate, how can I create a mapping file that will combine the base\_url from the HostingProvider table, into the Image class?
What you're looking for is this: <http://ayende.com/Blog/archive/2007/04/24/Multi-Table-Entities-in-NHibernate.aspx> Here's a peek of what it looks like: ``` <class name="Person"> <id name="Id" column="person_id" unsaved-value="0"> <generator class="native"/> </id> <property name="Name"/> <property name="Sex"/> <join table="address"> <key column="address_id"/> <property name="Address"/> <property name="Zip"/> <property name="Country"/> <property name="HomePhone"/> <property name="BusinessPhone"/> </join> </class> ```
246,656
<p>I am trying to match the folder name in a relative path using C#. I am using the expression: <code>"/(.*)?/"</code> and reversing the matching from left to right to right to left. When I pass <code>"images/gringo/"</code> into the regular expression, it correctly gives me <code>"gringo"</code> in the first group - I'm only interested in what is between the brackets. When I pass in <code>"images/"</code>, it fails to pick up <code>"images"</code>. I have tried using <code>[/^]</code> and <code>[/$]</code> but neither work.</p> <p>Thanks, David</p>
[ { "answer_id": 246663, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "<p>You're probably better off using the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx\" rel=\"noreferrer\">System.IO.DirectoryInfo</a> class to interpret your relative path. You can then pick off folder or file names using its members:</p>\n\n<pre><code>DirectoryInfo di = new DirectoryInfo(\"images/gringo/\");\nConsole.Out.WriteLine(di.Name);\n</code></pre>\n\n<p>This will be much safer than any regexps you could use.</p>\n" }, { "answer_id": 246665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Don't do this. Use System.IO.Path to break apart path parts and then compare them. </p>\n" }, { "answer_id": 246670, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>\"([^/]+)/?$\"\n</code></pre>\n\n<ul>\n<li>1 or more non / characters</li>\n<li>Optional /</li>\n<li>End of string</li>\n</ul>\n\n<p>But as <a href=\"https://stackoverflow.com/questions/246656/regular-expressions-and-relative-file-paths#246663\">@Blair Conrad</a> says - better to go with a class that encapsulates this for you....</p>\n" }, { "answer_id": 247616, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "<p>Agreed with the \"<em>don't do it this way</em>\" answers, but, since it's tagged \"<em>regex</em>\"...</p>\n\n<ul>\n<li>You don't need the <code>?</code>. <code>*</code> already accepts 0 repetitions as a match, so <code>(.*)</code> is exactly equivalent to <code>(.*)?</code></li>\n<li>You rarely actually want to use <code>.*</code> anyhow. If you're trying to capture what's between a pair of slashes, use <code>/([^/]*)/</code> or else testing against \"<em>foo/bar/baz/</em>\" will (on most regex implementations) return a single match for \"<em>bar/baz</em>\" instead of matching \"<em>bar</em>\" and \"<em>baz</em>\" separately.</li>\n</ul>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to match the folder name in a relative path using C#. I am using the expression: `"/(.*)?/"` and reversing the matching from left to right to right to left. When I pass `"images/gringo/"` into the regular expression, it correctly gives me `"gringo"` in the first group - I'm only interested in what is between the brackets. When I pass in `"images/"`, it fails to pick up `"images"`. I have tried using `[/^]` and `[/$]` but neither work. Thanks, David
You're probably better off using the [System.IO.DirectoryInfo](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx) class to interpret your relative path. You can then pick off folder or file names using its members: ``` DirectoryInfo di = new DirectoryInfo("images/gringo/"); Console.Out.WriteLine(di.Name); ``` This will be much safer than any regexps you could use.
246,667
<p>I have a table in Access 2007 with 11,000 rows and about 20 columns. I want to create a form button that exports the table to an Excel sheet. The code need to be VBA.</p> <p>Any Ideas?</p>
[ { "answer_id": 246663, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "<p>You're probably better off using the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx\" rel=\"noreferrer\">System.IO.DirectoryInfo</a> class to interpret your relative path. You can then pick off folder or file names using its members:</p>\n\n<pre><code>DirectoryInfo di = new DirectoryInfo(\"images/gringo/\");\nConsole.Out.WriteLine(di.Name);\n</code></pre>\n\n<p>This will be much safer than any regexps you could use.</p>\n" }, { "answer_id": 246665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Don't do this. Use System.IO.Path to break apart path parts and then compare them. </p>\n" }, { "answer_id": 246670, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>\"([^/]+)/?$\"\n</code></pre>\n\n<ul>\n<li>1 or more non / characters</li>\n<li>Optional /</li>\n<li>End of string</li>\n</ul>\n\n<p>But as <a href=\"https://stackoverflow.com/questions/246656/regular-expressions-and-relative-file-paths#246663\">@Blair Conrad</a> says - better to go with a class that encapsulates this for you....</p>\n" }, { "answer_id": 247616, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "<p>Agreed with the \"<em>don't do it this way</em>\" answers, but, since it's tagged \"<em>regex</em>\"...</p>\n\n<ul>\n<li>You don't need the <code>?</code>. <code>*</code> already accepts 0 repetitions as a match, so <code>(.*)</code> is exactly equivalent to <code>(.*)?</code></li>\n<li>You rarely actually want to use <code>.*</code> anyhow. If you're trying to capture what's between a pair of slashes, use <code>/([^/]*)/</code> or else testing against \"<em>foo/bar/baz/</em>\" will (on most regex implementations) return a single match for \"<em>bar/baz</em>\" instead of matching \"<em>bar</em>\" and \"<em>baz</em>\" separately.</li>\n</ul>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a table in Access 2007 with 11,000 rows and about 20 columns. I want to create a form button that exports the table to an Excel sheet. The code need to be VBA. Any Ideas?
You're probably better off using the [System.IO.DirectoryInfo](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx) class to interpret your relative path. You can then pick off folder or file names using its members: ``` DirectoryInfo di = new DirectoryInfo("images/gringo/"); Console.Out.WriteLine(di.Name); ``` This will be much safer than any regexps you could use.
246,671
<p>Is it possible to import csv data into mysql and automatically create the column names, as in can I create just the table, or must I create the table names as well?</p> <p>Is it possible to check for duplicate entries upon importing? I have an identifier field, but dont know how to make it so it will not be imported twice.</p> <p>How would you import a jpeg file on a website into a field? Assume the website has been stored locally, and has the same filename as an identifer with ".jpeg" added on to the end.</p>
[ { "answer_id": 246679, "author": "tante", "author_id": 2065014, "author_profile": "https://Stackoverflow.com/users/2065014", "pm_score": 0, "selected": false, "text": "<p>Sure, but you'll probably have to write a few lines of code yourself, it can be done with very little code. Checking for duplicates is quite easy then, you can do that before inserting in your little script.</p>\n\n<p>You could store the file as a combination of two fields, one Varchar for the name and a blob for the file contents.</p>\n" }, { "answer_id": 246684, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<ol>\n<li>No</li>\n<li>You could add a unique\nconstraint - it really depends what\nyou want to do if a duplicate is\nfound</li>\n<li>Not using mysql - use a\nscripting language to pull the image\ndata from the URL then insert that</li>\n</ol>\n" }, { "answer_id": 246695, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": true, "text": "<p>As tante said you'll have to handle the table creation yourself, but as far as importing csv is concerned you should have a look at <a href=\"http://dev.mysql.com/doc/refman/5.0/en/load-data.html\" rel=\"nofollow noreferrer\">LOAD DATA INFILE</a></p>\n\n<pre><code>LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'\n[REPLACE | IGNORE]\nINTO TABLE tbl_name\n[CHARACTER SET charset_name]\n[{FIELDS | COLUMNS}\n [TERMINATED BY 'string']\n [[OPTIONALLY] ENCLOSED BY 'char']\n [ESCAPED BY 'char']\n]\n[LINES\n [STARTING BY 'string']\n [TERMINATED BY 'string']\n]\n[IGNORE number LINES]\n[(col_name_or_user_var,...)]\n[SET col_name = expr,...]\n</code></pre>\n\n<p>Duplicate entries won't be a problem if you have set primary keys on your table.</p>\n\n<p>The jpeg question seems like a completely different issue (unless the data is in your csv)</p>\n" }, { "answer_id": 247199, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Looks like the answers you got covers at least the first two items. For the Jpeg question, take a look at <a href=\"https://stackoverflow.com/questions/8952/storing-a-file-in-a-database-as-opposed-to-the-file-system\" title=\"Storing a file in a database as opposed to the file system?\">Storing a file in a database as opposed to the file system?</a>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
Is it possible to import csv data into mysql and automatically create the column names, as in can I create just the table, or must I create the table names as well? Is it possible to check for duplicate entries upon importing? I have an identifier field, but dont know how to make it so it will not be imported twice. How would you import a jpeg file on a website into a field? Assume the website has been stored locally, and has the same filename as an identifer with ".jpeg" added on to the end.
As tante said you'll have to handle the table creation yourself, but as far as importing csv is concerned you should have a look at [LOAD DATA INFILE](http://dev.mysql.com/doc/refman/5.0/en/load-data.html) ``` LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name' [REPLACE | IGNORE] INTO TABLE tbl_name [CHARACTER SET charset_name] [{FIELDS | COLUMNS} [TERMINATED BY 'string'] [[OPTIONALLY] ENCLOSED BY 'char'] [ESCAPED BY 'char'] ] [LINES [STARTING BY 'string'] [TERMINATED BY 'string'] ] [IGNORE number LINES] [(col_name_or_user_var,...)] [SET col_name = expr,...] ``` Duplicate entries won't be a problem if you have set primary keys on your table. The jpeg question seems like a completely different issue (unless the data is in your csv)
246,697
<p>I need to create some windows service which will execute every N period of time.<br> The question is:<br> Which timer control should I use: <code>System.Timers.Timer</code> or <code>System.Threading.Timer</code> one? Does it influence on something? </p> <p>I am asking because I heard many evidences to non correct work of <code>System.Timers.Timer</code> in windows services.<br> Thank you.</p>
[ { "answer_id": 246706, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 3, "selected": false, "text": "<p>Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.</p>\n\n<p>Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.</p>\n\n<p>What problems have you seen so far?</p>\n" }, { "answer_id": 246719, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 8, "selected": true, "text": "<p>Both <a href=\"http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx\" rel=\"noreferrer\"><code>System.Timers.Timer</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx\" rel=\"noreferrer\"><code>System.Threading.Timer</code></a> will work for services.</p>\n\n<p>The timers you want to avoid are <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.timer.aspx\" rel=\"noreferrer\"><code>System.Web.UI.Timer</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.timer.aspx\" rel=\"noreferrer\"><code>System.Windows.Forms.Timer</code></a>, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.</p>\n\n<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx\" rel=\"noreferrer\"><code>System.Timers.Timer</code></a> like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):</p>\n\n<pre><code>using System;\nusing System.Timers;\n\npublic class Timer1\n{\n private static System.Timers.Timer aTimer;\n\n public static void Main()\n {\n // Normally, the timer is declared at the class level,\n // so that it stays in scope as long as it is needed.\n // If the timer is declared in a long-running method, \n // KeepAlive must be used to prevent the JIT compiler \n // from allowing aggressive garbage collection to occur \n // before the method ends. (See end of method.)\n //System.Timers.Timer aTimer;\n\n // Create a timer with a ten second interval.\n aTimer = new System.Timers.Timer(10000);\n\n // Hook up the Elapsed event for the timer.\n aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n\n // Set the Interval to 2 seconds (2000 milliseconds).\n aTimer.Interval = 2000;\n aTimer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit the program.\");\n Console.ReadLine();\n\n // If the timer is declared in a long-running method, use\n // KeepAlive to prevent garbage collection from occurring\n // before the method ends.\n //GC.KeepAlive(aTimer);\n }\n\n // Specify what you want to happen when the Elapsed event is \n // raised.\n private static void OnTimedEvent(object source, ElapsedEventArgs e)\n {\n Console.WriteLine(\"The Elapsed event was raised at {0}\", e.SignalTime);\n }\n}\n\n/* This code example produces output similar to the following:\n\nPress the Enter key to exit the program.\nThe Elapsed event was raised at 5/20/2007 8:42:27 PM\nThe Elapsed event was raised at 5/20/2007 8:42:29 PM\nThe Elapsed event was raised at 5/20/2007 8:42:31 PM\n...\n */\n</code></pre>\n\n<p>If you choose <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx\" rel=\"noreferrer\"><code>System.Threading.Timer</code></a>, you can use as follows:</p>\n\n<pre><code>using System;\nusing System.Threading;\n\nclass TimerExample\n{\n static void Main()\n {\n AutoResetEvent autoEvent = new AutoResetEvent(false);\n StatusChecker statusChecker = new StatusChecker(10);\n\n // Create the delegate that invokes methods for the timer.\n TimerCallback timerDelegate = \n new TimerCallback(statusChecker.CheckStatus);\n\n // Create a timer that signals the delegate to invoke \n // CheckStatus after one second, and every 1/4 second \n // thereafter.\n Console.WriteLine(\"{0} Creating timer.\\n\", \n DateTime.Now.ToString(\"h:mm:ss.fff\"));\n Timer stateTimer = \n new Timer(timerDelegate, autoEvent, 1000, 250);\n\n // When autoEvent signals, change the period to every \n // 1/2 second.\n autoEvent.WaitOne(5000, false);\n stateTimer.Change(0, 500);\n Console.WriteLine(\"\\nChanging period.\\n\");\n\n // When autoEvent signals the second time, dispose of \n // the timer.\n autoEvent.WaitOne(5000, false);\n stateTimer.Dispose();\n Console.WriteLine(\"\\nDestroying timer.\");\n }\n}\n\nclass StatusChecker\n{\n int invokeCount, maxCount;\n\n public StatusChecker(int count)\n {\n invokeCount = 0;\n maxCount = count;\n }\n\n // This method is called by the timer delegate.\n public void CheckStatus(Object stateInfo)\n {\n AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;\n Console.WriteLine(\"{0} Checking status {1,2}.\", \n DateTime.Now.ToString(\"h:mm:ss.fff\"), \n (++invokeCount).ToString());\n\n if(invokeCount == maxCount)\n {\n // Reset the counter and signal Main.\n invokeCount = 0;\n autoEvent.Set();\n }\n }\n}\n</code></pre>\n\n<p>Both examples comes from the MSDN pages.</p>\n" }, { "answer_id": 246839, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Don't use a service for this. Create a normal application and create a scheduled task to run it.</p>\n<p>This is the commonly held best practice. <a href=\"http://weblogs.asp.net/jgalloway/archive/2005/10/24/428303.aspx\" rel=\"noreferrer\">Jon Galloway agrees with me. Or maybe its the other way around.</a> Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.</p>\n<blockquote>\n<p><strong>&quot;If you're writing a Windows Service that runs a timer, you should re-evaluate your solution.&quot;</strong></p>\n<p>–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero</p>\n</blockquote>\n" }, { "answer_id": 247004, "author": "user32378", "author_id": 32378, "author_profile": "https://Stackoverflow.com/users/32378", "pm_score": 2, "selected": false, "text": "<p>I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:</p>\n\n<p>This will:</p>\n\n<ul>\n<li>Reduce plumbing code that replicates scheduler behaviour</li>\n<li>Provide greater flexibility in terms\nof scheduling behaviour (e.g. only\nrun on weekends) with all scheduling logic abstracted from application code</li>\n<li>Utilise the command line arguments\nfor parameters without having to\nsetup configuration values in config\nfiles etc</li>\n<li>Far easier to debug/test during development</li>\n<li>Allow a support user to execute by invoking\nthe console application directly\n(e.g. useful during support\nsituations)</li>\n</ul>\n" }, { "answer_id": 16566309, "author": "Nick N.", "author_id": 869033, "author_profile": "https://Stackoverflow.com/users/869033", "pm_score": 1, "selected": false, "text": "<p>As already stated both <code>System.Threading.Timer</code> and <code>System.Timers.Timer</code> will work. The big difference between the two is that <code>System.Threading.Timer</code> is a wrapper arround the other one. </p>\n\n<blockquote>\n <p><code>System.Threading.Timer</code> will have more exception handling while\n <code>System.Timers.Timer</code> will swallow all the exceptions.</p>\n</blockquote>\n\n<p>This gave me big problems in the past so I would always use 'System.Threading.Timer' and still handle your exceptions very well.</p>\n" }, { "answer_id": 31071436, "author": "MigaelM", "author_id": 5052740, "author_profile": "https://Stackoverflow.com/users/5052740", "pm_score": 0, "selected": false, "text": "<p>I know this thread is a little old but it came in handy for a specific scenario I had and I thought it worth while to note that there is another reason why <code>System.Threading.Timer</code> might be a good approach. \nWhen you have to periodically execute a Job that might take a long time and you want to ensure that the entire waiting period is used between jobs or if you don't want the job to run again before the previous job has finished in the case where the job takes longer than the timer period. \nYou could use the following:</p>\n\n<pre><code>using System;\nusing System.ServiceProcess;\nusing System.Threading;\n\n public partial class TimerExampleService : ServiceBase\n {\n private AutoResetEvent AutoEventInstance { get; set; }\n private StatusChecker StatusCheckerInstance { get; set; }\n private Timer StateTimer { get; set; }\n public int TimerInterval { get; set; }\n\n public CaseIndexingService()\n {\n InitializeComponent();\n TimerInterval = 300000;\n }\n\n protected override void OnStart(string[] args)\n {\n AutoEventInstance = new AutoResetEvent(false);\n StatusCheckerInstance = new StatusChecker();\n\n // Create the delegate that invokes methods for the timer.\n TimerCallback timerDelegate =\n new TimerCallback(StatusCheckerInstance.CheckStatus);\n\n // Create a timer that signals the delegate to invoke \n // 1.CheckStatus immediately, \n // 2.Wait until the job is finished,\n // 3.then wait 5 minutes before executing again. \n // 4.Repeat from point 2.\n Console.WriteLine(\"{0} Creating timer.\\n\",\n DateTime.Now.ToString(\"h:mm:ss.fff\"));\n //Start Immediately but don't run again.\n StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);\n while (StateTimer != null)\n {\n //Wait until the job is done\n AutoEventInstance.WaitOne();\n //Wait for 5 minutes before starting the job again.\n StateTimer.Change(TimerInterval, Timeout.Infinite);\n }\n //If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.\n }\n\n protected override void OnStop()\n {\n StateTimer.Dispose();\n }\n }\n\n class StatusChecker\n {\n\n public StatusChecker()\n {\n }\n\n // This method is called by the timer delegate.\n public void CheckStatus(Object stateInfo)\n {\n AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;\n Console.WriteLine(\"{0} Start Checking status.\",\n DateTime.Now.ToString(\"h:mm:ss.fff\"));\n //This job takes time to run. For example purposes, I put a delay in here.\n int milliseconds = 5000;\n Thread.Sleep(milliseconds);\n //Job is now done running and the timer can now be reset to wait for the next interval\n Console.WriteLine(\"{0} Done Checking status.\",\n DateTime.Now.ToString(\"h:mm:ss.fff\"));\n autoEvent.Set();\n }\n }\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to create some windows service which will execute every N period of time. The question is: Which timer control should I use: `System.Timers.Timer` or `System.Threading.Timer` one? Does it influence on something? I am asking because I heard many evidences to non correct work of `System.Timers.Timer` in windows services. Thank you.
Both [`System.Timers.Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) and [`System.Threading.Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) will work for services. The timers you want to avoid are [`System.Web.UI.Timer`](http://msdn.microsoft.com/en-us/library/system.web.ui.timer.aspx) and [`System.Windows.Forms.Timer`](http://msdn.microsoft.com/en-us/library/system.web.ui.timer.aspx), which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building. Use [`System.Timers.Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer): ``` using System; using System.Timers; public class Timer1 { private static System.Timers.Timer aTimer; public static void Main() { // Normally, the timer is declared at the class level, // so that it stays in scope as long as it is needed. // If the timer is declared in a long-running method, // KeepAlive must be used to prevent the JIT compiler // from allowing aggressive garbage collection to occur // before the method ends. (See end of method.) //System.Timers.Timer aTimer; // Create a timer with a ten second interval. aTimer = new System.Timers.Timer(10000); // Hook up the Elapsed event for the timer. aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 2 seconds (2000 milliseconds). aTimer.Interval = 2000; aTimer.Enabled = true; Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); // If the timer is declared in a long-running method, use // KeepAlive to prevent garbage collection from occurring // before the method ends. //GC.KeepAlive(aTimer); } // Specify what you want to happen when the Elapsed event is // raised. private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); } } /* This code example produces output similar to the following: Press the Enter key to exit the program. The Elapsed event was raised at 5/20/2007 8:42:27 PM The Elapsed event was raised at 5/20/2007 8:42:29 PM The Elapsed event was raised at 5/20/2007 8:42:31 PM ... */ ``` If you choose [`System.Threading.Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx), you can use as follows: ``` using System; using System.Threading; class TimerExample { static void Main() { AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(10); // Create the delegate that invokes methods for the timer. TimerCallback timerDelegate = new TimerCallback(statusChecker.CheckStatus); // Create a timer that signals the delegate to invoke // CheckStatus after one second, and every 1/4 second // thereafter. Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250); // When autoEvent signals, change the period to every // 1/2 second. autoEvent.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging period.\n"); // When autoEvent signals the second time, dispose of // the timer. autoEvent.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying timer."); } } class StatusChecker { int invokeCount, maxCount; public StatusChecker(int count) { invokeCount = 0; maxCount = count; } // This method is called by the timer delegate. public void CheckStatus(Object stateInfo) { AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; Console.WriteLine("{0} Checking status {1,2}.", DateTime.Now.ToString("h:mm:ss.fff"), (++invokeCount).ToString()); if(invokeCount == maxCount) { // Reset the counter and signal Main. invokeCount = 0; autoEvent.Set(); } } } ``` Both examples comes from the MSDN pages.
246,701
<p>Why do database guys go on about normalisation? </p> <p>What is it? How does it help? </p> <p>Does it apply to anything outside of databases? </p>
[ { "answer_id": 246722, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 4, "selected": false, "text": "<p>Most importantly it serves to remove duplication from the database records.\nFor example if you have more than one place (tables) where the name of a person could come up you move the name to a separate table and reference it everywhere else. This way if you need to change the person name later you only have to change it in one place.</p>\n\n<p>It is crucial for proper database design and in theory you should use it as much as possible to keep your data integrity. However when retrieving information from many tables you're losing some performance and that's why sometimes you could see denormalised database tables (also called flattened) used in performance critical applications.</p>\n\n<p>My advise is to start with good degree of normalisation and only do de-normalisation when really needed </p>\n\n<p>P.S. also check this article: <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Database_normalization</a> to read more on the subject and about so-called <em>normal forms</em></p>\n" }, { "answer_id": 246727, "author": "Nenad Dobrilovic", "author_id": 22062, "author_profile": "https://Stackoverflow.com/users/22062", "pm_score": 2, "selected": false, "text": "<p>Normalization is one of the basic concepts. It means that two things do not influence on each other.</p>\n\n<p>In databases specifically means that two (or more) tables do not contain the same data, i.e. do not have any redundancy.</p>\n\n<p>On the first sight that is really good because your chances to make some synchronization problems are close to zero, you always knows where your data is, etc. But, probably, your number of tables will grow and you will have problems to cross the data and to get some summary results.</p>\n\n<p>So, at the end you will finish with database design that is not pure normalized, with some redundancy (it will be in some of the possible levels of normalization).</p>\n" }, { "answer_id": 246745, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 3, "selected": false, "text": "<p>Normalization a procedure used to eliminate redundancy and functional dependencies between columns in a table. </p>\n\n<p>There exist several normal forms, generally indicated by a number. A higher number means fewer redundancies and dependencies. Any SQL table is in 1NF (first normal form, pretty much by definition) Normalizing means changing the schema (often partitioning the tables) in a reversible way, giving a model which is functionally identical, except with less redundancy and dependencies.</p>\n\n<p>Redundancy and dependency of data is undesirable because it can lead to inconsisencies when modifying the data. </p>\n" }, { "answer_id": 246746, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 3, "selected": false, "text": "<p>It is intended to reduce redundancy of data.</p>\n\n<p>For a more formal discussion, see the Wikipedia <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Database_normalization</a></p>\n\n<p>I'll give a somewhat simplistic example.</p>\n\n<p>Assume an organization's database that usually contains family members</p>\n\n<pre><code>id, name, address\n214 Mr. Chris 123 Main St.\n317 Mrs. Chris 123 Main St.\n</code></pre>\n\n<p>could be normalized as</p>\n\n<pre><code>id name familyID\n214 Mr. Chris 27\n317 Mrs. Chris 27\n</code></pre>\n\n<p>and a family table</p>\n\n<pre><code>ID, address\n27 123 Main St.\n</code></pre>\n\n<p>Near-Complete normalization (BCNF) is usually not used in production, but is an intermediate step. Once you've put the database in BCNF, the next step is usually to <strong>De-normalize</strong> it in a logical way to speed up queries and reduce the complexity of certain common inserts. However, you can't do this well without properly normalizing it first.</p>\n\n<p>The idea being that the redundant information is reduced to a single entry. This is particularly useful in fields like addresses, where Mr. Chris submits his address as Unit-7 123 Main St. and Mrs. Chris lists Suite-7 123 Main Street, which would show up in the original table as two distinct addresses. </p>\n\n<p>Typically, the technique used is to find repeated elements, and isolate those fields into another table with unique ids and to replace the repeated elements with a primary key referencing the new table. </p>\n" }, { "answer_id": 246751, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 9, "selected": true, "text": "<p>Normalization is basically to design a database schema such that duplicate and redundant data is avoided. If the same information is repeated in multiple places in the database, there is the risk that it is updated in one place but not the other, leading to data corruption.</p>\n<p>There is a number of normalization levels from 1. normal form through 5. normal form. Each normal form describes how to get rid of some specific problem.</p>\n<p>First normal form (1NF) is special because it is not about redundancy. 1NF disallows nested tables, more specifically columns which allows tables as values. Nested tables are not supported by SQL in the first place, so most normal relational databases will be in 1NF by default. So we can ignore 1NF for the rest of the discussions.</p>\n<p>The normal forms 2NF to 5NF all concerns scenarios where the same information is represented multiple times in the same table.</p>\n<p>For example consider a database of moons and planets:</p>\n<pre><code>Moon(PK) | Planet | Planet kind\n------------------------------\nPhobos | Mars | Rock\nDaimos | Mars | Rock\nIo | Jupiter | Gas\nEuropa | Jupiter | Gas\nGanymede | Jupiter | Gas\n</code></pre>\n<p>The redundancy is obvious: The fact that Jupiter is a gas planet is repeated three times, one for each moon. This is a waste of space, but much more seriously this schema makes <em>inconsistent</em> information possible:</p>\n<pre><code>Moon(PK) | Planet | Planet kind\n------------------------------\nPhobos | Mars | Rock\nDeimos | Mars | Rock\nIo | Jupiter | Gas\nEuropa | Jupiter | Rock &lt;-- Oh no!\nGanymede | Jupiter | Gas\n</code></pre>\n<p>A query can now give inconsistent results which can have disastrous consequences.</p>\n<p>(Of course a database cannot protect against <em>wrong</em> information being entered. But it can protect against <em>inconsistent</em> information, which is just as serious a problem.)</p>\n<p>The normalized design would split the table into two tables:</p>\n<pre><code>Moon(PK) | Planet(FK) Planet(PK) | Planet kind\n--------------------- ------------------------\nPhobos | Mars Mars | Rock\nDeimos | Mars Jupiter | Gas\nIo | Jupiter \nEuropa | Jupiter \nGanymede | Jupiter \n</code></pre>\n<p>Now no fact is repeated multiple times, so there is no possibility of inconsistent data. (It may look like there still is some repetition since the planet names are repeated, but repeating primary key values as foreign keys does not violate normalization since it does not introduce a risk of inconsistent data.)</p>\n<p><strong>Rule of thumb</strong>\nIf the same information can be represented with fewer individual cell values, not counting foreign keys, then the table should be normalized by splitting it into more tables. For example the first table has 12 individual values, while the two tables only have 9 individual (non-FK) values. This means we eliminate 3 redundant values.</p>\n<p>We know the same information is still there, since we can write a <code>join</code> query which return the same data as the original un-normalized table.</p>\n<p><strong>How do I avoid such problems?</strong>\nNormalization problems are easily avoided by giving a bit of though to the conceptual model, for example by drawing an entity-relationship diagram. Planets and moons have a one-to-many relationship which means they should be represented in two different tables with a foreign key-association. Normalization issues happen when multiple entities with a one-to-many or many-to-many relationship are represented in the same table row.</p>\n<p><strong>Is normalization it important?</strong> Yes, it is <em>very</em> important. By having a database with normalization errors, you open the risk of getting invalid or corrupt data into the database. Since data &quot;lives forever&quot; it is very hard to get rid of corrupt data when first it has entered the database.</p>\n<p>But I don't really think it is important to distinguish between the different normal forms from 2NF to 5NF. It is typically pretty obvious when a schema contains redundancies - whether it is 3NF or 5NF which is violated is less important as long as the problem is fixed.</p>\n<p>(There are also some additional normal forms like DKNF and 6NF which are only relevant for special purpose systems like data-warehouses.)</p>\n<p><strong>Don't be scared of normalization</strong>. The official technical definitions of the normalization levels are quite obtuse. It makes it sound like normalization is a complicated mathematical process. However, normalization is basically just the common sense, and you will find that if you design a database schema using common sense it will typically be fully normalized.</p>\n<p>There are a number of misconceptions around normalization:</p>\n<ul>\n<li><p>some believe that normalized databases are slower, and the denormalization improves performance. This is only true in very special cases however. Typically a normalized database is also the fastest.</p>\n</li>\n<li><p>sometimes normalization is described as a gradual design process and you have to decide &quot;when to stop&quot;. But actually the normalization levels just describe different specific problems. The problem solved by normal forms above 3rd NF are pretty rare problems in the first place, so chances are that your schema is already in 5NF.</p>\n</li>\n</ul>\n<p><strong>Does it apply to anything outside of databases?</strong> Not directly, no. The principles of normalization is quite specific for relational databases. However the general underlying theme - that you shouldn't have duplicate data if the different instances can get out of sync - can be applied broadly. This is basically the <a href=\"http://www.artima.com/intv/dry.html\" rel=\"noreferrer\">DRY principle</a>.</p>\n" }, { "answer_id": 253445, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "<p>Quoting CJ Date: Theory IS practical.</p>\n\n<p>Departures from normalization will result in certain anomalies in your database.</p>\n\n<p>Departures from First Normal Form will cause access anomalies, meaning that you have to decompose and scan individual values in order to find what you are looking for. For example, if one of the values is the string \"Ford, Cadillac\" as given by an earlier response, and you are looking for all the ocurrences of \"Ford\", you are going to have to break open the string and look at the substrings. This, to some extent, defeats the purpose of storing the data in a relational database.</p>\n\n<p>The definition of First Normal Form has changed since 1970, but those differences need not concern you for now. If you design your SQL tables using the relational data model, your tables will automatically be in 1NF.</p>\n\n<p>Departures from Second Normal Form and beyond will cause update anomalies, because the same fact is stored in more than one place. These problems make it impossible to store some facts without storing other facts that may not exist, and therefore have to be invented. Or when the facts change, you may have to locate all the plces where a fact is stored and update all those places, lest you end up with a database that contradicts itself. And, when you go to delete a row from the database, you may find that if you do, you are deleting the only place where a fact that is still needed is stored. </p>\n\n<p>These are logical problems, not performance problems or space problems. Sometimes you can get around these update anomalies by careful programming. Sometimes (often) it's better to prevent the problems in the first place by adhering to normal forms.</p>\n\n<p>Notwithstanding the value in what's already been said, it should be mentioned that normalization is a bottom up approach, not a top down approach. If you follow certain methodologies in your analysis of the data, and in your intial design, you can be guaranteed that the design will conform to 3NF at the very least. In many cases, the design will be fully normalized.</p>\n\n<p>Where you may really want to apply the concepts taught under normalization is when you are given legacy data, out of a legacy database or out of files made up of records, and the data was designed in complete ignorance of normal forms and the consequences of departing from them. In these cases you may need to discover the departures from normalization, and correct the design.</p>\n\n<p>Warning: normalization is often taught with religious overtones, as if every departure from full normalization is a sin, an offense against Codd. (little pun there). Don't buy that. When you really, really learn database design, you'll not only know how to follow the rules, but also know when it's safe to break them.</p>\n" }, { "answer_id": 31643716, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>What is Normalization? </p>\n</blockquote>\n\n<p>Normalization is a step wise formal process that allows us to decompose database tables in such a way that both <strong>data redundancy</strong> and <a href=\"http://www.mahipalreddy.com/dbdesign/dbqa.htm#update\" rel=\"nofollow noreferrer\"><strong>update anomalies</strong></a> are minimized. </p>\n\n<p><strong>Normalization Process</strong><br>\n<a href=\"https://i.stack.imgur.com/gMLRj.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gMLRj.jpg\" alt=\"enter image description here\"></a>\n<a href=\"http://www.mahipalreddy.com/dbdesign/dbqa.htm#update\" rel=\"nofollow noreferrer\">Courtesy</a> </p>\n\n<p><strong>First normal form</strong> if and only if the domain of each attribute contains only atomic values (an atomic value is a value that cannot be divided), and the value of each attribute contains only a single value from that domain(example:- domain for the gender column is: \"M\", \"F\". ). </p>\n\n<p><strong>First normal form enforces these criteria:</strong> </p>\n\n<ul>\n<li>Eliminate repeating groups in individual tables. </li>\n<li>Create a separate table for each set of related data. </li>\n<li>Identify each set of related data with a primary key </li>\n</ul>\n\n<p><strong>Second normal form</strong> = 1NF + no partial dependencies i.e. All non-key attributes are fully functional dependent on the primary key.</p>\n\n<p><strong>Third normal form</strong> = 2NF + no transitive dependencies i.e. All non-key attributes are fully functional dependent DIRECTLY only on the primary key.</p>\n\n<p><strong>Boyce–Codd normal form</strong> (or BCNF or 3.5NF) is a slightly stronger version of the third normal form (3NF). </p>\n\n<p>Note:- Second, Third, and Boyce–Codd normal forms are concerned with functional dependencies.\n<a href=\"http://www.1keydata.com/database-normalization\" rel=\"nofollow noreferrer\">Examples</a></p>\n\n<p><strong>Fourth normal form</strong> = 3NF + remove Multivalued dependencies</p>\n\n<p><strong>Fifth normal form</strong> = 4NF + remove join dependencies</p>\n" }, { "answer_id": 61332101, "author": "Arun", "author_id": 9610893, "author_profile": "https://Stackoverflow.com/users/9610893", "pm_score": 2, "selected": false, "text": "<p><em>As Martin Kleppman says in his book Designing Data Intensive Applications:</em></p>\n\n<p>Literature on the relational model distinguishes several different normal forms, but the distinctions are of little practical interest. As a rule of thumb, if you’re duplicating values that could be stored in just one place, the schema is not normalized.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
Why do database guys go on about normalisation? What is it? How does it help? Does it apply to anything outside of databases?
Normalization is basically to design a database schema such that duplicate and redundant data is avoided. If the same information is repeated in multiple places in the database, there is the risk that it is updated in one place but not the other, leading to data corruption. There is a number of normalization levels from 1. normal form through 5. normal form. Each normal form describes how to get rid of some specific problem. First normal form (1NF) is special because it is not about redundancy. 1NF disallows nested tables, more specifically columns which allows tables as values. Nested tables are not supported by SQL in the first place, so most normal relational databases will be in 1NF by default. So we can ignore 1NF for the rest of the discussions. The normal forms 2NF to 5NF all concerns scenarios where the same information is represented multiple times in the same table. For example consider a database of moons and planets: ``` Moon(PK) | Planet | Planet kind ------------------------------ Phobos | Mars | Rock Daimos | Mars | Rock Io | Jupiter | Gas Europa | Jupiter | Gas Ganymede | Jupiter | Gas ``` The redundancy is obvious: The fact that Jupiter is a gas planet is repeated three times, one for each moon. This is a waste of space, but much more seriously this schema makes *inconsistent* information possible: ``` Moon(PK) | Planet | Planet kind ------------------------------ Phobos | Mars | Rock Deimos | Mars | Rock Io | Jupiter | Gas Europa | Jupiter | Rock <-- Oh no! Ganymede | Jupiter | Gas ``` A query can now give inconsistent results which can have disastrous consequences. (Of course a database cannot protect against *wrong* information being entered. But it can protect against *inconsistent* information, which is just as serious a problem.) The normalized design would split the table into two tables: ``` Moon(PK) | Planet(FK) Planet(PK) | Planet kind --------------------- ------------------------ Phobos | Mars Mars | Rock Deimos | Mars Jupiter | Gas Io | Jupiter Europa | Jupiter Ganymede | Jupiter ``` Now no fact is repeated multiple times, so there is no possibility of inconsistent data. (It may look like there still is some repetition since the planet names are repeated, but repeating primary key values as foreign keys does not violate normalization since it does not introduce a risk of inconsistent data.) **Rule of thumb** If the same information can be represented with fewer individual cell values, not counting foreign keys, then the table should be normalized by splitting it into more tables. For example the first table has 12 individual values, while the two tables only have 9 individual (non-FK) values. This means we eliminate 3 redundant values. We know the same information is still there, since we can write a `join` query which return the same data as the original un-normalized table. **How do I avoid such problems?** Normalization problems are easily avoided by giving a bit of though to the conceptual model, for example by drawing an entity-relationship diagram. Planets and moons have a one-to-many relationship which means they should be represented in two different tables with a foreign key-association. Normalization issues happen when multiple entities with a one-to-many or many-to-many relationship are represented in the same table row. **Is normalization it important?** Yes, it is *very* important. By having a database with normalization errors, you open the risk of getting invalid or corrupt data into the database. Since data "lives forever" it is very hard to get rid of corrupt data when first it has entered the database. But I don't really think it is important to distinguish between the different normal forms from 2NF to 5NF. It is typically pretty obvious when a schema contains redundancies - whether it is 3NF or 5NF which is violated is less important as long as the problem is fixed. (There are also some additional normal forms like DKNF and 6NF which are only relevant for special purpose systems like data-warehouses.) **Don't be scared of normalization**. The official technical definitions of the normalization levels are quite obtuse. It makes it sound like normalization is a complicated mathematical process. However, normalization is basically just the common sense, and you will find that if you design a database schema using common sense it will typically be fully normalized. There are a number of misconceptions around normalization: * some believe that normalized databases are slower, and the denormalization improves performance. This is only true in very special cases however. Typically a normalized database is also the fastest. * sometimes normalization is described as a gradual design process and you have to decide "when to stop". But actually the normalization levels just describe different specific problems. The problem solved by normal forms above 3rd NF are pretty rare problems in the first place, so chances are that your schema is already in 5NF. **Does it apply to anything outside of databases?** Not directly, no. The principles of normalization is quite specific for relational databases. However the general underlying theme - that you shouldn't have duplicate data if the different instances can get out of sync - can be applied broadly. This is basically the [DRY principle](http://www.artima.com/intv/dry.html).
246,710
<p>How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.</p>
[ { "answer_id": 246737, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 2, "selected": false, "text": "<p>I would recommend you read the article <a href=\"http://msdn.microsoft.com/en-us/library/ms954629.aspx\" rel=\"nofollow noreferrer\">Exploring the Singleton Design Pattern</a> available on MSDN. It details the features of the framework which make the pattern simple to implement.</p>\n\n<p>As an aside, I'd check out the <a href=\"https://stackoverflow.com/search?q=singleton\">related reading on SO regarding Singletons</a>.</p>\n" }, { "answer_id": 246740, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "<p><code>Singleton != Global</code>. You seem to be looking for the keyword <code>static</code>.</p>\n" }, { "answer_id": 246750, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "<p>If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.</p>\n\n<pre><code>public static class GlobalSomething\n{\n public static int NumberOfSomething { get; set; }\n\n public static string MangleString( string someValue )\n {\n }\n}\n</code></pre>\n\n<p>Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.</p>\n" }, { "answer_id": 246786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Singletons only make sense if <strong>both</strong> of these conditions are true:</p>\n\n<ol>\n<li>The object must be <strong>global</strong></li>\n<li>There must only ever exist a <strong>single</strong> instance of the object</li>\n</ol>\n\n<p>Note that #2 does not mean that you'd <em>like</em> the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there <strong>must</strong> (as in, it's dangerous for this not to be true) only ever be a single instance.</p>\n\n<p>If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).\nIf you want only one instance, again, static is your friend. Also, simply instantiate only one object.</p>\n\n<p>Thats my opinion anyway.</p>\n" }, { "answer_id": 246829, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 2, "selected": false, "text": "<p>Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Thread-safe singleton implementation\n/// &lt;/summary&gt;\npublic sealed class MySingleton {\n\n private static volatile MySingleton instance = null;\n private static object syncRoot = new object();\n\n /// &lt;summary&gt;\n /// The instance of the singleton\n /// safe for multithreading\n /// &lt;/summary&gt;\n public static MySingleton Instance {\n get {\n // only create a new instance if one doesn't already exist.\n if (instance == null) {\n // use this lock to ensure that only one thread can access\n // this block of code at once.\n lock (syncRoot) {\n if (instance == null) {\n instance = new MySingleton();\n }\n }\n }\n // return instance where it was just created or already existed.\n return instance;\n }\n }\n\n\n /// &lt;summary&gt;\n /// This constructor must be kept private\n /// only access the singleton through the static Instance property\n /// &lt;/summary&gt;\n private MySingleton() {\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 247058, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 2, "selected": false, "text": "<p>Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as <a href=\"http://ninject.org/\" rel=\"nofollow noreferrer\">http://ninject.org/</a> or <a href=\"http://code.google.com/p/autofac/\" rel=\"nofollow noreferrer\">http://code.google.com/p/autofac/</a>.</p>\n\n<p>To register / consume a type configured as a singleton in autofac you would do something like the following:</p>\n\n<pre><code>var builder = new ContainerBuilder()\nbuilder.Register(typeof(Dependency)).SingletonScoped()\nbuilder.Register(c =&gt; new RequiresDependency(c.Resolve&lt;Dependency&gt;()))\n\nvar container = builder.Build();\n\nvar configured = container.Resolve&lt;RequiresDependency&gt;();\n</code></pre>\n\n<p>The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern. </p>\n" }, { "answer_id": 247079, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>You can really simplify a singleton implementation, this is what I use:</p>\n\n<pre><code> internal FooService() { } \n static FooService() { }\n\n private static readonly FooService _instance = new FooService();\n\n public static FooService Instance\n {\n get { return _instance; }\n }\n</code></pre>\n" }, { "answer_id": 247773, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 1, "selected": false, "text": "<p>What you are describing is merely static functions and constants, <em>not</em> a singleton. The singleton design pattern (which is very rarely needed) describes a class that <em>is</em> instantiated, but only once, automatically, when first used.</p>\n\n<p>It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.</p>\n\n<p>Static constants and functions are just that: code that doesn't need an instance at all.</p>\n\n<p>Ask yourself this: \"Will this class break if there is more than one instance of it?\" If the answer is no, you don't need a singleton.</p>\n" }, { "answer_id": 247947, "author": "Newtopian", "author_id": 25812, "author_profile": "https://Stackoverflow.com/users/25812", "pm_score": 1, "selected": false, "text": "<p>hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.</p>\n\n<p>If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.</p>\n\n<p>My 2 cent</p>\n" }, { "answer_id": 249057, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "<p>By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance</p>\n\n<pre><code>public class MySingleton \n{ \n private static MySingleton sngltn; \n private static object locker; \n private MySingleton() {} // Hides parameterless ctor, inhibits use of new() \n public static MySingleton GetMySingleton() \n { \n lock(locker)\n return sngltn?? new MySingleton();\n } \n}\n</code></pre>\n" }, { "answer_id": 249881, "author": "t3mujin", "author_id": 15968, "author_profile": "https://Stackoverflow.com/users/15968", "pm_score": 1, "selected": false, "text": "<p>Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.</p>\n" }, { "answer_id": 249939, "author": "Chris Brooks", "author_id": 27812, "author_profile": "https://Stackoverflow.com/users/27812", "pm_score": 2, "selected": false, "text": "<p>Hmm, this all seems a bit complex.</p>\n<p>Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.</p>\n<p>Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...</p>\n" }, { "answer_id": 373688, "author": "awaisj", "author_id": 46520, "author_profile": "https://Stackoverflow.com/users/46520", "pm_score": 2, "selected": false, "text": "<pre><code>public class Globals\n{\n private string setting1;\n private string setting2;\n\n #region Singleton Pattern Implementation\n\n private class SingletonCreator\n {\n internal static readonly Globals uniqueInstance = new Globals();\n\n static SingletonCreator()\n {\n }\n }\n\n /// &lt;summary&gt;Private Constructor for Singleton Pattern Implementaion&lt;/summary&gt;\n /// &lt;remarks&gt;can be used for initializing member variables&lt;/remarks&gt;\n private Globals()\n {\n\n }\n\n /// &lt;summary&gt;Returns a reference to the unique instance of Globals class&lt;/summary&gt;\n /// &lt;remarks&gt;used for getting a reference of Globals class&lt;/remarks&gt;\n public static Globals GetInstance\n {\n get { return SingletonCreator.uniqueInstance; }\n }\n\n #endregion\n\n public string Setting1\n {\n get { return this.setting1; }\n set { this.setting1 = value; }\n }\n\n public string Setting2\n {\n get { return this.setting2; }\n set { this.setting2 = value; }\n }\n\n public static int Constant1 \n {\n get { reutrn 100; }\n }\n\n public static int Constat2\n {\n get { return 200; }\n }\n\n public static DateTime SqlMinDate\n {\n get { return new DateTime(1900, 1, 1, 0, 0, 0); }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 384807, "author": "Scott P", "author_id": 33848, "author_profile": "https://Stackoverflow.com/users/33848", "pm_score": 2, "selected": false, "text": "<p>I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...</p>\n\n<pre><code> public class GenericSingleton&lt;T&gt; where T : new()\n {\n private static T ms_StaticInstance = new T();\n\n public T Build()\n {\n return ms_StaticInstance;\n }\n }\n\n...\n GenericSingleton&lt;SimpleType&gt; builder1 = new GenericSingleton&lt;SimpleType&gt;();\n SimpleType simple = builder1.Build();\n</code></pre>\n\n<p>This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.</p>\n" }, { "answer_id": 47729056, "author": "Sapnandu", "author_id": 746270, "author_profile": "https://Stackoverflow.com/users/746270", "pm_score": 0, "selected": false, "text": "<p>I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace TEClaim.Models\n{\npublic class LogedinUserDetails\n{\n public string UserID { get; set; }\n public string UserRole { get; set; }\n public string UserSupervisor { get; set; }\n public LogedinUserDetails()\n {\n\n }\n\n public static LogedinUserDetails Singleton()\n {\n LogedinUserDetails oSingleton;\n\n if (null == System.Web.HttpContext.Current.Session[\"LogedinUserDetails\"])\n { \n oSingleton = new LogedinUserDetails();\n System.Web.HttpContext.Current.Session[\"LogedinUserDetails\"] = oSingleton;\n }\n else\n { \n oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session[\"LogedinUserDetails\"];\n }\n\n //Return the single instance of this class that was stored in the session\n return oSingleton;\n }\n}\n}\n</code></pre>\n\n<p>Now you can set variable value for the above code in your application like this..</p>\n\n<pre><code>[HttpPost]\npublic ActionResult Login(FormCollection collection)\n{\n LogedinUserDetails User_Details = LogedinUserDetails.Singleton();\n User_Details.UserID = \"12\";\n User_Details.UserRole = \"SuperAdmin\";\n User_Details.UserSupervisor = \"815978\";\n return RedirectToAction(\"Dashboard\", \"Home\");\n}\n</code></pre>\n\n<p>And you can retrieve those value like this..</p>\n\n<pre><code>public ActionResult Dashboard()\n {\n LogedinUserDetails User_Details = LogedinUserDetails.Singleton();\n ViewData[\"UserID\"] = User_Details.UserID;\n ViewData[\"UserRole\"] = User_Details.UserRole;\n ViewData[\"UserSupervisor\"] = User_Details.UserSupervisor;\n\n return View();\n }\n</code></pre>\n" }, { "answer_id": 49667561, "author": "brajesh jaishwal", "author_id": 9456863, "author_profile": "https://Stackoverflow.com/users/9456863", "pm_score": 0, "selected": false, "text": "<p>In c# it could be (Thread safe as well as lazy initialization):</p>\n\n<pre><code>public sealed class MySingleton\n{\n static volatile Lazy&lt;MySingleton&gt; _instance = new Lazy&lt;MySingleton&gt;(() =&gt; new MySingleton(), true);\n public static MySingleton Instance =&gt; _instance.Value;\n private MySingleton() { }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22562/" ]
How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static. ``` public static class GlobalSomething { public static int NumberOfSomething { get; set; } public static string MangleString( string someValue ) { } } ``` Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
246,723
<p>Which functions are available within Delphi to play a sound-file?</p>
[ { "answer_id": 246756, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>A full tutorial is available at: <a href=\"http://sheepdogguides.com/dt3f.htm\" rel=\"nofollow noreferrer\">http://sheepdogguides.com/dt3f.htm</a></p>\n\n<p>It is a bit old. But it should work.</p>\n" }, { "answer_id": 246767, "author": "Name", "author_id": 32354, "author_profile": "https://Stackoverflow.com/users/32354", "pm_score": 3, "selected": false, "text": "<p>With the function sndPlaySound from the WIN32-API (Unit MMSystem):</p>\n\n<p>sndPlaySound('C:\\Windows\\Media\\Tada.wav', SND_ASYNC);</p>\n" }, { "answer_id": 246772, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 6, "selected": true, "text": "<p>Here's the fastest way:</p>\n\n<pre><code>uses MMSystem;\n\nprocedure TForm1.Button1Click(Sender: TObject);\nbegin\n sndPlaySound('C:\\Windows\\Media\\Tada.wav',\n SND_NODEFAULT Or SND_ASYNC Or SND_LOOP);\nend;\n\nprocedure TForm1.Button2Click(Sender: TObject);\nbegin\n sndPlaySound(nil, 0); // Stops the sound\nend;\n</code></pre>\n" }, { "answer_id": 250359, "author": "Name", "author_id": 32354, "author_profile": "https://Stackoverflow.com/users/32354", "pm_score": 2, "selected": false, "text": "<p>This page explains quite good how to use the function sndPlaySound and how to embed the wav-file as a resource:\n<a href=\"http://www.latiumsoftware.com/en/delphi/00024.php\" rel=\"nofollow noreferrer\">http://www.latiumsoftware.com/en/delphi/00024.php</a></p>\n" }, { "answer_id": 36690395, "author": "Server Overflow", "author_id": 46207, "author_profile": "https://Stackoverflow.com/users/46207", "pm_score": 3, "selected": false, "text": "<p>People keep quoting sndPlaySound, but this is quite obsolete, and it is available in Delphi for backward compatibility only.\n<strong>So, stop using it!</strong></p>\n<hr />\n<p>That being said, use:</p>\n<pre><code>procedure PlaySoundFile(FileName: string);\nbegin\n if FileExists(FileName)\n then PlaySound(pchar(FileName), 0, SND_ASYNC or SND_FILENAME); \n \n { Flags are:\n SND_SYNC =0 = Start playing, and wait for the sound to finish\n SND_ASYNC =1 = Start playing, and don't wait to return\n SND_LOOP =8 = Keep looping the sound until another sound is played }\nend;\n</code></pre>\n<hr />\n<p>To play a predefined Windows sound, use this:</p>\n<pre><code>procedure PlayWinSound(SystemSoundName: string);\nbegin\n Winapi.MMSystem.PlaySound(PChar(SystemSoundName), 0, SND_ASYNC);\nend;\n\n\nFor SystemSoundName use one of the constants below:\n\n SystemEXCLAMATION - Note)\n SystemHAND - Critical Stop)\n SystemQUESTION - Question)\n SystemSTART - Windows-Start)\n SystemEXIT - Windows-Shutdown)\n SystemASTERIX - Star)\n RESTOREUP - Enlarge)\n RESTOREDOWN - Shrink)\n MENUCOMMAND - Menu)\n MENUPOPUP - Pop-Up)\n MAXIMIZE - Maximize)\n MINIMIZE - Minimize)\n MAILBEEP - New Mail)\n OPEN - Open Application)\n CLOSE - Close Application)\n APPGPFAULT - Program Error)\n Asterisk - played when a popup alert is displayed, like a warning message.\n Calendar Reminder - played when a Calendar event is taking place.\n Critical Battery Alarm - played when your battery reaches its critical level.\n Critical Stop - played when a fatal error occurs.\n Default Beep - played for multiple reasons, depending on what you do. For example, it will play if you try to select a parent window before closing the active one.\n Desktop Mail Notif - played when you receive a message in your desktop email client.\n Device Connect - played when you connect a device to your computer. For example, when you insert a memory stick.\n Device Disconnect - played when you disconnect a device from your computer.\n Device Connect Failed - played when something happened with the device that you were trying to connect.\n Exclamation - played when you try to do something that is not supported by Windows.\n Instant Message Notif - played when you receive an instant message.\n Low Battery Alarm - played when the battery is running Low.\n Message Nudge - played when you receive a BUZZ in an instant message.\n New Fax Notification - played when you receive a fax via your fax-modem.\n New Mail Notification - played when you receive an email message.\n New Text Message Notif - played when you receive a text message.\n NFP Completion - played when the transfer of data via NFC between your Windows device and another device is completed.\n NFP Connection - played when your Windows device is connecting to another device via NFC.\n Notification - played when a default notification from a program or app is displayed.\n System Notification - played when a system notification is displayed.\n</code></pre>\n<p>All available constants are defined in the registry under the path HKEY_CURRENT_USER -&gt; AppEvents -&gt; Schemes -&gt; Apps -&gt; .Default.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32354/" ]
Which functions are available within Delphi to play a sound-file?
Here's the fastest way: ``` uses MMSystem; procedure TForm1.Button1Click(Sender: TObject); begin sndPlaySound('C:\Windows\Media\Tada.wav', SND_NODEFAULT Or SND_ASYNC Or SND_LOOP); end; procedure TForm1.Button2Click(Sender: TObject); begin sndPlaySound(nil, 0); // Stops the sound end; ```
246,725
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
[ { "answer_id": 246774, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 5, "selected": false, "text": "<p>I think django does something like <a href=\"https://docs.python.org/library/rlcompleter.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/rlcompleter.html</a></p>\n\n<p>If you want to have a really good interactive interpreter have a look at \n<a href=\"https://ipython.org/\" rel=\"nofollow noreferrer\">IPython</a>.</p>\n" }, { "answer_id": 246779, "author": "ashchristopher", "author_id": 22306, "author_profile": "https://Stackoverflow.com/users/22306", "pm_score": 9, "selected": true, "text": "<p>I may have found a way to do it.</p>\n\n<p>Create a file .pythonrc</p>\n\n<pre><code># ~/.pythonrc\n# enable syntax completion\ntry:\n import readline\nexcept ImportError:\n print(\"Module readline not available.\")\nelse:\n import rlcompleter\n readline.parse_and_bind(\"tab: complete\")\n</code></pre>\n\n<p>then in your .bashrc file, add</p>\n\n<pre><code>export PYTHONSTARTUP=~/.pythonrc\n</code></pre>\n\n<p>That seems to work.</p>\n" }, { "answer_id": 247513, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 5, "selected": false, "text": "<p>For the record, this is covered in the tutorial: <a href=\"http://docs.python.org/tutorial/interactive.html\" rel=\"noreferrer\">http://docs.python.org/tutorial/interactive.html</a></p>\n" }, { "answer_id": 32135426, "author": "alan_wang", "author_id": 3924168, "author_profile": "https://Stackoverflow.com/users/3924168", "pm_score": 4, "selected": false, "text": "<p>I use <a href=\"https://github.com/jonathanslenders/ptpython/\" rel=\"nofollow noreferrer\">ptpython</a> - it is a wonderful tool autocomplete shell cmd.</p>\n<p>Installing ptpython is very easy, use pip tool</p>\n<pre><code>pip install ptpython\n</code></pre>\n<p><strong>and for django shell, you should import the django env, like this</strong></p>\n<pre><code>import os\n\nos.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;testweb.settings&quot;)\n</code></pre>\n<p>Trust me, this is the best way for you!!!</p>\n" }, { "answer_id": 42987661, "author": "Michel Samia", "author_id": 611677, "author_profile": "https://Stackoverflow.com/users/611677", "pm_score": 2, "selected": false, "text": "<p>It looks like python3 has it out-of box!</p>\n" }, { "answer_id": 44874592, "author": "TrigonaMinima", "author_id": 2650427, "author_profile": "https://Stackoverflow.com/users/2650427", "pm_score": 1, "selected": false, "text": "<p>In Python3 this feature is enabled by default. My system didn't have the module <code>readline</code> installed. I am on Manjaro. I didn't face this tab completion issue on other linux distributions (elementary, ubuntu, mint).</p>\n\n<p>After <code>pip</code> installing the module, while importing, it was throwing the following error-</p>\n\n<p><code>ImportError: libncursesw.so.5: cannot open shared object file: No such file or directory\n</code></p>\n\n<p>To solve this, I ran-</p>\n\n<p><code>cd /usr/lib\nln -s libncursesw.so libncursesw.so.5\n</code></p>\n\n<p>This resolved the import error. And, it also brought the tab completion in the python repl without any creation/changes of <code>.pythonrc</code> and <code>.bashrc</code>.</p>\n" }, { "answer_id": 55012067, "author": "Mr.B", "author_id": 11156479, "author_profile": "https://Stackoverflow.com/users/11156479", "pm_score": 3, "selected": false, "text": "<p>Fix for Windows 10 shell:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>pip install pyreadline3 # previously, pyreadline but that package was abandoned\npip install ipython\n</code></pre>\n" }, { "answer_id": 60163620, "author": "Ruwinda Fernando", "author_id": 10165556, "author_profile": "https://Stackoverflow.com/users/10165556", "pm_score": 0, "selected": false, "text": "<p>Yes. It's built in to 3.6.</p>\n<pre><code>fernanr@gnuruwi ~ $ python3.6\nPython 3.6.3 (default, Apr 10 2019, 14:37:36)\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.\nDisplay all 318 possibilities? (y or n)\nos.CLD_CONTINUED os.O_RDONLY os.ST_NOEXEC os.environ os.getpid( os.readlink( os.spawnvpe(\nos.CLD_DUMPED os.O_RDWR os.ST_NOSUID os.environb os.getppid( os.readv( os.st\n</code></pre>\n" }, { "answer_id": 60163736, "author": "Ruwinda Fernando", "author_id": 10165556, "author_profile": "https://Stackoverflow.com/users/10165556", "pm_score": -1, "selected": false, "text": "<p>For older versions (2.x) above script works like charm :)</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>fernanr@crsatx4 ~ $ cat .bashrc | grep -i python\n#Tab completion for python shell\nexport PYTHONSTARTUP=~/.pythonrc\nfernanr@crsatx4 ~ $ . ~/.bashrc\nfernanr@crsatx4 ~ $ echo $?\n0\nfernanr@crsatx4 ~ $ python2\nPython 2.7.5 (default, Jun 11 2019, 14:33:56)\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.\nDisplay all 249 possibilities? (y or n)\nos.EX_CANTCREAT os.O_WRONLY \n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ]
When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc. ``` Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) ``` When just starting a python interpreter using `python`, it doesn't offer tab completion. Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?
I may have found a way to do it. Create a file .pythonrc ``` # ~/.pythonrc # enable syntax completion try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") ``` then in your .bashrc file, add ``` export PYTHONSTARTUP=~/.pythonrc ``` That seems to work.
246,762
<p>I have a Spring Interceptor which attempts to add an HTTP header in the postHandle() method.</p> <pre><code>public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object obj1, ModelAndView mv) throws Exception { response.setHeader("SomeHeaderSet", "set"); response.addHeader("SomeHeaderAdd", "added"); } } </code></pre> <p>However, neither header is added with either setHeader() or addHeader().</p> <p>Is this even valid to do in the interceptor? I figured it WOULD be, but it ain't workin.</p> <p>Regards, Dustin</p>
[ { "answer_id": 246851, "author": "Jonathan", "author_id": 28209, "author_profile": "https://Stackoverflow.com/users/28209", "pm_score": 1, "selected": false, "text": "<p>Have you tried setting the headers in the preHandle method? If that doesn't work try writing a Filter for the container and set the headers in there instead.</p>\n" }, { "answer_id": 247522, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 2, "selected": true, "text": "<p>Well, I figured it out...Kinda...</p>\n\n<p>Turns out, same issue with Jetty and Tomcat (figured MAYBE it was a container issue). So...</p>\n\n<p>Debugged to ensure that the response object contained the correct header value up until Spring returned back to the container. Result: The HttpServletResponse instance still had the correct header value.</p>\n\n<p>I found in my code I was invoking <code>response.setContentLength()</code> BEFORE I was doing anything with the headers. If I comment it out, everything works fine.</p>\n\n<p>So, the remaining mystery is, why does calling <code>response.setContentLength()</code> lock things down and not allow any headers to be modified? I didn't think the content body had anything to do with the other headers.</p>\n" }, { "answer_id": 3092988, "author": "Kristian", "author_id": 11429, "author_profile": "https://Stackoverflow.com/users/11429", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem, it works when I have the following in the web.xml (haven't figured out why)</p>\n\n<pre><code>&lt;filter&gt;\n &lt;filter-name&gt;etagFilter&lt;/filter-name&gt;\n &lt;filter-class&gt;org.springframework.web.filter.ShallowEtagHeaderFilter&lt;/filter-class&gt;\n&lt;/filter&gt;\n\n&lt;filter-mapping&gt;\n &lt;filter-name&gt;etagFilter&lt;/filter-name&gt;\n &lt;servlet-name&gt;myServlet&lt;/servlet-name&gt;\n&lt;/filter-mapping&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7888/" ]
I have a Spring Interceptor which attempts to add an HTTP header in the postHandle() method. ``` public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object obj1, ModelAndView mv) throws Exception { response.setHeader("SomeHeaderSet", "set"); response.addHeader("SomeHeaderAdd", "added"); } } ``` However, neither header is added with either setHeader() or addHeader(). Is this even valid to do in the interceptor? I figured it WOULD be, but it ain't workin. Regards, Dustin
Well, I figured it out...Kinda... Turns out, same issue with Jetty and Tomcat (figured MAYBE it was a container issue). So... Debugged to ensure that the response object contained the correct header value up until Spring returned back to the container. Result: The HttpServletResponse instance still had the correct header value. I found in my code I was invoking `response.setContentLength()` BEFORE I was doing anything with the headers. If I comment it out, everything works fine. So, the remaining mystery is, why does calling `response.setContentLength()` lock things down and not allow any headers to be modified? I didn't think the content body had anything to do with the other headers.
246,766
<p>I'm using Castle ActiveRecord, but this question applies to NHibernate, too, since a solution that works with NHibernate should work for ActiveRecord. Anyway, what I have is an underlying table structure like this:</p> <p>TableA -hasMany-> TableB</p> <p>I have corresponding objects EntityA and EntityB. EntityA has an IList of EntityB objects. This part works fine. Now, I want EntityB to have some kind of reference back to EntityA. I know I can use the BelongsTo attribute on EntityB to give it an actual reference back to the full EntityA type, like:</p> <pre><code>[BelongsTo("tableAid")] public EntityA Parent { get; set; } </code></pre> <p>But what I'd really like to do is:</p> <pre><code>[BelongsTo("tableAid")] public int ParentId { get; set; } </code></pre> <p>So, EntityB would store only the ID of the parent object, not a reference to the actual object. This is a trivial example, but I have good reasons for wanting to go with this approach. In the application I'm working on, we have pages that display specific EntityB-like objects, and we'd like for those pages to include links (as in hyperlinks) to the corresponding parent pages. We can do that by using the first approach above, but that requires that the entire EntityA object be loaded when all I really need is the ID. It's not a huge deal, but it just seems wasteful. I know I can use lazy-loading, but again, that seems more like a hack to me...</p> <p>I have tried flagging the foreign key with the [Property] attribute like so:</p> <pre><code>[Property] public int ParentId { get; set; } </code></pre> <p>The problem with this approach is that EntityB.ParentId remains null when you do a EntityA.SaveAndFlush() on a new object tree. The correct value is being written to the database, and I can force the value back into EntityB.ParentId by doing an EntityA.Refresh(), but again, that seems like a bit of a hack.</p>
[ { "answer_id": 246988, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "<p>Just this:</p>\n\n<pre><code>[Property] public int ParentId { get; set; }\n</code></pre>\n\n<p>...assuming <code>ParentId</code> is the actual column name.</p>\n\n<p>A couple of other comments. </p>\n\n<p>First, you should consider lazy loading many-to-one properties anyway. If you eagerly load them, you must be aware of possible cascades of eager loads, which can make a serious performance hit. To do this you must mark all public members of the lazily loaded class as virtual.</p>\n\n<p>Second, be aware that any time you have a one-to-many association with no corresponding relation from the child back to the parent, you must make the FK nullable in the database. That's because when NH creates new child items, it will insert it with the parent id null and then in a second step update it.</p>\n" }, { "answer_id": 816875, "author": "Jonathan Moffatt", "author_id": 45031, "author_profile": "https://Stackoverflow.com/users/45031", "pm_score": 3, "selected": true, "text": "<p>Lazy loading is exactly what you want - and it's not a hack either, it's a well tested and baked in part of NHIbernate and an important tool when performance tuning any substantial NHibernate app.</p>\n\n<p>If you were to mark your \"parent\" EntityA as lazy loaded, referring to EntityB.Parent.Id would not load EntityA at all (as behind the scenes NHIbernate has already loaded EntityA's id when loading EntityB) - thus letting you setup your links without incurring a performance penalty. </p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32353/" ]
I'm using Castle ActiveRecord, but this question applies to NHibernate, too, since a solution that works with NHibernate should work for ActiveRecord. Anyway, what I have is an underlying table structure like this: TableA -hasMany-> TableB I have corresponding objects EntityA and EntityB. EntityA has an IList of EntityB objects. This part works fine. Now, I want EntityB to have some kind of reference back to EntityA. I know I can use the BelongsTo attribute on EntityB to give it an actual reference back to the full EntityA type, like: ``` [BelongsTo("tableAid")] public EntityA Parent { get; set; } ``` But what I'd really like to do is: ``` [BelongsTo("tableAid")] public int ParentId { get; set; } ``` So, EntityB would store only the ID of the parent object, not a reference to the actual object. This is a trivial example, but I have good reasons for wanting to go with this approach. In the application I'm working on, we have pages that display specific EntityB-like objects, and we'd like for those pages to include links (as in hyperlinks) to the corresponding parent pages. We can do that by using the first approach above, but that requires that the entire EntityA object be loaded when all I really need is the ID. It's not a huge deal, but it just seems wasteful. I know I can use lazy-loading, but again, that seems more like a hack to me... I have tried flagging the foreign key with the [Property] attribute like so: ``` [Property] public int ParentId { get; set; } ``` The problem with this approach is that EntityB.ParentId remains null when you do a EntityA.SaveAndFlush() on a new object tree. The correct value is being written to the database, and I can force the value back into EntityB.ParentId by doing an EntityA.Refresh(), but again, that seems like a bit of a hack.
Lazy loading is exactly what you want - and it's not a hack either, it's a well tested and baked in part of NHIbernate and an important tool when performance tuning any substantial NHibernate app. If you were to mark your "parent" EntityA as lazy loaded, referring to EntityB.Parent.Id would not load EntityA at all (as behind the scenes NHIbernate has already loaded EntityA's id when loading EntityB) - thus letting you setup your links without incurring a performance penalty.
246,791
<p>I'm consuming a third-party resource (a .dll) in a web service, and my problem is, that invoking this resource (calling a method) is done asynchronous - I need to subscribe to an event, to get the answer for my request. How do I do that in a c# web service?</p> <p><strong>Update:</strong></p> <p>With regard to <a href="https://stackoverflow.com/questions/246791/invoking-asynchronous-call-in-a-c-web-service/246892#246892">Sunny's answer</a>:</p> <p>I don't want to make my web service asynchronous.</p>
[ { "answer_id": 246892, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/aa719796.aspx\" rel=\"nofollow noreferrer\">MSDN docs</a>:</p>\n\n<pre><code>using System;\nusing System.Web.Services;\n\n[WebService(Namespace=\"http://www.contoso.com/\")]\npublic class MyService : WebService {\n public RemoteService remoteService;\n public MyService() {\n // Create a new instance of proxy class for \n // the XML Web service to be called.\n remoteService = new RemoteService();\n }\n // Define the Begin method.\n [WebMethod]\n public IAsyncResult BeginGetAuthorRoyalties(String Author,\n AsyncCallback callback, object asyncState) {\n // Begin asynchronous communictation with a different XML Web\n // service.\n return remoteService.BeginReturnedStronglyTypedDS(Author,\n callback,asyncState);\n }\n // Define the End method.\n [WebMethod]\n public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult\n asyncResult) {\n // Return the asynchronous result from the other XML Web service.\n return remoteService.EndReturnedStronglyTypedDS(asyncResult);\n }\n}\n</code></pre>\n" }, { "answer_id": 247661, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 2, "selected": false, "text": "<p>Assuming your 3rd party component is using the asynchronous programming model pattern used throughout the .NET Framework you could do something like this</p>\n\n<pre><code> HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(\"http://www.stackoverflow.com\");\n IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);\n\n asyncResult.AsyncWaitHandle.WaitOne();\n\n using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))\n using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))\n {\n string responseText = responseStreamReader.ReadToEnd();\n }\n</code></pre>\n\n<p>Since you need your web service operation to block you should use the IAsyncResult.AsyncWaitHandle instead of the callback to block until the operation is complete.</p>\n" }, { "answer_id": 249532, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 2, "selected": true, "text": "<p>If the 3rd party component does not support the standard asynchronous programming model (i.e it does not use IAsyncResult), you can still achieve synchronization using AutoResetEvent or ManualResetEvent. To do this, declare a field of type AutoResetEvent in your web service class:</p>\n\n<pre><code>AutoResetEvent processingCompleteEvent = new AutoResetEvent();\n</code></pre>\n\n<p>Then wait for the event to be signaled after calling the 3rd party component </p>\n\n<pre><code>// call 3rd party component\nprocessingCompleteEvent.WaitOne()\n</code></pre>\n\n<p>And in the callback event handler signal the event to let the waiting thread continue execution:</p>\n\n<pre><code> processingCompleteEvent.Set()\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm consuming a third-party resource (a .dll) in a web service, and my problem is, that invoking this resource (calling a method) is done asynchronous - I need to subscribe to an event, to get the answer for my request. How do I do that in a c# web service? **Update:** With regard to [Sunny's answer](https://stackoverflow.com/questions/246791/invoking-asynchronous-call-in-a-c-web-service/246892#246892): I don't want to make my web service asynchronous.
If the 3rd party component does not support the standard asynchronous programming model (i.e it does not use IAsyncResult), you can still achieve synchronization using AutoResetEvent or ManualResetEvent. To do this, declare a field of type AutoResetEvent in your web service class: ``` AutoResetEvent processingCompleteEvent = new AutoResetEvent(); ``` Then wait for the event to be signaled after calling the 3rd party component ``` // call 3rd party component processingCompleteEvent.WaitOne() ``` And in the callback event handler signal the event to let the waiting thread continue execution: ``` processingCompleteEvent.Set() ```
246,806
<p>Is there any method? My computer is AMD64.</p> <pre><code>::std::string str; BOOL loadU(const wchar_t* lpszPathName, int flag = 0); </code></pre> <p>When I used: </p> <pre><code>loadU(&amp;str); </code></pre> <p>the VS2005 compiler says:</p> <pre><code>Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *' </code></pre> <p>How can I do it?</p>
[ { "answer_id": 246811, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 7, "selected": true, "text": "<p>If you have a std::wstring object, you can call <code>c_str()</code> on it to get a <code>wchar_t*</code>:</p>\n\n<pre><code>std::wstring name( L\"Steve Nash\" );\nconst wchar_t* szName = name.c_str();\n</code></pre>\n\n<p>Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in <a href=\"http://msdn.microsoft.com/en-us/library/dd319072%28v=vs.85%29.aspx\" rel=\"noreferrer\"><code>MultiByteToWideChar</code></a> routine. That will give you an <code>LPWSTR</code>, which is equivalent to <code>wchar_t*</code>.</p>\n" }, { "answer_id": 246818, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 7, "selected": false, "text": "<p>First convert it to std::wstring:</p>\n\n<pre><code>std::wstring widestr = std::wstring(str.begin(), str.end());\n</code></pre>\n\n<p>Then get the C string:</p>\n\n<pre><code>const wchar_t* widecstr = widestr.c_str();\n</code></pre>\n\n<p>This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.</p>\n" }, { "answer_id": 246852, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "<p>You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:</p>\n\n<pre><code>#include &lt;atlconv.h&gt;\n...\nstd::string str = \"Hello, world!\";\nCA2W pszWide(str.c_str());\nloadU(pszWide);\n</code></pre>\n\n<p>You can also specify a code page, so if your std::string contains UTF-8 chars you can use:</p>\n\n<pre><code>CA2W pszWide(str.c_str(), CP_UTF8);\n</code></pre>\n\n<p>Very useful but Windows only.</p>\n" }, { "answer_id": 2064486, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 3, "selected": false, "text": "<p>If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).</p>\n\n<ul>\n<li><p>mbs stand for \"Multi Bytes String\" and is basically the usual zero terminated C string.</p></li>\n<li><p>wcs stand for Wide Char String and is an array of wchar_t.</p></li>\n</ul>\n\n<p>For more background details on wide chars have a look at glibc documentation <a href=\"http://www.delorie.com/gnu/docs/glibc/libc_86.html\" rel=\"noreferrer\">here</a>. </p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25749/" ]
Is there any method? My computer is AMD64. ``` ::std::string str; BOOL loadU(const wchar_t* lpszPathName, int flag = 0); ``` When I used: ``` loadU(&str); ``` the VS2005 compiler says: ``` Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *' ``` How can I do it?
If you have a std::wstring object, you can call `c_str()` on it to get a `wchar_t*`: ``` std::wstring name( L"Steve Nash" ); const wchar_t* szName = name.c_str(); ``` Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in [`MultiByteToWideChar`](http://msdn.microsoft.com/en-us/library/dd319072%28v=vs.85%29.aspx) routine. That will give you an `LPWSTR`, which is equivalent to `wchar_t*`.
246,814
<p>I have a function called FindSpecificRowValue that takes in a datatable and returns the row number that contains a particular value. If that value isn't found, I want to indicate so to the calling function.</p> <p>Is the best approach to:</p> <ol> <li>Write a function that returns false if not found, true if found, and the found row number as a byref/output parameter, or</li> <li>Write a function that returns an int and pass back -999 if the row value isn't found, the row number if it is?</li> </ol>
[ { "answer_id": 246836, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "<p>I would choose option 2. Although I think I would just use -1 not -999.</p>\n\n<p>Richard Harrison is right that a named constant is better than a bare -1 or -999.</p>\n" }, { "answer_id": 246845, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 2, "selected": false, "text": "<p>functions that fail should throw exceptions. </p>\n\n<p>If failure is part of the expected flow then returning an out of band value is OK, except where you cannot pre-determine what an out-of-band value would be, in which case you have to throw an exception.</p>\n\n<p>If I had to choose between your options I would choose option 2, but use a constant rather than -999...</p>\n" }, { "answer_id": 246872, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": true, "text": "<p>Personally I would not do either with that method name.</p>\n\n<p>I would instead make two methods:</p>\n\n<pre><code>TryFindSpecificRow\nFindSpecificRow\n</code></pre>\n\n<p>This would follow the pattern of Int32.Parse/TryParse, and in C# they could look like this:</p>\n\n<pre><code>public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber)\n{\n if (row-can-be-found)\n {\n rowNumber = index-of-row-that-was-found;\n return true;\n }\n else\n {\n rowNumber = 0; // this value will not be used anyway\n return false;\n }\n}\n\npublic static Int32 FindSpecificRow(DataTable table)\n{\n Int32 rowNumber;\n\n\n if (TryFindSpecificRow(table, out rowNumber))\n return rowNumber;\n else\n throw new RowNotFoundException(String.Format(\"Row {0} was not found\", rowNumber));\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> Changed to be more appropriate to the question.</p>\n" }, { "answer_id": 246885, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 2, "selected": false, "text": "<p>You could also define return value as <a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx\" rel=\"nofollow noreferrer\">Nullable</a> and return Nothing if nothing found.</p>\n" }, { "answer_id": 246995, "author": "Silverfish", "author_id": 27415, "author_profile": "https://Stackoverflow.com/users/27415", "pm_score": 1, "selected": false, "text": "<p>I would go with 2, or some other variation where the return value indicates whether the value was found.</p>\n\n<p>It seems that the value of the row the function returns (or provides a reference to) already indicates whether the value was found. If a value was not found, then it seems to make no sense to provide a row number that doesn't contain the value, so the return value should be -1, or Null, or whatever other value is suitable for the particular language. Otherwise, the fact that a row number was returned indicates the value was found.</p>\n\n<p>Thus, there doesn't seem to be a need for a separate return value to indicate whether the value was found. However, type 1 might be appropriate if it fits with the idioms of the particular language, and the way function calls are performed in it.</p>\n" }, { "answer_id": 247037, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 1, "selected": false, "text": "<p>Go with 2) but return -1 (or a null reference if returning a reference to the row), that idiom is uses extensively (including by by .nets indexOf (item) functions), it's what I'd probably do.</p>\n\n<p>BTW -1 is more acceptable and widly used \"magic number\" than -999, thats the only reason why it's \"correct\" (quotes used there for a reason).</p>\n\n<p>However much of this has to do with what you expect. Should the item always be in there, but you just don't know where? In that case return the index normally, and throw an error/exception if it's not there.</p>\n" }, { "answer_id": 247237, "author": "Caveatrob", "author_id": 335036, "author_profile": "https://Stackoverflow.com/users/335036", "pm_score": 0, "selected": false, "text": "<p>In this case, the item might not be there, and that's an okay condition. It's an error trap for unselected values in a GridView that binds to a datatable.</p>\n" }, { "answer_id": 9831543, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>Another few possibilities not yet mentioned:</p>\n\n<pre>\n// Method 1: Supports covariance; can return default&lt;T&gt; on failure.\nT TryGetThing(ref bool success); \n\n// Method 2: Does not support covariance, but may allow cleaner code in some cases\n// where calling code would use some particular value in in case of failure.\nT TryGetThing(T DefaultValue);\n\n// Method 3: Does not support covariance, but may allow cleaner code in some cases\n// where calling code would use some particular value in case of failure, but should\n// not take the time to compute that value except when necessary.\nT TryGetThing(Func&lt;T&gt; AlternateGetMethod);\n\n// Method 4: Does support covariance; ErrorMethod can throw if that's what should\n// happen, or it can set some flag which is visible to the caller in some other way.\nT TryGetThing(Action ErrorMethod);\n</pre>\n\n<p>The first approach is the reverse of the method Microsoft developed in the days before support existed for covariant interfaces. The last is in some ways the most versatile, but is likely to require the creation of a couple of new GC object instances (e.g. a closure and a delegate) each time it's used.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335036/" ]
I have a function called FindSpecificRowValue that takes in a datatable and returns the row number that contains a particular value. If that value isn't found, I want to indicate so to the calling function. Is the best approach to: 1. Write a function that returns false if not found, true if found, and the found row number as a byref/output parameter, or 2. Write a function that returns an int and pass back -999 if the row value isn't found, the row number if it is?
Personally I would not do either with that method name. I would instead make two methods: ``` TryFindSpecificRow FindSpecificRow ``` This would follow the pattern of Int32.Parse/TryParse, and in C# they could look like this: ``` public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber) { if (row-can-be-found) { rowNumber = index-of-row-that-was-found; return true; } else { rowNumber = 0; // this value will not be used anyway return false; } } public static Int32 FindSpecificRow(DataTable table) { Int32 rowNumber; if (TryFindSpecificRow(table, out rowNumber)) return rowNumber; else throw new RowNotFoundException(String.Format("Row {0} was not found", rowNumber)); } ``` --- **Edit:** Changed to be more appropriate to the question.
246,817
<p>I want to automate SVN adds using NAnt. I want to add to SVN all new files in a given directory. The NAnt script will successfully execute the add command, however it displays the Tortoise SVN add dialog and this is not acceptable because it will execute on a build server running CruiseControl. The build server is running Windows Server 2003. </p> <p>Any ideas?</p> <pre><code>&lt;target name="addtest"&gt; &lt;exec program="c:\program files\tortoisesvn\bin\tortoiseproc.exe" commandline="/command:add * --force /path:C:\svn\test /notempfile /closeonend:1" basedir="C:\svn\test" failonerror="false"/&gt; &lt;/target&gt; </code></pre>
[ { "answer_id": 246833, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>don't use tortoise!</p>\n\n<p>just drop to command line svn.</p>\n\n<pre><code>c:\\&gt;svn add ...\n</code></pre>\n" }, { "answer_id": 246846, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 3, "selected": false, "text": "<p>Don't use tortoisesvn. Get a <a href=\"http://www.collab.net/downloads/subversion/\" rel=\"nofollow noreferrer\">commandline svn client</a>.</p>\n" }, { "answer_id": 247688, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 3, "selected": false, "text": "<p>Instead of using the exec task, there is a <a href=\"http://nantcontrib.sourceforge.net/release/0.85/help/tasks/svn.html\" rel=\"noreferrer\">svn task</a> which is provided by the <a href=\"http://nantcontrib.sourceforge.net/\" rel=\"noreferrer\">NAntContrib</a> set of tasks/tools. </p>\n\n<pre><code>&lt;svn command=\"add\" ... /&gt;\n</code></pre>\n\n<p>Of course doing this probably requires the command line version of subversion, so doing an exec on svn.exe is probably just as good.</p>\n\n<pre><code>&lt;exec program=\"svn.exe\" commandline=\"add...\" /&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to automate SVN adds using NAnt. I want to add to SVN all new files in a given directory. The NAnt script will successfully execute the add command, however it displays the Tortoise SVN add dialog and this is not acceptable because it will execute on a build server running CruiseControl. The build server is running Windows Server 2003. Any ideas? ``` <target name="addtest"> <exec program="c:\program files\tortoisesvn\bin\tortoiseproc.exe" commandline="/command:add * --force /path:C:\svn\test /notempfile /closeonend:1" basedir="C:\svn\test" failonerror="false"/> </target> ```
Don't use tortoisesvn. Get a [commandline svn client](http://www.collab.net/downloads/subversion/).
246,822
<p>I'm writing a password encryption routine. I've written the below app to illustrate my problem. About 20% of the time, this code works as expected. The rest of the time, the decryption throws a cryptographic exception - "The data is invalid".</p> <p>I believe the problem is in the encryption portion, because the decryption portion works the same every time. That is, if the encryption routine yields a value that the decryption routine can decrypt, it can always decrypt it. But if the encryption routine yields a value that chokes the decryption routine, it always chokes. So the decrypt routine is consistent; the encrypt routine is not.</p> <p>I suspect my use of Unicode encoding is incorrect, but I've tried others with the same result.</p> <p>What am I doing wrong?</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Security.Cryptography; namespace DataProtectionTest { public partial class Form1 : Form { private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 }; private string password; public Form1() { InitializeComponent(); } private void btnEncryptIt_Click(object sender, EventArgs e) { Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text); Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine); password = Encoding.Unicode.GetString(encryptedPw); } private void btnDecryptIt_Click(object sender, EventArgs e) { Byte[] pwBytes = Encoding.Unicode.GetBytes(password); try { Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine); string pw = Encoding.Unicode.GetString(decryptedPw); textBox2.Text = pw; } catch (CryptographicException ce) { textBox2.Text = ce.Message; } } } } </code></pre>
[ { "answer_id": 246878, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 0, "selected": false, "text": "<p>I strongly suspect that it's the call to Encoding.Unicode.GetString that's causing the problem. You need to ensure that the data passed to the Unprotect call is <strong>exactly</strong> the same as that returned from the Protect call. If you're encoding the binary data as Unicode text as an interim step then you can't guarantee this. Why do you need this step anyway - why not just store the byte[]?</p>\n" }, { "answer_id": 247019, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<p>The best solution is to <a href=\"https://stackoverflow.com/questions/246822/protecteddataprotect-intermittent-failure#247195\">convert the byte array to a base 64 string</a>.</p>\n\n<p>You can also use Latin-1 aka ISO-8859-1 aka codepage 28591 for this scenario, as it maps values in the range 0-255 unchanged. The following are interchangeable:</p>\n\n<pre><code>Encoding.GetEncoding(28591)\nEncoding.GetEncoding(\"Latin1\")\nEncoding.GetEncoding(\"iso-8859-1\")\n</code></pre>\n\n<p>With this encoding you will always be able to convert byte[] -> string -> byte[] without loss.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/111460/net-8-bit-encoding#111549\">this post</a> for a sample that illustrates the use of this encoding.</p>\n" }, { "answer_id": 247070, "author": "Eric", "author_id": 2610, "author_profile": "https://Stackoverflow.com/users/2610", "pm_score": 4, "selected": true, "text": "<p>On the advice of a colleague, I opted for Convert.ToBase64String. Works well. Corrected program below.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Security.Cryptography;\n\nnamespace DataProtectionTest\n{\n public partial class Form1 : Form\n {\n private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };\n private string password;\n public Form1()\n {\n InitializeComponent();\n }\n\n private void btnEncryptIt_Click(object sender, EventArgs e)\n {\n Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text);\n Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine);\n //password = Encoding.Unicode.GetString(encryptedPw); \n password = Convert.ToBase64String(encryptedPw);\n }\n\n private void btnDecryptIt_Click(object sender, EventArgs e)\n {\n //Byte[] pwBytes = Encoding.Unicode.GetBytes(password);\n Byte[] pwBytes = Convert.FromBase64String(password);\n try\n {\n Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine);\n string pw = Encoding.Unicode.GetString(decryptedPw);\n textBox2.Text = pw;\n }\n catch (CryptographicException ce)\n {\n textBox2.Text = ce.Message;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 247195, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 1, "selected": false, "text": "<p>The problem is the conversion to unicode and the end of the encryption method, Encoding.Unicode.GetString works only if the bytes you give it form a valid UTF-16 string.</p>\n\n<p>I suspect that sometimes the result of ProtectedData.Protect is not a valid UTF-16 string - so Encoding.Unicode.GetString drops bytes that not make sense out of the returned string resulting in a string that can't be converted back into the encrypted data.</p>\n" }, { "answer_id": 8682691, "author": "Dave Black", "author_id": 251267, "author_profile": "https://Stackoverflow.com/users/251267", "pm_score": 2, "selected": false, "text": "<p>You should never use any of the <code>System.Text.Encoding</code> classes for cipher text. You <em>will</em> experience intermittent errors. You should use Base64 encoding and the <code>System.Convert</code> class methods.</p>\n\n<ol>\n<li><p>To obtain an encrypted <code>string</code> from an encrypted <code>byte[]</code>, you should use:</p>\n\n<pre><code>Convert.ToBase64String(byte[] bytes)\n</code></pre></li>\n<li><p>To obtain a a raw <code>byte[]</code> from a <code>string</code> to be encrypted, you should use:</p>\n\n<pre><code>Convert.FromBase64String(string data)\n</code></pre></li>\n</ol>\n\n<p>For additional info, please refer to <a href=\"http://blogs.msdn.com/b/shawnfa/archive/2005/11/10/491431.aspx\" rel=\"nofollow noreferrer\">MS Security guru Shawn Fanning's post.</a> </p>\n" }, { "answer_id": 42580745, "author": "Vladimir Arustamian", "author_id": 3945778, "author_profile": "https://Stackoverflow.com/users/3945778", "pm_score": 1, "selected": false, "text": "<p>This class should help:</p>\n\n<pre><code>public static class StringEncryptor\n{\n private static readonly byte[] key = { 0x45, 0x4E, 0x3A, 0x8C, 0x89, 0x70, 0x37, 0x99, 0x58, 0x31, 0x24, 0x98, 0x3A, 0x87, 0x9B, 0x34 };\n\n public static string EncryptString(this string sourceString)\n {\n if (string.IsNullOrEmpty(sourceString))\n {\n return string.Empty;\n }\n\n var base64String = Base64Encode(sourceString);\n var protectedBytes = ProtectedData.Protect(Convert.FromBase64String(base64String), key, DataProtectionScope.CurrentUser);\n return Convert.ToBase64String(protectedBytes);\n }\n\n public static string DecryptString(this string sourceString)\n {\n if (string.IsNullOrEmpty(sourceString))\n {\n return string.Empty;\n }\n\n var unprotectedBytes = ProtectedData.Unprotect(Convert.FromBase64String(sourceString), key, DataProtectionScope.CurrentUser);\n var base64String = Convert.ToBase64String(unprotectedBytes);\n return Base64Decode(base64String);\n }\n\n private static string Base64Encode(string plainText)\n {\n var plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n return Convert.ToBase64String(plainTextBytes);\n }\n\n private static string Base64Decode(string base64EncodedData)\n {\n var base64EncodedBytes = Convert.FromBase64String(base64EncodedData);\n return Encoding.UTF8.GetString(base64EncodedBytes);\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2610/" ]
I'm writing a password encryption routine. I've written the below app to illustrate my problem. About 20% of the time, this code works as expected. The rest of the time, the decryption throws a cryptographic exception - "The data is invalid". I believe the problem is in the encryption portion, because the decryption portion works the same every time. That is, if the encryption routine yields a value that the decryption routine can decrypt, it can always decrypt it. But if the encryption routine yields a value that chokes the decryption routine, it always chokes. So the decrypt routine is consistent; the encrypt routine is not. I suspect my use of Unicode encoding is incorrect, but I've tried others with the same result. What am I doing wrong? ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Security.Cryptography; namespace DataProtectionTest { public partial class Form1 : Form { private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 }; private string password; public Form1() { InitializeComponent(); } private void btnEncryptIt_Click(object sender, EventArgs e) { Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text); Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine); password = Encoding.Unicode.GetString(encryptedPw); } private void btnDecryptIt_Click(object sender, EventArgs e) { Byte[] pwBytes = Encoding.Unicode.GetBytes(password); try { Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine); string pw = Encoding.Unicode.GetString(decryptedPw); textBox2.Text = pw; } catch (CryptographicException ce) { textBox2.Text = ce.Message; } } } } ```
On the advice of a colleague, I opted for Convert.ToBase64String. Works well. Corrected program below. ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Security.Cryptography; namespace DataProtectionTest { public partial class Form1 : Form { private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 }; private string password; public Form1() { InitializeComponent(); } private void btnEncryptIt_Click(object sender, EventArgs e) { Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text); Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine); //password = Encoding.Unicode.GetString(encryptedPw); password = Convert.ToBase64String(encryptedPw); } private void btnDecryptIt_Click(object sender, EventArgs e) { //Byte[] pwBytes = Encoding.Unicode.GetBytes(password); Byte[] pwBytes = Convert.FromBase64String(password); try { Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine); string pw = Encoding.Unicode.GetString(decryptedPw); textBox2.Text = pw; } catch (CryptographicException ce) { textBox2.Text = ce.Message; } } } } ```
246,841
<p>We may tag a question with multiple tags in StackOverflow website, I'm wondering how to find out the most related questions with common tags.</p> <p>Assume we have 100 questions in a database, each question has several tags. Let's say user is browsing a specific question, and we want to make the system to display the related questions on the page. The criteria for related question is they have most common tags.</p> <p>For example: Question 1 is tagged with AAA, BBB, CCC, DDD, EEE.</p> <p>Question 2 is top 1 related because it also has all those 5 tags. Question 3 is top 2 related because it has only 4 or 3 tags that Questio1 has. ......</p> <p>So my question is how to design the database and find out the questions that's related to Question 1 quickly. Thank you very much.</p>
[ { "answer_id": 246847, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>Not entirely sure what you mean, but <a href=\"https://stackoverflow.com/tags\">the Tags page</a> lists tags in order of popularity (as in amount tagged).</p>\n\n<p><strong>Edit:</strong> is this about SO or about your own application? If it is about your own app, remove the SO tag as it's kind of misleading.</p>\n\n<p><strong>Edit2:</strong> I'd say something like:</p>\n\n<pre><code>SELECT * FROM `questions` WHERE `tag` LIKE '%tagname%' OR (looped for each tag) LIMIT 5,0\n</code></pre>\n\n<p>Where 5 is the maximum results you want to return (for at least some optimisation). Probably not the best solution, but I could see it working. </p>\n\n<p>You might also want to try a <code>LIKE</code> match using the title.</p>\n" }, { "answer_id": 247041, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "<p>Perhaps something like:</p>\n\n<pre><code>select qt.question_id, count(*)\nfrom question_tags qt\nwhere qt.tag in\n( select qt2.tag\n from question_tags qt2\n where qt2.question_id = 123\n)\ngroup by qt.question_id\norder by 2 desc\n</code></pre>\n" }, { "answer_id": 247236, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 2, "selected": false, "text": "<p>If you can guarantee that there are not duplicate tags for a question, then you can do the following:</p>\n\n<pre><code>SELECT\n QT2.question_id,\n COUNT(*) AS cnt\nFROM\n Question_Tags QT1\nINNER JOIN Question_Tags QT2 ON QT2.tag = QT1.tag AND QT2.question_id &lt;&gt; QT1.question_id\nWHERE\n QT1.question_id = @question_id\nGROUP BY\n QT2.question_id\nORDER BY\n cnt DESC\n</code></pre>\n\n<p>If you can't guarantee uniqueness of tags within a question, then Tony Andrews' solution will work. His will work in any event, but you should compare performance on your system with this method if you can make the guarantee of uniqueness through constraints.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We may tag a question with multiple tags in StackOverflow website, I'm wondering how to find out the most related questions with common tags. Assume we have 100 questions in a database, each question has several tags. Let's say user is browsing a specific question, and we want to make the system to display the related questions on the page. The criteria for related question is they have most common tags. For example: Question 1 is tagged with AAA, BBB, CCC, DDD, EEE. Question 2 is top 1 related because it also has all those 5 tags. Question 3 is top 2 related because it has only 4 or 3 tags that Questio1 has. ...... So my question is how to design the database and find out the questions that's related to Question 1 quickly. Thank you very much.
Perhaps something like: ``` select qt.question_id, count(*) from question_tags qt where qt.tag in ( select qt2.tag from question_tags qt2 where qt2.question_id = 123 ) group by qt.question_id order by 2 desc ```
246,849
<p>we're currently planning a larger WPF LoB application and i wonder what others think being the best practice for storing lots of UI settings e.g.</p> <ul> <li>Expander States</li> <li>Menu orders</li> <li>Sizing Properties</li> <li>etc...</li> </ul> <p>i don't like the idea of having dozens of stored values using the delivered SettingsProvider (i.e. App.config file) although it can be used to store it in an embedded database using a custom SettingsProvider. being able to use some kind of databinding is also a concern. Has anyone had the same problems? </p> <p>What did you do to store lots of ui user settings?</p>
[ { "answer_id": 246860, "author": "DancesWithBamboo", "author_id": 1334, "author_profile": "https://Stackoverflow.com/users/1334", "pm_score": 1, "selected": false, "text": "<p>Seems to be losing popularity for some reason; but the registry has always been an appropriate place for these kinds of settings.</p>\n" }, { "answer_id": 246880, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 4, "selected": false, "text": "<p>We store the preferences file here:</p>\n\n<pre><code>Environment.SpecialFolder.ApplicationData\n</code></pre>\n\n<p>Store it as xml \"preferences\" file so it's not so hard to get to and change if it ever gets corrupted.</p>\n\n<p>So far this has worked much better than the registry for us, it's cleaner and easier to blow out if anything gets corrupted or needs to be reset. </p>\n" }, { "answer_id": 246889, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "<p>We store all in the <code>Isolation Storage</code> (we are running with ClickOnce). We have some object that we serialize (XmlSerializer).</p>\n" }, { "answer_id": 246896, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 1, "selected": false, "text": "<p>We use a custom SettingsProvider to store the config information in a table in the app's database. This is a good solution if you're already using a database.</p>\n" }, { "answer_id": 247675, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 1, "selected": false, "text": "<p>In the Programming WPF by Chris Sells &amp; Ian Griffiths it says</p>\n\n<p><em>The preferred setting mechanism for WPF application is the one provided by .NET and VS: the ApplicationSettingBase class from the System.Configuration namespace with the built-in designer.</em></p>\n" }, { "answer_id": 247839, "author": "decasteljau", "author_id": 12082, "author_profile": "https://Stackoverflow.com/users/12082", "pm_score": 3, "selected": false, "text": "<p>The quicker way to store UI settings is using the Properties.Settings.Default system. What can be nice with it is to use WPF binding to the value. <a href=\"http://blogs.microsoft.co.il/blogs/tamir/archive/2008/04/22/quick-wpf-tip-how-to-bind-to-wpf-application-resources-and-settings.aspx\" rel=\"nofollow noreferrer\">Example here</a>. Settings are automatically updated and loaded.</p>\n<pre><code>&lt;Window ...\n xmlns:p=&quot;clr-namespace:UserSettings.Properties&quot;\n Height=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}&quot; \n Width=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Width, Mode=TwoWay}&quot; \n Left=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Left, Mode=TwoWay}&quot; \n Top=&quot;{Binding Source={x:Static p:Settings.Default}, Path=Top, Mode=TwoWay}&quot;&gt;\n\n...\nprotected override void OnClosing(System.ComponentModel.CancelEventArgs e) \n{ \n Settings.Default.Save(); \n base.OnClosing(e); \n}\n</code></pre>\n<p>The problem with that is that it quickly becomes a mess if your application is large.</p>\n<p>Another solution (proposed by someone here) is to use the ApplicationData path to store your own preferences into XML. There you can build your own setting class and use the XML serializer to persist it. This approach enables you to do migration from versions to versions. While being more powerful, this method requires a bit more code.</p>\n" }, { "answer_id": 2227269, "author": "sean e", "author_id": 103912, "author_profile": "https://Stackoverflow.com/users/103912", "pm_score": 2, "selected": false, "text": "<p>Digging into aogan's answer and combining it with decasteljau's answer and the blog post he referenced, here is an example that fills in some gaps that weren't clear to me.</p>\n\n<p>The xaml file:</p>\n\n<pre><code>&lt;Window ...\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:p=\"clr-namespace:MyApp\"\n Height=\"{Binding Source={x:Static p:MyAppSettings.Default}, Path=MainWndHeight, Mode=TwoWay}\"\n Width=\"{Binding Source={x:Static p:MyAppSettings.Default}, Path=MainWndWidth, Mode=TwoWay}\"\n Left=\"{Binding Source={x:Static p:MyAppSettings.Default}, Path=MainWndLeft, Mode=TwoWay}\"\n Top=\"{Binding Source={x:Static p:MyAppSettings.Default}, Path=MainWndTop, Mode=TwoWay}\"\n ...\n</code></pre>\n\n<p>And the source file:</p>\n\n<pre><code>namespace MyApp\n{\n class MainWindow ....\n {\n ...\n\n protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n {\n MyAppSettings.Default.Save();\n base.OnClosing(e);\n }\n }\n\n public sealed class MyAppSettings : System.Configuration.ApplicationSettingsBase\n {\n private static MyAppSettings defaultInstance = ((MyAppSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new MyAppSettings())));\n public static MyAppSettings Default\n {\n get { return defaultInstance; }\n }\n\n [System.Configuration.UserScopedSettingAttribute()]\n [System.Configuration.DefaultSettingValueAttribute(\"540\")]\n public int MainWndHeight\n {\n get { return (int)this[\"MainWndHeight\"]; }\n set { this[\"MainWndHeight\"] = value; }\n }\n\n [System.Configuration.UserScopedSettingAttribute()]\n [System.Configuration.DefaultSettingValueAttribute(\"790\")]\n public int MainWndWidth\n {\n get { return (int)this[\"MainWndWidth\"]; }\n set { this[\"MainWndWidth\"] = value; }\n }\n\n [System.Configuration.UserScopedSettingAttribute()]\n [System.Configuration.DefaultSettingValueAttribute(\"300\")]\n public int MainWndTop\n {\n get { return (int)this[\"MainWndTop\"]; }\n set { this[\"MainWndTop\"] = value; }\n }\n\n [System.Configuration.UserScopedSettingAttribute()]\n [System.Configuration.DefaultSettingValueAttribute(\"300\")]\n public int MainWndLeft\n {\n get { return (int)this[\"MainWndLeft\"]; }\n set { this[\"MainWndLeft\"] = value; }\n }\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20227/" ]
we're currently planning a larger WPF LoB application and i wonder what others think being the best practice for storing lots of UI settings e.g. * Expander States * Menu orders * Sizing Properties * etc... i don't like the idea of having dozens of stored values using the delivered SettingsProvider (i.e. App.config file) although it can be used to store it in an embedded database using a custom SettingsProvider. being able to use some kind of databinding is also a concern. Has anyone had the same problems? What did you do to store lots of ui user settings?
We store the preferences file here: ``` Environment.SpecialFolder.ApplicationData ``` Store it as xml "preferences" file so it's not so hard to get to and change if it ever gets corrupted. So far this has worked much better than the registry for us, it's cleaner and easier to blow out if anything gets corrupted or needs to be reset.
246,859
<p>Could somebody give me a brief overview of the differences between HTTP 1.0 and HTTP 1.1? I've spent some time with both of the RFCs, but haven't been able to pull out a lot of difference between them. Wikipedia says this:</p> <blockquote> <p><strong>HTTP/1.1 (1997-1999)</strong></p> <p>Current version; persistent connections enabled by default and works well with proxies. Also supports request pipelining, allowing multiple requests to be sent at the same time, allowing the server to prepare for the workload and potentially transfer the requested resources more quickly to the client.</p> </blockquote> <p>But that doesn't mean a lot to me. I realize this is a somewhat complicated subject, so I'm not expecting a full answer, but can someone give me a brief overview of the differences at a bit lower level?<br /> By this I mean that I'm looking for the info I would need to know to implement either an HTTP server or application. I'm mostly looking for a nudge in the right direction so that I can figure it out on my own.</p>
[ { "answer_id": 246897, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 3, "selected": false, "text": "<p>One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).</p>\n\n<p>If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you <strong>should</strong> know the difference between <code>GET</code> and <code>POST</code> verbs at least.</p>\n\n<p>Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.</p>\n\n<p>If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.</p>\n" }, { "answer_id": 246953, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 4, "selected": false, "text": "<p>For trivial applications (e.g. sporadically retrieving a temperature value from a web-enabled thermometer) HTTP 1.0 is fine for both a client and a server. You can write a bare-bones socket-based HTTP 1.0 client or server in about 20 lines of code.</p>\n\n<p>For more complicated scenarios HTTP 1.1 is the way to go. Expect a 3 to 5-fold increase in code size for dealing with the intricacies of the more complex HTTP 1.1 protocol. The complexity mainly comes, because in HTTP 1.1 you will need to create, parse, and respond to various headers. You can shield your application from this complexity by having a client use an HTTP library, or server use a web application server.</p>\n" }, { "answer_id": 247026, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 10, "selected": true, "text": "<p><strong>Proxy support and the Host field:</strong></p>\n\n<p>HTTP 1.1 has a required Host header by spec.</p>\n\n<p>HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.</p>\n\n<p>Example:</p>\n\n<pre><code>GET / HTTP/1.1\nHost: www.blahblahblahblah.com\n</code></pre>\n\n<p>This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.</p>\n\n<p>So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants. </p>\n\n<p><strong>Persistent connections:</strong></p>\n\n<p>HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection. </p>\n\n<p>In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of <a href=\"http://en.wikipedia.org/wiki/Slow-start\" rel=\"noreferrer\">TCP Slow Start</a>.</p>\n\n<p><strong>OPTIONS method:</strong></p>\n\n<p>HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.</p>\n\n<p><strong>Caching:</strong></p>\n\n<p>HTTP 1.0 had support for caching via the header: If-Modified-Since.</p>\n\n<p>HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. \nIf 2 resources are the same, then they will have the same entity tags. </p>\n\n<p>HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers. </p>\n\n<p>There are also further additions relating to caching like the Cache-Control header. </p>\n\n<p><strong>100 Continue status:</strong></p>\n\n<p>There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body. </p>\n\n<p><strong>Much more:</strong></p>\n\n<ul>\n<li>Digest authentication and proxy authentication</li>\n<li>Extra new status codes</li>\n<li>Chunked transfer encoding</li>\n<li>Connection header</li>\n<li>Enhanced compression support</li>\n<li>Much much more. </li>\n</ul>\n" }, { "answer_id": 247029, "author": "Troy J. Farrell", "author_id": 26244, "author_profile": "https://Stackoverflow.com/users/26244", "pm_score": 3, "selected": false, "text": "<p>A key compatibility issue is support for <a href=\"http://tools.ietf.org/rfcmarkup?doc=2616#section-8\" rel=\"noreferrer\">persistent connections</a>. I recently worked on a server that \"supported\" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.</p>\n" }, { "answer_id": 33426626, "author": "I_Al-thamary", "author_id": 4694757, "author_profile": "https://Stackoverflow.com/users/4694757", "pm_score": 4, "selected": false, "text": "<p> HTTP 1.0 (1994)</p>\n\n<ul>\n<li>It is still in use</li>\n<li>Can be used by a client that cannot deal with chunked\n(or compressed) server replies</li>\n</ul>\n\n<p> HTTP 1.1 (1996- 2015)</p>\n\n<ul>\n<li>Formalizes many extensions to version 1.0</li>\n<li>Supports persistent and pipelined connections</li>\n<li>Supports chunked transfers, compression/decompression</li>\n<li>Supports virtual hosting (a server with a single IP Address hosting multiple domains)</li>\n<li>Supports multiple languages</li>\n<li>Supports byte-range transfers; useful for resuming interrupted data\ntransfers</li>\n</ul>\n\n<p>HTTP 1.1 is an enhancement of HTTP 1.0. The following lists the\nfour major improvements:</p>\n\n<ol>\n<li><p>Efficient use of IP addresses, by allowing multiple domains to be\nserved from a single IP address.</p></li>\n<li><p>Faster response, by allowing a web browser to send multiple\nrequests over a single persistent connection.</p></li>\n<li>Faster response for dynamically-generated pages, by support for\nchunked encoding, which allows a response to be sent before its\ntotal length is known.</li>\n<li>Faster response and great bandwidth savings, by adding cache\nsupport.</li>\n</ol>\n" }, { "answer_id": 42555733, "author": "Krishna Mohan", "author_id": 7538871, "author_profile": "https://Stackoverflow.com/users/7538871", "pm_score": 2, "selected": false, "text": "<p>HTTP 1.1 is the latest version of Hypertext Transfer Protocol, the World Wide Web application protocol that runs on top of the Internet's TCP/IP suite of protocols. compare to HTTP 1.0 , HTTP 1.1 provides faster delivery of Web pages than the original HTTP and reduces Web traffic.</p>\n\n<p>Web traffic Example: For example, if you are accessing a server. At the same time so many users are accessing the server for the data, Then there is a chance for hanging the Server. This is Web traffic.</p>\n" }, { "answer_id": 60274548, "author": "Niraj Kumar Jena", "author_id": 12916807, "author_profile": "https://Stackoverflow.com/users/12916807", "pm_score": 2, "selected": false, "text": "<p>HTTP 1.1 comes with the host header in its specification while the HTTP 1.0 doesn't officially have a host header, but it doesn't refuse to add one.</p>\n\n<p>The host header is useful because it allows the client to route a message throughout the proxy server, and the major difference between 1.0 and 1.1 versions HTTP are:</p>\n\n<ol>\n<li>HTTP 1.1 comes with persistent connections which define that we can have more than one request or response on the same HTTP connection.</li>\n<li>while in HTTP 1.0 you have to open a new connection for each request and response</li>\n<li>In HTTP 1.0 it has a pragma while in HTTP 1.1 it has Cache-Control\nthis is similar to pragma</li>\n</ol>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Could somebody give me a brief overview of the differences between HTTP 1.0 and HTTP 1.1? I've spent some time with both of the RFCs, but haven't been able to pull out a lot of difference between them. Wikipedia says this: > > **HTTP/1.1 (1997-1999)** > > > Current version; persistent connections enabled by default and works well with proxies. Also supports request pipelining, allowing multiple requests to be sent at the same time, allowing the server to prepare for the workload and potentially transfer the requested resources more quickly to the client. > > > But that doesn't mean a lot to me. I realize this is a somewhat complicated subject, so I'm not expecting a full answer, but can someone give me a brief overview of the differences at a bit lower level? By this I mean that I'm looking for the info I would need to know to implement either an HTTP server or application. I'm mostly looking for a nudge in the right direction so that I can figure it out on my own.
**Proxy support and the Host field:** HTTP 1.1 has a required Host header by spec. HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version. Example: ``` GET / HTTP/1.1 Host: www.blahblahblahblah.com ``` This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server. So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants. **Persistent connections:** HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection. In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of [TCP Slow Start](http://en.wikipedia.org/wiki/Slow-start). **OPTIONS method:** HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications. **Caching:** HTTP 1.0 had support for caching via the header: If-Modified-Since. HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags. HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers. There are also further additions relating to caching like the Cache-Control header. **100 Continue status:** There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body. **Much more:** * Digest authentication and proxy authentication * Extra new status codes * Chunked transfer encoding * Connection header * Enhanced compression support * Much much more.
246,870
<p>Each of my clients can have many todo items and every todo item has a due date.</p> <p>What would be the query for discovering the next undone todo item by due date for each file? In the event that a client has more than one todo, the one with the lowest id is the correct one.</p> <p>Assuming the following minimal schema:</p> <pre><code>clients (id, name) todos (id, client_id, description, timestamp_due, timestamp_completed) </code></pre> <p>Thank you.</p>
[ { "answer_id": 246918, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>The following should get you close, first get the min time for each client, then lookup the client/todo information</p>\n\n<pre><code>SELECT\n C.Id,\n C.Name,\n T.Id\n T.Description,\n T.timestamp_due\nFROM\n{\n SELECT\n client_id,\n MIN(timestamp_due) AS \"DueDate\"\n FROM todos\n WHERE timestamp_completed IS NULL\n GROUP BY ClientId\n} AS MinValues\n INNER JOIN Clients C\n ON (MinValues.client_id = C.Id)\n INNER JOIN todos T\n ON (MinValues.client_id = T.client_id\n AND MinValues.DueDate = T.timestamp_due)\nORDER BY C.Name\n</code></pre>\n\n<p><strong>NOTE:</strong> Written assuming SQL Server</p>\n" }, { "answer_id": 246927, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT c.name, MIN(t.id)\nFROM clients c, todos t\nWHERE c.id = t.client_id AND t.timestamp_complete IS NULL\nGROUP BY c.id\nHAVING t.timestamp_due &lt;= MIN(t.timestamp_due)\n</code></pre>\n\n<p>Avoids a subquery, correlated or otherwise but introduces a bunch of aggregate operations which aren't much better.</p>\n" }, { "answer_id": 246934, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>This question is the classic <strong><em>pick-a-winner for each group</em></strong>. It gets posted about twice a day.</p>\n\n<pre><code>SELECT *\nFROM todos t\nWHERE t.timestamp_completed is null\n and\n(\n SELECT top 1 t2.id\n FROM todos t2\n WHERE t.client_id = t2.client_id\n and t2.timestamp_completed is null\n --there is no earlier record\n and\n (t.timestamp_due &gt; t2.timestamp_due\n or (t.timestamp_due = t2.timestamp_due and t.id &gt; t2.id)\n )\n) is null\n</code></pre>\n" }, { "answer_id": 247008, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>Some Jet SQL, I realize it is unlikely that the questioner is using Jet, however the reader may be.</p>\n\n<pre><code>SELECT c.name, t.description, t.timestamp_due\nFROM (clients c \n INNER JOIN \n (SELECT t.client_id, Min(t.id) AS MinOfid\n FROM todos t\n WHERE t.timestamp_completed Is Null\n GROUP BY t.client_id) AS tm \nON c.id = tm.client_id) \nINNER JOIN todos t ON tm.MinOfid = t.id\n</code></pre>\n" }, { "answer_id": 247157, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 3, "selected": true, "text": "<p>I haven't tested this yet, so you may have to tweak it:</p>\n\n<pre><code>SELECT\n TD1.client_id,\n TD1.id,\n TD1.description,\n TD1.timestamp_due\nFROM\n Todos TD1\nLEFT OUTER JOIN Todos TD2 ON\n TD2.client_id = TD1.client_id AND\n TD2.timestamp_completed IS NULL AND\n (\n TD2.timestamp_due &lt; TD1.timestamp_due OR\n (TD2.timestamp_due = TD1.timestamp_due AND TD2.id &lt; TD1.id)\n )\nWHERE\n TD2.id IS NULL\n</code></pre>\n\n<p>Instead of trying to sort and aggregate, you're basically answering the question, \"Is there any other todo that would come before this one?\" (based on your definition of \"before\"). If not, then this is the one that you want.</p>\n\n<p>This should be valid on most SQL platforms.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
Each of my clients can have many todo items and every todo item has a due date. What would be the query for discovering the next undone todo item by due date for each file? In the event that a client has more than one todo, the one with the lowest id is the correct one. Assuming the following minimal schema: ``` clients (id, name) todos (id, client_id, description, timestamp_due, timestamp_completed) ``` Thank you.
I haven't tested this yet, so you may have to tweak it: ``` SELECT TD1.client_id, TD1.id, TD1.description, TD1.timestamp_due FROM Todos TD1 LEFT OUTER JOIN Todos TD2 ON TD2.client_id = TD1.client_id AND TD2.timestamp_completed IS NULL AND ( TD2.timestamp_due < TD1.timestamp_due OR (TD2.timestamp_due = TD1.timestamp_due AND TD2.id < TD1.id) ) WHERE TD2.id IS NULL ``` Instead of trying to sort and aggregate, you're basically answering the question, "Is there any other todo that would come before this one?" (based on your definition of "before"). If not, then this is the one that you want. This should be valid on most SQL platforms.
246,876
<pre><code>$doba = explode("/", $dob); $date = date("Y-m-d", mktime(0,0,0, $doba[0], $doba[1], $doba[2])); </code></pre> <p>The above code turns any date i pass through into 1999-11-30 and i know it was working yesterday. Date is correct when I echo $doba. Anyone have any ideas?</p> <p>Cheers</p>
[ { "answer_id": 246891, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": true, "text": "<p>What is the format of <code>$doba</code>? Remember <code>mktime</code>'s syntax goes hour, minute, second, <strong>month, day year</strong> which can be confusing.</p>\n\n<p>Here's some examples:</p>\n\n<pre><code>$doba = explode('/', '1991/08/03');\necho(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[2], $doba[0]);\n\n$doba = explode('/', '03/08/1991');\necho(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[0], $doba[2]);\n</code></pre>\n" }, { "answer_id": 246908, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 2, "selected": false, "text": "<p>It is a bit overkill to use <code>mktime</code> in this case. Assuming <code>$dob</code> is in the following format:</p>\n\n<blockquote>\n <p><code>MM/DD/YYYY</code></p>\n</blockquote>\n\n<p>you could just to the following to acheive the same result (assuming <code>$dob</code> is always valid):</p>\n\n<pre><code>$doba = explode(\"/\", $dob);\n$date = vsprintf('%3$04d-%1$02d-%2$02d', $doba);\n</code></pre>\n" }, { "answer_id": 247648, "author": "jcoby", "author_id": 2884, "author_profile": "https://Stackoverflow.com/users/2884", "pm_score": 2, "selected": false, "text": "<p>or even easier: <code>$date = date('Y-m-d', strtotime($dob))</code></p>\n" }, { "answer_id": 247681, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 0, "selected": false, "text": "<p>If you have issues with what jcoby said above, the <a href=\"http://www.php.net/strptime\" rel=\"nofollow noreferrer\">strptime</a>() command gives you more control by allowing you to specify the format as well.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31677/" ]
``` $doba = explode("/", $dob); $date = date("Y-m-d", mktime(0,0,0, $doba[0], $doba[1], $doba[2])); ``` The above code turns any date i pass through into 1999-11-30 and i know it was working yesterday. Date is correct when I echo $doba. Anyone have any ideas? Cheers
What is the format of `$doba`? Remember `mktime`'s syntax goes hour, minute, second, **month, day year** which can be confusing. Here's some examples: ``` $doba = explode('/', '1991/08/03'); echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[2], $doba[0]); $doba = explode('/', '03/08/1991'); echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[0], $doba[2]); ```
246,884
<p>I haven´t experience in making setup, but I all ready make mine but now I need help because when I made a new version I want that the user double click the shortcut and it do the update if there are any.</p> <p>The application is in <code>c#</code>.</p> <p>Could you help?</p>
[ { "answer_id": 246955, "author": "Dan Walker", "author_id": 752, "author_profile": "https://Stackoverflow.com/users/752", "pm_score": 1, "selected": false, "text": "<p>Here's how I have implemented an updater program I wrote earlier.</p>\n\n<p>First off, you grab an ini file off of your server. This file will contain information about the latest version and where the setup file is. Getting that file isn't too hard.</p>\n\n<pre><code> WebClient wc = new WebClient();\n wc.DownloadFile(UrlOfIniContainingLatestVersion, PlacetoSaveIniFile);\n</code></pre>\n\n<p>I also had it setup to read information from a local ini file to determine the latest version. The better way of doing this would be to read the file version directly, but I don't have the code to do that handy.</p>\n\n<p>Next we do a very simple check to see how the two versions compare and download the update.</p>\n\n<pre><code> if (LatestVersion &gt; CurrentVersion)\n {\n //Download update.\n }\n</code></pre>\n\n<p>Downloading the update is just as simple as downloading the original ini. You simply change change the two parameters.</p>\n\n<pre><code>wc.DownloadFile(UrlOfLatestSetupFile, PlaceToSaveSetupFile);\n</code></pre>\n\n<p>Now that you have the file downloaded, it's a simple matter of running the installer.</p>\n\n<pre><code>System.Diagnostics.Start(PathOfDownloadedSetupFile);\n</code></pre>\n\n<hr>\n\n<p>If you're not sure how to read an ini file, I found the following class somewhere over at CodeProject</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace Ini\n{\n /// &lt;summary&gt;\n /// Create a New INI file to store or load data\n /// &lt;/summary&gt;\n public class IniFile\n {\n public string path;\n\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string section,\n string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section,\n string key, string def, StringBuilder retVal,\n int size, string filePath);\n\n /// &lt;summary&gt;\n /// INIFile Constructor.\n /// &lt;/summary&gt;\n /// &lt;PARAM name=\"INIPath\"&gt;&lt;/PARAM&gt;\n public IniFile(string INIPath)\n {\n path = INIPath;\n }\n\n /// &lt;summary&gt;\n /// Write Data to the INI File\n /// &lt;/summary&gt;\n /// &lt;PARAM name=\"Section\"&gt;&lt;/PARAM&gt;\n /// Section name\n /// &lt;PARAM name=\"Key\"&gt;&lt;/PARAM&gt;\n /// Key Name\n /// &lt;PARAM name=\"Value\"&gt;&lt;/PARAM&gt;\n /// Value Name\n public void IniWriteValue(string Section, string Key, string Value)\n {\n WritePrivateProfileString(Section, Key, Value, this.path);\n }\n\n /// &lt;summary&gt;\n /// Read Data Value From the Ini File\n /// &lt;/summary&gt;\n /// &lt;PARAM name=\"Section\"&gt;&lt;/PARAM&gt;\n /// &lt;PARAM name=\"Key\"&gt;&lt;/PARAM&gt;\n /// &lt;PARAM name=\"Path\"&gt;&lt;/PARAM&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public string IniReadValue(string Section, string Key)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(Section, Key, \"\", temp,\n 255, this.path);\n return temp.ToString();\n\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 247144, "author": "thijs", "author_id": 26796, "author_profile": "https://Stackoverflow.com/users/26796", "pm_score": 0, "selected": false, "text": "<p>Sounds like you might be able to use <a href=\"http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx\" rel=\"nofollow noreferrer\">ClickOnce</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32115/" ]
I haven´t experience in making setup, but I all ready make mine but now I need help because when I made a new version I want that the user double click the shortcut and it do the update if there are any. The application is in `c#`. Could you help?
Here's how I have implemented an updater program I wrote earlier. First off, you grab an ini file off of your server. This file will contain information about the latest version and where the setup file is. Getting that file isn't too hard. ``` WebClient wc = new WebClient(); wc.DownloadFile(UrlOfIniContainingLatestVersion, PlacetoSaveIniFile); ``` I also had it setup to read information from a local ini file to determine the latest version. The better way of doing this would be to read the file version directly, but I don't have the code to do that handy. Next we do a very simple check to see how the two versions compare and download the update. ``` if (LatestVersion > CurrentVersion) { //Download update. } ``` Downloading the update is just as simple as downloading the original ini. You simply change change the two parameters. ``` wc.DownloadFile(UrlOfLatestSetupFile, PlaceToSaveSetupFile); ``` Now that you have the file downloaded, it's a simple matter of running the installer. ``` System.Diagnostics.Start(PathOfDownloadedSetupFile); ``` --- If you're not sure how to read an ini file, I found the following class somewhere over at CodeProject ``` using System; using System.Runtime.InteropServices; using System.Text; namespace Ini { /// <summary> /// Create a New INI file to store or load data /// </summary> public class IniFile { public string path; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); /// <summary> /// INIFile Constructor. /// </summary> /// <PARAM name="INIPath"></PARAM> public IniFile(string INIPath) { path = INIPath; } /// <summary> /// Write Data to the INI File /// </summary> /// <PARAM name="Section"></PARAM> /// Section name /// <PARAM name="Key"></PARAM> /// Key Name /// <PARAM name="Value"></PARAM> /// Value Name public void IniWriteValue(string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, this.path); } /// <summary> /// Read Data Value From the Ini File /// </summary> /// <PARAM name="Section"></PARAM> /// <PARAM name="Key"></PARAM> /// <PARAM name="Path"></PARAM> /// <returns></returns> public string IniReadValue(string Section, string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path); return temp.ToString(); } } } ```
246,890
<p>I recently converted a site from asp to CF. Unfortunately, alot of the old users had the "homepage" bookmarked. www.example.com/homepage.asp</p> <p>Is there a sort of catch all way I could redirect any traffic from that page to the current index.cfm?</p> <p>I would normally just delete those files, but the owner(s) wanted to keep it around for their own comparison reasons.</p> <p>Any ideas?</p> <p>Thanks</p>
[ { "answer_id": 246899, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>The best bet is to do either a meta refresh in the actual homepage.asp page, it is quick and dirty, but works.</p>\n\n<p>A better solution would be to have the .asp page do a 301 redirect to the new homepage, that way when search engines access the page as well they know it has moved.</p>\n" }, { "answer_id": 246929, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 4, "selected": true, "text": "<p>Put this in the old homepage.asp</p>\n\n<pre><code>&lt;%@ Language=VBScript %&gt;\n&lt;%\nResponse.Status=\"301 Moved Permanently\"\nResponse.AddHeader \"Location\", \"/index.cfm\"\n%&gt;\n</code></pre>\n" }, { "answer_id": 247173, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>What I do on Linux machines when I run into something like this is to create a symbolic link (<code>ln -s /path/to/source /path/to/target</code>).</p>\n\n<p>Not sure what the Windows equivalent would be, so going with @<a href=\"https://stackoverflow.com/questions/246890/bookmarked-page-redirect#246929\">Patrick's</a> answer is probably best.</p>\n\n<p><strong>EDIT</strong> - The NTFS way of making a symlink:<br>\n<a href=\"http://en.wikipedia.org/wiki/NTFS_symbolic_link\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/NTFS_symbolic_link</a><br>\nsee also <a href=\"http://en.wikipedia.org/wiki/Symbolic_link\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Symbolic_link</a></p>\n" }, { "answer_id": 248325, "author": "Andy Waschick", "author_id": 6000, "author_profile": "https://Stackoverflow.com/users/6000", "pm_score": 2, "selected": false, "text": "<p>If you don't want run an onerous asp file at all on the new site, you can do a custom 404 on the web server. If you point the 404 page to a .cfm file, you can extract all the various features from the request by including:</p>\n\n<pre><code>&lt;!--- parse out the text in the URL parameters into an array ---&gt;\n&lt;cfset variables.requestparams = listtoarray(cgi.query_string,'/?&amp;')&gt;\n\n&lt;!--- get rid of the first 2 items in the array since they dont represent request info ---&gt;\n&lt;cfset foo = arraydeleteat(variables.requestparams,1)&gt;\n&lt;cfset foo = arraydeleteat(variables.requestparams,1)&gt;\n</code></pre>\n\n<p>You'll be left with an array representing the parameters that were passed in the original request. You can follow up on this by doing whatever analysis you need to on the url components to map it against the analogous pages in your CF site. </p>\n" }, { "answer_id": 255521, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 2, "selected": false, "text": "<p>I'm surprised nobody has mentioned URL Rewriting. You can use mod_rewrite on *nix/apache, or <a href=\"http://www.isapirewrite.com/\" rel=\"nofollow noreferrer\">ISAPI Rewrite</a> or <a href=\"http://www.codeplex.com/IIRF\" rel=\"nofollow noreferrer\">Ionics ISAPI Rewrite</a> on Windows/IIS. I prefer Ionics if I'm on IIS.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
I recently converted a site from asp to CF. Unfortunately, alot of the old users had the "homepage" bookmarked. www.example.com/homepage.asp Is there a sort of catch all way I could redirect any traffic from that page to the current index.cfm? I would normally just delete those files, but the owner(s) wanted to keep it around for their own comparison reasons. Any ideas? Thanks
Put this in the old homepage.asp ``` <%@ Language=VBScript %> <% Response.Status="301 Moved Permanently" Response.AddHeader "Location", "/index.cfm" %> ```
246,905
<p>I just finished a 2d platformer in C++/Allegro. Its still in an incomplete stage...</p> <p>I wonder how to go about a peer-review from people who are into game development. I would like to review my project on grounds of </p> <ol> <li>game play</li> <li>Collision detection</li> <li>use of OOP</li> <li>programming of sounds, effects etc</li> <li>any further ideas</li> <li>ways in which i could have done better</li> <li>ways to optimize</li> </ol> <p>current code looks like a garbage at some places... so could you also suggest some simplification techniques?</p> <p>you can view my project (if you wish) at updated link - <a href="http://ideamonk.blogspot.com/2008/09/nincompoop-all-ready-for-shaastra-2008.html" rel="nofollow noreferrer">nincompoop</a> <a href="http://ideamonk.googlepages.com/nincompoop_distro.rar" rel="nofollow noreferrer">(direct link)</a></p> <p><a href="http://ideamonk.googlepages.com/nincompoop_distro.rar" rel="nofollow noreferrer">http://ideamonk.googlepages.com/nincompoop_distro.rar</a></p> <p>As of now I am switching to C# and XNA, finding it very easy and fast to learn all because I'm impressed from - </p> <p><a href="http://catalog.xna.com/GameDetails.aspx?releaseId=341" rel="nofollow noreferrer">http://catalog.xna.com/GameDetails.aspx?releaseId=341</a></p> <blockquote> <p>I do no intend to sell any product or popularise anything here... my intent is to get tips to be better from people who are better. As for the page where I have uploaded my project, its not supported by ads of any kind. so please feel safe.</p> </blockquote>
[ { "answer_id": 246942, "author": "Abhishek Mishra", "author_id": 8786, "author_profile": "https://Stackoverflow.com/users/8786", "pm_score": 1, "selected": false, "text": "<p><strong>RECAP from previous episode -</strong></p>\n\n<p>I do not understand why people vote you down and offensive. Keep the good work... – Daok (27 mins ago)</p>\n\n<p>anything awefully wrong in asking for a peer review ? think before hitting the down button, tomorrow you might too be in need of peer review! – Abhishek Mishra (26 mins ago) </p>\n\n<p>@Daok : thats what I was precisely wondering 58 seconds ago! – Abhishek Mishra (25 mins ago)</p>\n\n<p>This is silly. It might not fit the typical mold of a SO question, but a peer-review isn't a bad thing, and not worthy of an offensive much less 4 down votes. – Thomas Owens (23 mins ago)</p>\n\n<p>@Mitchel Sellers : you know what, there had been a good discussion over game dev while I was working on this project.. so I thought it would be good to put it up fr review.. but @ stackoverflow ... things are really great! ycombinator crowd is yet more intelligent, they come up wid amazing feedbacks – Abhishek Mishra (21 mins ago)</p>\n\n<p>I think it might be the phrase and tone of the question. It sounds more like product announcement, than a question for help. If it had been phrased as a \"How to properly peer-review my project\" etc then people might have been less harsh. – Mark Ingram (21 mins ago)</p>\n\n<p>Point is, this is not what Stack Overflow is for. It's for asking specific technical questions. – Remi Despres-Smyth (19 mins ago) </p>\n\n<p>woops... yeah it was rolling in my mind as I typed the question... let me rephrase it into a <em>REAL</em> question! :) – Abhishek Mishra (18 mins ago)</p>\n\n<p>and one could've as well given technical feedbacks as on how to improve the game.. besides I'm putting up the source code for review as well! Is there any way to OPEN a question again ? – Abhishek Mishra (17 mins ago) </p>\n\n<p>I've asked for code review, and received it here. Abhishek, if someone reopens this and you get to edit it, look at this question: <a href=\"https://stackoverflow.com/questions/161873/k-r-exercise-my-code-works-but-feels-stinky-advice-for-cleanup\">K &amp; R Exercise: My Code Works, But Feels Stinky; Advice for Cleanup?</a> as a code review question example. – John Rudy (12 mins ago)</p>\n\n<p>@John : Thanks! hope it works!</p>\n" }, { "answer_id": 254242, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 3, "selected": true, "text": "<p>The first thing I noticed in your source code is that you've got most of your game logic is in the main.cpp file, with the nesting going as deep as 11 tabs! For code organizational purposes, this is a nightmare. Of course, I did this too on my first game. :) The first thing you can do is simplify your main game loop to look something like this:</p>\n\n<pre><code>int main () \n{\n game_object gob;\n gob.init_allegro();\n gob.load_assets();\n while(true) {\n gob.handle_inputs()\n if (!gob.update())\n break;\n gob.render();\n }\n gob.cleanup();\n}\n</code></pre>\n\n<p>Everything else should be refactored into your game_object class. It will be much easier to manage this way, also your code might actually fit on the page since you can avoid deep nesting. If you find your code getting more than 3 tabs deep, then whatever you are doing needs to be refactored into another method or even a separate class.</p>\n\n<p>My second suggestion would be to replace your goto's with something a little more sane like this:</p>\n\n<pre><code>bool playerwins = check_win_condition();\n\nif(playerwins) {\n // win condition code\n} else {\n // lose condition code\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786/" ]
I just finished a 2d platformer in C++/Allegro. Its still in an incomplete stage... I wonder how to go about a peer-review from people who are into game development. I would like to review my project on grounds of 1. game play 2. Collision detection 3. use of OOP 4. programming of sounds, effects etc 5. any further ideas 6. ways in which i could have done better 7. ways to optimize current code looks like a garbage at some places... so could you also suggest some simplification techniques? you can view my project (if you wish) at updated link - [nincompoop](http://ideamonk.blogspot.com/2008/09/nincompoop-all-ready-for-shaastra-2008.html) [(direct link)](http://ideamonk.googlepages.com/nincompoop_distro.rar) <http://ideamonk.googlepages.com/nincompoop_distro.rar> As of now I am switching to C# and XNA, finding it very easy and fast to learn all because I'm impressed from - <http://catalog.xna.com/GameDetails.aspx?releaseId=341> > > I do no intend to sell any product or popularise anything here... my intent is to get tips to be better from people who are better. As for the page where I have uploaded my project, its not supported by ads of any kind. so please feel safe. > > >
The first thing I noticed in your source code is that you've got most of your game logic is in the main.cpp file, with the nesting going as deep as 11 tabs! For code organizational purposes, this is a nightmare. Of course, I did this too on my first game. :) The first thing you can do is simplify your main game loop to look something like this: ``` int main () { game_object gob; gob.init_allegro(); gob.load_assets(); while(true) { gob.handle_inputs() if (!gob.update()) break; gob.render(); } gob.cleanup(); } ``` Everything else should be refactored into your game\_object class. It will be much easier to manage this way, also your code might actually fit on the page since you can avoid deep nesting. If you find your code getting more than 3 tabs deep, then whatever you are doing needs to be refactored into another method or even a separate class. My second suggestion would be to replace your goto's with something a little more sane like this: ``` bool playerwins = check_win_condition(); if(playerwins) { // win condition code } else { // lose condition code } ```
246,912
<p>Currently there are 2 pages in a jsp file: one of them displays the data and the second one is used for pagination. The task is to include exactly the same paginator table above the data table. Sorry, couldn't resist to draw it :)</p> <pre><code>|-----------------------------------------| | Page 2 of 200 &lt; &gt; | |-----------------------------------------| |-----------------------------------------| | Some weird business data comes here | |-----------------------------------------| |-----------------------------------------| | Page 2 of 200 &lt; &gt; | |-----------------------------------------| </code></pre> <p>The question is: how do I do it w/o shameless copypasting?</p>
[ { "answer_id": 246975, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 2, "selected": false, "text": "<p>Perhaps you can define the pagination stuff in a separate jsp, and then include it twice into your main jsp. For example:</p>\n\n<pre><code>&lt;jsp:include page=\"pagination.jsp\" flush=\"true\" /&gt;\n\n&lt;table&gt;...business data...&lt;/table&gt;\n\n&lt;jsp:include page=\"pagination.jsp\" flush=\"true\" /&gt;\n</code></pre>\n\n<p>This way, if you ever want to change the pagination stuff, you can just edit pagination.jsp.</p>\n" }, { "answer_id": 247034, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 3, "selected": true, "text": "<p>The four mechanisms of abstracting within JSP today are the jsp:include tag, the &lt;%@ include> directive, custom tag libraries, and custom tag files.</p>\n\n<p>jsp:include inserts the results of executing another JSP page, so you could do:</p>\n\n<pre><code>&lt;jsp:include \"page_naviagtor.jsp\"/&gt;\n&lt;table id=\"results\"&gt;...&lt;/table&gt;\n&lt;jsp:include \"page_navigator.jsp\"/&gt;\n</code></pre>\n\n<p>&lt;%@ include> is similar to jsp:include, save that it does not actually execute the code, rather it simply stamps it in to the original JSP source and is compiled with the rest of the page.</p>\n\n<p>Custom tag libraries give you (almost) the full power of JSP tags, so you can do something like:</p>\n\n<pre><code>&lt;tag:wrap_in_page_nav&gt;\n &lt;table id=\"results\"&gt; ... &lt;/table&gt;\n&lt;/tag:wrap_in_page_nav&gt;\n</code></pre>\n\n<p>These require you to write custom Java code, however.</p>\n\n<p>The final, and frankly, the best option for most cases, is the JSP 2.0 Tag FIle.</p>\n\n<p>Tag Files are a cross between jsp:include and custom tags. They let you do something akin to the \"wrap_in_page_nav\" tag, but you actually create the tag use JSP markup.</p>\n\n<p>So, in many cases, you can simply cut out the part you want to refactor, and paste it in to a Tag File, then simply use the tag.</p>\n\n<p>page.tag</p>\n\n<pre><code>&lt;%@tag description=\"put the tag description here\" pageEncoding=\"UTF-8\"%&gt;\n&lt;%@ taglib prefix=\"t\" tagdir=\"/WEB-INF/yourtags\" %&gt; \n&lt;%@attribute name=\"startPage\" required=\"true\"%&gt;\n&lt;%@attribute name=\"endPage\" required=\"true\"%&gt; \n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Page Title&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;tag:page_nav startPage=\"${startPage}\" endPage=\"${endPage}\"/&gt;\n &lt;jsp:doBody/&gt;\n &lt;tag:page_nav startPage=\"${startPage}\" endPage=\"${endPage}\"/&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>page_nav.tag</p>\n\n<pre><code>&lt;%@tag description=\"put the tag description here\" pageEncoding=\"UTF-8\"%&gt;\n&lt;%@ taglib prefix=\"t\" tagdir=\"/WEB-INF/yourtags\" %&gt; \n&lt;%@attribute name=\"startPage\" required=\"true\"%&gt;\n&lt;%@attribute name=\"endPage\" required=\"true\"%&gt; \n&lt;div&gt;${startPage} .. ${endPage}&lt;/div&gt;\n</code></pre>\n\n<p>Finally, your JSP</p>\n\n<pre><code>&lt;%@page contentType=\"text/html\"%&gt;\n&lt;%@page pageEncoding=\"UTF-8\"%&gt;\n&lt;%@ taglib prefix=\"t\" tagdir=\"/WEB-INF/yourtags\" %&gt;\n&lt;tag:page startPage=\"1\" endPage=\"4\"&gt;\n &lt;table&gt; ... &lt;/table&gt;\n&lt;/tag:page&gt;\n</code></pre>\n\n<p>Each of the tag files has the full power of JSP, the only limitation is that when using your own custom tag file, you can not include scriptlet code between your custom tag file tags (you can with normal JSP tags, just now tag file tags).</p>\n\n<p>Tag Files are a very powerful abstraction tool for use within JSP.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
Currently there are 2 pages in a jsp file: one of them displays the data and the second one is used for pagination. The task is to include exactly the same paginator table above the data table. Sorry, couldn't resist to draw it :) ``` |-----------------------------------------| | Page 2 of 200 < > | |-----------------------------------------| |-----------------------------------------| | Some weird business data comes here | |-----------------------------------------| |-----------------------------------------| | Page 2 of 200 < > | |-----------------------------------------| ``` The question is: how do I do it w/o shameless copypasting?
The four mechanisms of abstracting within JSP today are the jsp:include tag, the <%@ include> directive, custom tag libraries, and custom tag files. jsp:include inserts the results of executing another JSP page, so you could do: ``` <jsp:include "page_naviagtor.jsp"/> <table id="results">...</table> <jsp:include "page_navigator.jsp"/> ``` <%@ include> is similar to jsp:include, save that it does not actually execute the code, rather it simply stamps it in to the original JSP source and is compiled with the rest of the page. Custom tag libraries give you (almost) the full power of JSP tags, so you can do something like: ``` <tag:wrap_in_page_nav> <table id="results"> ... </table> </tag:wrap_in_page_nav> ``` These require you to write custom Java code, however. The final, and frankly, the best option for most cases, is the JSP 2.0 Tag FIle. Tag Files are a cross between jsp:include and custom tags. They let you do something akin to the "wrap\_in\_page\_nav" tag, but you actually create the tag use JSP markup. So, in many cases, you can simply cut out the part you want to refactor, and paste it in to a Tag File, then simply use the tag. page.tag ``` <%@tag description="put the tag description here" pageEncoding="UTF-8"%> <%@ taglib prefix="t" tagdir="/WEB-INF/yourtags" %> <%@attribute name="startPage" required="true"%> <%@attribute name="endPage" required="true"%> <html> <head> <title>Page Title</title> </head> <body> <tag:page_nav startPage="${startPage}" endPage="${endPage}"/> <jsp:doBody/> <tag:page_nav startPage="${startPage}" endPage="${endPage}"/> </body> </html> ``` page\_nav.tag ``` <%@tag description="put the tag description here" pageEncoding="UTF-8"%> <%@ taglib prefix="t" tagdir="/WEB-INF/yourtags" %> <%@attribute name="startPage" required="true"%> <%@attribute name="endPage" required="true"%> <div>${startPage} .. ${endPage}</div> ``` Finally, your JSP ``` <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ taglib prefix="t" tagdir="/WEB-INF/yourtags" %> <tag:page startPage="1" endPage="4"> <table> ... </table> </tag:page> ``` Each of the tag files has the full power of JSP, the only limitation is that when using your own custom tag file, you can not include scriptlet code between your custom tag file tags (you can with normal JSP tags, just now tag file tags). Tag Files are a very powerful abstraction tool for use within JSP.
246,919
<p>What is the best way to implement the page view counter like the ones they have here on the site where each question has a "Views" counter?</p> <p>Factoring in Performance and Scalability issues.</p>
[ { "answer_id": 246968, "author": "François", "author_id": 32379, "author_profile": "https://Stackoverflow.com/users/32379", "pm_score": 3, "selected": false, "text": "<p>An efficient way may be :\nStore your counters in the Application object, you may persist it to file/DB periodically and on application close.</p>\n" }, { "answer_id": 246980, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 4, "selected": true, "text": "<p>The counter i optimized works like this:</p>\n\n<pre><code>UPDATE page_views SET counter = counter + 1 WHERE page_id = x\nif (affected_rows == 0 ) {\n INSERT INTO page_views (page_id, counter) VALUES (x, 1)\n}\n</code></pre>\n\n<p>This way you run 2 query for the first view, the other views require only 1 query.</p>\n" }, { "answer_id": 246991, "author": "Zote", "author_id": 20683, "author_profile": "https://Stackoverflow.com/users/20683", "pm_score": 0, "selected": false, "text": "<p>You can implement an IHttpHandler to do that.</p>\n" }, { "answer_id": 247010, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 0, "selected": false, "text": "<p>I'm a fan of @Guillaume's style of implementation. I use a transparent GIF handler and in-memory queues to batch-up sets of changes that are then periodically flushed using a seperate thread created in global.asax.</p>\n\n<p>The handler implements IHttpHandler, processes the request parameters e.g. page id, language etc., updates the queue, then response.writes the transparent GIF.</p>\n\n<p>By moving persistent changes to a seperate thread than the user-request you also deal much better with potential serialization issues from running multiple servers etc.</p>\n\n<p>Of course you could just pay someone else to do the work too e.g. with transparent gifs.</p>\n" }, { "answer_id": 247015, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 0, "selected": false, "text": "<p>For me the best way is to have a field in the question table and update it when the question is accessed</p>\n\n<pre><code>UPDATE Questions SET views = views + 1 WHERE QuestionID = x\n</code></pre>\n\n<p>Application Object: IMO is not scalable because the may end with lots of memory consumption as more questions are accessed.<br>\nPage_views table: no need to, you have to do a costly join after </p>\n" }, { "answer_id": 247222, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "<p>I've made two observations on the stackoverflow views counter:</p>\n\n<ul>\n<li><p>There's a <code>link</code> element in the header that handles triggering the count update. For this question, the markup looks like this:<br>\n<code>&lt;link href=\"/questions/246919/increment-view-count\" type=\"text/css\" rel=\"stylesheet\" /&gt;</code><br>\nI imagine you could hit that url to update the viewcount without ever actually viewing the page, but I haven't tried it.</p></li>\n<li><p>I had a <a href=\"http://stackoverflow.uservoice.com/pages/general/suggestions/33016\" rel=\"noreferrer\">uservoice ticket</a>, where the response from Jeff indicated that views are not incremented from the same ip twice in a row.</p></li>\n</ul>\n" }, { "answer_id": 1563579, "author": "Luke101", "author_id": 184773, "author_profile": "https://Stackoverflow.com/users/184773", "pm_score": 2, "selected": false, "text": "<p>Instead of making a database call everytime the database is hit, I would increment a counter using a cache object and depending on how many visits you get to your site every day you have send the page hits to the database every 100th hit to the site. This is waay faster then updating the database on every single hit.</p>\n\n<p>Or another solution is analyzing the IIS log file and updating hits every 30min through a windows service. This is what I have implemented and it work wonders.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32372/" ]
What is the best way to implement the page view counter like the ones they have here on the site where each question has a "Views" counter? Factoring in Performance and Scalability issues.
The counter i optimized works like this: ``` UPDATE page_views SET counter = counter + 1 WHERE page_id = x if (affected_rows == 0 ) { INSERT INTO page_views (page_id, counter) VALUES (x, 1) } ``` This way you run 2 query for the first view, the other views require only 1 query.
246,921
<p>I was thinking about the idea of using Ajax instead of TagLib. The most elegant way would be: Using Java Annotation. The idea is, designers or anybody can make the HTML without any taglib ,just using the "standard" HTML tags with id or name, and call the Javascript. That way any WYSIWYG can be used, developer don't have to care about HTML format or the way it's designed. In many (at least open-source) WYSIWYG don't show the taglibs in that final result (or have a template of it), so it's hard to "preview". Other reason is, developer should know Java and HTML/TagLibs should not be a must-have, since we got CSS and AJAX.</p> <p>It should work just like that:</p> <p><strong>MyClass.java</strong>: <code></p> <pre><code>import ... // Use the ResourceBundle resource[.{Locale}].properties @Jay2JI18n(resourceBundle="org.format.resource",name="MyClassForm") public class MyClass { private Integer age; private String name private Date dob; private salary; @Jay2JLabel(resource="label.name") @Jay2JMaxLength(value=50,required=true,) @Jay2JException(resource="exception.message") public String getName() { ... } public void setName(String name) { if ( name.trim().equal("") ) { throw new Exception("Name is required"); } } /* Getter and setter for age */ ... @Jay2JLabel(message="Salary") @Jay2JFormat(format="##,###.00",language="en") @Jay2JFormat(format="##.###,00",language="pt_BR") // or you could use that to access a property of the ResourceBundle //@Jay2I18nResource(resource="money.format") public Date getSalary() { ... } /* Setter for salary and getter/setter for the rest */ ... } </code></pre> <p></code></p> <p><strong>Page.html</strong>: <code></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;SCRIPT&gt; &lt;/SCRIPT&gt; &lt;/head&gt; &lt;body&gt; &lt;form onload="Jay2J.formalize(this)"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p></code></p> <p>of it can be a HTML with the fields filled; <strong>PageWithFields.html</strong>: <code></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;SCRIPT&gt; &lt;/SCRIPT&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="myfavoritewaytopostthis" onsubmit="return Jay2J.validate(this)" onload="Jay2J.formalizeExistField(this)"&gt; &lt;label&gt;Name&lt;/label&gt;&lt;input type="text" name="name" id="name" /&gt; &lt;label&gt;DOB&lt;/label&gt;&lt;input type="text" name="dateOfBirth" id="dob" /&gt; &lt;label&gt;Salary&lt;/label&gt;&lt;input type="text" name="salary" id="salary" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p></code></p> <p>That way the Annotation (no XML, it's like HTML in the way that it's only another file modify and XML is not Java) will define how the HTML will be treated. That way developer can stop developing in HTML and use just JAVA (or JavaScript), do you think that's a valid idea?</p>
[ { "answer_id": 247043, "author": "Peter", "author_id": 26483, "author_profile": "https://Stackoverflow.com/users/26483", "pm_score": 2, "selected": false, "text": "<p>When i see your topic title i thought:</p>\n\n<p>You cant use Ajax in stead of a taglib. AJAX is javascript on the client and the taglib is java code on the server.</p>\n\n<p>After reading your post i thought, ah he whats to do what [link text][1] does </p>\n\n<p>But then not entrily the same. </p>\n\n<p>[1]: <a href=\"http://code.google.com/webtoolkit/\" rel=\"nofollow noreferrer\">http://code.google.com/webtoolkit/</a> GWT</p>\n" }, { "answer_id": 248242, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 1, "selected": false, "text": "<p>First impression is ... yuck, someone who picks this up will have no idea what they're looking at without learning your (new, different, non-standard) way of doing things. You could do something similar by implementing a tag that takes a bean (value object) and maybe does some minor reflection/annotation inspection to emit the proper html, and you'll save yourself a lot of heartache down the line. </p>\n\n<p>Make your value objects implement a simple interface that your tag will use to extract and format the html, and you can probably get 80-90% of where you're trying to go with 1/2 the work or less.</p>\n" }, { "answer_id": 251332, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 1, "selected": false, "text": "<p>First impression was, WTF. After reading further, I get a impression that you are trying to address the 'separation of concerns'problem in a different way. Some observations on your approach.</p>\n\n<ol>\n<li>Requires client side scripting to be enabled and hence fails accessibility guide lines.</li>\n<li>Reinventing the wheel: Many web frameworks like Tapestry, Wicket try to address these issues and have done a commendable work.</li>\n<li>On your comment on binding Java to HTML, the code example doesn't convey the idea very clearly. formalize() seems to create the UI, that implies you have UI (HTML) coded into java (Bad Idea? probably not NakedObjects attempts to you domain models for UI, probably yes if one were to write a page specific code)</li>\n<li>validate() is invoked on onSubmit(), Why would I want it to be processed asynchronously!! That aside, using obstrusive java script is way out of fashion (seperation of concerns again)</li>\n<li>Your argument on taglibs preventing WYSIWIG, though justifiable, is not entirely valid. Tags cannot be used to compose other tags, each tag is a unique entity that either deals with behaviour or emits some html code. Your argument is valid for the second case. However, if I understand your formalize() correctly, you are doing the same!</li>\n</ol>\n\n<p>Nice to hear some new ideas and Welcome to SO. Also, please use the edit question option until you earn enough reputation to add comments. Adding answers is not the right way!</p>\n" }, { "answer_id": 1360074, "author": "James Black", "author_id": 67566, "author_profile": "https://Stackoverflow.com/users/67566", "pm_score": 1, "selected": false, "text": "<p>This idea has some merit, if I understand it correctly.</p>\n\n<p>You could use AOP to modify a servlet that would actually be called for the page. The servlet would then return the html, using the annotations.</p>\n\n<p>This way the programmers don't see the html generation, and if you have a standard javascript library for it, then it may work.</p>\n\n<p>But, just because it works doesn't mean that you should do it.</p>\n\n<p>As was mentioned, there are many frameworks out there that can hide the javascript from programmers, such as JSF, which is basically taglibs and a different navigation scheme.</p>\n\n<p>I remember using the beehive project to do something similar, it was annotation driven so I could basically do everything in java and it generated the javascript, years ago. :)</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438405/" ]
I was thinking about the idea of using Ajax instead of TagLib. The most elegant way would be: Using Java Annotation. The idea is, designers or anybody can make the HTML without any taglib ,just using the "standard" HTML tags with id or name, and call the Javascript. That way any WYSIWYG can be used, developer don't have to care about HTML format or the way it's designed. In many (at least open-source) WYSIWYG don't show the taglibs in that final result (or have a template of it), so it's hard to "preview". Other reason is, developer should know Java and HTML/TagLibs should not be a must-have, since we got CSS and AJAX. It should work just like that: **MyClass.java**: ``` import ... // Use the ResourceBundle resource[.{Locale}].properties @Jay2JI18n(resourceBundle="org.format.resource",name="MyClassForm") public class MyClass { private Integer age; private String name private Date dob; private salary; @Jay2JLabel(resource="label.name") @Jay2JMaxLength(value=50,required=true,) @Jay2JException(resource="exception.message") public String getName() { ... } public void setName(String name) { if ( name.trim().equal("") ) { throw new Exception("Name is required"); } } /* Getter and setter for age */ ... @Jay2JLabel(message="Salary") @Jay2JFormat(format="##,###.00",language="en") @Jay2JFormat(format="##.###,00",language="pt_BR") // or you could use that to access a property of the ResourceBundle //@Jay2I18nResource(resource="money.format") public Date getSalary() { ... } /* Setter for salary and getter/setter for the rest */ ... } ``` **Page.html**: ``` <html> <head> <SCRIPT> </SCRIPT> </head> <body> <form onload="Jay2J.formalize(this)"> </form> </body> </html> ``` of it can be a HTML with the fields filled; **PageWithFields.html**: ``` <html> <head> <SCRIPT> </SCRIPT> </head> <body> <form action="myfavoritewaytopostthis" onsubmit="return Jay2J.validate(this)" onload="Jay2J.formalizeExistField(this)"> <label>Name</label><input type="text" name="name" id="name" /> <label>DOB</label><input type="text" name="dateOfBirth" id="dob" /> <label>Salary</label><input type="text" name="salary" id="salary" /> <input type="submit" /> </form> </body> </html> ``` That way the Annotation (no XML, it's like HTML in the way that it's only another file modify and XML is not Java) will define how the HTML will be treated. That way developer can stop developing in HTML and use just JAVA (or JavaScript), do you think that's a valid idea?
When i see your topic title i thought: You cant use Ajax in stead of a taglib. AJAX is javascript on the client and the taglib is java code on the server. After reading your post i thought, ah he whats to do what [link text][1] does But then not entrily the same. [1]: <http://code.google.com/webtoolkit/> GWT
246,930
<p>I see these two acronyms being thrown around and I was wondering if there are any differences between a GUID and a UUID?</p>
[ { "answer_id": 246935, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 9, "selected": false, "text": "<p>GUID is Microsoft's implementation of the UUID standard.</p>\n<p>Per <a href=\"https://en.wikipedia.org/w/index.php?title=Globally_unique_identifier&amp;oldid=760379804\" rel=\"noreferrer\" title=\"That bastion of all knowledge\">Wikipedia</a>:</p>\n<blockquote>\n<p>The term GUID usually refers to Microsoft's implementation of the <a href=\"http://en.wikipedia.org/wiki/Universally_unique_identifier\" rel=\"noreferrer\">Universally Unique Identifier</a> (UUID) standard.</p>\n</blockquote>\n<p>An updated quote from that same Wikipedia article:</p>\n<blockquote>\n<p>RFC 4122 itself states that UUIDs &quot;are also known as GUIDs&quot;. All this suggests that &quot;GUID&quot;, while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…</p>\n</blockquote>\n" }, { "answer_id": 246938, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": false, "text": "<p>Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the <em>urn:uuid:</em> URN scheme, and in CORBA).</p>\n" }, { "answer_id": 6953207, "author": "Hoylen", "author_id": 232064, "author_profile": "https://Stackoverflow.com/users/232064", "pm_score": 11, "selected": true, "text": "<p><strike>The <strong>simple answer</strong> is: **no difference, they are the same thing.</strike></p>\n<p><strong>2020-08-20 Update</strong>: While GUIDs (as used by Microsoft) and UUIDs (as defined by RFC4122) look similar and serve similar purposes, there are subtle-but-occasionally-important differences. Specifically, <a href=\"https://learn.microsoft.com/en-us/windows/win32/msi/guid\" rel=\"noreferrer\">some Microsoft GUID docs</a> allow GUIDs to contain any hex digit in any position, while RFC4122 requires certain values for the <code>version</code> and <code>variant</code> fields. Also, [per that same link], GUIDs should be all-upper case, whereas UUIDs <a href=\"https://www.rfc-editor.org/rfc/rfc4122#section-3\" rel=\"noreferrer\">should be</a> &quot;output as lower case characters and are case insensitive on input&quot;. This can lead to incompatibilities between code libraries (<a href=\"https://github.com/uuidjs/uuid/issues/511\" rel=\"noreferrer\">such as this</a>).</p>\n<p>(Original answer follows)</p>\n<hr />\n<p>Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak.</p>\n<p>Even the authors of the UUID specification and Microsoft claim they are synonyms:</p>\n<ul>\n<li><p>From the introduction to IETF <a href=\"https://datatracker.ietf.org/doc/html/rfc4122\" rel=\"noreferrer\">RFC 4122</a> &quot;<em>A Universally Unique IDentifier (UUID) URN Namespace</em>&quot;: &quot;a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier).&quot;</p>\n</li>\n<li><p>From the <a href=\"http://www.itu.int/ITU-T/studygroups/com17/oid.html\" rel=\"noreferrer\">ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard</a>: &quot;UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation.&quot;</p>\n</li>\n<li><p>And Microsoft even <a href=\"http://msdn.microsoft.com/en-us/library/cc246025%28v=PROT.13%29.aspx\" rel=\"noreferrer\">claims</a> a GUID is specified by the UUID RFC: &quot;In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID.&quot;</p>\n</li>\n</ul>\n<p>But the <strong>correct answer</strong> depends on what the question means when it says &quot;UUID&quot;...</p>\n<p>The first part depends on what the asker is thinking when they are saying &quot;UUID&quot;.</p>\n<p>Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set?</p>\n<p>Looking at the details of the RFC 4122, there are four different &quot;variants&quot; of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of <a href=\"https://datatracker.ietf.org/doc/html/rfc4122\" rel=\"noreferrer\">RFC 4122</a>, the four <em>variants</em> of UUID are:</p>\n<ol>\n<li>Reserved, Network Computing System backward compatibility</li>\n<li>The <em>variant</em> specified in RFC 4122 (of which there are five sub-variants, which are called &quot;versions&quot;)</li>\n<li>Reserved, Microsoft Corporation backward compatibility</li>\n<li>Reserved for future definition.</li>\n</ol>\n<p>According to RFC 4122, all UUID <em>variants</em> are &quot;real UUIDs&quot;, then all GUIDs are real UUIDs. To the literal question &quot;is there any difference between GUID and UUID&quot; the answer is definitely no for RFC 4122 UUIDs: <strong>no difference</strong> (but subject to the second part below).</p>\n<p>But not all GUIDs are <em>variant</em> 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was &quot;is there any difference between GUID and variant 2 UUIDs&quot;, then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about <em>variants</em> and they might be only thinking of <em>variant</em> 2 UUIDs when they say the word &quot;UUID&quot; (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both <em>versions</em> of <em>variant</em> 2). In which case, the answer is <strong>yes different</strong>.</p>\n<p>So the answer, in part, depends on what the person asking is thinking when they say the word &quot;UUID&quot;. Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs?</p>\n<p>The second part depends on which specification being used as the definition of UUID.</p>\n<p>If you think that was confusing, read the <a href=\"http://www.itu.int/ITU-T/studygroups/com17/oid.html\" rel=\"noreferrer\">ITU-T X.667 ISO/IEC 9834-8:2004</a> which is supposed to be aligned and fully technically compatible with <a href=\"https://datatracker.ietf.org/doc/html/rfc4122\" rel=\"noreferrer\">RFC 4122</a>. It has an extra sentence in Clause 11.2 that says, &quot;All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0&quot;. Which means that only <em>variant</em> 2 UUID conform to that Standard (those two bit values mean <em>variant</em> 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be <em>variant</em> 2 values.</p>\n<p>Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is <strong>no difference</strong> between GUID and IETF's UUIDs, but <strong>yes difference</strong> between GUID and <em>conforming</em> ITU-T/ISO/IEC's UUIDs!</p>\n<p><strong>Binary encodings could differ</strong></p>\n<p>When encoded in binary (as opposed to the human-readable text format), the GUID <a href=\"http://en.wikipedia.org/wiki/Globally_unique_identifier\" rel=\"noreferrer\">may be stored</a> in a structure with four different fields as follows. This format differs from the [UUID standard] <a href=\"https://www.rfc-editor.org/rfc/rfc4122\" rel=\"noreferrer\">8</a> only in the byte order of the first 3 fields.</p>\n<pre><code>Bits Bytes Name Endianness Endianness\n (GUID) RFC 4122\n\n32 4 Data1 Native Big\n16 2 Data2 Native Big\n16 2 Data3 Native Big\n64 8 Data4 Big Big\n</code></pre>\n" }, { "answer_id": 11348603, "author": "Tony Arcieri", "author_id": 448684, "author_profile": "https://Stackoverflow.com/users/448684", "pm_score": 3, "selected": false, "text": "<p>GUID has longstanding usage in areas where it isn't necessarily a 128-bit value in the same way as a UUID. For example, the <a href=\"http://cyber.law.harvard.edu/rss/rss.html#ltguidgtSubelementOfLtitemgt\" rel=\"noreferrer\">RSS specification defines GUIDs</a> to be any string of your choosing, as long as it's unique, with an \"isPermalink\" attribute to specify that the value you're using is just a permalink back to the item being syndicated.</p>\n" }, { "answer_id": 55876039, "author": "eezing", "author_id": 4740728, "author_profile": "https://Stackoverflow.com/users/4740728", "pm_score": 1, "selected": false, "text": "<p>One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.</p>\n<p>The hexadecimal values &quot;a&quot; through &quot;f&quot; are output as lower case characters and are case insensitive on input. - <a href=\"https://www.rfc-editor.org/rfc/rfc4122#section-3\" rel=\"nofollow noreferrer\">rfc4122#section-3</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
I see these two acronyms being thrown around and I was wondering if there are any differences between a GUID and a UUID?
The **simple answer** is: \*\*no difference, they are the same thing. **2020-08-20 Update**: While GUIDs (as used by Microsoft) and UUIDs (as defined by RFC4122) look similar and serve similar purposes, there are subtle-but-occasionally-important differences. Specifically, [some Microsoft GUID docs](https://learn.microsoft.com/en-us/windows/win32/msi/guid) allow GUIDs to contain any hex digit in any position, while RFC4122 requires certain values for the `version` and `variant` fields. Also, [per that same link], GUIDs should be all-upper case, whereas UUIDs [should be](https://www.rfc-editor.org/rfc/rfc4122#section-3) "output as lower case characters and are case insensitive on input". This can lead to incompatibilities between code libraries ([such as this](https://github.com/uuidjs/uuid/issues/511)). (Original answer follows) --- Treat them as a 16 byte (128 bits) value that is used as a unique value. In Microsoft-speak they are called GUIDs, but call them UUIDs when not using Microsoft-speak. Even the authors of the UUID specification and Microsoft claim they are synonyms: * From the introduction to IETF [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) "*A Universally Unique IDentifier (UUID) URN Namespace*": "a Uniform Resource Name namespace for UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier)." * From the [ITU-T Recommendation X.667, ISO/IEC 9834-8:2004 International Standard](http://www.itu.int/ITU-T/studygroups/com17/oid.html): "UUIDs are also known as Globally Unique Identifiers (GUIDs), but this term is not used in this Recommendation." * And Microsoft even [claims](http://msdn.microsoft.com/en-us/library/cc246025%28v=PROT.13%29.aspx) a GUID is specified by the UUID RFC: "In Microsoft Windows programming and in Windows operating systems, a globally unique identifier (GUID), as specified in [RFC4122], is ... The term universally unique identifier (UUID) is sometimes used in Windows protocol specifications as a synonym for GUID." But the **correct answer** depends on what the question means when it says "UUID"... The first part depends on what the asker is thinking when they are saying "UUID". Microsoft's claim implies that all UUIDs are GUIDs. But are all GUIDs real UUIDs? That is, is the set of all UUIDs just a proper subset of the set of all GUIDs, or is it the exact same set? Looking at the details of the RFC 4122, there are four different "variants" of UUIDs. This is mostly because such 16 byte identifiers were in use before those specifications were brought together in the creation of a UUID specification. From section 4.1.1 of [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122), the four *variants* of UUID are: 1. Reserved, Network Computing System backward compatibility 2. The *variant* specified in RFC 4122 (of which there are five sub-variants, which are called "versions") 3. Reserved, Microsoft Corporation backward compatibility 4. Reserved for future definition. According to RFC 4122, all UUID *variants* are "real UUIDs", then all GUIDs are real UUIDs. To the literal question "is there any difference between GUID and UUID" the answer is definitely no for RFC 4122 UUIDs: **no difference** (but subject to the second part below). But not all GUIDs are *variant* 2 UUIDs (e.g. Microsoft COM has GUIDs which are variant 3 UUIDs). If the question was "is there any difference between GUID and variant 2 UUIDs", then the answer would be yes -- they can be different. Someone asking the question probably doesn't know about *variants* and they might be only thinking of *variant* 2 UUIDs when they say the word "UUID" (e.g. they vaguely know of the MAC address+time and the random number algorithms forms of UUID, which are both *versions* of *variant* 2). In which case, the answer is **yes different**. So the answer, in part, depends on what the person asking is thinking when they say the word "UUID". Do they mean variant 2 UUID (because that is the only variant they are aware of) or all UUIDs? The second part depends on which specification being used as the definition of UUID. If you think that was confusing, read the [ITU-T X.667 ISO/IEC 9834-8:2004](http://www.itu.int/ITU-T/studygroups/com17/oid.html) which is supposed to be aligned and fully technically compatible with [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122). It has an extra sentence in Clause 11.2 that says, "All UUIDs conforming to this Recommendation | International Standard shall have variant bits with bit 7 of octet 7 set to 1 and bit 6 of octet 7 set to 0". Which means that only *variant* 2 UUID conform to that Standard (those two bit values mean *variant* 2). If that is true, then not all GUIDs are conforming ITU-T/ISO/IEC UUIDs, because conformant ITU-T/ISO/IEC UUIDs can only be *variant* 2 values. Therefore, the real answer also depends on which specification of UUID the question is asking about. Assuming we are clearly talking about all UUIDs and not just variant 2 UUIDs: there is **no difference** between GUID and IETF's UUIDs, but **yes difference** between GUID and *conforming* ITU-T/ISO/IEC's UUIDs! **Binary encodings could differ** When encoded in binary (as opposed to the human-readable text format), the GUID [may be stored](http://en.wikipedia.org/wiki/Globally_unique_identifier) in a structure with four different fields as follows. This format differs from the [UUID standard] [8](https://www.rfc-editor.org/rfc/rfc4122) only in the byte order of the first 3 fields. ``` Bits Bytes Name Endianness Endianness (GUID) RFC 4122 32 4 Data1 Native Big 16 2 Data2 Native Big 16 2 Data3 Native Big 64 8 Data4 Big Big ```
246,931
<p>I have two models, Article and Post that both inherit from a base model called ContentBase.</p> <p>You can leave comments on both Articles and Posts, so I am using a Polymorphic Association between Comments and Article or Post.</p> <p>However, since both Article and Post inherit from ContentBase, the commentable_type field ends up being "ContentBase" for both and screws everything up.</p> <p>Is there a way to specify the commentable_type field in the has_many relationship in Article and Post?</p> <p>Edit:</p> <p>By "screws everything up" I mean if there is an Article with ID=1 and Post with ID=1 and I add a Comment with commentable_id=1, commentable_type=ContentBase, that comment will show up for both the Article and Post.</p> <p>Here's the code:</p> <pre><code>class Article &lt; BaseContent has_many :comments, :as =&gt; :commentable end class Post &lt; BaseContent has_many :comments, :as =&gt; :commentable end </code></pre> <p>and here's my Comment model:</p> <pre><code>class Comment &lt; ActiveRecord::Base belongs_to :commentable, :polymorphic =&gt; true end </code></pre>
[ { "answer_id": 247445, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 1, "selected": false, "text": "<p>I don't think you want to do that. For polymorphic associations, you want the XXX_type field to be the base model class, not the actual class. I'm not exactly sure of the reason, but I believe it has to do with determining the table name to select from to get the polymorphic data.</p>\n\n<p>I think you need to look at Single Table Inheritance, which is what ActiveRecord uses for storing derived classes in the database. It assumes that since Article and Post are subclasses of ContentBase, they will all be in the same table (\"content_bases\" by default). If that's the case, you'll never have an Article with ID=1 and a Post with ID=1.</p>\n\n<p>A few references:</p>\n\n<ul>\n <li><a href=\"http://www.juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/\" rel=\"nofollow noreferrer\">Rails Single Table Inheritance | Juixe Technow</a> </li>\n <li><a href=\"http://wiki.rubyonrails.org/rails/pages/singletableinheritance\" rel=\"nofollow noreferrer\">Single Table Inheritance in Ruby on Rails</a></li>\n</ul>\n" }, { "answer_id": 247617, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 3, "selected": true, "text": "<p>What's in the ContentBase class? Can you move that code into a module instead of using inheritance?</p>\n\n<pre><code>Module BaseContent\n def self.included(base)\n base.class_eval do\n validates_presence_of :somefield\n validates_length_of :someotherfield\n\n def my_method\n \"hello\"\n end\n end\n end\n\nend\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396/" ]
I have two models, Article and Post that both inherit from a base model called ContentBase. You can leave comments on both Articles and Posts, so I am using a Polymorphic Association between Comments and Article or Post. However, since both Article and Post inherit from ContentBase, the commentable\_type field ends up being "ContentBase" for both and screws everything up. Is there a way to specify the commentable\_type field in the has\_many relationship in Article and Post? Edit: By "screws everything up" I mean if there is an Article with ID=1 and Post with ID=1 and I add a Comment with commentable\_id=1, commentable\_type=ContentBase, that comment will show up for both the Article and Post. Here's the code: ``` class Article < BaseContent has_many :comments, :as => :commentable end class Post < BaseContent has_many :comments, :as => :commentable end ``` and here's my Comment model: ``` class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end ```
What's in the ContentBase class? Can you move that code into a module instead of using inheritance? ``` Module BaseContent def self.included(base) base.class_eval do validates_presence_of :somefield validates_length_of :someotherfield def my_method "hello" end end end end ```
246,963
<p>Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users.</p> <p>Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere:</p> <pre><code> PermissionManager.getInstance().isReadPermissionEnabled(this) </code></pre> <p>But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.).</p> <p>So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?</p> <p>Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me?</p> <hr> <p><strong>Additional info</strong> Note that when I say "Dependency Injection", I'm talking about the DI <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">Pattern</a>...I am not using any DI framework like Guice or Spring. (...yet)</p>
[ { "answer_id": 246987, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 0, "selected": false, "text": "<p>The singleton pattern is not bad by itself, what makes it ugly is the way it's commonly used, as being the requirement of only wanting a single instance of a certain class, which I think it's a big mistake.</p>\n\n<p>In this case I'd make PermissionManager a static class unless for any reason you need it to be an instanciable type.</p>\n" }, { "answer_id": 247056, "author": "Eddie Deyo", "author_id": 9323, "author_profile": "https://Stackoverflow.com/users/9323", "pm_score": 3, "selected": true, "text": "<p>If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you. </p>\n\n<p>If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.</p>\n\n<p>You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).</p>\n\n<p>One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:</p>\n\n<pre><code>PermissionManager mManager = null;\npublic PermissionManager Permissions\n{\n if (mManager == null)\n {\n return mManager;\n }\n return PermissionManager.getInstance();\n}\n</code></pre>\n\n<p>Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and <strong>that's</strong> what your other class should reference so a dummy implementation can be substituted more easily during testing.</p>\n" }, { "answer_id": 247062, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 2, "selected": false, "text": "<p>You can indeed start by injecting the PermissionManager. This will make your class more testable.</p>\n\n<p>If this causes problems for the users of that class you can have them use a factory method or an abstract factory. Or you can add a parameterless constructor that for them to call that injects the PermissionManager while your tests use another constructor that you can use to mock the PermissionManager.</p>\n\n<p>Decoupling your classes more makes your classes more flexible but it can also make them harder to use. It depends on the situation what you'll need. If you only have one PermissionManager and have no problem testing the classes that use it then there's no reason to use DI. If you want people to be able to add their own PermissionManager implementation then DI is the way to go.</p>\n" }, { "answer_id": 247087, "author": "Mike Furtak", "author_id": 3005, "author_profile": "https://Stackoverflow.com/users/3005", "pm_score": 2, "selected": false, "text": "<p>If you are subscribing to the dependency injection way of doing things, whatever classes need your <code>PermissionManager</code> should have it injected as an object instance. The mechanism that controls its instantiation (to enforce the singleton nature) works at a higher level. If you use a dependency injection framework like Guice, it can do the enforcement work. If you are doing your object wiring by hand, dependency injection favors grouping code that does instantiation (new operator work) away from your business logic.</p>\n\n<p>Either way, though, the classic \"capital-S\" Singleton is generally seen as an anti-pattern in the context of dependency injection.</p>\n\n<p>These posts have been insightful for me in the past:</p>\n\n<ul>\n<li><a href=\"http://googletesting.blogspot.com/2008/05/tott-using-dependancy-injection-to.html\" rel=\"nofollow noreferrer\">Using Dependency Injection to Avoid Singletons</a></li>\n<li><a href=\"http://googletesting.blogspot.com/2008/07/how-to-think-about-new-operator-with.html\" rel=\"nofollow noreferrer\">How to Think About the \"new\" Operator with Respect to Unit Testing</a></li>\n</ul>\n" }, { "answer_id": 247140, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?</p>\n</blockquote>\n\n<p>Yes, this is all you need to do. Whether a dependency is a singleton / per request / per thread or a factory method is the responsibility of your container and configuration. In the .net world we would ideally have the dependency on an IPermissionsManager interface to further reduce coupling, I assume this is best practice in Java too.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users. Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere: ``` PermissionManager.getInstance().isReadPermissionEnabled(this) ``` But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.). So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application? Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me? --- **Additional info** Note that when I say "Dependency Injection", I'm talking about the DI [Pattern](http://en.wikipedia.org/wiki/Dependency_injection)...I am not using any DI framework like Guice or Spring. (...yet)
If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you. If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager. You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager). One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like: ``` PermissionManager mManager = null; public PermissionManager Permissions { if (mManager == null) { return mManager; } return PermissionManager.getInstance(); } ``` Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and **that's** what your other class should reference so a dummy implementation can be substituted more easily during testing.
246,966
<p>I've found that given a form in a HTML page like this:</p> <pre><code>&lt;form name="form"&gt; &lt;input type="image" name="foo" src="somewhere.gif" alt="image" value="blah"/&gt; &lt;input type="text" name="bar" value="blah"/&gt; &lt;/form&gt; </code></pre> <p>When accessing the elements via the DOM in Javascript, there is <em>no</em> element for the image input! It is just omitted. So, <code>document.forms[0].elements.length</code> is 1, and <code>document.forms[0].element[0].type</code> is "text".</p> <p>This seems to be the case in Firefox, and IE. I can't find this fact documented anywhere in my reference books or on the web. All I can find is a throwaway comment here:</p> <p><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4" rel="nofollow noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4</a></p> <p>Which suggests it "just is like this". If so, well so be it - but is it <em>really</em> not documented anywhere? Is it a historical mistake, or is there a reason for it?</p>
[ { "answer_id": 247002, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>It looks like that's the behavior of the <code>elements</code> property in all browsers.</p>\n\n<p>However, you should still be able to access it through the DOM in JavaScript using the <code>childNodes</code> property.</p>\n\n<p>For your example:</p>\n\n<pre><code>document.forms[0].childNodes.length; // equals 5 (2 inputs and 3 text nodes).\ndocument.forms[0].childNodes[1]; // This is your input with type='image'\n</code></pre>\n" }, { "answer_id": 247042, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>Interesting... the <a href=\"http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html\" rel=\"nofollow noreferrer\">DOM 1</a> spec defines <code>.elements</code> as:</p>\n\n<blockquote>\n <p>elements\n Returns a collection of all control elements in the form.</p>\n</blockquote>\n\n<p>The <a href=\"http://www.w3.org/TR/REC-html40/interact/forms.html#input-control-types\" rel=\"nofollow noreferrer\">HTML 4</a> spec part 17.2.1 doesn't list \"image\" types, so I guess that's the answer.</p>\n" }, { "answer_id": 247782, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Indeed, I see a comment: \"<em>The DOM is supposed to work that way, that's how it works in Mozilla, NS4x, and IE. We can't change that even if we wanted to, lots of sites would break.</em>\" so I would lean toward an historical error. Image element is already in HTML 2 DTD...</p>\n\n<p>Perhaps that's for that and possible other culprits that authors discourage using Dom hierarchy like that in favor of getElement[s]ByXxx functions (or XPath!).</p>\n" }, { "answer_id": 247799, "author": "David Grant", "author_id": 26829, "author_profile": "https://Stackoverflow.com/users/26829", "pm_score": 0, "selected": false, "text": "<p>Been bitten by it myself. It's <a href=\"http://msdn.microsoft.com/en-us/library/ie/hh826022(v=vs.85).aspx\" rel=\"nofollow noreferrer\">stated in the MSDN DHTML docs</a>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've found that given a form in a HTML page like this: ``` <form name="form"> <input type="image" name="foo" src="somewhere.gif" alt="image" value="blah"/> <input type="text" name="bar" value="blah"/> </form> ``` When accessing the elements via the DOM in Javascript, there is *no* element for the image input! It is just omitted. So, `document.forms[0].elements.length` is 1, and `document.forms[0].element[0].type` is "text". This seems to be the case in Firefox, and IE. I can't find this fact documented anywhere in my reference books or on the web. All I can find is a throwaway comment here: <https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4> Which suggests it "just is like this". If so, well so be it - but is it *really* not documented anywhere? Is it a historical mistake, or is there a reason for it?
It looks like that's the behavior of the `elements` property in all browsers. However, you should still be able to access it through the DOM in JavaScript using the `childNodes` property. For your example: ``` document.forms[0].childNodes.length; // equals 5 (2 inputs and 3 text nodes). document.forms[0].childNodes[1]; // This is your input with type='image' ```
246,969
<p>I want to do something like this:</p> <pre><code>const MyFirstConstArray: array[0..1] of string = ('Hi', 'Foo'); MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = MyFirstConstArray + ('Bar'); </code></pre> <p>Basically I want the following result:</p> <pre><code>MyFirstConstArray -&gt; ('Hi', 'Foo'); MySecondConstArrayWhichIncludesTheFirstOne -&gt; ('Hi', 'Foo', 'Bar'); </code></pre> <p>Is it possible somehow?</p>
[ { "answer_id": 247063, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 0, "selected": false, "text": "<p>I don't think so. You'll have to do it in code. If these are global constants, you can do the initialization in the 'initialization' section of the unit.</p>\n" }, { "answer_id": 247618, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 3, "selected": true, "text": "<p>AFAIK, you can't do that.<br>\nBut if the goal is to ensure you declare your actual constant string only once, I suggest you declare the individual strings and then group them in arrays: </p>\n\n<pre><code>const\n MyConst1 = 'Hi';\n MyConst2 = 'Foo';\n MyConst3 = 'Bar';\n MyFirstConstArray: array[0..1] of string = (MyConst1, MyConst2);\n MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = \n (MyConst1, MyConst2, MyConst3);\n</code></pre>\n\n<p>BTW, your syntax is incorrect, you have to precise the type of the array elements.</p>\n" }, { "answer_id": 247672, "author": "X-Ray", "author_id": 14031, "author_profile": "https://Stackoverflow.com/users/14031", "pm_score": 1, "selected": false, "text": "<p>Actually, you can but do it using records. i use this technique in a big way for creating definitions for certain behaviours of entities in my software. it's a very powerful technique:</p>\n\n<pre><code>type\n TPerson=record\n // generally you'd put all kinds of addition stuff here including enums, \n // sets, etc\n saPets:array[0..2] of string;\n end;\n\nconst\n scDog='Dog';\n\n MyPeople:array[0..1] of TPerson=\n ((saPets:(scDog, 'Cat', 'Fish'); ),\n (saPets:('Iguana', 'Tarantula', ''); ));\n\nbegin\n ShowMessage(MyPeople[0].saPets[0]);\n\nend;\n</code></pre>\n\n<p>one thing you can't do with it is refer to resource strings. therefore any translation must be done by the code that retrieves the value. i generally index them with enums--in doing so, i can make the software easier to change because it won't compile if i've left something important out.</p>\n" }, { "answer_id": 255093, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "<p>If order isn't relevant, then use enumerated sets.</p>\n\n<pre><code>type\n TMyConsts = (tConstFoo, tConstHi, TConstBar);\nconst\n MyFirstConstSet = [tConstFoo, tConstHi];\n MySecondConstSet = MyFirstConstSet + [TConstBar];\n MyConstStrings: array[TMyConsts] of string = ('Foo', 'Hi', 'Bar');\n</code></pre>\n\n<p>You can use the <em>MyConstStrings</em> array to resolve your enumerations into strings if you want. Depends on your objective. </p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
I want to do something like this: ``` const MyFirstConstArray: array[0..1] of string = ('Hi', 'Foo'); MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = MyFirstConstArray + ('Bar'); ``` Basically I want the following result: ``` MyFirstConstArray -> ('Hi', 'Foo'); MySecondConstArrayWhichIncludesTheFirstOne -> ('Hi', 'Foo', 'Bar'); ``` Is it possible somehow?
AFAIK, you can't do that. But if the goal is to ensure you declare your actual constant string only once, I suggest you declare the individual strings and then group them in arrays: ``` const MyConst1 = 'Hi'; MyConst2 = 'Foo'; MyConst3 = 'Bar'; MyFirstConstArray: array[0..1] of string = (MyConst1, MyConst2); MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = (MyConst1, MyConst2, MyConst3); ``` BTW, your syntax is incorrect, you have to precise the type of the array elements.
246,977
<p>I recently read that using flexible array members in C was poor software engineering practice. However, that statement was not backed by any argument. Is this an accepted fact?</p> <p>(<a href="https://en.wikipedia.org/wiki/Flexible_array_member" rel="noreferrer">Flexible array members</a> are a C feature introduced in C99 whereby one can declare the last element to be an array of unspecified size. For example: )</p> <pre><code>struct header { size_t len; unsigned char data[]; }; </code></pre>
[ { "answer_id": 247038, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "<p>You meant...</p>\n\n<pre><code>struct header\n{\n size_t len;\n unsigned char data[];\n}; \n</code></pre>\n\n<p>In C, that's a common idiom. I think many compilers also accept:</p>\n\n<pre><code> unsigned char data[0];\n</code></pre>\n\n<p>Yes, it's dangerous, but then again, it's really no more dangerous than normal C arrays - i.e., VERY dangerous ;-) . Use it with care and only in circumstances where you truly need an array of unknown size. Make sure you malloc and free the memory correctly, using something like:-</p>\n\n<pre><code> foo = malloc(sizeof(header) + N * sizeof(data[0]));\n foo-&gt;len = N;\n</code></pre>\n\n<p>An alternative is to make data just be a pointer to the elements. You can then realloc() data to the correct size as required.</p>\n\n<pre><code> struct header\n {\n size_t len;\n unsigned char *data;\n }; \n</code></pre>\n\n<p>Of course, if you were asking about C++, either of these would be bad practice. Then you'd typically use STL vectors instead.</p>\n" }, { "answer_id": 247039, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 5, "selected": false, "text": "<p>It is an accepted \"fact\" that using goto is poor software engineering practice. That doesn't make it true. There are times when goto is useful, particularly when handling cleanup and when porting from assembler. </p>\n\n<p>Flexible array members strike me as having one main use, off the top of my head, which is mapping legacy data formats like window template formats on RiscOS. They would have been supremely useful for this about 15 years ago, and I'm sure there are still people out there dealing with such things who would find them useful.</p>\n\n<p>If using flexible array members is bad practice, then I suggest that we all go tell the authors of the C99 spec this. I suspect they might have a different answer.</p>\n" }, { "answer_id": 247040, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 4, "selected": false, "text": "<p><strong>PLEASE READ CAREFULLY THE COMMENTS BELOW THIS ANSWER</strong></p>\n\n<p><em>As C Standardization move forward there is no reason to use [1] anymore.</em></p>\n\n<p>The reason I would give for not doing it is that it's not worth it to tie your code to C99 just to use this feature.</p>\n\n<p>The point is that you can always use the following idiom:</p>\n\n<pre><code>struct header {\n size_t len;\n unsigned char data[1];\n};\n</code></pre>\n\n<p>That is fully portable. Then you can take the 1 into account when allocating the memory for n elements in the array <code>data</code> :</p>\n\n<pre><code>ptr = malloc(sizeof(struct header) + (n-1));\n</code></pre>\n\n<p>If you already have C99 as requirement to build your code for any other reason or you are target a specific compiler, I see no harm.</p>\n" }, { "answer_id": 888252, "author": "diapir", "author_id": 108172, "author_profile": "https://Stackoverflow.com/users/108172", "pm_score": 3, "selected": false, "text": "<p>As a side note, for C89 compatibility, such structure should be allocated like :</p>\n\n<pre><code>struct header *my_header\n = malloc(offsetof(struct header, data) + n * sizeof my_header-&gt;data);\n</code></pre>\n\n<p>Or with macros :</p>\n\n<pre><code>#define FLEXIBLE_SIZE SIZE_MAX /* or whatever maximum length for an array */\n#define SIZEOF_FLEXIBLE(type, member, length) \\\n ( offsetof(type, member) + (length) * sizeof ((type *)0)-&gt;member[0] )\n\nstruct header {\n size_t len;\n unsigned char data[FLEXIBLE_SIZE];\n};\n\n...\n\nsize_t n = 123;\nstruct header *my_header = malloc(SIZEOF_FLEXIBLE(struct header, data, n));\n</code></pre>\n\n<p>Setting FLEXIBLE_SIZE to SIZE_MAX almost ensures this will fail :</p>\n\n<pre><code>struct header *my_header = malloc(sizeof *my_header);\n</code></pre>\n" }, { "answer_id": 2948597, "author": "Nyan", "author_id": 210946, "author_profile": "https://Stackoverflow.com/users/210946", "pm_score": 3, "selected": false, "text": "<p>I've seen something like this:\nfrom C interface and implementation.</p>\n\n<pre><code> struct header {\n size_t len;\n unsigned char *data;\n};\n\n struct header *p;\n p = malloc(sizeof(*p) + len + 1 );\n p-&gt;data = (unsigned char*) (p + 1 ); // memory after p is mine! \n</code></pre>\n\n<p>Note: data need not be last member.</p>\n" }, { "answer_id": 22143014, "author": "wds", "author_id": 10098, "author_profile": "https://Stackoverflow.com/users/10098", "pm_score": 3, "selected": false, "text": "<p>There are some downsides related to how structs are sometimes used, and it can be dangerous if you don't think through the implications.</p>\n<p>For your example, if you start a function:</p>\n<pre><code>void test(void) {\n struct header;\n char *p = &amp;header.data[0];\n\n ...\n}\n</code></pre>\n<p>Then the results are undefined (since no storage was ever allocated for data). This is something that you will normally be aware of, but there are cases where C programmers are likely used to being able to use value semantics for structs, which breaks down in various other ways.</p>\n<p>For instance, if I define:</p>\n<pre><code>struct header2 {\n int len;\n char data[MAXLEN]; /* MAXLEN some appropriately large number */\n}\n</code></pre>\n<p>Then I can copy two instances simply by assignment, i.e.:</p>\n<pre><code>struct header2 inst1 = inst2;\n</code></pre>\n<p>Or if they are defined as pointers:</p>\n<pre><code>struct header2 *inst1 = *inst2;\n</code></pre>\n<p>This however won't work for flexible array members, since their content is not copied over. What you want is to dynamically malloc the size of the struct and copy over the array with <code>memcpy</code> or equivalent.</p>\n<pre><code>struct header3 {\n int len;\n char data[]; /* flexible array member */\n}\n</code></pre>\n<p>Likewise, writing a function that accepts a <code>struct header3</code> will not work, since arguments in function calls are, again, copied by value, and thus what you will get is likely only the first element of your flexible array member.</p>\n<pre><code> void not_good ( struct header3 ) ;\n</code></pre>\n<p>This does not make it a bad idea to use, but you do have to keep in mind to always dynamically allocate these structures and only pass them around as pointers.</p>\n<pre><code> void good ( struct header3 * ) ;\n</code></pre>\n" }, { "answer_id": 46251908, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 5, "selected": false, "text": "<p>No, using <a href=\"https://en.wikipedia.org/wiki/Flexible_array_member\" rel=\"noreferrer\">flexible array members</a> in C is not bad practice.</p>\n<p>This language feature was first standardized in ISO C99, 6.7.2.1 (16). In the following revision, ISO C11, it is specified in Section 6.7.2.1 (18).</p>\n<p>You can use them like this:</p>\n<pre><code>struct Header {\n size_t d;\n long v[];\n};\ntypedef struct Header Header;\nsize_t n = 123; // can dynamically change during program execution\n// ...\nHeader *h = malloc(sizeof(Header) + sizeof(long[n]));\nh-&gt;n = n;\n</code></pre>\n<p>Alternatively, you can allocate like this:</p>\n<pre><code>Header *h = malloc(sizeof *h + n * sizeof h-&gt;v[0]);\n</code></pre>\n<p>Note that <code>sizeof(Header)</code> includes eventual padding bytes, thus, the following allocation is incorrect and may yield a buffer overflow:</p>\n<pre><code>Header *h = malloc(sizeof(size_t) + sizeof(long[n])); // invalid!\n</code></pre>\n<p>A struct with a flexible array members reduces the number of allocations for it by 1/2, i.e. instead of 2 allocations for one struct object you need just 1. Meaning less effort and less memory occupied by memory allocator bookkeeping overhead. Furthermore, you save the storage for one additional pointer. Thus, if you have to allocate a large number of such struct instances you measurably improve the runtime and memory usage of your program (by a constant factor).</p>\n<p>In contrast to that, using non-standardized constructs for flexible array members that yield undefined behavior (e.g. as in <code>long v[0];</code> or <code>long v[1];</code>) obviously is bad practice. Thus, as any undefined-behaviour this should be avoided.</p>\n<p>Since ISO C99 was released in 1999, more than 20 years ago, striving for ISO C89 compatibility is a weak argument.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I recently read that using flexible array members in C was poor software engineering practice. However, that statement was not backed by any argument. Is this an accepted fact? ([Flexible array members](https://en.wikipedia.org/wiki/Flexible_array_member) are a C feature introduced in C99 whereby one can declare the last element to be an array of unspecified size. For example: ) ``` struct header { size_t len; unsigned char data[]; }; ```
It is an accepted "fact" that using goto is poor software engineering practice. That doesn't make it true. There are times when goto is useful, particularly when handling cleanup and when porting from assembler. Flexible array members strike me as having one main use, off the top of my head, which is mapping legacy data formats like window template formats on RiscOS. They would have been supremely useful for this about 15 years ago, and I'm sure there are still people out there dealing with such things who would find them useful. If using flexible array members is bad practice, then I suggest that we all go tell the authors of the C99 spec this. I suspect they might have a different answer.
246,981
<p>Does anyone have any idea what is wrong with this create statement for mysql? </p> <p>EDIT: now it states the error is near: revised VARCHAR(20), paypal_accept TINYINT, pre_terminat' at line 4</p> <p>Thanks for the help everyone</p> <p>Still errors after using sql beautifier though</p> <pre><code>CREATE TABLE AUCTIONS ( ARTICLE_NO VARCHAR(20), ARTICLE_NAME VARCHAR(100), SUBTITLE VARCHAR(20), CURRENT_BID VARCHAR(20), START_PRICE VARCHAR(20), BID_COUNT VARCHAR(20), QUANT_TOTAL VARCHAR(20), QUANT_SOLD VARCHAR(20), START DATETIME, ENDS DATETIME, ORIGIN_END DATETIME, SELLER_ID VARCHAR(20), BEST_BIDDER_ID VARCHAR(20), FINISHED VARCHAR(20), WATCH VARCHAR(20), BUYITNOW_PRICE VARCHAR(20), PIC_URL VARCHAR(20), PRIVATE_AUCTION VARCHAR(20), AUCTION_TYPE VARCHAR(20), INSERT_DATE DATETIME, UPDATE_DATE DATETIME, CAT_1_ID VARCHAR(20), CAT_2_ID VARCHAR(20), ARTICLE_DESC VARCHAR(20), DESC_TEXTONLY VARCHAR(20), COUNTRYCODE VARCHAR(20), LOCATION VARCHAR(20), CONDITION VARCHAR(20), REVISED VARCHAR(20), PAYPAL_ACCEPT TINYINT, PRE_TERMINATED VARCHAR(20), SHIPPING_TO VARCHAR(20), FEE_INSERTION VARCHAR(20), FEE_FINAL VARCHAR(20), FEE_LISTING VARCHAR(20), PIC_XXL TINYINT, PIC_DIASHOW TINYINT, PIC_COUNT VARCHAR(20), ITEM_SITE_ID VARCHAR(20), PRIMARY KEY ( `ARTICLE_NO` )); </code></pre> <p>The error is now near 'CONDITION VARCHAR(20), REVISED VARCHAR(20), PAYPAL_ACCEPT TI' at line 29</p> <p>I really can't see what is wrong, does TINYINT need a parameter?</p> <p>Do MYSQL column names have to be capitals?</p>
[ { "answer_id": 246993, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 1, "selected": false, "text": "<p>\"VARCHAR(20),\" doesn't assign a name.</p>\n" }, { "answer_id": 246996, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 3, "selected": false, "text": "<pre><code>watch VARCHAR(20), **????** VARCHAR(20), \nauction_type VARCHAR(20),\n</code></pre>\n\n<p>Between watch and auction_type you have missed a column name. Only the varchar(20) is there, either delete that or add in missing column name.</p>\n" }, { "answer_id": 247061, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 0, "selected": false, "text": "<p>The answer about the missing field name is correct (would vote it up if I had the rep) but I would also recommend placing the following line after 'cat_2_id VARCHAR(20)':</p>\n\n<pre><code>PRIMARY KEY (`article_no`)\n</code></pre>\n" }, { "answer_id": 247075, "author": "andy", "author_id": 32033, "author_profile": "https://Stackoverflow.com/users/32033", "pm_score": 2, "selected": false, "text": "<p>From the end: </p>\n\n<blockquote>\n <p><code>pic_count VARCHAR(20),item_site_id);</code></p>\n</blockquote>\n\n<p><code>item_site_id</code> doesn't seem to have a type. Give it a type and your query validates...</p>\n\n<p>(Test it here: <a href=\"http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl\" rel=\"nofollow noreferrer\">http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl</a> for finding these kinds of errors)</p>\n" }, { "answer_id": 247100, "author": "Dave", "author_id": 21294, "author_profile": "https://Stackoverflow.com/users/21294", "pm_score": 2, "selected": false, "text": "<p>The formatting.</p>\n" }, { "answer_id": 247121, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 2, "selected": false, "text": "<p>Tip: <strong>Format code for readability</strong>.</p>\n\n<p>I take your code and apply simple formatting...</p>\n\n<pre><code>CREATE TABLE auctions (\n article_no VARCHAR(20),\n article_name VARCHAR(100),\n subtitle VARCHAR(20),\n current_bid VARCHAR(20),\n start_price VARCHAR(20),\n bid_count VARCHAR(20),\n quant_total VARCHAR(20),\n quant_sold VARCHAR(20),\n start DATETIME,\n ends DATETIME,\n origin_end DATETIME,\n seller_id VARCHAR(20),\n best_bidder_id VARCHAR(20),\n finished VARCHAR(20),\n watch VARCHAR(20),\n buyitnow_price VARCHAR(20),\n pic_url VARCHAR(20),\n private_auction VARCHAR(20),\n auction_type VARCHAR(20),\n insert_date DATETIME,\n update_date DATETIME,\n cat_1_id VARCHAR(20),\n cat_2_id VARCHAR(20),\n article_desc VARCHAR(20),\n desc_textonly VARCHAR(20),\n countrycode VARCHAR(20),\n location VARCHAR(20),\n condition VARCHAR(20),\n revised VARCHAR(20),\n paypal_accept TINYINT,\n pre_terminated VARCHAR(20),\n shipping_to VARCHAR(20),\n fee_insertion VARCHAR(20),\n fee_final VARCHAR(20),\n fee_listing VARCHAR(20),\n pic_xxl TINYINT,\n pic_diashow TINYINT,\n pic_count VARCHAR(20),\n item_site_id\n);\n</code></pre>\n\n<p>...and straight away I can see <strong>item_site_id</strong> is missing a data type.</p>\n" }, { "answer_id": 247208, "author": "JGW", "author_id": 26288, "author_profile": "https://Stackoverflow.com/users/26288", "pm_score": 3, "selected": true, "text": "<p>I believe the column names \"START\" and \"CONDITION\" are 'special' words in MySQL? All I did was simply paste the beautified code into Query Browser and noticed that some column names were 'blue'... :P</p>\n" }, { "answer_id": 247359, "author": "grammar31", "author_id": 12815, "author_profile": "https://Stackoverflow.com/users/12815", "pm_score": 2, "selected": false, "text": "<p>According to the list of <a href=\"http://dev.mysql.com/doc/mysqld-version-reference/en/mysqld-version-reference-reservedwords-5-0.html\" rel=\"nofollow noreferrer\">MySQL Reserved Keywords</a>, <code>CONDITION</code> is a reserved keyword, and you must escape it (using back-ticks) to use it as the name of an object (e.g. table, column, etc.). </p>\n\n<p>I would recommend against using a reserved keyword as a name of a column (even if you escaped it) because that causes all sorts of problems when writing queries in the future.</p>\n" }, { "answer_id": 247377, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>Check your column names against the list of MySQL reserved words:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html</a></p>\n\n<p>You'll see that <code>CONDITION</code> is a reserved word. You can use MySQL reserved words for column names, but you have to enclose them in back-quotes to clearly tell MySQL that you're not using the word in its conventional use.</p>\n\n<pre><code>. . .\nLOCATION VARCHAR(20),\n`CONDITION` VARCHAR(20),\nREVISED VARCHAR(20),\n. . .\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
Does anyone have any idea what is wrong with this create statement for mysql? EDIT: now it states the error is near: revised VARCHAR(20), paypal\_accept TINYINT, pre\_terminat' at line 4 Thanks for the help everyone Still errors after using sql beautifier though ``` CREATE TABLE AUCTIONS ( ARTICLE_NO VARCHAR(20), ARTICLE_NAME VARCHAR(100), SUBTITLE VARCHAR(20), CURRENT_BID VARCHAR(20), START_PRICE VARCHAR(20), BID_COUNT VARCHAR(20), QUANT_TOTAL VARCHAR(20), QUANT_SOLD VARCHAR(20), START DATETIME, ENDS DATETIME, ORIGIN_END DATETIME, SELLER_ID VARCHAR(20), BEST_BIDDER_ID VARCHAR(20), FINISHED VARCHAR(20), WATCH VARCHAR(20), BUYITNOW_PRICE VARCHAR(20), PIC_URL VARCHAR(20), PRIVATE_AUCTION VARCHAR(20), AUCTION_TYPE VARCHAR(20), INSERT_DATE DATETIME, UPDATE_DATE DATETIME, CAT_1_ID VARCHAR(20), CAT_2_ID VARCHAR(20), ARTICLE_DESC VARCHAR(20), DESC_TEXTONLY VARCHAR(20), COUNTRYCODE VARCHAR(20), LOCATION VARCHAR(20), CONDITION VARCHAR(20), REVISED VARCHAR(20), PAYPAL_ACCEPT TINYINT, PRE_TERMINATED VARCHAR(20), SHIPPING_TO VARCHAR(20), FEE_INSERTION VARCHAR(20), FEE_FINAL VARCHAR(20), FEE_LISTING VARCHAR(20), PIC_XXL TINYINT, PIC_DIASHOW TINYINT, PIC_COUNT VARCHAR(20), ITEM_SITE_ID VARCHAR(20), PRIMARY KEY ( `ARTICLE_NO` )); ``` The error is now near 'CONDITION VARCHAR(20), REVISED VARCHAR(20), PAYPAL\_ACCEPT TI' at line 29 I really can't see what is wrong, does TINYINT need a parameter? Do MYSQL column names have to be capitals?
I believe the column names "START" and "CONDITION" are 'special' words in MySQL? All I did was simply paste the beautified code into Query Browser and noticed that some column names were 'blue'... :P
246,983
<p>What's the most efficient way of getting the value of the SERIAL column after the INSERT statement? I.e. I am looking for a way to replicate <code>@@IDENTITY</code> or <code>SCOPE_IDENTITY</code> functionality of MS SQL</p>
[ { "answer_id": 247159, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": false, "text": "<p>I have seen this used.</p>\n<pre><code>if LOCAL_SQLCA^.sqlcode = 0 then\n/* return serial */\n Result := LOCAL_SQLCA^.sqlerrd[1]\nelse\n/* return error code */\n Result := -(Abs(LOCAL_SQLCA^.sqlcode));\n</code></pre>\n" }, { "answer_id": 248663, "author": "Jody", "author_id": 10235, "author_profile": "https://Stackoverflow.com/users/10235", "pm_score": -1, "selected": false, "text": "<p>I don't think \"efficient\" is the word you're looking for here. It's more of a question of accuracy. I'm not sure I can do a better job of explaining it than the SQL Books Online can, but generally, unless you really know what you're doing and have a specific reason for using @@IDENTITY, use SCOPE_IDENTITY. The most obvious reason for this is that @@IDENTITY will not return the identity of the latest record added by your program/sp/etc if there is a trigger attached to the table. Also, there could be issues in high volume applications where two transactions occur at the same time and the following would occur...</p>\n\n<ol>\n<li>Your insert</li>\n<li>Other user's insert</li>\n<li>Return other user's identity to you</li>\n</ol>\n" }, { "answer_id": 252433, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 5, "selected": true, "text": "<p>The value of the last SERIAL insert is stored in the SQLCA record, as the second entry in the sqlerrd array. Brian's answer is correct for ESQL/C, but you haven't mentioned what language you're using.</p>\n\n<p>If you're writing a stored procedure, the value can be found thus:</p>\n\n<pre><code>LET new_id = DBINFO('sqlca.sqlerrd1');\n</code></pre>\n\n<p>It can also be found in <code>$sth-&gt;{ix_sqlerrd}[1]</code> if using DBI</p>\n\n<p>There are variants for other languages/interfaces, but I'm sure you'll get the idea.</p>\n" }, { "answer_id": 2122187, "author": "FrankRuperto", "author_id": 366797, "author_profile": "https://Stackoverflow.com/users/366797", "pm_score": -1, "selected": false, "text": "<p>The OP did not specify which version of Informix is being used, so there can be different answers</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/246983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15329/" ]
What's the most efficient way of getting the value of the SERIAL column after the INSERT statement? I.e. I am looking for a way to replicate `@@IDENTITY` or `SCOPE_IDENTITY` functionality of MS SQL
The value of the last SERIAL insert is stored in the SQLCA record, as the second entry in the sqlerrd array. Brian's answer is correct for ESQL/C, but you haven't mentioned what language you're using. If you're writing a stored procedure, the value can be found thus: ``` LET new_id = DBINFO('sqlca.sqlerrd1'); ``` It can also be found in `$sth->{ix_sqlerrd}[1]` if using DBI There are variants for other languages/interfaces, but I'm sure you'll get the idea.
247,006
<p>I've got a PHP application which needs to grab the contents from another web page, and the web page I'm reading needs a cookie.</p> <p>I've found info on how to make this call once i have the cookie ( <a href="http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a" rel="nofollow noreferrer">http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a</a> ), however I've no idea how to generate the cookie, or how / where the cookie is saved.</p> <p>For example, to read this web page via wget I do the following:</p> <pre><code>wget --quiet --save-cookies cookie.file --output-document=who.cares \ http://remoteServer/login.php?user=xxx&amp;pass=yyy wget --quiet --load-cookies cookie.file --output-document=documentiwant.html \ http://remoteServer/pageicareabout.html </code></pre> <p>... my question is how do I do the '--save-cookies' bit in PHP so that I can use the cookie in the follow-up PHP stream_context_create / file_get_contents block:</p> <pre><code>$opts = array(http'=&gt; array( 'method'=&gt; "GET", 'header'=&gt; "Accept-language: en\r\n" . "Cookie: **NoClueAtAll**\r\n" ) ); $context = stream_context_create($opts); $documentiwant = file_get_contents("http://remoteServer/pageicareabout.html", 0, $context); </code></pre>
[ { "answer_id": 247080, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "<p>You'd probably be better off using <a href=\"http://www.php.net/curl\" rel=\"noreferrer\">cURL</a>.\nUse <a href=\"http://www.php.net/manual/en/function.curl-setopt.php\" rel=\"noreferrer\">curl_setopt</a> to set up the cookie handling options.</p>\n\n<p>If this is just a one-off thing, you could use Firefox with <a href=\"http://livehttpheaders.mozdev.org/\" rel=\"noreferrer\">Live HTTP Headers</a> to get the header, then paste it into your PHP code.</p>\n" }, { "answer_id": 247472, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><strong>Shazam</strong> - that worked ! Thx soooo much ! In case someone else stumbles upon this page, here's what was needed in detail:</p>\n\n<ol>\n<li>install cURL (for me it'was as\nsimple as 'sudo apt-get install\nphp5-curl' in ubuntu)</li>\n<li><p>change the\nprior-listed PHP to the following:</p>\n\n<pre><code>&lt;?php\n\n$cr = curl_init('http://remoteServer/login.php?user=xxx&amp;pass=yyy');\ncurl_setopt($cr, CURLOPT_RETURNTRANSFER, true); \ncurl_setopt($cr, CURLOPT_COOKIEJAR, 'cookie.txt'); \n$whoCares = curl_exec($cr); \ncurl_close($cr); \n\n$cr = curl_init('http://remoteServer/pageicareabout.html');\ncurl_setopt($cr, CURLOPT_RETURNTRANSFER, true); \ncurl_setopt($cr, CURLOPT_COOKIEFILE, 'cookie.txt'); \n$documentiwant = curl_exec($cr);\ncurl_close($cr);\n\n?&gt;\n</code></pre></li>\n</ol>\n\n<p>Above code snippet heavily influenced by <a href=\"http://www.weberdev.com/get_example-4555.html\" rel=\"noreferrer\">http://www.weberdev.com/get_example-4555.html</a>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a PHP application which needs to grab the contents from another web page, and the web page I'm reading needs a cookie. I've found info on how to make this call once i have the cookie ( <http://groups.google.com/group/comp.lang.php/msg/4f618114ab15ae2a> ), however I've no idea how to generate the cookie, or how / where the cookie is saved. For example, to read this web page via wget I do the following: ``` wget --quiet --save-cookies cookie.file --output-document=who.cares \ http://remoteServer/login.php?user=xxx&pass=yyy wget --quiet --load-cookies cookie.file --output-document=documentiwant.html \ http://remoteServer/pageicareabout.html ``` ... my question is how do I do the '--save-cookies' bit in PHP so that I can use the cookie in the follow-up PHP stream\_context\_create / file\_get\_contents block: ``` $opts = array(http'=> array( 'method'=> "GET", 'header'=> "Accept-language: en\r\n" . "Cookie: **NoClueAtAll**\r\n" ) ); $context = stream_context_create($opts); $documentiwant = file_get_contents("http://remoteServer/pageicareabout.html", 0, $context); ```
You'd probably be better off using [cURL](http://www.php.net/curl). Use [curl\_setopt](http://www.php.net/manual/en/function.curl-setopt.php) to set up the cookie handling options. If this is just a one-off thing, you could use Firefox with [Live HTTP Headers](http://livehttpheaders.mozdev.org/) to get the header, then paste it into your PHP code.
247,023
<p>I have a structure like this:</p> <pre><code>&lt;ul&gt; &lt;li&gt;text1&lt;/li&gt; &lt;li&gt;text2&lt;/li&gt; &lt;li&gt;text3&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>How do I use javascript or jQuery to get the text as an array?</p> <pre><code>['text1', 'text2', 'text3'] </code></pre> <p>My plan after this is to assemble it into a string, probably using <code>.join(', ')</code>, and get it in a format like this:</p> <pre><code>'"text1", "text2", "text3"' </code></pre>
[ { "answer_id": 247057, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 8, "selected": true, "text": "<pre><code>var optionTexts = [];\n$(\"ul li\").each(function() { optionTexts.push($(this).text()) });\n</code></pre>\n\n<p>...should do the trick. To get the final output you're looking for, <code>join()</code> plus some concatenation will do nicely:</p>\n\n<pre><code>var quotedCSV = '\"' + optionTexts.join('\", \"') + '\"';\n</code></pre>\n" }, { "answer_id": 247067, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": false, "text": "<pre><code>var arr = new Array();\n\n$('li').each(function() { \n arr.push(this.innerHTML); \n})\n</code></pre>\n" }, { "answer_id": 247203, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 4, "selected": false, "text": "<p>And in clean javascript:</p>\n\n<pre><code>var texts = [], lis = document.getElementsByTagName(\"li\");\nfor(var i=0, im=lis.length; im&gt;i; i++)\n texts.push(lis[i].firstChild.nodeValue);\n\nalert(texts);\n</code></pre>\n" }, { "answer_id": 5196124, "author": "kimstik", "author_id": 645031, "author_profile": "https://Stackoverflow.com/users/645031", "pm_score": 6, "selected": false, "text": "<p>Without redundant intermediate arrays:</p>\n<pre><code>var arr = $('li').map(function(i,el) {\n return $(el).text();\n}).get();\n</code></pre>\n<p>See jsfiddle <a href=\"http://jsfiddle.net/cC8fT/\" rel=\"nofollow noreferrer\">demo</a></p>\n" }, { "answer_id": 7518268, "author": "Cybolic", "author_id": 242846, "author_profile": "https://Stackoverflow.com/users/242846", "pm_score": 4, "selected": false, "text": "<p>kimstik was close, but not quite.</p>\n\n<p>Here's how to do it in a convenient one-liner:</p>\n\n<pre><code>$.map( $('li'), function (element) { return $(element).text() });\n</code></pre>\n\n<p>Here's the full documentation for jQuery's map function, it's quite handy: <a href=\"http://api.jquery.com/jQuery.map/\" rel=\"noreferrer\">http://api.jquery.com/jQuery.map/</a></p>\n\n<p>Just to answer fully, here's the complete functionality you were looking for:</p>\n\n<pre><code>$.map( $('li'), function (element) { return $(element).text() }).join(', ');\n</code></pre>\n" }, { "answer_id": 54793123, "author": "noone", "author_id": 5229871, "author_profile": "https://Stackoverflow.com/users/5229871", "pm_score": 2, "selected": false, "text": "<p>You may do as follows. \none line of code will be enough </p>\n\n<ul>\n<li><code>let array = $('ul&gt;li').toArray().map(item =&gt; $(item).html());</code></li>\n<li><p>Get the interested element</p>\n\n<ol>\n<li><p>get children</p></li>\n<li><p>get the array from toArray() method</p></li>\n<li><p>filter out the results you want</p></li>\n</ol></li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let array = $('ul&gt;li').toArray().map(item =&gt; $(item).html());\r\nconsole.log(array);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;ul&gt;\r\n &lt;li&gt;text1&lt;/li&gt;\r\n &lt;li&gt;text2&lt;/li&gt;\r\n &lt;li&gt;text3&lt;/li&gt;\r\n&lt;/ul&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3757/" ]
I have a structure like this: ``` <ul> <li>text1</li> <li>text2</li> <li>text3</li> </ul> ``` How do I use javascript or jQuery to get the text as an array? ``` ['text1', 'text2', 'text3'] ``` My plan after this is to assemble it into a string, probably using `.join(', ')`, and get it in a format like this: ``` '"text1", "text2", "text3"' ```
``` var optionTexts = []; $("ul li").each(function() { optionTexts.push($(this).text()) }); ``` ...should do the trick. To get the final output you're looking for, `join()` plus some concatenation will do nicely: ``` var quotedCSV = '"' + optionTexts.join('", "') + '"'; ```
247,045
<p>Been a while since I've dealt with ASP.NET and this is the first time I've had to deal with master pages. Been following tutorials everything is fine except a problem I'm having with the footer.</p> <p>The master page has divs for topContent, mainContent and footerContent. In mainContent I have a ContentPlaceHolder.</p> <p>The default content page (just getting some proof-of-concept going here) has a few labels and text boxes in it with one multi-line text box in the Content area. "Content1" properly links back to ContentPlaceHolder1 back on the master page.</p> <p>When I run the site, the content appears but the footer section isn't "pushed down" by the now-filled ContentPlaceHolder - it almost acts like a background image.</p> <p>What attribute am I missing here? I tried using CSS to force the footerContent to the bottom, but that just put the fotter content at the bottom of the browser and when I expanded the multi-line text box to greater than the browser's window height, the same thing happened (content overlaying the footer)</p> <p>I know this has to be something simple that I'm missing.</p> <p>The basics of the master page are as follows:</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;div id="topContent"&gt; &lt;table style="width: 832px"&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id="mainContent"&gt; &lt;asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"&gt; &lt;/asp:ContentPlaceHolder&gt; &lt;/div&gt; &lt;div id="footerContent"&gt; &lt;br/&gt;&lt;br/&gt; &lt;center style="font-size: small; font-style: italic; font-family: Arial"&gt; &lt;a target="_new" href="/Disclaimer.html"&gt;Security and Privacy Notice&lt;/a&gt;&lt;br/&gt; ... &lt;/center&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Help!</p> <p>EDIT: Turns out that VS2005 was putting "position: absolute" tags on all the components (labels and text boxes) that I put on the content.aspx page. Going into the asp tags and changing them to "position: relative" did the trick.</p>
[ { "answer_id": 247077, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>This doesn't sound like a master page issue, this sounds like an HTML/CSS layouting issue. What you haven't stated is whether your DIVs are absolutely positioned or whether they occur within page flow.</p>\n\n<p>Normally, assuming you're NOT positioning those DIVs absolutely, the header DIV will be statically sized, the footer will be statically sized, but the content DIV should be allowed to stretch vertically to fit the content. This in turn pushes your footer DIV below the last line of content, which is what you want. But in order for that to happen, we usually omit \"position: absolute;\" from the footer DIV. It needs to flow.</p>\n\n<p>Your question is basically asking, \"I have 3 DIVs, one on top of the other. They're not pushing each other downward appropriately.\"</p>\n\n<p>The answer is almost always a rogue \"position: absolute;\" tag, a margin issue, or maybe you're using a \"page container DIV\" that's not set appropriately to expand as its interior DIVs expand.</p>\n" }, { "answer_id": 247095, "author": "Schalk Versteeg", "author_id": 15724, "author_profile": "https://Stackoverflow.com/users/15724", "pm_score": 2, "selected": false, "text": "<p>This is more an HTML + CSS issue and not an asp.net masterpage issue.<br>\nHere is how I would Change the Code to:</p>\n\n<pre><code> &lt;div id=\"mainContent\"style=\"position:relative;\"&gt;\n &lt;asp:ContentPlaceHolder id=\"ContentPlaceHolder1\" runat=\"server\"&gt;\n &lt;/asp:ContentPlaceHolder&gt;\n &lt;/div&gt;\n&lt;br style=\"clear:both;\" /&gt;\n &lt;div id=\"footerContent\" style=\"position:relative;\"&gt;\n &lt;br/&gt;&lt;br/&gt;\n &lt;center style=\"font-size: small; font-style: italic; font-family: Arial\"&gt;\n &lt;a target=\"_new\" href=\"/Disclaimer.html\"&gt;Security and Privacy Notice&lt;/a&gt;&lt;br/&gt;\n ...\n &lt;/center&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 247231, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 1, "selected": false, "text": "<p>A clearing div between maincontent and footercontent will help, but other things to watch out for, especially in sucky browsers like IE6 that don't clear or float well, are height and overflow. You're probably not, but if you're hiding overflow and setting a height, that truncates any content that flows past the height. Something to check.</p>\n\n<p>Often, setting float: left; on all your main div elements will help in conjunction with the clearing div.</p>\n\n<p>Also, \"putting the footer content at the bottom\" implies that it is absolutely positioned, as the other responders have pointed out. As long as footercontent follows the clearing div, it should set up at the bottom of your content, and not at the bottom of the page.</p>\n\n<p>I notice you're using a center tag, as well. That, and div align=center, aren't standard anymore, and could be messing with you as well. Use margin: 0px auto; and text-align: center; instead.</p>\n\n<p>I recommend you do three things in general:</p>\n\n<ul>\n<li>pull up your app in at least three browsers, at least one of which should be Firefox with Firebug installed. When you launch the app, paste the URL from your default browser into the others you're using. Identify where you're having the problem.</li>\n<li>read up at positioniseverything.net to see if any of the problems listed there resemble yours. The Bergevins do great work, and will set you straight. Especially if IE6/7 is a problem.</li>\n<li>make a clear class with clear:both and height: 0 that you can reuse. If you have to tweak it, it's easier than touching each of the inline styles.</li>\n</ul>\n\n<p>Good luck. By any chance, can you edit your question so that we can see the styles, too?</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15891/" ]
Been a while since I've dealt with ASP.NET and this is the first time I've had to deal with master pages. Been following tutorials everything is fine except a problem I'm having with the footer. The master page has divs for topContent, mainContent and footerContent. In mainContent I have a ContentPlaceHolder. The default content page (just getting some proof-of-concept going here) has a few labels and text boxes in it with one multi-line text box in the Content area. "Content1" properly links back to ContentPlaceHolder1 back on the master page. When I run the site, the content appears but the footer section isn't "pushed down" by the now-filled ContentPlaceHolder - it almost acts like a background image. What attribute am I missing here? I tried using CSS to force the footerContent to the bottom, but that just put the fotter content at the bottom of the browser and when I expanded the multi-line text box to greater than the browser's window height, the same thing happened (content overlaying the footer) I know this has to be something simple that I'm missing. The basics of the master page are as follows: ``` <form id="form1" runat="server"> <div id="topContent"> <table style="width: 832px"> </table> </div> <div id="mainContent"> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> <div id="footerContent"> <br/><br/> <center style="font-size: small; font-style: italic; font-family: Arial"> <a target="_new" href="/Disclaimer.html">Security and Privacy Notice</a><br/> ... </center> </div> </form> ``` Help! EDIT: Turns out that VS2005 was putting "position: absolute" tags on all the components (labels and text boxes) that I put on the content.aspx page. Going into the asp tags and changing them to "position: relative" did the trick.
This doesn't sound like a master page issue, this sounds like an HTML/CSS layouting issue. What you haven't stated is whether your DIVs are absolutely positioned or whether they occur within page flow. Normally, assuming you're NOT positioning those DIVs absolutely, the header DIV will be statically sized, the footer will be statically sized, but the content DIV should be allowed to stretch vertically to fit the content. This in turn pushes your footer DIV below the last line of content, which is what you want. But in order for that to happen, we usually omit "position: absolute;" from the footer DIV. It needs to flow. Your question is basically asking, "I have 3 DIVs, one on top of the other. They're not pushing each other downward appropriately." The answer is almost always a rogue "position: absolute;" tag, a margin issue, or maybe you're using a "page container DIV" that's not set appropriately to expand as its interior DIVs expand.
247,053
<p>On Linux, feenableexcept and fedisableexcept can be used to control the generation of SIGFPE interrupts on floating point exceptions. How can I do this on Mac OS X Intel?</p> <p>Inline assembly for enabling floating point interrupts is provided in <a href="http://developer.apple.com/documentation/Performance/Conceptual/Mac_OSX_Numerics/Mac_OSX_Numerics.pdf" rel="noreferrer">http://developer.apple.com/documentation/Performance/Conceptual/Mac_OSX_Numerics/Mac_OSX_Numerics.pdf</a>, pp. 7-15, but only for PowerPC assembly.</p>
[ { "answer_id": 252590, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 3, "selected": false, "text": "<p>On Mac OS X this is moderately complicated. OS X uses the SSE unit for all FP math by default, not the x87 FP unit. The SSE unit does not honor the interrupt options, so that means that in addition to enabling interrupts, you need to make sure to compile all your code not to use SSE math.</p>\n\n<p>You can disable the math by adding \"-mno-sse -mno-sse2 -mno-sse3\" to your CFLAGS. Once you do that you can use some inline assembly to configure your FP exceptions, with basically the same flags as Linux. </p>\n\n<pre><code>short fpflags = 0x1332 // Default FP flags, change this however you want. \nasm(\"fnclex\");\nasm(\"fldcw _fpflags\");\n</code></pre>\n\n<p>The one catch you may find is that since OS X is built entirely using sse there may be uncaught bugs. I know there used to be a big with the signal handler not passing back the proper codes, but that was a few years ago, hopefully it is fixed now.</p>\n" }, { "answer_id": 340683, "author": "Geoffrey Irving", "author_id": 16480, "author_profile": "https://Stackoverflow.com/users/16480", "pm_score": 6, "selected": true, "text": "<p>Exceptions for sse can be enabled using <code>_MM_SET_EXCEPTION_MASK</code> from <code>xmmintrin.h</code>. For example, to enable invalid (nan) exceptions, do</p>\n\n<pre><code>#include &lt;xmmintrin.h&gt;\n...\n_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() &amp; ~_MM_MASK_INVALID);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16480/" ]
On Linux, feenableexcept and fedisableexcept can be used to control the generation of SIGFPE interrupts on floating point exceptions. How can I do this on Mac OS X Intel? Inline assembly for enabling floating point interrupts is provided in <http://developer.apple.com/documentation/Performance/Conceptual/Mac_OSX_Numerics/Mac_OSX_Numerics.pdf>, pp. 7-15, but only for PowerPC assembly.
Exceptions for sse can be enabled using `_MM_SET_EXCEPTION_MASK` from `xmmintrin.h`. For example, to enable invalid (nan) exceptions, do ``` #include <xmmintrin.h> ... _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); ```
247,059
<p>In C# there is the static property <a href="http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx" rel="noreferrer">Environment.Newline</a> that changed depending on the running platform.</p> <p>Is there anything similar in Java?</p>
[ { "answer_id": 247069, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 9, "selected": true, "text": "<p><strong>As of Java 7 (and Android API level 19):</strong></p>\n\n<pre><code>System.lineSeparator()\n</code></pre>\n\n<p>Documentation: <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29\" rel=\"noreferrer\">Java Platform SE 7</a></p>\n\n<hr>\n\n<p><strong>For older versions of Java, use:</strong></p>\n\n<pre><code>System.getProperty(\"line.separator\");\n</code></pre>\n\n<p>See <a href=\"https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html\" rel=\"noreferrer\">https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html</a> for other properties.</p>\n" }, { "answer_id": 247597, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 6, "selected": false, "text": "<p>Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of <code>\\n</code> and <code>\\r\\n</code>, having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows <code>\\r\\n</code>, Unix/Linux/OSX <code>\\n</code> and pre-OSX Mac <code>\\r</code>.</p>\n<p>When you're <em>writing</em> text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use <code>\\r\\n</code> because it only recognizes the one kind of separator.</p>\n" }, { "answer_id": 30217755, "author": "J.Steve", "author_id": 736737, "author_profile": "https://Stackoverflow.com/users/736737", "pm_score": 7, "selected": false, "text": "<p>As of Java 7: </p>\n\n<pre><code>System.lineSeparator()\n</code></pre>\n\n<blockquote>\n <p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29\"><B>Java API : System.lineSeparator</B></a></p>\n \n <p>Returns the system-dependent line separator string. It always returns\n the same value - the initial value of the system property\n line.separator. On UNIX systems, it returns \"\\n\"; on Microsoft Windows\n systems it returns \"\\r\\n\".</p>\n</blockquote>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20480/" ]
In C# there is the static property [Environment.Newline](http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx) that changed depending on the running platform. Is there anything similar in Java?
**As of Java 7 (and Android API level 19):** ``` System.lineSeparator() ``` Documentation: [Java Platform SE 7](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29) --- **For older versions of Java, use:** ``` System.getProperty("line.separator"); ``` See <https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html> for other properties.
247,066
<p>I want the most performat way to read and parse a file.</p> <p>Is it possible to read a file in .NET, but not load the entire file into memory? i.e. just load the file line by line as I parse the content of each row?</p> <p>Does XmlTextReader load the entire file into memory or does it stream the file into memory as it reads the file?</p>
[ { "answer_id": 247081, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about XMLTextReader, but you can read a file line by line using the FileReader objects. )</p>\n" }, { "answer_id": 247104, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "<p>XmlTextReader works on a stream - so it does not read the whole file in memory.</p>\n" }, { "answer_id": 247107, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "<p>You could use the ReadLine method of StreamReader Class:</p>\n\n<pre><code>string line;\n\n// Read the file and display it line by line.\nSystem.IO.StreamReader file = \n new System.IO.StreamReader(\"c:\\\\test.txt\");\n\nwhile((line = file.ReadLine()) != null)\n{\n Console.WriteLine (line);\n}\n\nfile.Close();\n</code></pre>\n\n<p>For XML files I would go with XMLTextReader. See this <a href=\"http://www.ddj.com/windows/184416669\" rel=\"nofollow noreferrer\">article on Dr. Dobb's Journal</a>:</p>\n\n<p><em>\"<strong>Parsing XML Files in .NET Using C#:</strong> Five different parsing techniques are available in .NET, and each has its own advantages\"</em></p>\n" }, { "answer_id": 247111, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": "<p>What you can try is using the StreamReader.ReadLine function and test the performance compared to things like FileStream/TextReader.</p>\n" }, { "answer_id": 247112, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about the XMLTextReader either, but you can read line by line like this:</p>\n\n<pre><code>Dim theLine as String\nDim fsFile As New FileStream(inputFile, FileMode.Open) 'File Stream for the Input File\nDim fsImport As New FileStream(outputFile, FileMode.OpenOrCreate) 'File Stream for the Output File\nDim srFile As New StreamReader(fsFile) 'Stream Reader for Input File\nDim swfile As New StreamWriter(fsImport) 'Stream Writer for Output File\n\nDo While srFile.Peek &lt;&gt; -1 'Do While it's not the last line of the file\n theLine = srFile.ReadLine 'Read the line\n Messagebox.Show(theLine, \"Line-by-Line!\")\nLoop\n</code></pre>\n" }, { "answer_id": 247145, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 0, "selected": false, "text": "<p>XmlTextReader does not load the entire file into memory, it operates on a stream.</p>\n\n<p>All of filestream objects read the file in \"chunks\".\nYou can specify how much data (i.e. how big a chunk) to bring back to your program with each call (i.e. m bytes, where m is any integer - possibly long - value, or with a text reader, a single line of arbitrary length)\nThe OS will cache n bytes (where n is 0 some or all) per read for performance reasons. \nYou have absolutely no control over the size of n, and will only frustrate yourself experimenting to find out what it is, as it changes due to a thousand different environmental factors.</p>\n" }, { "answer_id": 251882, "author": "quimbo", "author_id": 12250, "author_profile": "https://Stackoverflow.com/users/12250", "pm_score": 1, "selected": false, "text": "<p>here is a TextFileReader Class I have been using for years</p>\n\n<p><a href=\"http://www.dotnet2themax.com/ShowContent.aspx?ID=4ee44d6c-79a9-466d-ab47-56bba526534f\" rel=\"nofollow noreferrer\">http://www.dotnet2themax.com/ShowContent.aspx?ID=4ee44d6c-79a9-466d-ab47-56bba526534f</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want the most performat way to read and parse a file. Is it possible to read a file in .NET, but not load the entire file into memory? i.e. just load the file line by line as I parse the content of each row? Does XmlTextReader load the entire file into memory or does it stream the file into memory as it reads the file?
You could use the ReadLine method of StreamReader Class: ``` string line; // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt"); while((line = file.ReadLine()) != null) { Console.WriteLine (line); } file.Close(); ``` For XML files I would go with XMLTextReader. See this [article on Dr. Dobb's Journal](http://www.ddj.com/windows/184416669): *"**Parsing XML Files in .NET Using C#:** Five different parsing techniques are available in .NET, and each has its own advantages"*
247,093
<p>I want to change the registry values on the pocketPC. I ran the following code:</p> <pre><code>if(enabled) { dwData = 120; } if(RegSetValueEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Power\\Timeouts\\BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&amp;dwData, sizeof(DWORD))) { return FALSE; } </code></pre> <p>but it doesn't shange the registry entry. Does anyone know how to set registry key values with c++?</p> <p>Thanks!</p>
[ { "answer_id": 247323, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>RegSetValueEx returns a descriptive error code. You can get a human-readable message out of this error code using FormatMessage and possibly via the Error Lookup tool, or the @ERR facility in VS. The code you have looks correct so see what the error message tells you.</p>\n" }, { "answer_id": 247581, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>Assuming that your looking with RegEdit, did you refresh (F5) the registry view?</p>\n" }, { "answer_id": 247629, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 1, "selected": false, "text": "<p>How are you verifying the change? Keep in mind that making this change will <em>not</em> be reflected automatically in the device behavior and it probably won't show up in the Control Panel either (depends on if the CPL has already been loaded or not). The shell is unaware that you made the change and it doesn't poll the value - you have to tell it to go out and re-read. How to do it is <a href=\"http://msdn.microsoft.com/en-us/library/aa932196.aspx\" rel=\"nofollow noreferrer\">documented in MSDN</a> (basically you set a named system event).</p>\n" }, { "answer_id": 248604, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 4, "selected": true, "text": "<p>There are a two problems with what you are doing:</p>\n\n<p>1: RegSetValueEx does not take a path, only a valuename. So you need to open the key path first.</p>\n\n<p>e.g.</p>\n\n<pre><code>HKEY key;\nif(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, \"System\\\\CurrentControlSet\\\\Control\\\\Power\\\\Timeouts\", 0, 0, &amp;key))\n{\n if(RegSetValueEx(key, _T(\"BattSuspendTimeout\"), 0, REG_DWORD, (LPBYTE)&amp;dwData, sizeof(DWORD)))\n {\n RegCloseKey(key);\n return FALSE;\n }\n\n RegCloseKey(key);\n}\n</code></pre>\n\n<p>2: That area of the registry requires Privileged code signing to work on all Windows Mobile devices. You can get away with it on most current touch-screen windows mobile devices if the user says \"yes\" to the unknown publisher question when the application is first run or installed. If you get a \"Access Denied\" error on the set, then you really need to be Privileged code signed for the set to work.</p>\n" }, { "answer_id": 249734, "author": "redsolo", "author_id": 28553, "author_profile": "https://Stackoverflow.com/users/28553", "pm_score": 1, "selected": false, "text": "<p>Check out [VORegistry][1], it makes working with the registry so much easier.</p>\n\n<p>[1]: <a href=\"http://www.voscorp.com/products/developer/winmobile/voregistry/index.htm\" rel=\"nofollow noreferrer\">http://www.voscorp.com/products/developer/winmobile/voregistry/index.htm</a> VORegistry</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
I want to change the registry values on the pocketPC. I ran the following code: ``` if(enabled) { dwData = 120; } if(RegSetValueEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Power\\Timeouts\\BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD))) { return FALSE; } ``` but it doesn't shange the registry entry. Does anyone know how to set registry key values with c++? Thanks!
There are a two problems with what you are doing: 1: RegSetValueEx does not take a path, only a valuename. So you need to open the key path first. e.g. ``` HKEY key; if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\Power\\Timeouts", 0, 0, &key)) { if(RegSetValueEx(key, _T("BattSuspendTimeout"), 0, REG_DWORD, (LPBYTE)&dwData, sizeof(DWORD))) { RegCloseKey(key); return FALSE; } RegCloseKey(key); } ``` 2: That area of the registry requires Privileged code signing to work on all Windows Mobile devices. You can get away with it on most current touch-screen windows mobile devices if the user says "yes" to the unknown publisher question when the application is first run or installed. If you get a "Access Denied" error on the set, then you really need to be Privileged code signed for the set to work.
247,106
<p>Looking at this loop that copies one c-string to another:</p> <pre><code>void strcpyr(char *s, char *t) { while(*s++=*t++)// Why does this work? ; } </code></pre> <p>Why do we not check for the '\0' character in the while loop, like this?</p> <pre><code>while((*s++=*r++)!='\0').. </code></pre> <p>How does the first loop terminate?</p>
[ { "answer_id": 247122, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>When we hit the <code>'\\0'</code> in the string initially pointed to by <code>t</code>, the <code>*s++=*t++</code>, which does the assignment, also returns the value that's assigned to the position pointed to by <code>s</code>, or <code>'\\0'</code>, which evaluates to <code>false</code> and terminates the loop.</p>\n\n<p>In your second example, you explicitly rely on the fact that the assignment returns the assigned character, while the first example implicitly uses this fact (and the fact that the <code>0</code> character (also written <code>'\\0'</code>) is considered to be false, while all other characters evaluate to true, so the expression <code>c != '\\0'</code> will yield the same result as <code>c</code>.</p>\n" }, { "answer_id": 247126, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>The reason we are not explicitly checking for zero is that in C 0 is false.</p>\n\n<p>Therefore the loop</p>\n\n<pre><code>while(*s++=*t++)\n;\n</code></pre>\n\n<p>will terminate when the character pointed to by t is 0.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 247129, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 2, "selected": false, "text": "<p>The loop is going to terminate because '\\0' is effectively 0, and the what the \"while\" is evaluating is not a the result of an equality test (==), but the right-value of the assignment expression.</p>\n" }, { "answer_id": 247130, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": false, "text": "<p>The statement *s++=*t++ not only assigns the next character from t to s but also returns the current value of *t as the result of the expression. The while loop terminates on any false value, including '\\0'.</p>\n\n<p>Think of it this way. If you did:</p>\n\n<pre><code>char c = *s++ = *t++;\n</code></pre>\n\n<p>in addition to copying a char from *t to *s and incrementing both, it would also set c to the current value of *t.</p>\n" }, { "answer_id": 247136, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<p>I think you mean to write this:</p>\n\n<pre><code>void strcpyr(char *s, char *t) {\n while (*s++ = *t++);\n}\n</code></pre>\n\n<p>The loop terminates when the value pointed to by \"t\" is zero. For C (and C++) loops and conditionals, any integer that is non-zero is true.</p>\n" }, { "answer_id": 247187, "author": "fadein", "author_id": 31205, "author_profile": "https://Stackoverflow.com/users/31205", "pm_score": 0, "selected": false, "text": "<p>The while loop is testing the result of the assignment.\nThe result of an assignment is the value assigned into the left-hand side of the statement. On the last iteration, when *t == '\\0', the '\\0' is assigned into s, which becomes the value the while loop considers before deciding it is time to quit.</p>\n" }, { "answer_id": 247512, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 0, "selected": false, "text": "<p>In C, a=b is actually an expression which is evaluated as 'b'. It is easier to write:</p>\n\n<pre>\n\nif(a=b) {\n //some block\n}\n\n</pre>\n\n<p>then:</p>\n\n<pre>\n\na=b;\nif(a!=0) {\n //some block\n}\n\n</pre>\n\n<p>In C language within if, while, for statement the check that is made is: is expression not zero?</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Looking at this loop that copies one c-string to another: ``` void strcpyr(char *s, char *t) { while(*s++=*t++)// Why does this work? ; } ``` Why do we not check for the '\0' character in the while loop, like this? ``` while((*s++=*r++)!='\0').. ``` How does the first loop terminate?
The statement \*s++=\*t++ not only assigns the next character from t to s but also returns the current value of \*t as the result of the expression. The while loop terminates on any false value, including '\0'. Think of it this way. If you did: ``` char c = *s++ = *t++; ``` in addition to copying a char from \*t to \*s and incrementing both, it would also set c to the current value of \*t.
247,110
<p>I'm getting started on building a REST API for a project I'm working on, and it led me to do a little research as to the best way to build an API using RoR. I find out pretty quickly that by default, models are open to the world and can be called via URL by simply putting a ".xml" at the end of the URL and passing appropriate parameters.</p> <p>So then the next question came. How do I secure my app to prevent unauthorized changes? In doing some research I found a couple articles talking about <code>attr_accessible</code> and <code>attr_protected</code> and how they can be used. The particular URL I found talking about these was posted back in May of '07 (<a href="http://railscasts.com/episodes/26-hackers-love-mass-assignment" rel="noreferrer">here</a>). </p> <p>As with all things ruby, I'm sure that things have evolved since then. So my question is, is this still the best way to secure a REST API within RoR?</p> <p>If not what do you suggest in either a "new project" or an "existing project"scenario?</p>
[ { "answer_id": 247162, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>I'm facing similar questions as you at the moment because i'm also building out a REST api for a rails application.</p>\n\n<p>I suggest making sure that only attributes that can be user edited are marked with attr_accessible. This will set up a white list of attributes that can be assigned using update_attributes.</p>\n\n<p>What I do is something like this:</p>\n\n<pre><code> class Model &lt; ActiveRecord::Base \n attr_accessible nil \n end\n</code></pre>\n\n<p>All my models inherit from that, so that they are forced to define attr_accessible for any fields they want to make mass assignable. Personally, I wish there was a way to enable this behaviour by default (there might be, and I don't know about it).</p>\n\n<p>Just so you know someone can mass assign a property not only using the REST api but also using a regular form post.</p>\n" }, { "answer_id": 248101, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>How do I secure my app to prevent\n unauthorized changes?</p>\n</blockquote>\n\n<p><code>attr_accessible</code> and <code>attr_protected</code> are both useful for controlling the ability to perform mass-assignments on an ActiveRecord model. You definitely want to use attr_protected to prevent form injection attacks; see <a href=\"http://b.lesseverything.com/2008/3/11/use-attr_protected-or-we-will-hack-you\" rel=\"nofollow noreferrer\">Use attr_protected or we will hack you</a>.</p>\n\n<p>Also, in order to prevent anyone from being able to access the controllers in your Rails app, you're almost certainly going to need some kind of user authentication system and put a <code>before_filter</code> in your controllers to ensure that you have an authorized user making the request before you allow the requested controller action to execute.</p>\n\n<p>See the <a href=\"http://guides.rails.info/security.html\" rel=\"nofollow noreferrer\">Ruby on Rails Security Guide</a> (part of the Rails Documentation Project) for tons more helpful info.</p>\n" }, { "answer_id": 250308, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 8, "selected": true, "text": "<p>There are several schemes for authenticating API requests, and they're different than normal authentication provided by plugins like restful_authentication or acts_as_authenticated. Most importantly, clients will not be maintaining sessions, so there's no concept of a login.</p>\n\n<p><strong>HTTP Authentication</strong></p>\n\n<p>You can use basic HTTP authentication. For this, API clients will use a regular username and password and just put it in the URL like so:</p>\n\n<pre><code>http://myusername:[email protected]/\n</code></pre>\n\n<p>I believe that restful_authentication supports this out of the box, so you can ignore whether or not someone is using your app via the API or via a browser.</p>\n\n<p>One downside here is that you're asking users to put their username and password in the clear in every request. By doing it over SSL, you can make this safe.</p>\n\n<p>I don't think I've ever actually seen an API that uses this, though. It seems like a decently good idea to me, especially since it's supported out of the box by the current authentication schemes, so I don't know what the problem is.</p>\n\n<p><strong>API Key</strong></p>\n\n<p>Another easy way to enable API authentication is to use API keys. It's essentially a username for a remote service. When someone signs up to use your API, you give them an API key. This needs to be passed with each request.</p>\n\n<p>One downside here is that if anyone gets someone else's API key, they can make requests as that user. I think that by making all your API requests use HTTPS (SSL), you can offset this risk somewhat.</p>\n\n<p>Another downside is that users use the same authentication credentials (the API key) everywhere they go. If they want to revoke access to an API client their only option is to change their API key, which will disable all other clients as well. This can be mitigated by allowing users to generate multiple API keys.</p>\n\n<p><strong>API Key + Secret Key signing</strong></p>\n\n<p><em>Deprecated(sort of) - see OAuth below</em></p>\n\n<p>Significantly more complex is signing the request with a secret key. This is what Amazon Web Services (S3, EC2, and such do). Essentially, you give the user 2 keys: their API key (ie. username) and their secret key (ie. password). The API key is transmitted with each request, but the secret key is not. Instead, it is used to sign each request, usually by adding another parameter.</p>\n\n<p>IIRC, Amazon accomplishes this by taking all the parameters to the request, and ordering them by parameter name. Then, this string is hashed, using the user's secret key as the hash key. This new value is appended as a new parameter to the request prior to being sent. On Amazon's side, they do the same thing. They take all parameters (except the signature), order them, and hash using the secret key. If this matches the signature, they know the request is legitimate.</p>\n\n<p>The downside here is complexity. Getting this scheme to work correctly is a pain, both for the API developer and the clients. Expect lots of support calls and angry emails from client developers who can't get things to work.</p>\n\n<p><strong>OAuth</strong></p>\n\n<p>To combat some of the complexity issues with key + secret signing, a standard has emerged called <a href=\"http://oauth.net/\" rel=\"noreferrer\">OAuth</a>. At the core OAuth is a flavor of key + secret signing, but much of it is standardized and has been included into <a href=\"http://oauth.net/code/\" rel=\"noreferrer\">libraries for many languages</a>.</p>\n\n<p>In general, it's much easier on both the API producer and consumer to use OAuth rather than creating your own key/signature system.</p>\n\n<p>OAuth also inherently segments access, providing different access credentials for each API consumer. This allows users to selectively revoke access without affecting their other consuming applications.</p>\n\n<p>Specifically for Ruby, there is an <a href=\"http://oauth.rubyforge.org/\" rel=\"noreferrer\">OAuth gem</a> that provides support out of the box for both producers and consumers of OAuth. I have used this gem to build an API and also to consume OAuth APIs and was very impressed. If you think your application needs OAuth (as opposed to the simpler API key scheme), then I can easily recommend using the OAuth gem.</p>\n" }, { "answer_id": 10870496, "author": "steve", "author_id": 70088, "author_profile": "https://Stackoverflow.com/users/70088", "pm_score": 0, "selected": false, "text": "<p>Another approach that saves building a lot of the stuff yourself is to use something like <a href=\"http://www.3scale.net/\" rel=\"nofollow\">http://www.3scale.net/</a> which handles keys, tokens, quotas etc. for individual developers. It also does analytics and creates a developer portal. </p>\n\n<p>There's a ruby/rails plugin <a href=\"https://github.com/3scale/3scale_ws_api_for_ruby\" rel=\"nofollow\">ruby API plugin</a> which will apply to policies to traffic as it arrives - you can use it in conjunction with the <a href=\"http://oauth.rubyforge.org/\" rel=\"nofollow\">oAuth gem</a>. You can also us it by dropping varnish in front of the app and using the varnish lib mod: <a href=\"https://github.com/3scale/libvmod-3scale/\" rel=\"nofollow\">Varnish API Module</a>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23458/" ]
I'm getting started on building a REST API for a project I'm working on, and it led me to do a little research as to the best way to build an API using RoR. I find out pretty quickly that by default, models are open to the world and can be called via URL by simply putting a ".xml" at the end of the URL and passing appropriate parameters. So then the next question came. How do I secure my app to prevent unauthorized changes? In doing some research I found a couple articles talking about `attr_accessible` and `attr_protected` and how they can be used. The particular URL I found talking about these was posted back in May of '07 ([here](http://railscasts.com/episodes/26-hackers-love-mass-assignment)). As with all things ruby, I'm sure that things have evolved since then. So my question is, is this still the best way to secure a REST API within RoR? If not what do you suggest in either a "new project" or an "existing project"scenario?
There are several schemes for authenticating API requests, and they're different than normal authentication provided by plugins like restful\_authentication or acts\_as\_authenticated. Most importantly, clients will not be maintaining sessions, so there's no concept of a login. **HTTP Authentication** You can use basic HTTP authentication. For this, API clients will use a regular username and password and just put it in the URL like so: ``` http://myusername:[email protected]/ ``` I believe that restful\_authentication supports this out of the box, so you can ignore whether or not someone is using your app via the API or via a browser. One downside here is that you're asking users to put their username and password in the clear in every request. By doing it over SSL, you can make this safe. I don't think I've ever actually seen an API that uses this, though. It seems like a decently good idea to me, especially since it's supported out of the box by the current authentication schemes, so I don't know what the problem is. **API Key** Another easy way to enable API authentication is to use API keys. It's essentially a username for a remote service. When someone signs up to use your API, you give them an API key. This needs to be passed with each request. One downside here is that if anyone gets someone else's API key, they can make requests as that user. I think that by making all your API requests use HTTPS (SSL), you can offset this risk somewhat. Another downside is that users use the same authentication credentials (the API key) everywhere they go. If they want to revoke access to an API client their only option is to change their API key, which will disable all other clients as well. This can be mitigated by allowing users to generate multiple API keys. **API Key + Secret Key signing** *Deprecated(sort of) - see OAuth below* Significantly more complex is signing the request with a secret key. This is what Amazon Web Services (S3, EC2, and such do). Essentially, you give the user 2 keys: their API key (ie. username) and their secret key (ie. password). The API key is transmitted with each request, but the secret key is not. Instead, it is used to sign each request, usually by adding another parameter. IIRC, Amazon accomplishes this by taking all the parameters to the request, and ordering them by parameter name. Then, this string is hashed, using the user's secret key as the hash key. This new value is appended as a new parameter to the request prior to being sent. On Amazon's side, they do the same thing. They take all parameters (except the signature), order them, and hash using the secret key. If this matches the signature, they know the request is legitimate. The downside here is complexity. Getting this scheme to work correctly is a pain, both for the API developer and the clients. Expect lots of support calls and angry emails from client developers who can't get things to work. **OAuth** To combat some of the complexity issues with key + secret signing, a standard has emerged called [OAuth](http://oauth.net/). At the core OAuth is a flavor of key + secret signing, but much of it is standardized and has been included into [libraries for many languages](http://oauth.net/code/). In general, it's much easier on both the API producer and consumer to use OAuth rather than creating your own key/signature system. OAuth also inherently segments access, providing different access credentials for each API consumer. This allows users to selectively revoke access without affecting their other consuming applications. Specifically for Ruby, there is an [OAuth gem](http://oauth.rubyforge.org/) that provides support out of the box for both producers and consumers of OAuth. I have used this gem to build an API and also to consume OAuth APIs and was very impressed. If you think your application needs OAuth (as opposed to the simpler API key scheme), then I can easily recommend using the OAuth gem.
247,128
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content">Resizing an iframe based on content</a> </p> </blockquote> <p>I'm loading an iFrame and want the parent to automatically change the height based upon the height of the iFrame's content.</p> <p>To simply things, all pages belong to the same domain, so I shouldn't run into cross-site scripting issues.</p>
[ { "answer_id": 247160, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 5, "selected": false, "text": "<p>On any other element, I would use the <code>scrollHeight</code> of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.</p>\n\n<p>Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the <code>offsetHeight</code>:</p>\n\n<pre><code>function setHeight() {\n parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';\n}\n</code></pre>\n\n<p>And attach that to run with the iframe-body's <code>onLoad</code> event.</p>\n" }, { "answer_id": 247221, "author": "Allan", "author_id": 5123, "author_profile": "https://Stackoverflow.com/users/5123", "pm_score": 0, "selected": false, "text": "<p>Oli has a solution that will work for me. For the record, the page inside my iFrame is rendered by javascript, so I'll need an infinitesimal delay before reporting back the offsetHeight. It looks like something along these lines:</p>\n\n<pre><code>\n $(document).ready(function(){\n setTimeout(setHeight);\n });\n\n function setHeight() {\n alert(document['body'].offsetHeight); \n }\n</code></pre>\n" }, { "answer_id": 247230, "author": "TimeSpace Traveller", "author_id": 5116, "author_profile": "https://Stackoverflow.com/users/5116", "pm_score": 1, "selected": false, "text": "<p>In IE 5.5+, you can use the contentWindow property:</p>\n\n<pre><code>iframe.height = iframe.contentWindow.document.scrollHeight;\n</code></pre>\n\n<p>In Netscape 6 (assuming firefox as well), contentDocument property:</p>\n\n<pre><code>iframe.height = iframe.contentDocument.scrollHeight\n</code></pre>\n" }, { "answer_id": 247821, "author": "Allan", "author_id": 5123, "author_profile": "https://Stackoverflow.com/users/5123", "pm_score": -1, "selected": false, "text": "<p>Actually - Patrick's code sort of worked for me as well. The correct way to do it would be along the lines of this:</p>\n\n<p>Note: there's a bit of jquery ahead:</p>\n\n<pre><code>\nif ($.browser.msie == false) {\n var h = (document.getElementById(\"iframeID\").contentDocument.body.offsetHeight);\n} else {\n var h = (document.getElementById(\"iframeID\").Document.body.scrollHeight);\n}\n</code></pre>\n" }, { "answer_id": 687062, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 2, "selected": false, "text": "<p>This <a href=\"http://sonspring.com/journal/jquery-iframe-sizing\" rel=\"nofollow noreferrer\">solution</a> worked best for me. It uses jQuery and the iframe's \".load\" event.</p>\n" }, { "answer_id": 2967388, "author": "Shripad Krishna", "author_id": 277537, "author_profile": "https://Stackoverflow.com/users/277537", "pm_score": 4, "selected": false, "text": "<p>I just happened to come by your question and i have a solution. But its in jquery. Its too simple.</p>\n\n<pre><code>$('iframe').contents().find('body').css({\"min-height\": \"100\", \"overflow\" : \"hidden\"});\nsetInterval( \"$('iframe').height($('iframe').contents().find('body').height() + 20)\", 1 );\n</code></pre>\n\n<p>There you go!</p>\n\n<p>Cheers! :)</p>\n\n<p><strong>Edit:</strong> If you have a Rich Text Editor based on the iframe method and not the div method and want it to expand every new line then this code will do the needful.</p>\n" }, { "answer_id": 3454721, "author": "Sky", "author_id": 91379, "author_profile": "https://Stackoverflow.com/users/91379", "pm_score": 3, "selected": false, "text": "<p>Here is a dead simple solution that works on every browser and with cross domains:</p>\n\n<p>First, this works on the concept that if the html page containing the iframe is set to a height of 100% and the iframe is styled using css to have a height of 100%, then css will automatically size everything to fit.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>&lt;head&gt;\n&lt;style type=\"text/css\"&gt; \nhtml {height:100%}\nbody {\nmargin:0;\nheight:100%;\noverflow:hidden\n}\n&lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n&lt;iframe allowtransparency=true frameborder=0 id=rf sandbox=\"allow-same-origin allow-forms allow-scripts\" scrolling=auto src=\"http://www.externaldomain.com/\" style=\"width:100%;height:100%\"&gt;&lt;/iframe&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 4111904, "author": "Gale", "author_id": 499041, "author_profile": "https://Stackoverflow.com/users/499041", "pm_score": 0, "selected": false, "text": "<p>My workaround is to set the iframe the height/width well over any anticipated source page size in CSS &amp; the <code>background</code> property to <code>transparent</code>. </p>\n\n<p>In the iframe set <code>allow-transparency</code> to <code>true</code> and <code>scrolling</code> to <code>no</code>.</p>\n\n<p>The only thing visible will be whatever source file you use. It works in IE8, Firefox 3, &amp; Safari.</p>\n" }, { "answer_id": 6383596, "author": "Ian Harrigan", "author_id": 611329, "author_profile": "https://Stackoverflow.com/users/611329", "pm_score": 0, "selected": false, "text": "<p>This is the easiest method i have found using prototype:</p>\n\n<p>Main.html:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n\n\n&lt;script src=\"prototype.js\"&gt;&lt;/script&gt;\n\n&lt;script&gt;\n function init() {\n var iframe = $(document.getElementById(\"iframe\"));\n var iframe_content = $(iframe.contentWindow.document.getElementById(\"iframe_content\"));\n var cy = iframe_content.getDimensions().height;\n iframe.style.height = cy + \"px\";\n }\n&lt;/script&gt;\n\n&lt;/head&gt;\n\n&lt;body onload=\"init()\"&gt;\n\n\n&lt;iframe src=\"./content.html\" id=\"iframe\" frameBorder=\"0\" scroll=\"no\"&gt;&lt;/iframe&gt;\n\n&lt;br&gt;\nthis is the next line\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>content.html:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script src=\"prototype.js\"&gt;&lt;/script&gt;\n\n\n&lt;style&gt;\nbody {\n margin: 0px;\n padding: 0px;\n}\n&lt;/style&gt;\n\n\n&lt;/head&gt;\n\n&lt;body&gt;\n\n\n&lt;div id=\"iframe_content\" style=\"max-height:200px;\"&gt;\nSub content&lt;br&gt;\nSub content&lt;br&gt;\n...\n...\n...\n&lt;/div&gt;\n\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This seems to work (so far) in all the major browsers.</p>\n" }, { "answer_id": 7372390, "author": "geekQ", "author_id": 111995, "author_profile": "https://Stackoverflow.com/users/111995", "pm_score": 1, "selected": false, "text": "<p>I found the solution by @ShripadK most helpful, but it does not\nwork, if there is more than one iframe. My fix is:</p>\n\n<pre><code>function autoResizeIFrame() {\n $('iframe').height(\n function() {\n return $(this).contents().find('body').height() + 20;\n }\n )\n}\n\n$('iframe').contents().find('body').css(\n {\"min-height\": \"100\", \"overflow\" : \"hidden\"});\n\nsetTimeout(autoResizeIFrame, 2000);\nsetTimeout(autoResizeIFrame, 10000);\n</code></pre>\n\n<ul>\n<li><code>$('iframe').height($('iframe').contents().find('body').height() + 20)</code> would set\nthe height of every frame to the same value, namely the height of the content of the first frame.\nSo I am using jquery's <code>height()</code> with a function instead of a value. That way the individual\nheights are calculated</li>\n<li><code>+ 20</code> is a hack to work around iframe scrollbar problems. The number must be bigger than the size of a scrollbar. The hack can probably \nbe avoided but disabling the scrollbars for the iframe.</li>\n<li>I use <code>setTimeout</code> instead of <code>setInterval(..., 1)</code> to reduce CPU load in my case</li>\n</ul>\n" }, { "answer_id": 7402107, "author": "xmedeko", "author_id": 254109, "author_profile": "https://Stackoverflow.com/users/254109", "pm_score": 4, "selected": false, "text": "<p>Try:</p>\n\n<ul>\n<li><a href=\"https://github.com/house9/jquery-iframe-auto-height\" rel=\"nofollow noreferrer\">jquery-iframe-auto-height</a></li>\n<li><a href=\"https://github.com/davidjbradshaw/iframe-resizer\" rel=\"nofollow noreferrer\">iframe-resizer</a></li>\n</ul>\n" }, { "answer_id": 7889432, "author": "iknowitwasyoufredo", "author_id": 607890, "author_profile": "https://Stackoverflow.com/users/607890", "pm_score": 1, "selected": false, "text": "<p>My solution, (using jquery):</p>\n\n<pre><code>&lt;iframe id=\"Iframe1\" class=\"tabFrame\" width=\"100%\" height=\"100%\" scrolling=\"no\" src=\"http://samedomain\" frameborder=\"0\" &gt;\n&lt;/iframe&gt; \n&lt;script type=\"text/javascript\"&gt;\n $(function () {\n\n $('.tabFrame').load(function () {\n var iframeContentWindow = this.contentWindow;\n var height = iframeContentWindow.$(document).height();\n this.style.height = height + 'px';\n });\n });\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5123/" ]
> > **Possible Duplicate:** > > [Resizing an iframe based on content](https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content) > > > I'm loading an iFrame and want the parent to automatically change the height based upon the height of the iFrame's content. To simply things, all pages belong to the same domain, so I shouldn't run into cross-site scripting issues.
On any other element, I would use the `scrollHeight` of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try. Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the `offsetHeight`: ``` function setHeight() { parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px'; } ``` And attach that to run with the iframe-body's `onLoad` event.
247,135
<p>I use <a href="http://xpath.alephzarro.com/" rel="noreferrer">XPather Browser</a> to check my XPATH expressions on an HTML page.</p> <p>My end goal is to use these expressions in Selenium for the testing of my user interfaces.</p> <p>I got an HTML file with a content similar to this:</p> <pre> &lt;tr&gt; &lt;td&gt;abc&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; </pre> <p>I want to select a node with a text containing the string "<code>&amp;nbsp;</code>".</p> <p>With a normal string like "abc" there is no problem. I use an XPATH similar to <code>//td[text()="abc"]</code>.</p> <p>When I try with an an XPATH like <code>//td[text()="&amp;nbsp;"]</code> it returns nothing. Is there a special rule concerning texts with "<code>&amp;</code>" ?</p>
[ { "answer_id": 247158, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Search for <code>&amp;nbsp;</code> or only <code>nbsp</code> - did you try this?</p>\n" }, { "answer_id": 247368, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 3, "selected": false, "text": "<p>Try using the decimal entity <code>&amp;#160;</code> instead of the named entity. If that doesn't work, you should be able to simply use the <a href=\"http://www.fileformat.info/info/unicode/char/00a0/index.htm\" rel=\"nofollow noreferrer\">unicode character for a non-breaking space</a> instead of the <code>&amp;nbsp;</code> entity. </p>\n\n<p>(Note: I did not try this in XPather, but I did try it in Oxygen.)</p>\n" }, { "answer_id": 247405, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": false, "text": "<p>I found I can make the match when I input a hard-coded non-breaking space (U+00A0) by typing Alt+0160 on Windows between the two quotes...</p>\n\n<pre><code>//table[@id='TableID']//td[text()=' ']\n</code></pre>\n\n<p>worked for me with the special char.</p>\n\n<p>From what I understood, the XPath 1.0 standard doesn't handle escaping Unicode chars. There seems to be functions for that in XPath 2.0 but it looks like Firefox doesn't support it (or I misunderstood something). So you have to do with local codepage. Ugly, I know.</p>\n\n<p>Actually, it looks like the standard is relying on the programming language using XPath to provide the correct Unicode escape sequence... So, somehow, I did the right thing.</p>\n" }, { "answer_id": 247628, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 0, "selected": false, "text": "<p>I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:</p>\n\n<pre><code>&lt;xsl:value-of select=\"count(//td[text()='&amp;nbsp;'])\" /&gt;\n</code></pre>\n\n<p>The value returned is 1, which is the correct value in my test case. </p>\n\n<p>However, I did have to declare <strong>nbsp</strong> as an entity within my XML and XSL using the following:</p>\n\n<pre><code>&lt;!DOCTYPE xsl:stylesheet [ &lt;!ENTITY nbsp \"&amp;#160;\"&gt; ]&gt;\n</code></pre>\n\n<p>I'm not sure if that helps you, but I was able to <em>actually</em> find <strong>nbsp</strong> using an XPath expression.</p>\n\n<p>Edit: My code sample actually contains the characters <strong>'&amp;nbsp;'</strong> but the JavaScript syntax highlight converts it to the space character. Don't be mislead!</p>\n" }, { "answer_id": 247903, "author": "Bergeroy", "author_id": 16927, "author_profile": "https://Stackoverflow.com/users/16927", "pm_score": 8, "selected": true, "text": "<p>It seems that <a href=\"http://www.openqa.org/\" rel=\"noreferrer\">OpenQA</a>, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to <code>//td[text()=\"${nbsp}\"]</code>.</p>\n\n<p>I reproduced here the text from OpenQA concerning this issue (found <a href=\"https://svn.openqa.org/svn/selenium-core/trunk/src/main/resources/doctool/doc2html.xml\" rel=\"noreferrer\">here</a>):</p>\n\n<blockquote>\n <p>HTML automatically normalizes\n whitespace within elements, ignoring\n leading/trailing spaces and converting\n extra spaces, tabs and newlines into a\n single space. When Selenium reads text\n out of the page, it attempts to\n duplicate this behavior, so you can\n ignore all the tabs and newlines in\n your HTML and do assertions based on\n how the text looks in the browser when\n rendered. We do this by replacing all\n non-visible whitespace (including the\n non-breaking space \"<code>&amp;nbsp;</code>\") with a\n single space. All visible newlines\n (<code>&lt;br&gt;</code>, <code>&lt;p&gt;</code>, and <code>&lt;pre&gt;</code> formatted\n new lines) should be preserved.</p>\n \n <p>We use the same normalization logic on\n the text of HTML Selenese test case\n tables. This has a number of\n advantages. First, you don't need to\n look at the HTML source of the page to\n figure out what your assertions should\n be; \"<code>&amp;nbsp;</code>\" symbols are invisible\n to the end user, and so you shouldn't\n have to worry about them when writing\n Selenese tests. (You don't need to put\n \"<code>&amp;nbsp;</code>\" markers in your test case\n to assertText on a field that contains\n \"<code>&amp;nbsp;</code>\".) You may also put extra\n newlines and spaces in your Selenese\n <code>&lt;td&gt;</code> tags; since we use the same\n normalization logic on the test case\n as we do on the text, we can ensure\n that assertions and the extracted text\n will match exactly.</p>\n \n <p>This creates a bit of a problem on\n those rare occasions when you really\n want/need to insert extra whitespace\n in your test case. For example, you\n may need to type text in a field like\n this: \"<code>foo</code> \". But if you simply\n write <code>&lt;td&gt;foo &lt;/td&gt;</code> in your\n Selenese test case, we'll replace your\n extra spaces with just one space.</p>\n \n <p>This problem has a simple workaround.\n We've defined a variable in Selenese,\n <code>${space}</code>, whose value is a single\n space. You can use <code>${space}</code> to\n insert a space that won't be\n automatically trimmed, like this:\n <code>&lt;td&gt;foo${space}${space}${space}&lt;/td&gt;</code>.\n We've also included a variable\n <code>${nbsp}</code>, that you can use to insert\n a non-breaking space.</p>\n \n <p>Note that XPaths do <em>not</em> normalize\n whitespace the way we do. If you need\n to write an XPath like\n <code>//div[text()=\"hello world\"]</code> but the\n HTML of the link is really\n \"<code>hello&amp;nbsp;world</code>\", you'll need to\n insert a real \"<code>&amp;nbsp;</code>\" into your\n Selenese test case to get it to match,\n like this:\n <code>//div[text()=\"hello${nbsp}world\"]</code>.</p>\n</blockquote>\n" }, { "answer_id": 248097, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 1, "selected": false, "text": "<p>Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (<code>&amp;amp;</code>, <code>&amp;gt;</code>, <code>&amp;lt;</code>, <code>&amp;apos;</code>, <code>&amp;quot;</code>) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter <code>&amp;#160;</code> in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.</p>\n" }, { "answer_id": 59699055, "author": "undetected Selenium", "author_id": 7429447, "author_profile": "https://Stackoverflow.com/users/7429447", "pm_score": 3, "selected": false, "text": "<p>As per the HTML you have provided:</p>\n\n<pre><code>&lt;tr&gt;\n &lt;td&gt;abc&lt;/td&gt;\n &lt;td&gt;&amp;nbsp;&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>To locate the node with the string <strong><code>&amp;nbsp;</code></strong> you can use either of the following <a href=\"/questions/tagged/xpath\" class=\"post-tag\" title=\"show questions tagged &#39;xpath&#39;\" rel=\"tag\">xpath</a> based solutions:</p>\n\n<ul>\n<li><p>Using <code>text()</code>:</p>\n\n<pre><code>\"//td[text()='\\u00A0']\"\n</code></pre></li>\n<li><p>Using <code>contains()</code>: </p>\n\n<pre><code>\"//td[contains(., '\\u00A0')]\"\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>However, ideally you may like to avoid the <em>NO-BREAK SPACE</em> character and use either of the following <a href=\"https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890\">Locator Strategies</a>:</p>\n\n<ul>\n<li><p>Using the parent <code>&lt;tr&gt;</code> node and <code>following-sibling</code>:</p>\n\n<pre><code>\"//tr//following-sibling::td[2]\"\n</code></pre></li>\n<li><p>Using <code>starts-with()</code>:</p>\n\n<pre><code>\"//tr//td[last()]\"\n</code></pre></li>\n<li><p>Using the preceeding <code>&lt;td&gt;</code> node and <code>following</code><code>node and</code>following-sibling`: </p>\n\n<pre><code>\"//td[text()='abc']//following::td[1]\"\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h2>Reference</h2>\n\n<p>You can find a relevant detailed discussion in:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/59624749/how-to-find-an-element-which-contains-nbsp-using-selenium/59625175#59625175\">How to find an element which contains <code>&amp;nbsp;</code> using Selenium</a></li>\n</ul>\n\n<hr>\n\n<h2>tl; dr</h2>\n\n<p><a href=\"http://www.fileformat.info/info/unicode/char/00a0/index.htm\" rel=\"noreferrer\">Unicode Character 'NO-BREAK SPACE' (U+00A0)</a></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16927/" ]
I use [XPather Browser](http://xpath.alephzarro.com/) to check my XPATH expressions on an HTML page. My end goal is to use these expressions in Selenium for the testing of my user interfaces. I got an HTML file with a content similar to this: ``` <tr> <td>abc</td> <td>&nbsp;</td> </tr> ``` I want to select a node with a text containing the string "`&nbsp;`". With a normal string like "abc" there is no problem. I use an XPATH similar to `//td[text()="abc"]`. When I try with an an XPATH like `//td[text()="&nbsp;"]` it returns nothing. Is there a special rule concerning texts with "`&`" ?
It seems that [OpenQA](http://www.openqa.org/), guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to `//td[text()="${nbsp}"]`. I reproduced here the text from OpenQA concerning this issue (found [here](https://svn.openqa.org/svn/selenium-core/trunk/src/main/resources/doctool/doc2html.xml)): > > HTML automatically normalizes > whitespace within elements, ignoring > leading/trailing spaces and converting > extra spaces, tabs and newlines into a > single space. When Selenium reads text > out of the page, it attempts to > duplicate this behavior, so you can > ignore all the tabs and newlines in > your HTML and do assertions based on > how the text looks in the browser when > rendered. We do this by replacing all > non-visible whitespace (including the > non-breaking space "`&nbsp;`") with a > single space. All visible newlines > (`<br>`, `<p>`, and `<pre>` formatted > new lines) should be preserved. > > > We use the same normalization logic on > the text of HTML Selenese test case > tables. This has a number of > advantages. First, you don't need to > look at the HTML source of the page to > figure out what your assertions should > be; "`&nbsp;`" symbols are invisible > to the end user, and so you shouldn't > have to worry about them when writing > Selenese tests. (You don't need to put > "`&nbsp;`" markers in your test case > to assertText on a field that contains > "`&nbsp;`".) You may also put extra > newlines and spaces in your Selenese > `<td>` tags; since we use the same > normalization logic on the test case > as we do on the text, we can ensure > that assertions and the extracted text > will match exactly. > > > This creates a bit of a problem on > those rare occasions when you really > want/need to insert extra whitespace > in your test case. For example, you > may need to type text in a field like > this: "`foo` ". But if you simply > write `<td>foo </td>` in your > Selenese test case, we'll replace your > extra spaces with just one space. > > > This problem has a simple workaround. > We've defined a variable in Selenese, > `${space}`, whose value is a single > space. You can use `${space}` to > insert a space that won't be > automatically trimmed, like this: > `<td>foo${space}${space}${space}</td>`. > We've also included a variable > `${nbsp}`, that you can use to insert > a non-breaking space. > > > Note that XPaths do *not* normalize > whitespace the way we do. If you need > to write an XPath like > `//div[text()="hello world"]` but the > HTML of the link is really > "`hello&nbsp;world`", you'll need to > insert a real "`&nbsp;`" into your > Selenese test case to get it to match, > like this: > `//div[text()="hello${nbsp}world"]`. > > >
247,149
<pre><code>&lt;?php /** * My codebase is littered with the same conditionals over and over * again. I'm trying to refactor using inheritance and the Factory * pattern and I've had some success but I'm now stuck. * * I'm stuck because I want to derive a new class from the one * returned by the Factory. But I can't do that, so I'm obviously * doing something wrong somewhere else. */ /** * The old implementation was as follows. There's if statements * everywhere throughout both LayoutView and ItemIndexView and * SomeOtherView. */ class LayoutView { } class IndexView extends LayoutView { } class SomeOtherView extends LayoutView { } /** * Below is the new implementation. So far I've managed to tidy * up LayoutView (I think I have anyway). But now I'm stuck because * the way I've tidied it up has left me not knowing how to extend * it. * * For example's sake, let's say the conditions were relating to a * type of fish: salmon or tuna. */ abstract class LayoutView { protected function prepareHeader() { echo __METHOD__, "\n"; } protected function prepareLeftHandSide() { echo __METHOD__, "\n"; } protected function prepareFooter() { echo __METHOD__, "\n"; } public function prepare() { $this-&gt;prepareHeader(); $this-&gt;prepareLeftHandSide(); $this-&gt;prepareFooter(); } } class SalmonLayoutView extends LayoutView { protected function prepareLeftHandSide() { echo __METHOD__, "\n"; } } class TunaLayoutView extends LayoutView { protected function prepareLeftHandSide() { echo __METHOD__, "\n"; } protected function prepareFooter() { echo __METHOD__, "\n"; } } class ViewFactory { public static function getLayoutView($fishType) { switch($this-&gt;$fishType) { case 'salmon': return new SalmonLayoutView(); break; case 'tuna': return new TunaLayoutView(); break; } } } /** * Now LayoutView has been cleaned up and the condition that was once * scattered through every LayoutView method is now in one place. */ $view = ViewFactory::getLayoutView( Config::getOption('fishtype') ); $view-&gt;prepare(); /** * Now here's where I'm stuck. I want to effectively extend whatever * class $view is an instance of. * * The reason being, I wish to derive a view to show an index of * articles within the appropriate *LayoutView. The IndexView code is * the same for Salmon and Tuna. * * I can do something like this: */ class SalmonIndexView extends SalmonLayoutView { } class TunaIndexView extends TunaLayoutView { } /** * But then I'll be writing the same IndexView code twice. What I'd * like to do is something like this: */ $view = ViewFactory::getLayoutView( Config::getOption('fishtype') ); class IndexView extends get_class($view) { } /** * But I'm pretty certain that's not possible, and even if it was * it seems very wrong. * * Can someone more experienced in refactoring and OO please let * me know where I've gone wrong and suggest a clean way to solve * this? */ </code></pre>
[ { "answer_id": 247172, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>If the IndexView code really is the same then you don't need inheritance, but composition. Add, in your base LayoutView class, an instance of IndexView that then you'll be able to call from each *LayoutView.</p>\n\n<p>Inheritance is due only when the relationship between objects is is-a. I deduce that an IndexView is not a LayoutView, but rather the LayoutView has an IndexView.</p>\n\n<p>Check this out, I don't agree with everything it says, but still:\n<a href=\"http://phpimpact.wordpress.com/2008/09/04/favour-object-composition-over-class-inheritance/\" rel=\"nofollow noreferrer\">http://phpimpact.wordpress.com/2008/09/04/favour-object-composition-over-class-inheritance/</a></p>\n" }, { "answer_id": 249602, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>Just pass the template as a parameter to the subviews you'll compose. I don't think that'd be evil in this case. Although if it's a standard framework you might be better asking in their forums, because they might have a functionality we are unaware of for this case (it usually happens)</p>\n\n<p>You could have something like</p>\n\n<pre><code>class LayoutView {\n protected View $subview; //Potentially an array of views\n public function prepare() {\n // empty, to be filled out by derived classes\n }\n public function setSubView($view) { $this-&gt;subview = $view; }\n public function display() {\n $this-&gt;prepare();\n $this-&gt;subview-&gt;prepare($this-&gt;template);\n $this-&gt;template-&gt;render();\n }\n}\n\nclass IndexView {\n protected View $subview; //Potentially an array of views\n public function prepare() {\n // empty, to be filled out by derived classes\n }\n public function prepare($template) {\n //operate on it, maybe even assigning it to $this-&gt;template\n }\n public function setSubView($view) { $this-&gt;subview = $view; }\n public function display() {\n $this-&gt;prepare();\n $this-&gt;subview-&gt;prepare($this-&gt;template);\n $this-&gt;template-&gt;render();\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` <?php /** * My codebase is littered with the same conditionals over and over * again. I'm trying to refactor using inheritance and the Factory * pattern and I've had some success but I'm now stuck. * * I'm stuck because I want to derive a new class from the one * returned by the Factory. But I can't do that, so I'm obviously * doing something wrong somewhere else. */ /** * The old implementation was as follows. There's if statements * everywhere throughout both LayoutView and ItemIndexView and * SomeOtherView. */ class LayoutView { } class IndexView extends LayoutView { } class SomeOtherView extends LayoutView { } /** * Below is the new implementation. So far I've managed to tidy * up LayoutView (I think I have anyway). But now I'm stuck because * the way I've tidied it up has left me not knowing how to extend * it. * * For example's sake, let's say the conditions were relating to a * type of fish: salmon or tuna. */ abstract class LayoutView { protected function prepareHeader() { echo __METHOD__, "\n"; } protected function prepareLeftHandSide() { echo __METHOD__, "\n"; } protected function prepareFooter() { echo __METHOD__, "\n"; } public function prepare() { $this->prepareHeader(); $this->prepareLeftHandSide(); $this->prepareFooter(); } } class SalmonLayoutView extends LayoutView { protected function prepareLeftHandSide() { echo __METHOD__, "\n"; } } class TunaLayoutView extends LayoutView { protected function prepareLeftHandSide() { echo __METHOD__, "\n"; } protected function prepareFooter() { echo __METHOD__, "\n"; } } class ViewFactory { public static function getLayoutView($fishType) { switch($this->$fishType) { case 'salmon': return new SalmonLayoutView(); break; case 'tuna': return new TunaLayoutView(); break; } } } /** * Now LayoutView has been cleaned up and the condition that was once * scattered through every LayoutView method is now in one place. */ $view = ViewFactory::getLayoutView( Config::getOption('fishtype') ); $view->prepare(); /** * Now here's where I'm stuck. I want to effectively extend whatever * class $view is an instance of. * * The reason being, I wish to derive a view to show an index of * articles within the appropriate *LayoutView. The IndexView code is * the same for Salmon and Tuna. * * I can do something like this: */ class SalmonIndexView extends SalmonLayoutView { } class TunaIndexView extends TunaLayoutView { } /** * But then I'll be writing the same IndexView code twice. What I'd * like to do is something like this: */ $view = ViewFactory::getLayoutView( Config::getOption('fishtype') ); class IndexView extends get_class($view) { } /** * But I'm pretty certain that's not possible, and even if it was * it seems very wrong. * * Can someone more experienced in refactoring and OO please let * me know where I've gone wrong and suggest a clean way to solve * this? */ ```
If the IndexView code really is the same then you don't need inheritance, but composition. Add, in your base LayoutView class, an instance of IndexView that then you'll be able to call from each \*LayoutView. Inheritance is due only when the relationship between objects is is-a. I deduce that an IndexView is not a LayoutView, but rather the LayoutView has an IndexView. Check this out, I don't agree with everything it says, but still: <http://phpimpact.wordpress.com/2008/09/04/favour-object-composition-over-class-inheritance/>
247,156
<p>I'm having a disagreement with someone over how best to implement a simple method that takes an array of integers, and returns the highest integer (using C# 2.0).</p> <p>Below are the two implementations - I have my own opinion of which is better, and why, but I'd appreciate any impartial opinions.</p> <p><strong>Option A</strong></p> <pre><code>public int GetLargestValue(int[] values) { try { Array.Sort(values); return values[values.Length - 1]; } catch (Exception){ return -1;} } </code></pre> <p><strong>Option B</strong></p> <pre><code>public int GetLargestValue(int[] values) { if(values == null) return -1; if(values.Length &lt; 1) return -1; int highestValue = values[0]; foreach(int value in values) if(value &gt; highestValue) highestValue = value; return highestValue; } </code></pre>
[ { "answer_id": 247170, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I prefer <strong>Option B</strong> as it only traverses the collection exactly once. </p>\n\n<p>In <strong>Option A</strong>, you may have to access many elements more than once (the number of times is dependant upon the implementation of the sort alogrithm).</p>\n\n<p>The <strong>Option A</strong> is an inefficent implementation, but results in a fairly clear algorithm. It does however use a fairly ugly Exception catch which would only ever be triggered if an empty array is passed in (so could probably be written clearer with a pre-sort check). </p>\n\n<p>PS, you should never simply catch \"Exception\" and then correct things. There are many types of Exceptions and generally you should catch each possible one and handle accordingly.</p>\n" }, { "answer_id": 247176, "author": "SharePoint Newbie", "author_id": 21586, "author_profile": "https://Stackoverflow.com/users/21586", "pm_score": 3, "selected": false, "text": "<p>The second one is better.\nThe complexity of the first is <code>O(N LogN)</code>, and for the second it is <code>O(N)</code>.</p>\n" }, { "answer_id": 247179, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "<p>I have to choose option B - not that it's perfect but because option A uses exceptions to represent logic.</p>\n" }, { "answer_id": 247181, "author": "François", "author_id": 32379, "author_profile": "https://Stackoverflow.com/users/32379", "pm_score": 4, "selected": false, "text": "<p>Ôption B of course.</p>\n\n<p>A is ugly :</p>\n\n<ul>\n<li><p>Catch(Exception) is a really bad practice</p></li>\n<li><p>You shoul not rely on exception for null ref, out of range,...</p></li>\n<li><p>Sorting is way complexier than iteration</p></li>\n</ul>\n\n<p>Complexity :</p>\n\n<ul>\n<li><p>A will be O(n log(n)) and even O(n²) in worst case</p></li>\n<li><p>B worst case is O(n)</p></li>\n</ul>\n" }, { "answer_id": 247186, "author": "Ian Andrews", "author_id": 2382102, "author_profile": "https://Stackoverflow.com/users/2382102", "pm_score": 0, "selected": false, "text": "<p>I would say that it depends on what your goal is, speed or readability. </p>\n\n<p>If processing speed is your goal, I'd say the second solution, but if readability is the goal, I'd pick the first one.</p>\n\n<p>I'd probably go for speed for this type of function, so I'd pick the second one.</p>\n" }, { "answer_id": 247190, "author": "Ty.", "author_id": 8873, "author_profile": "https://Stackoverflow.com/users/8873", "pm_score": 0, "selected": false, "text": "<p>There are many factors to consider here. Both options should include the bounds checks that are in option B and do away with using Exception handling in that manner. The second option should perform better most of the time as it only needs to traverse the array once. However, if the data was already sorted or needed to be sorted; then Option A would be preferable.</p>\n\n<p>No sorting algorithm performs in <em>n</em> time, so Option B will be the fastest on average.</p>\n\n<p>Edit: <a href=\"http://linux.wku.edu/~lamonml/algor/sort/sort.html\" rel=\"nofollow noreferrer\">Article on sorting</a></p>\n" }, { "answer_id": 247196, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "<p>I see two points here:</p>\n\n<ol>\n<li>Parameter testing as opposed to exception handling: Better use explicit checking, should also be faster. </li>\n<li>Sorting and picking the largest value as opposed to walking the whole array. Since sorting involves handling each integer in the array <em>at least once</em>, it will not perform as well as walking the whole array (only) once.</li>\n</ol>\n\n<p>Which is better? For the first point, definitely explicit checking. For the second, it depends...</p>\n\n<p>The first example is shorter, makes it quicker to write and read/understand. The second is faster. So: If runtime efficiency is an issue, choose the second option. If fast coding is your goal, use the first one.</p>\n" }, { "answer_id": 247201, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 3, "selected": false, "text": "<p>A has the side effect that it sorts the array. This might be unexpected by the caller.</p>\n\n<p>Edit: I don't like to return -1 for empty or null array (in both solutions), since -1 might be a legal value in the array. This should really generate an exception (perhaps <code>ArgumentException</code>).</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm having a disagreement with someone over how best to implement a simple method that takes an array of integers, and returns the highest integer (using C# 2.0). Below are the two implementations - I have my own opinion of which is better, and why, but I'd appreciate any impartial opinions. **Option A** ``` public int GetLargestValue(int[] values) { try { Array.Sort(values); return values[values.Length - 1]; } catch (Exception){ return -1;} } ``` **Option B** ``` public int GetLargestValue(int[] values) { if(values == null) return -1; if(values.Length < 1) return -1; int highestValue = values[0]; foreach(int value in values) if(value > highestValue) highestValue = value; return highestValue; } ```
Ôption B of course. A is ugly : * Catch(Exception) is a really bad practice * You shoul not rely on exception for null ref, out of range,... * Sorting is way complexier than iteration Complexity : * A will be O(n log(n)) and even O(n²) in worst case * B worst case is O(n)
247,161
<p>How can I transform a <code>String</code> value into an <code>InputStreamReader</code>?</p>
[ { "answer_id": 247169, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 5, "selected": false, "text": "<p>Does it have to be specifically an InputStreamReader? How about using <a href=\"http://java.sun.com/javase/6/docs/api/java/io/StringReader.html\" rel=\"noreferrer\">StringReader</a>?</p>\n\n<p>Otherwise, you could use <a href=\"http://java.sun.com/javase/6/docs/api/java/io/StringBufferInputStream.html\" rel=\"noreferrer\">StringBufferInputStream</a>, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).</p>\n" }, { "answer_id": 247184, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 9, "selected": true, "text": "<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html\" rel=\"noreferrer\">ByteArrayInputStream</a> also does the trick:</p>\n\n<pre><code>InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );\n</code></pre>\n\n<p>Then convert to reader:</p>\n\n<pre><code>InputStreamReader reader = new InputStreamReader(is);\n</code></pre>\n" }, { "answer_id": 247193, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": false, "text": "<p>Same question as <a href=\"https://stackoverflow.com/questions/247161/how-do-i-turn-a-string-into-a-stream-in-java#247169\">@Dan</a> - why not StringReader ?</p>\n\n<p>If it has to be InputStreamReader, then:</p>\n\n<pre><code>String charset = ...; // your charset\nbyte[] bytes = string.getBytes(charset);\nByteArrayInputStream bais = new ByteArrayInputStream(bytes);\nInputStreamReader isr = new InputStreamReader(bais);\n</code></pre>\n" }, { "answer_id": 247344, "author": "Yossale", "author_id": 4038, "author_profile": "https://Stackoverflow.com/users/4038", "pm_score": 6, "selected": false, "text": "<p>I also found the apache commons <code>IOUtils</code> class , so : </p>\n\n<pre><code>InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));\n</code></pre>\n" }, { "answer_id": 27907431, "author": "Fai Ng", "author_id": 1413206, "author_profile": "https://Stackoverflow.com/users/1413206", "pm_score": 2, "selected": false, "text": "<p>Are you trying to get a) <code>Reader</code> functionality out of <code>InputStreamReader</code>, or b) <code>InputStream</code> functionality out of <code>InputStreamReader</code>? You won't get b). <code>InputStreamReader</code> is not an <code>InputStream</code>.</p>\n\n<p>The purpose of <code>InputStreamReader</code> is to take an <code>InputStream</code> - a source of bytes - and decode the bytes to chars in the form of a <code>Reader</code>. You already have your data as chars (your original String). Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.</p>\n\n<p>If you are trying to get a <code>Reader</code> out of your source, use <code>StringReader</code>.</p>\n\n<p>If you are trying to get an <code>InputStream</code> (which only gives you bytes), use apache commons <code>IOUtils.toInputStream(..)</code> as suggested by other answers here.</p>\n" }, { "answer_id": 45905170, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 2, "selected": false, "text": "<p>You can try <a href=\"http://www.cactoos.org\" rel=\"nofollow noreferrer\">Cactoos</a>:</p>\n\n<pre><code>InputStream stream = new InputStreamOf(str);\n</code></pre>\n\n<p>Then, if you need a <code>Reader</code>:</p>\n\n<pre><code>Reader reader = new ReaderOf(stream);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4038/" ]
How can I transform a `String` value into an `InputStreamReader`?
[ByteArrayInputStream](http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html) also does the trick: ``` InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) ); ``` Then convert to reader: ``` InputStreamReader reader = new InputStreamReader(is); ```
247,167
<p>Looking for a bit of regex help. I'd like to design an expression that matches a string with "<em>foo</em>" OR "<em>bar</em>", but not both "<em>foo</em>" AND "<em>bar</em>"</p> <p>If I do something like...</p> <pre><code>/((foo)|(bar))/ </code></pre> <p>It'll match "<em>foobar</em>". Not what I'm looking for. So, how can I make regex match only when one term or the other is present?</p> <p>Thanks!</p>
[ { "answer_id": 247177, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 4, "selected": true, "text": "<p>You can do this with a single regex but I suggest for the sake of readability you do something like...</p>\n\n<pre><code>(/foo/ and not /bar/) || (/bar/ and not /foo/)\n</code></pre>\n" }, { "answer_id": 247202, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 0, "selected": false, "text": "<p>I'd use something like this. It just checks for space around the words, but you could use the <code>\\b</code> or <code>\\B</code> to check for a border if you use <code>\\w</code>. This would match \" foo \" or \" bar \", so obviously you'd have to replace the whitespace as well, just in case. (Assuming you're replacing anything.)</p>\n\n<pre><code>/\\s((foo)|(bar))\\s/\n</code></pre>\n" }, { "answer_id": 247227, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 0, "selected": false, "text": "<p>I don't think this can be done with a single regular expression. And boundaries may or may not work depending on what you're matching against.</p>\n\n<p>I would match against each regex separately, and do an XOR on the results.</p>\n\n<pre><code>foo = re.search(\"foo\", str) != None\nbar = re.search(\"bar\", str) != None\nif foo ^ bar:\n # do someting...\n</code></pre>\n" }, { "answer_id": 247243, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>I tried with Regex Coach against:</p>\n\n<pre><code>x foo y\nx bar y\nx foobar y\n</code></pre>\n\n<p>If I check the <code>g</code> option, indeed it matches all three words, because it searches again after each match.<br>\nIf you don't want this behavior, you can anchor the expression, for example matching only on word boundaries:</p>\n\n<pre><code>\\b(foo|bar)\\b\n</code></pre>\n\n<p>Giving more context on the problem (what the data looks like) might give better answers.</p>\n" }, { "answer_id": 247299, "author": "Andrew Cowenhoven", "author_id": 12281, "author_profile": "https://Stackoverflow.com/users/12281", "pm_score": 0, "selected": false, "text": "<pre><code>\\b(foo)\\b|\\b(bar)\\b\n</code></pre>\n\n<p>And use only the first <a href=\"http://www.regular-expressions.info/brackets.html\" rel=\"nofollow noreferrer\">capture group</a>.</p>\n" }, { "answer_id": 247363, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 2, "selected": false, "text": "<p>You might want to consider the ? conditional test.</p>\n\n<pre><code>(?(?=regex)then|else)\n</code></pre>\n\n<p><a href=\"http://www.regular-expressions.info/conditional.html\" rel=\"nofollow noreferrer\">Regular Expression Conditionals</a></p>\n" }, { "answer_id": 247485, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "<p>If your regex language supports it, use <a href=\"http://www.regular-expressions.info/lookaround.html\" rel=\"noreferrer\">negative lookaround</a>:</p>\n\n<pre><code>(?&lt;!foo|bar)(foo|bar)(?!foo|bar)\n</code></pre>\n\n<p>This will match \"foo\" or \"bar\" that is not immediately preceded or followed by \"foo\" or \"bar\", which I think is what you wanted. </p>\n\n<p>It's not clear from your question or examples if the string you're trying to match can contain other tokens: \"foocuzbar\". If so, this pattern won't work.</p>\n\n<p>Here are the results of your test cases (\"true\" means the pattern was found in the input):</p>\n\n<pre><code>foo: true\nbar: true\nfoofoo: false\nbarfoo: false\nfoobarfoo: false\nbarbar: false\nbarfoofoo: false\n</code></pre>\n" }, { "answer_id": 247525, "author": "bill_the_loser", "author_id": 5239, "author_profile": "https://Stackoverflow.com/users/5239", "pm_score": 0, "selected": false, "text": "<p>Using the word boundaries, you can get the single word... </p>\n\n<pre><code>me@home ~ \n$ echo \"Where is my bar of soap?\" | egrep \"\\bfoo\\b|\\bbar\\b\" \nWhere is my bar of soap? \n\nme@home ~ \n$ echo \"What the foo happened here?\" | egrep \"\\bfoo\\b|\\bbar\\b\" \nWhat the foo happened here? \n\nme@home ~ \n$ echo \"Boy, that sure is foobar\\!\" | egrep \"\\bfoo\\b|\\bbar\\b\" \n</code></pre>\n" }, { "answer_id": 247585, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>You haven't specified behaviour regarding content other than \"foo\" and \"bar\" or repetitions of one in the absence of the other. e.g., Should \"<strong>foo</strong>d\" or \"<strong>barbar</strong>ian\" match?</p>\n\n<p>Assuming that you want to match strings which contain only one instance of either \"foo\" or \"bar\", but not both and not multiple instances of the same one, without regard for anything else in the string (i.e., \"food\" matches and \"barbarian\" does not match), then you could use a regex which returns the number of matches found and only consider it successful if exactly one match is found. e.g., in Perl:</p>\n\n<pre><code>@matches = ($value =~ /(foo|bar)/g) # @matches now hold all foos or bars present\nif (scalar @matches == 1) { # exactly one match found\n ...\n}\n</code></pre>\n\n<p>If multiple repetitions of that same target are allowed (i.e., \"barbarian\" matches), then this same general approach could be used by then walking the list of matches to see whether the matches are all repeats of the same text or if the other option is also present.</p>\n" }, { "answer_id": 247789, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<p>If you want a true exclusive or, I'd just do that in code instead of in the regex. In Perl:</p>\n\n<pre><code>/foo/ xor /bar/\n</code></pre>\n\n<p>But your comment:</p>\n\n<blockquote>\n <p>Matches: \"foo\", \"bar\" nonmatches:\n \"foofoo\" \"barfoo\" \"foobarfoo\" \"barbar\"\n \"barfoofoo\"</p>\n</blockquote>\n\n<p>indicates that you're not really looking for exclusive or. You actually mean\n\"Does <code>/foo|bar/</code> match exactly once?\"</p>\n\n<pre><code>my $matches = 0;\nwhile (/foo|bar/g) {\n last if ++$matches &gt; 1;\n}\n\nmy $ok = ($matches == 1)\n</code></pre>\n" }, { "answer_id": 8361884, "author": "Tristan", "author_id": 1078141, "author_profile": "https://Stackoverflow.com/users/1078141", "pm_score": 5, "selected": false, "text": "<p>This is what I use:</p>\n\n<pre><code>/^(foo|bar){1}$/\n</code></pre>\n\n<p>See: <a href=\"http://www.regular-expressions.info/quickstart.html\" rel=\"noreferrer\">http://www.regular-expressions.info/quickstart.html</a> under repetition </p>\n" }, { "answer_id": 25742668, "author": "oriadam", "author_id": 3356679, "author_profile": "https://Stackoverflow.com/users/3356679", "pm_score": 3, "selected": false, "text": "<p>This will take 'foo' and 'bar' but not 'foobar' and not 'blafoo' and not 'blabar':</p>\n\n<pre><code>/^(foo|bar)$/\n\n^ = mark start of string (or line)\n$ = mark end of string (or line)\n</code></pre>\n\n<p>This will take 'foo' and 'bar' and 'foo bar' and 'bar-foo' but not 'foobar' and not 'blafoo' and not 'blabar':</p>\n\n<pre><code>/\\b(foo|bar)\\b/\n\n\\b = mark word boundry\n</code></pre>\n" }, { "answer_id": 31237322, "author": "qmckinsey", "author_id": 5030228, "author_profile": "https://Stackoverflow.com/users/5030228", "pm_score": 1, "selected": false, "text": "<p>I know this is a late entry, but just to help others who may be looking:</p>\n\n<pre><code>(/b(?:(?:(?!foo)bar)|(?:(?!bar)foo))/b)\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26001/" ]
Looking for a bit of regex help. I'd like to design an expression that matches a string with "*foo*" OR "*bar*", but not both "*foo*" AND "*bar*" If I do something like... ``` /((foo)|(bar))/ ``` It'll match "*foobar*". Not what I'm looking for. So, how can I make regex match only when one term or the other is present? Thanks!
You can do this with a single regex but I suggest for the sake of readability you do something like... ``` (/foo/ and not /bar/) || (/bar/ and not /foo/) ```
247,209
<p>As JavaScript frameworks like jQuery make client side web applications richer and more functional, I've started to notice one problem...</p> <p><strong>How in the world do you keep this organized?</strong></p> <ul> <li>Put all your handlers in one spot and write functions for all the events?</li> <li>Create function/classes to wrap all your functionality?</li> <li>Write like crazy and just hope it works out for the best?</li> <li>Give up and get a new career?</li> </ul> <p>I mention jQuery, but it's really any JavaScript code in general. I'm finding that as lines upon lines begin to pile up, it gets harder to manage the script files or find what you are looking for. Quite possibly the biggest propblems I've found is there are so many ways to do the same thing, it's hard to know which one is the current commonly accepted best practice.</p> <p>Are there any general recommendations on the best way to keep your <strong>.js</strong> files as nice and neat as the rest of your application? Or is this just a matter of IDE? Is there a better option out there?</p> <hr> <p><strong>EDIT</strong></p> <p>This question was intended to be more about code organization and not file organization. There has been some really good examples of merging files or splitting content around.</p> <p>My question is: what is the current commonly accepted best practice way to organize your actual code? What is your way, or even a recommended way to interact with page elements and create reuseable code that doesn't conflict with each other?</p> <p>Some people have listed <strong>namespaces</strong> which is a good idea. What are some other ways, more specifically dealing with elements on the page and keeping the code organized and neat?</p>
[ { "answer_id": 247223, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "<p>You can break up your scripts into separate files for development, then create a \"release\" version where you cram them all together and run <a href=\"http://developer.yahoo.com/yui/compressor/\" rel=\"noreferrer\">YUI Compressor</a> or something similar on it.</p>\n" }, { "answer_id": 247251, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 2, "selected": false, "text": "<p>A few days ago, the guys at 37Signals <a href=\"http://github.com/37signals/wysihat/tree/master\" rel=\"nofollow noreferrer\">released a RTE control</a>, with a twist. They made a library that bundles javascript files using a sort of pre-processor commands.</p>\n\n<p>I've been using it since to separate my JS files and then in the end merge them as one. That way I can separate concerns and, in the end, have only one file that goes through the pipe (gzipped, no less).</p>\n\n<p>In your templates, check if you're in development mode, and include the separate files, and if in production, include the final one (which you'll have to \"build\" yourself).</p>\n" }, { "answer_id": 247256, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 0, "selected": false, "text": "<p>I use a custom script inspired by Ben Nolan's behaviour (I can't find a current link to this anymore, sadly) to store most of my event handlers. These event handlers are triggered by the elements className or Id, for example. \nExample:</p>\n\n<pre><code>Behaviour.register({ \n 'a.delete-post': function(element) {\n element.observe('click', function(event) { ... });\n },\n\n 'a.anotherlink': function(element) {\n element.observe('click', function(event) { ... });\n }\n\n});\n</code></pre>\n\n<p>I like to include most of my Javascript libraries on the fly, except the ones that contain global behaviour. I use <a href=\"http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.headscript\" rel=\"nofollow noreferrer\">Zend Framework's headScript() placeholder helper</a> for this, but you can also <a href=\"http://ajaxpatterns.org/On-Demand_Javascript\" rel=\"nofollow noreferrer\">use javascript to load other scripts on the fly</a> with <a href=\"http://ajile.iskitz.com/\" rel=\"nofollow noreferrer\">Ajile</a> for example.</p>\n" }, { "answer_id": 247321, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 3, "selected": false, "text": "<p>My boss still speaks of the times when they wrote modular code (C language), and complains about how crappy the code is nowadays! It is said that programmers can write assembly in any framework. There is always a strategy to overcome code organisation. The basic problem is with guys who treat java script as a toy and never try to learn it.</p>\n\n<p>In my case, I write js files on a UI theme or application screen basis, with a proper init_screen(). Using proper id naming convention, I make sure that there are no name space conflicts at the root element level. In the unobstrusive window.load(), I tie the things up based on the top level id.</p>\n\n<p>I strictly use java script closures and patterns to hide all private methods. After doing this, never faced a problem of conflicting properties/function definitions/variable definitions. However, when working with a team it is often difficult to enforce the same rigour. </p>\n" }, { "answer_id": 247406, "author": "polarbear", "author_id": 3636, "author_profile": "https://Stackoverflow.com/users/3636", "pm_score": 8, "selected": false, "text": "<p>It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes <a href=\"http://www.dustindiaz.com/namespace-your-javascript/\" rel=\"noreferrer\">here</a> helps me a lot. </p>\n\n<pre><code>var DED = (function() {\n\n var private_var;\n\n function private_method()\n {\n // do stuff here\n }\n\n return {\n method_1 : function()\n {\n // do stuff here\n },\n method_2 : function()\n {\n // do stuff here\n }\n };\n})();\n</code></pre>\n\n<p>I put different \"namespaces\" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.</p>\n" }, { "answer_id": 248669, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 3, "selected": false, "text": "<p>I create singletons for every thing I really do not need to instantiate several times on screen, a classes for everything else. And all of them are put in the same namespace in the same file. Everything is commented, and designed with UML , state diagrams. The javascript code is clear of html so no inline javascript and I tend to use jquery to minimize cross browser issues.</p>\n" }, { "answer_id": 248783, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>You don't mention what your server-side language is. Or, more pertinently, what framework you are using -- if any -- on the server-side. </p>\n\n<p>IME, I organise things on the server-side and let it all shake out onto the web page. The framework is given the task of organising not only JS that every page has to load, but also JS fragments that work with generated markup. Such fragments you don't usually want emitted more than once - which is why they are abstracted into the framework for that code to look after that problem. :-)</p>\n\n<p>For end-pages that have to emit their own JS, I usually find that there is a logical structure in the generated markup. Such localised JS can often be assembled at the start and/or end of such a structure. </p>\n\n<p>Note that none of this absolves you from writing efficient JavaScript! :-)</p>\n" }, { "answer_id": 248951, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 5, "selected": false, "text": "<p>Inspired by earlier posts I made a copy of <strong>Rakefile</strong> and <strong>vendor</strong> directories distributed with <a href=\"http://github.com/37signals/wysihat/tree/master\" rel=\"noreferrer\"><strong>WysiHat</strong></a> (a RTE mentioned by changelog) and made a few modifications to include code-checking with <a href=\"http://www.jslint.com/lint.html\" rel=\"noreferrer\"><strong>JSLint</strong></a> and minification with <a href=\"http://developer.yahoo.com/yui/compressor/\" rel=\"noreferrer\"><strong>YUI Compressor</strong></a>.</p>\n\n<p>The idea is to use <a href=\"http://github.com/sstephenson/sprockets/tree/master\" rel=\"noreferrer\"><strong>Sprockets</strong></a> (from WysiHat) to merge multiple JavaScripts into one file, check syntax of the merged file with JSLint and minify it with YUI Compressor before distribution.</p>\n\n<p><strong>Prerequisites</strong></p>\n\n<ul>\n<li>Java Runtime</li>\n<li>ruby and rake gem</li>\n<li>You should know how to put a JAR into <a href=\"http://en.wikipedia.org/wiki/Classpath\" rel=\"noreferrer\">Classpath</a></li>\n</ul>\n\n<p><strong>Now do</strong></p>\n\n<ol>\n<li>Download <a href=\"http://www.mozilla.org/rhino/download.html\" rel=\"noreferrer\">Rhino</a> and put the JAR (\"js.jar\") to your classpath</li>\n<li>Download <a href=\"http://www.julienlecomte.net/yuicompressor/\" rel=\"noreferrer\">YUI Compressor</a> and put the JAR (build/yuicompressor-xyz.jar) to your classpath</li>\n<li>Download <a href=\"http://github.com/37signals/wysihat/tree/master\" rel=\"noreferrer\">WysiHat</a> and copy \"vendor\" directory to the root of your JavaScript project</li>\n<li>Download <a href=\"http://www.jslint.com/rhino/index.html\" rel=\"noreferrer\">JSLint for Rhino</a> and put it inside the \"vendor\" directory</li>\n</ol>\n\n<p>Now create a file named \"Rakefile\" in the root directory of the JavaScript project and add the following content to it:</p>\n\n<pre><code>require 'rake'\n\nROOT = File.expand_path(File.dirname(__FILE__))\nOUTPUT_MERGED = \"final.js\"\nOUTPUT_MINIFIED = \"final.min.js\"\n\ntask :default =&gt; :check\n\ndesc \"Merges the JavaScript sources.\"\ntask :merge do\n require File.join(ROOT, \"vendor\", \"sprockets\")\n\n environment = Sprockets::Environment.new(\".\")\n preprocessor = Sprockets::Preprocessor.new(environment)\n\n %w(main.js).each do |filename|\n pathname = environment.find(filename)\n preprocessor.require(pathname.source_file)\n end\n\n output = preprocessor.output_file\n File.open(File.join(ROOT, OUTPUT_MERGED), 'w') { |f| f.write(output) }\nend\n\ndesc \"Check the JavaScript source with JSLint.\"\ntask :check =&gt; [:merge] do\n jslint_path = File.join(ROOT, \"vendor\", \"jslint.js\")\n\n sh 'java', 'org.mozilla.javascript.tools.shell.Main',\n jslint_path, OUTPUT_MERGED\nend\n\ndesc \"Minifies the JavaScript source.\"\ntask :minify =&gt; [:merge] do\n sh 'java', 'com.yahoo.platform.yui.compressor.Bootstrap', '-v',\n OUTPUT_MERGED, '-o', OUTPUT_MINIFIED\nend\n</code></pre>\n\n<p>If you done everything correctly, you should be able to use the following commands in your console:</p>\n\n<ul>\n<li><code>rake merge</code> -- to merge different JavaScript files into one</li>\n<li><code>rake check</code> -- to check the syntax of your code (this is the <strong>default</strong> task, so you can simply type <code>rake</code>)</li>\n<li><code>rake minify</code> -- to prepare minified version of your JS code</li>\n</ul>\n\n<p><strong>On source merging</strong></p>\n\n<p>Using Sprockets, the JavaScript pre-processor you can include (or <code>require</code>) other JavaScript files. Use the following syntax to include other scripts from the initial file (named \"main.js\", but you can change that in the Rakefile):</p>\n\n<pre><code>(function() {\n//= require \"subdir/jsfile.js\"\n//= require \"anotherfile.js\"\n\n // some code that depends on included files\n // note that all included files can be in the same private scope\n})();\n</code></pre>\n\n<p><strong>And then...</strong></p>\n\n<p>Take a look at Rakefile provided with WysiHat to set the automated unit testing up. Nice stuff :)</p>\n\n<p><strong>And now for the answer</strong></p>\n\n<p>This does not answer the original question very well. I know and I'm sorry about that, but I've posted it here because I hope it may be useful to someone else to organize their mess.</p>\n\n<p>My approach to the problem is to do as much object-oriented modelling I can and separate implementations into different files. Then the handlers should be as short as possible. The example with <code>List</code> singleton is also nice one.</p>\n\n<p>And namespaces... well they can be imitated by deeper object structure.</p>\n\n<pre><code>if (typeof org === 'undefined') {\n var org = {};\n}\n\nif (!org.hasOwnProperty('example')) {\n org.example = {};\n}\n\norg.example.AnotherObject = function () {\n // constructor body\n};\n</code></pre>\n\n<p>I'm not big fan of imitations, but this can be helpful if you have many objects that you would like to move out of the global scope.</p>\n" }, { "answer_id": 270654, "author": "Alan", "author_id": 1663, "author_profile": "https://Stackoverflow.com/users/1663", "pm_score": 4, "selected": false, "text": "<p>I was able to successfully apply the <a href=\"http://yuiblog.com/blog/2007/06/12/module-pattern/\" rel=\"noreferrer\">Javascript Module Pattern</a> to an Ext JS application at my previous job. It provided a simple way to create nicely encapsulated code.</p>\n" }, { "answer_id": 284700, "author": "Jason Moore", "author_id": 18158, "author_profile": "https://Stackoverflow.com/users/18158", "pm_score": 6, "selected": false, "text": "<p>I try to avoid including any javascript with the HTML. All the code is encapsulated into classes and each class is in its own file. For development, I have separate &lt;script&gt; tags to include each js file, but they get merged into a single larger package for production to reduce the overhead of the HTTP requests.</p>\n\n<p>Typically, I'll have a single 'main' js file for each application. So, if I was writing a \"survey\" application, i would have a js file called \"survey.js\". This would contain the entry point into the jQuery code. I create jQuery references during instantiation and then pass them into my objects as parameters. This means that the javascript classes are 'pure' and don't contain any references to CSS ids or classnames. </p>\n\n<pre><code>// file: survey.js\n$(document).ready(function() {\n var jS = $('#surveycontainer');\n var jB = $('#dimscreencontainer');\n var d = new DimScreen({container: jB});\n var s = new Survey({container: jS, DimScreen: d});\n s.show();\n});\n</code></pre>\n\n<p>I also find naming convention to be important for readability. For example: I prepend 'j' to all jQuery instances.</p>\n\n<p>In the above example, there is a class called DimScreen. (Assume this dims the screen and pops up an alert box.) It needs a div element that it can enlarge to cover the screen, and then add an alert box, so I pass in a jQuery object. jQuery has a plug-in concept, but it seemed limiting (e.g. instances are not persistent and cannot be accessed) with no real upside. So the DimScreen class would be a standard javascript class that just happens to use jQuery.</p>\n\n<pre><code>// file: dimscreen.js\nfunction DimScreen(opts) { \n this.jB = opts.container;\n // ...\n}; // need the semi-colon for minimizing!\n\n\nDimScreen.prototype.draw = function(msg) {\n var me = this;\n me.jB.addClass('fullscreen').append('&lt;div&gt;'+msg+'&lt;/div&gt;');\n //...\n};\n</code></pre>\n\n<p>I've built some fairly complex appliations using this approach.</p>\n" }, { "answer_id": 387377, "author": "meouw", "author_id": 12161, "author_profile": "https://Stackoverflow.com/users/12161", "pm_score": 4, "selected": false, "text": "<p>Following good OO design principals and design patterns goes a long way to making your code easy to maintain and understand.\nBut one of the best things I've discovered recently are signals and slots aka publish/subscribe.\nHave a look at <a href=\"http://markdotmeyer.blogspot.com/2008/09/jquery-publish-subscribe.html\" rel=\"nofollow noreferrer\">http://markdotmeyer.blogspot.com/2008/09/jquery-publish-subscribe.html</a>\nfor a simple jQuery implementation.</p>\n\n<p>The idea is well used in other languages for GUI development. When something significant happens somewhere in your code you publish a global synthetic event which other methods in other objects may subscribe to.\nThis gives excellent separation of objects. </p>\n\n<p>I think Dojo (and Prototype?) have a built in version of this technique.</p>\n\n<p>see also <a href=\"https://stackoverflow.com/questions/312895/signals-and-slots\">What are signals and slots?</a></p>\n" }, { "answer_id": 387621, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 4, "selected": false, "text": "<p>Dojo had the module system from the day one. In fact it is considered to be a cornerstone of Dojo, the glue that holds it all together:</p>\n\n<ul>\n<li><a href=\"http://docs.dojocampus.org/dojo/require\" rel=\"nofollow noreferrer\">dojo.require &mdash; the official doc</a>.</li>\n<li><a href=\"http://dojocampus.org/content/2008/06/03/understanding-dojodeclare-dojorequire-and-dojoprovide/\" rel=\"nofollow noreferrer\">Understanding dojo.declare, dojo.require, and dojo.provide</a>.</li>\n<li><a href=\"http://dev.opera.com/articles/view/introducing-the-dojo-toolkit/\" rel=\"nofollow noreferrer\">Introducing Dojo</a>.</li>\n</ul>\n\n<p>Using modules Dojo achieves following objectives:</p>\n\n<ul>\n<li>Namespaces for Dojo code and custom code (<code>dojo.declare()</code>) &mdash; do not pollute the global space, coexist with other libraries, and user's non-Dojo-aware code.</li>\n<li>Loading modules synchronously or asynchronously by name (<code>dojo.require()</code>).</li>\n<li>Custom builds by analyzing module dependencies to create a single file or a group of interdependent files (so-called layers) to include only what your web application needs. Custom builds can include Dojo modules and customer-supplied modules as well.</li>\n<li>Transparent CDN-based access to Dojo and user's code. Both AOL and Google carry Dojo in this fashion, but some customers do that for their custom web applications as well.</li>\n</ul>\n" }, { "answer_id": 387637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Lazy Load the code you need on demand. Google does something like this with their <a href=\"http://code.google.com/apis/ajax/documentation/\" rel=\"nofollow noreferrer\">google.loader</a> </p>\n" }, { "answer_id": 388666, "author": "Danita", "author_id": 26481, "author_profile": "https://Stackoverflow.com/users/26481", "pm_score": 3, "selected": false, "text": "<p>In my last project -Viajeros.com- I've used a combination of several techniques. I wouldn't know how to organize a web app -- Viajeros is a social networking site for travellers with well-defined sections, so it's kind of easy to separate the code for each area.</p>\n\n<p>I use namespace simulation and lazy loading of modules according to the site section. On each page load I declare a \"vjr\" object, and always load a set of common functions to it (vjr.base.js). Then each HTML page decides which modules need with a simple:</p>\n\n<pre><code>vjr.Required = [\"vjr.gallery\", \"vjr.comments\", \"vjr.favorites\"];\n</code></pre>\n\n<p>Vjr.base.js gets each one gzipped from the server and executes them.</p>\n\n<pre><code>vjr.include(vjr.Required);\nvjr.include = function(moduleList) {\n if (!moduleList) return false;\n for (var i = 0; i &lt; moduleList.length; i++) {\n if (moduleList[i]) {\n $.ajax({\n type: \"GET\", url: vjr.module2fileName(moduleList[i]), dataType: \"script\"\n });\n }\n }\n};\n</code></pre>\n\n<p>Every \"module\" has this structure:</p>\n\n<pre><code>vjr.comments = {}\n\nvjr.comments.submitComment = function() { // do stuff }\nvjr.comments.validateComment = function() { // do stuff }\n\n// Handlers\nvjr.comments.setUpUI = function() {\n // Assign handlers to screen elements\n}\n\nvjr.comments.init = function () {\n // initialize stuff\n vjr.comments.setUpUI();\n}\n\n$(document).ready(vjr.comments.init);\n</code></pre>\n\n<p>Given my limited Javascript knowledge, I know there must be better ways to manage this, but until now it's working great for us.</p>\n" }, { "answer_id": 388689, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 3, "selected": false, "text": "<p>\"Write like crazy and just hope it works out for the best?\", I've seen a project like this which was developed and maintained by just 2 developers, a huge application with lots of javascript code. On top of that there were different shortcuts for every possible jquery function you can think of. I suggested they organize the code as plugins, as that is the jquery equivalent of class, module, namespace... and the whole universe. But things got much worse, now they started writing plugins replacing every combination of 3 lines of code used in the project.\nPersonaly I think jQuery is the devil and it shouldn't be used on projects with lots of javascript because it encourages you to be lazy and not think of organizing code in any way. I'd rather read 100 lines of javascript than one line with 40 chained jQuery functions (I'm not kidding).\nContrary to popular belief it's very easy to organize javascript code in equivalents to namespaces and classes. That's what YUI and Dojo do. You can easily roll your own if you like. I find YUI's approach much better and efficient. But you usualy need a nice editor with support for snippets to compensate for YUI naming conventions if you want to write anything useful.</p>\n" }, { "answer_id": 696428, "author": "ken", "author_id": 84473, "author_profile": "https://Stackoverflow.com/users/84473", "pm_score": 2, "selected": false, "text": "<p>I think this ties into, perhaps, DDD (Domain-Driven Design). The application I'm working on, although lacking a formal API, does give hints of such by way of the server-side code (class/file names, etc). Armed with that, I created a top-level object as a container for the entire problem domain; then, I added namespaces in where needed:</p>\n\n<pre><code>var App;\n(function()\n{\n App = new Domain( 'test' );\n\n function Domain( id )\n {\n this.id = id;\n this.echo = function echo( s )\n {\n alert( s );\n }\n return this;\n }\n})();\n\n// separate file\n(function(Domain)\n{\n Domain.Console = new Console();\n\n function Console()\n {\n this.Log = function Log( s )\n {\n console.log( s );\n }\n return this;\n }\n})(App);\n\n// implementation\nApp.Console.Log('foo');\n</code></pre>\n" }, { "answer_id": 756255, "author": "Darryl", "author_id": 87555, "author_profile": "https://Stackoverflow.com/users/87555", "pm_score": 3, "selected": false, "text": "<p>Organising your code in a Jquery centric NameSpace way may look as follows... and will not clash with other Javascript API's like Prototype, Ext either.</p>\n\n<pre><code>&lt;script src=\"jquery/1.3.2/jquery.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n\nvar AcmeJQ = jQuery.noConflict(true);\nvar Acme = {fn: function(){}};\n\n(function($){\n\n Acme.sayHi = function()\n {\n console.log('Hello');\n };\n\n Acme.sayBye = function()\n {\n console.log('Good Bye');\n };\n})(AcmeJQ);\n\n// Usage\n// Acme.sayHi();\n// or\n// &lt;a href=\"#\" onclick=\"Acme.sayHi();\"&gt;Say Hello&lt;/a&gt;\n\n\n&lt;/script&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 861483, "author": "Dmitri Farkov", "author_id": 103647, "author_profile": "https://Stackoverflow.com/users/103647", "pm_score": 2, "selected": false, "text": "<p>Create fake classes, and make sure that anything that can be thrown into a separate function that makes sense is done so. Also make sure to comment a lot, and not to write spagghetti code, rather keeping it all in sections. For example, some nonsense code depicting my ideals. Obviously in real life I also write many libraries that basically encompass their functionality.</p>\n\n<pre><code>$(function(){\n //Preload header images\n $('a.rollover').preload();\n\n //Create new datagrid\n var dGrid = datagrid.init({width: 5, url: 'datalist.txt', style: 'aero'});\n});\n\nvar datagrid = {\n init: function(w, url, style){\n //Rendering code goes here for style / width\n //code etc\n\n //Fetch data in\n $.get(url, {}, function(data){\n data = data.split('\\n');\n for(var i=0; i &lt; data.length; i++){\n //fetching data\n }\n })\n },\n refresh: function(deep){\n //more functions etc.\n }\n};\n</code></pre>\n" }, { "answer_id": 1175238, "author": "Justin Johnson", "author_id": 126562, "author_profile": "https://Stackoverflow.com/users/126562", "pm_score": 3, "selected": false, "text": "<p>I use <strong>Dojo's package management</strong> (<code>dojo.require</code> and <code>dojo.provide</code>) and class system (<code>dojo.declare</code> which also allows for simple multiple inheritance) to modularize all of my classes/widgets into separate files. Not only dose this keep your code organized, but it also lets you do lazy/just in time loading of classes/widgets.</p>\n" }, { "answer_id": 1657651, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 3, "selected": false, "text": "<p>Check out <a href=\"http://www.javascriptmvc.com\" rel=\"noreferrer\">JavasciptMVC</a>.</p>\n\n<p>You can :</p>\n\n<ul>\n<li><p>split up your code into model, view and controller layers.</p></li>\n<li><p>compress all code into a single production file</p></li>\n<li><p>auto-generate code</p></li>\n<li><p>create and run unit tests</p></li>\n<li><p>and lots more...</p></li>\n</ul>\n\n<p>Best of all, it uses jQuery, so you can take advantage of other jQuery plugins too.</p>\n" }, { "answer_id": 2016421, "author": "Jason Too Cool Webs", "author_id": 243450, "author_profile": "https://Stackoverflow.com/users/243450", "pm_score": 2, "selected": false, "text": "<p>For JavaScript organization been using the following</p>\n\n<ol>\n<li>Folder for all your javascript</li>\n<li>Page level javascript gets its' own file with the same name of the page. ProductDetail.aspx would be ProductDetail.js</li>\n<li>Inside the javascript folder for library files I have a lib folder </li>\n<li>Put related library functions in a lib folder that you want to use throughout your application.</li>\n<li>Ajax is the only javascript that I move outside of the javascript folder and gets it's own folder. Then I add two sub folders client and server</li>\n<li>Client folder gets all the .js files while server folder gets all the server side files.</li>\n</ol>\n" }, { "answer_id": 4179439, "author": "gaperton", "author_id": 507576, "author_profile": "https://Stackoverflow.com/users/507576", "pm_score": 2, "selected": false, "text": "<p>I'm using this little thing. It gives you 'include' directive for both JS and HTML templates. It eleminates the mess completely.</p>\n\n<p><a href=\"https://github.com/gaperton/include.js/\" rel=\"nofollow\">https://github.com/gaperton/include.js/</a></p>\n\n<pre><code>$.include({\n html: \"my_template.html\" // include template from file...\n})\n.define( function( _ ){ // define module...\n _.exports = function widget( $this, a_data, a_events ){ // exporting function...\n _.html.renderTo( $this, a_data ); // which expands template inside of $this.\n\n $this.find( \"#ok\").click( a_events.on_click ); // throw event up to the caller...\n $this.find( \"#refresh\").click( function(){\n widget( $this, a_data, a_events ); // ...and update ourself. Yep, in that easy way.\n });\n }\n});\n</code></pre>\n" }, { "answer_id": 5452805, "author": "Chetan", "author_id": 238030, "author_profile": "https://Stackoverflow.com/users/238030", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://alexsexton.com/?p=51\" rel=\"nofollow\">Use inheritance patterns to organize large jQuery applications.</a></p>\n" }, { "answer_id": 5521194, "author": "Adam", "author_id": 656259, "author_profile": "https://Stackoverflow.com/users/656259", "pm_score": 1, "selected": false, "text": "<p>Your question is one that plagued me late last year. The difference - handing the code off to new developers who had never heard of private and public methods. I had to build something simple.</p>\n\n<p>The end result was a small (around 1KB) framework that translates object literals into jQuery. The syntax is visually easier to scan, and if your js grows really large you can write reusable queries to find things like selectors used, loaded files, dependent functions, etc.</p>\n\n<p>Posting a small framework here is impractical, so I wrote a <a href=\"http://a-laughlin.com\" rel=\"nofollow\">blog post with examples</a> (My first. That was an adventure!). You're welcome to take a look.</p>\n\n<p>For any others here with a few minutes to check it out, I'd greatly appreciate feedback!</p>\n\n<p>FireFox recommended since it supports toSource() for the object query example.</p>\n\n<p>Cheers!</p>\n\n<p>Adam</p>\n" }, { "answer_id": 5721812, "author": "Chetan", "author_id": 238030, "author_profile": "https://Stackoverflow.com/users/238030", "pm_score": 3, "selected": false, "text": "<p>I'm surprised no one mentioned MVC frameworks. I've been using <a href=\"http://documentcloud.github.com/backbone/\">Backbone.js</a> to modularize and decouple my code, and it's been invaluable.</p>\n\n<p>There are quite a few of these kinds of frameworks out there, and most of them are pretty tiny too. My personal opinion is that if you're going to be writing more than just a couple lines of jQuery for flashy UI stuff, or want a rich Ajax application, an MVC framework will make your life much easier.</p>\n" }, { "answer_id": 6757813, "author": "rolnn", "author_id": 492563, "author_profile": "https://Stackoverflow.com/users/492563", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://javascriptmvc.com/docs.html\" rel=\"nofollow\">jquery mx</a> (used in javascriptMVC) which is a set of scripts that allows you to use models, views, and controllers. I've used it in a project and helped me create structured javascript, with minimal script sizes because of compression. This is a controller example:</p>\n\n<pre><code>$.Controller.extend('Todos',{\n \".todo mouseover\" : function( el, ev ) {\n el.css(\"backgroundColor\",\"red\")\n },\n \".todo mouseout\" : function( el, ev ) {\n el.css(\"backgroundColor\",\"\")\n },\n \".create click\" : function() {\n this.find(\"ol\").append(\"&lt;li class='todo'&gt;New Todo&lt;/li&gt;\"); \n }\n})\n\nnew Todos($('#todos'));\n</code></pre>\n\n<p>You can also use <a href=\"http://jupiterjs.com/news/organize-jquery-widgets-with-jquery-controller\" rel=\"nofollow\">only the controller</a> side of jquerymx if you aren't interested in the view and model parts. </p>\n" }, { "answer_id": 7129367, "author": "momo", "author_id": 576119, "author_profile": "https://Stackoverflow.com/users/576119", "pm_score": 3, "selected": false, "text": "<p>Good principal of OO + MVC would definitely go a long way for managing a complex javascript app. </p>\n\n<p>Basically I am organizing my app and javascript to the following familiar design (which exists all the way back from my desktop programming days to Web 2.0)</p>\n\n<p><img src=\"https://i.stack.imgur.com/EqeXL.png\" alt=\"JS OO and MVC\"></p>\n\n<p>Description for the numeric values on the image:</p>\n\n<ol>\n<li>Widgets representing the views of my application. This should be extensible and separated out neatly resulting good separation that MVC tries to achieve rather than turning my widget into a spaghetti code (equivalent in web app of putting a large block of Javascript directly in HTML). Each widget communicate via others by listening to the event generated by other widgets thus reducing the strong coupling between widgets that could lead to unmanageable code (remember the day of adding onclick everywhere pointing to a global functions in the script tag? Urgh...)</li>\n<li>Object models representing the data that I want to populate in the widgets and passing back and forth to the server. By encapsulating the data to its model, the application becomes data format agnostics. For example: while Naturally in Javascript these object models are mostly serialized and deserialized into JSON, if somehow the server is using XML for communication, all I need to change is changing the serialization/deserialization layer and not necessarily needs to change all the widget classes.</li>\n<li>Controller classes that manage the business logic and communication to the server + occasionally caching layer. This layer control the communication protocol to the server and put the necessary data into the object models</li>\n<li>Classes are wrapped neatly in their corresponding namespaces. I am sure we all know how nasty global namespace could be in Javascript.</li>\n</ol>\n\n<p>In the past, I would separate the files into its own js and use common practice to create OO principles in Javascript. The problem that I soon found that there are multiple ways to write JS OO and it's not necessarily that all team members have the same approach. As the team got larger (in my case more than 15 people), this gets complicated as there is no standard approach for Object Oriented Javascript. At the same time I don't want to write my own framework and repeat some of the work that I am sure smarter people than I have solved.</p>\n\n<p>jQuery is incredibly nice as Javascript Framework and I love it, however as project gets bigger, I clearly need additional structure for my web app especially to facilitate standardize OO practice. For myself, after several experiments, I find that YUI3 Base and Widget (<a href=\"http://yuilibrary.com/yui/docs/widget/\" rel=\"nofollow noreferrer\">http://yuilibrary.com/yui/docs/widget/</a> and <a href=\"http://yuilibrary.com/yui/docs/base/index.html\" rel=\"nofollow noreferrer\">http://yuilibrary.com/yui/docs/base/index.html</a>) infrastructure provides exactly what I need. Few reasons why I use them.</p>\n\n<ol>\n<li>It provides Namespace support. A real need for OO and neat organization of your code</li>\n<li>It support notion of classes and objects</li>\n<li>It gives a standardize means to add instance variables to your class</li>\n<li>It supports class extension neatly</li>\n<li>It provides constructor and destructor</li>\n<li>It provides render and event binding</li>\n<li>It has base widget framework</li>\n<li>Each widget now able to communicate to each other using standard event based model </li>\n<li>Most importantly, it gives all the engineers an OO Standard for Javascript development</li>\n</ol>\n\n<p>Contrary to many views, I don't necessarily have to choose between jQuery and YUI3. These two can peacefully co-exist. While YUI3 provides the necessary OO template for my complex web app, jQuery still provides my team with easy to use JS Abstraction that we all come to love and familiar with.</p>\n\n<p>Using YUI3, I have managed to create MVC pattern by separating classes that extend the Base as the Model, classes that extends Widget as a View and off course you have Controller classes that are making necessary logic and server side calls. </p>\n\n<p>Widget can communicate with each other using event based model and listening to the event and doing the necessary task based on predefined interface. Simply put, putting OO + MVC structure to JS is a joy for me. </p>\n\n<p>Just a disclaimer, I don't work for Yahoo! and simply an architect that is trying to cope with the same issue that is posed by the original question. I think if anyone finds equivalent OO framework, this would work as well. Principally, this question applies to other technologies as well. Thank God for all the people who came up with OO Principles + MVC to make our programming days more manageable. </p>\n" }, { "answer_id": 7626289, "author": "Nery Jr", "author_id": 848937, "author_profile": "https://Stackoverflow.com/users/848937", "pm_score": 4, "selected": false, "text": "<p>The code organization requires adoption of conventions and documentation standards:<br/>\n1. Namespace code for a physical file;<br/></p>\n\n<pre><code>Exc = {};\n</code></pre>\n\n<p><br/>2. Group classes in these namespaces javascript;<br/>\n3. Set Prototypes or related functions or classes for representing real-world objects;<br/></p>\n\n<pre><code>Exc = {};\nExc.ui = {};\nExc.ui.maskedInput = function (mask) {\n this.mask = mask;\n ...\n};\nExc.ui.domTips = function (dom, tips) {\n this.dom = gift;\n this.tips = tips;\n ...\n};\n</code></pre>\n\n<p><br/>\n4. Set conventions to improve the code. For example, group all of its internal functions or methods in its class attribute of an object type.</p>\n\n<pre><code>Exc.ui.domTips = function (dom, tips) {\n this.dom = gift;\n this.tips = tips;\n this.internal = {\n widthEstimates: function (tips) {\n ...\n }\n formatTips: function () {\n ...\n }\n };\n ...\n};\n</code></pre>\n\n<p><br/>5. Make documentation of namespaces, classes, methods and variables. Where necessary also discuss some of the code (some FIs and Fors, they usually implement important logic of the code).</p>\n\n<pre><code>/**\n * Namespace &lt;i&gt; Example &lt;/i&gt; created to group other namespaces of the \"Example\". \n */\nExc = {};\n/**\n * Namespace &lt;i&gt; ui &lt;/i&gt; created with the aim of grouping namespaces user interface.\n */\nExc.ui = {};\n\n/**\n * Class &lt;i&gt; maskdInput &lt;/i&gt; used to add an input HTML formatting capabilities and validation of data and information.\n * @ Param {String} mask - mask validation of input data.\n */\nExc.ui.maskedInput = function (mask) {\n this.mask = mask;\n ...\n};\n\n/**\n * Class &lt;i&gt; domTips &lt;/i&gt; used to add an HTML element the ability to present tips and information about its function or rule input etc..\n * @ Param {String} id - id of the HTML element.\n * @ Param {String} tips - tips on the element that will appear when the mouse is over the element whose identifier is id &lt;i&gt; &lt;/i&gt;.\n */\n Exc.ui.domTips = function (id, tips) {\n this.domID = id;\n this.tips = tips;\n ...\n};\n</code></pre>\n\n<p><br/>\nThese are just some tips, but that has greatly helped in organizing the code. Remember you must have discipline to succeed!</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
As JavaScript frameworks like jQuery make client side web applications richer and more functional, I've started to notice one problem... **How in the world do you keep this organized?** * Put all your handlers in one spot and write functions for all the events? * Create function/classes to wrap all your functionality? * Write like crazy and just hope it works out for the best? * Give up and get a new career? I mention jQuery, but it's really any JavaScript code in general. I'm finding that as lines upon lines begin to pile up, it gets harder to manage the script files or find what you are looking for. Quite possibly the biggest propblems I've found is there are so many ways to do the same thing, it's hard to know which one is the current commonly accepted best practice. Are there any general recommendations on the best way to keep your **.js** files as nice and neat as the rest of your application? Or is this just a matter of IDE? Is there a better option out there? --- **EDIT** This question was intended to be more about code organization and not file organization. There has been some really good examples of merging files or splitting content around. My question is: what is the current commonly accepted best practice way to organize your actual code? What is your way, or even a recommended way to interact with page elements and create reuseable code that doesn't conflict with each other? Some people have listed **namespaces** which is a good idea. What are some other ways, more specifically dealing with elements on the page and keeping the code organized and neat?
It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes [here](http://www.dustindiaz.com/namespace-your-javascript/) helps me a lot. ``` var DED = (function() { var private_var; function private_method() { // do stuff here } return { method_1 : function() { // do stuff here }, method_2 : function() { // do stuff here } }; })(); ``` I put different "namespaces" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.
247,228
<p>How can I run a stored procedure from a CL program? RUNSQLSTM requires a source member, but I just want to build a command so users can pass in variables easily, so this won't work.</p>
[ { "answer_id": 247457, "author": "Kwebble", "author_id": 4167, "author_profile": "https://Stackoverflow.com/users/4167", "pm_score": 2, "selected": false, "text": "<p>There may be 2 options:</p>\n\n<p>In the CL program create a temporary source member. Construct the SQL statement with the supplied parameters to execute the stored procedure and write this source code to the temporary member. Then add a call to RUNSQLSTM with the generated member as parameter.</p>\n\n<p>A second option is not to create a CL program but use RPG/COBOL. By using embedded SQL the stored procedure can be executed with the parameters. Their values should be passed from the command to the program.</p>\n" }, { "answer_id": 247925, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 2, "selected": false, "text": "<p>At one time, there was a command that someone wrote that I had used. I can't find that reference anymore, but I have two other options:</p>\n\n<ol>\n<li><a href=\"http://search400.techtarget.com/tip/0,,sid3_gci779945,00.html\" rel=\"nofollow noreferrer\">This article</a> uses REXX</li>\n<li><a href=\"http://systeminetwork.com/article/dynamic-embedded-sql-runsql-command-revealed\" rel=\"nofollow noreferrer\">This article</a> uses RPG</li>\n</ol>\n\n<p>They both include the source you need to get the command working.</p>\n" }, { "answer_id": 251921, "author": "Paul Morgan", "author_id": 16322, "author_profile": "https://Stackoverflow.com/users/16322", "pm_score": 3, "selected": false, "text": "<p>You can call the system program <code>QZDFMDB2</code> and pass it one parameter with the SQL string to execute. In this case the SQL string is the call to your stored procedure:</p>\n\n<pre><code> CALL PGM(QZDFMDB2) PARM('CALL PROCEDURE (''XYZ'', ''ABC'')')\n</code></pre>\n\n<p>To substitute in your values use a variable for the PARM:</p>\n\n<pre><code> DCL VAR(&amp;CALL) TYPE(*CHAR) LEN(200) \n\n CHGVAR VAR(&amp;CALL) \n VALUE('CALL PROCEDURE (''' *CAT &amp;PARM1 *TCAT ''', ''' *CAT &amp;PARM2 *TCAT ''')')\n\n CALL PGM(QZDFMDB2) PARM(&amp;CALL)\n</code></pre>\n" }, { "answer_id": 9124306, "author": "Mitch", "author_id": 1186823, "author_profile": "https://Stackoverflow.com/users/1186823", "pm_score": 0, "selected": false, "text": "<p><code>QCMDEXC</code> might be the command you are looking for.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I run a stored procedure from a CL program? RUNSQLSTM requires a source member, but I just want to build a command so users can pass in variables easily, so this won't work.
You can call the system program `QZDFMDB2` and pass it one parameter with the SQL string to execute. In this case the SQL string is the call to your stored procedure: ``` CALL PGM(QZDFMDB2) PARM('CALL PROCEDURE (''XYZ'', ''ABC'')') ``` To substitute in your values use a variable for the PARM: ``` DCL VAR(&CALL) TYPE(*CHAR) LEN(200) CHGVAR VAR(&CALL) VALUE('CALL PROCEDURE (''' *CAT &PARM1 *TCAT ''', ''' *CAT &PARM2 *TCAT ''')') CALL PGM(QZDFMDB2) PARM(&CALL) ```
247,245
<p>I have not had to mess with mailto links much. However I now need to add a link in the body of a mailto if it is possible. </p> <p>Is there a way to add a link or to change the email opened to an html email vs a text email?</p> <p>Something like:</p> <pre><code>&lt;a href="mailto:[email protected]?body=The message's first paragraph.%0A%0aSecond paragraph.%0A%0AThird Paragraph.%0A%0ALink goes here"&gt;Link text goes here&lt;/a&gt; </code></pre>
[ { "answer_id": 247351, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 3, "selected": false, "text": "<p>It isn't possible as far as I can tell, since a link needs HTML, and mailto links don't create an HTML email.</p>\n\n<p>This is probably for security as you could add javascript or iframes to this link and the email client might open up the end user for vulnerabilities.</p>\n" }, { "answer_id": 247395, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 8, "selected": true, "text": "<p>Section 2 of <a href=\"https://www.rfc-editor.org/rfc/rfc2368\" rel=\"noreferrer\" title=\"RFC 2368\">RFC 2368</a> says that the <code>body</code> field is supposed to be in <code>text/plain</code> format, so you can't do HTML.</p>\n<p>However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.</p>\n" }, { "answer_id": 247794, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 5, "selected": false, "text": "<p>Add the full link, with:</p>\n\n<pre><code> \"http://\"\n</code></pre>\n\n<p>to the beginning of a line, and most decent email clients will auto-link it either before sending, or at the other end when receiving.</p>\n\n<p>For really long urls that will likely wrap due to all the parameters, wrap the link in a less than/greater than symbol. This tells the email client <strong>not</strong> to wrap the url.</p>\n\n<p>e.g.</p>\n\n<pre><code> &lt;http://www.example.com/foo.php?this=a&amp;really=long&amp;url=with&amp;lots=and&amp;lots=and&amp;lots=of&amp;prameters=on_it&gt;\n</code></pre>\n" }, { "answer_id": 11830737, "author": "chanchal1987", "author_id": 395703, "author_profile": "https://Stackoverflow.com/users/395703", "pm_score": 3, "selected": false, "text": "<p>Please check below javascript in IE. Don't know if other modern browser will work or not.</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type=\"text/javascript\"&gt;\n function OpenOutlookDoc(){\n try {\n\n var outlookApp = new ActiveXObject(\"Outlook.Application\");\n var nameSpace = outlookApp.getNameSpace(\"MAPI\");\n mailFolder = nameSpace.getDefaultFolder(6);\n mailItem = mailFolder.Items.add('IPM.Note.FormA');\n mailItem.Subject=\"a subject test\";\n mailItem.To = \"[email protected]\";\n mailItem.HTMLBody = \"&lt;b&gt;bold&lt;/b&gt;\";\n mailItem.display (0); \n }\n catch(e){\n alert(e);\n // act on any error that you get\n }\n }\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;a href=\"javascript:OpenOutlookDoc()\"&gt;Click&lt;/a&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 15262608, "author": "Mike", "author_id": 2142622, "author_profile": "https://Stackoverflow.com/users/2142622", "pm_score": 1, "selected": false, "text": "<p>Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is </p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]?subject=Me&amp;body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E\"&gt;\n</code></pre>\n" }, { "answer_id": 21455516, "author": "Kamlesh", "author_id": 3021758, "author_profile": "https://Stackoverflow.com/users/3021758", "pm_score": 1, "selected": false, "text": "<p>I have implement following it working for iOS devices but failed on android devices</p>\n\n<pre><code>&lt;a href=\"mailto:?subject=Your mate might be interested...&amp;body=&lt;div style='padding: 0;'&gt;&lt;div style='padding: 0;'&gt;&lt;p&gt;I found this on the site I think you might find it interesting. &lt;a href='@(Request.Url.ToString())' &gt;Click here &lt;/a&gt;&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;\"&gt;Share This&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 39863510, "author": "hazmatzo", "author_id": 5811893, "author_profile": "https://Stackoverflow.com/users/5811893", "pm_score": 1, "selected": false, "text": "<p>The specification for 'mailto' body says:</p>\n<blockquote>\n<p>The body of a message is simply lines of US-ASCII characters. The\nonly two limitations on the body are as follows:</p>\n<ul>\n<li>CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body.</li>\n<li>Lines of characters in the body MUST be limited to 998 characters, and SHOULD be limited to 78 characters, excluding the CRLF.</li>\n</ul>\n</blockquote>\n<p><a href=\"https://www.rfc-editor.org/rfc/rfc5322#section-2.3\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc5322#section-2.3</a></p>\n<p>Generally nowadays most email clients are good at autolinking, but not all do, due to security concerns. You can likely find some work-arounds, but it won't necessarily work universally.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13341/" ]
I have not had to mess with mailto links much. However I now need to add a link in the body of a mailto if it is possible. Is there a way to add a link or to change the email opened to an html email vs a text email? Something like: ``` <a href="mailto:[email protected]?body=The message's first paragraph.%0A%0aSecond paragraph.%0A%0AThird Paragraph.%0A%0ALink goes here">Link text goes here</a> ```
Section 2 of [RFC 2368](https://www.rfc-editor.org/rfc/rfc2368 "RFC 2368") says that the `body` field is supposed to be in `text/plain` format, so you can't do HTML. However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.
247,252
<p>One of the "best practice" is accessing data via stored procedures. I understand why is this scenario good. My motivation is split database and application logic ( the tables can me changed, if the behaviour of stored procedures are same ), defence for SQL injection ( users can not execute "select * from some_tables", they can only call stored procedures ), and security ( in stored procedure can be "anything" which secure, that user can not select/insert/update/delete data, which is not for them ).</p> <p>What I don't know is how to access data with dynamic filters.</p> <p>I'm using MSSQL 2005.</p> <p>If I have table:</p> <pre><code>CREATE TABLE tblProduct ( ProductID uniqueidentifier -- PK , IDProductType uniqueidentifier -- FK to another table , ProductName nvarchar(255) -- name of product , ProductCode nvarchar(50) -- code of product for quick search , Weight decimal(18,4) , Volume decimal(18,4) ) </code></pre> <p>then I should create 4 stored procedures ( create / read / update / delete ).</p> <p>The stored procedure for "create" is easy.</p> <pre><code>CREATE PROC Insert_Product ( @ProductID uniqueidentifier, @IDProductType uniqueidentifier, ... etc ... ) AS BEGIN INSERT INTO tblProduct ( ProductID, IDProductType, ... etc .. ) VALUES ( @ProductID, @IDProductType, ... etc ... ) END </code></pre> <p>The stored procedure for "delete" is easy too.</p> <pre><code>CREATE PROC Delete_Product ( @ProductID uniqueidentifier, @IDProductType uniqueidentifier, ... etc ... ) AS BEGIN DELETE tblProduct WHERE ProductID = @ProductID AND IDProductType = @IDProductType AND ... etc ... END </code></pre> <p>The stored procedure for "update" is similar as for "delete", but I'm not sure this is the right way, how to do it. I think that updating all columns is not efficient.</p> <pre><code>CREATE PROC Update_Product( @ProductID uniqueidentifier, @Original_ProductID uniqueidentifier, @IDProductType uniqueidentifier, @Original_IDProductType uniqueidentifier, ... etc ... ) AS BEGIN UPDATE tblProduct SET ProductID = @ProductID, IDProductType = @IDProductType, ... etc ... WHERE ProductID = @Original_ProductID AND IDProductType = @Original_IDProductType AND ... etc ... END </code></pre> <p>And the last - stored procedure for "read" is littlebit mystery for me. How pass filter values for complex conditions? I have a few suggestion:</p> <p>Using XML parameter for passing where condition:</p> <pre><code>CREATE PROC Read_Product ( @WhereCondition XML ) AS BEGIN DECLARE @SELECT nvarchar(4000) SET @SELECT = 'SELECT ProductID, IDProductType, ProductName, ProductCode, Weight, Volume FROM tblProduct' DECLARE @WHERE nvarchar(4000) SET @WHERE = dbo.CreateSqlWherecondition( @WhereCondition ) --dbo.CreateSqlWherecondition is some function which returns text with WHERE condition from passed XML DECLARE @LEN_SELECT int SET @LEN_SELECT = LEN( @SELECT ) DECLARE @LEN_WHERE int SET @LEN_WHERE = LEN( @WHERE ) DECLARE @LEN_TOTAL int SET @LEN_TOTAL = @LEN_SELECT + @LEN_WHERE IF @LEN_TOTAL &gt; 4000 BEGIN -- RAISE SOME CONCRETE ERROR, BECAUSE DYNAMIC SQL ACCEPTS MAX 4000 chars END DECLARE @SQL nvarchar(4000) SET @SQL = @SELECT + @WHERE EXEC sp_execsql @SQL END </code></pre> <p>But, I think the limitation of "4000" characters for one query is ugly.</p> <p>The next suggestion is using filter tables for every column. Insert filter values into the filter table and then call stored procedure with ID of filters:</p> <pre><code>CREATE TABLE tblFilter ( PKID uniqueidentifier -- PK , IDFilter uniqueidentifier -- identification of filter , FilterType tinyint -- 0 = ignore, 1 = equals, 2 = not equals, 3 = greater than, etc ... , BitValue bit , TinyIntValue tinyint , SmallIntValue smallint, IntValue int , BigIntValue bigint, DecimalValue decimal(19,4), NVarCharValue nvarchar(4000) , GuidValue uniqueidentifier, etc ... ) CREATE TABLE Read_Product ( @Filter_ProductID uniqueidentifier, @Filter_IDProductType uniqueidentifier, @Filter_ProductName uniqueidentifier, ... etc ... ) AS BEGIN SELECT ProductID, IDProductType, ProductName, ProductCode, Weight, Volume FROM tblProduct WHERE ( @Filter_ProductID IS NULL OR ( ( ProductID IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_ProductID AND FilterType = 1 ) AND NOT ( ProductID IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_ProductID AND FilterType = 2 ) ) AND ( @Filter_IDProductType IS NULL OR ( ( IDProductType IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_IDProductType AND FilterType = 1 ) AND NOT ( IDProductType IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_IDProductType AND FilterType = 2 ) ) AND ( @Filter_ProductName IS NULL OR ( ... etc ... ) ) END </code></pre> <p>But this suggestion is littlebit complicated I think.</p> <p>Is there some "best practice" to do this type of stored procedures?</p>
[ { "answer_id": 247288, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 3, "selected": false, "text": "<p>For reading data, you do not need a stored procedure for security or to separate out logic, you can use views. </p>\n\n<p>Just grant only select on the view.</p>\n\n<p>You can limit the records shown, change field names, join many tables into one logical \"table\", etc.</p>\n" }, { "answer_id": 247298, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 4, "selected": true, "text": "<p>First: for your delete routine, your where clause should only include the primary key.</p>\n\n<p>Second: for your update routine, do not try to optimize before you have working code. In fact, do not try to optimize until you can profile your application and see where the bottlenecks are. I can tell you for sure that updating one column of one row and updating all columns of one row are nearly identical in speed. What takes time in a DBMS is (1) finding the disk block where you will write the data and (2) locking out other writers so that your write will be consistent. Finally, writing the code necessary to update only the columns that need to change will generally be harder to do and harder to maintain. If you really wanted to get picky, you'd have to compare the speed of figuring out which columns changed compared with just updating every column. If you update them all, you don't have to read any of them.</p>\n\n<p>Third: I tend to write one stored procedure for each retrieval path. In your example, I'd make one by primary key, one by each foreign key and then I'd add one for each new access path as I needed them in the application. Be agile; don't write code you don't need. I also agree with using views instead of stored procedures, however, you can use a stored procedure to return multiple result sets (in some version of MSSQL) or to change rows into columns, which can be useful.</p>\n\n<p>If you need to get, for example, 7 rows by primary key, you have some options. You can call the stored procedure that gets one row by primary key seven times. This may be fast enough if you keep the connection opened between all the calls. If you know you never need more than a certain number (say 10) of IDs at a time, you can write a stored procedure that includes a where clause like \"and ID in (arg1, arg2, arg3...)\" and make sure that unused arguments are set to NULL. If you decide you need to generate dynamic SQL, I wouldn't bother with a stored procedure because TSQL is just as easy to make a mistake as any other language. Also, you gain no benefit from using the database to do string manipulation -- it's almost always your bottleneck, so there is no point in giving the DB any more work than necessary.</p>\n" }, { "answer_id": 247354, "author": "TimeSpace Traveller", "author_id": 5116, "author_profile": "https://Stackoverflow.com/users/5116", "pm_score": 0, "selected": false, "text": "<p>In SQL 2005, it supports nvarchar(max), which has a limit of 2G, but virtually accepting all string operations upon normal nvarchar. You may want to test if this can fit into what you need in the first approach.</p>\n" }, { "answer_id": 247391, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 2, "selected": false, "text": "<p>My suggestion is that you don't try to create a stored procedure that does everything that you might now or ever need to do. If you need to retrieve a row based on the table's primary key then write a stored procedure to do that. If you need to search for all rows meeting a set of criteria then find out what that criteria might be and write a stored procedure to do that.</p>\n\n<p>If you try to write software that solves every possible problem rather than a specific set of problems you will usually fail at providing anything useful.</p>\n" }, { "answer_id": 247440, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "<p>your select stored procedure can be done as follows to require only one stored proc but any number of different items in the where clause. Pass in any one or combination of the parameters and you will get ALL items which match - so you only need one stored proc.</p>\n\n<pre><code>Create sp_ProductSelect\n(\n @ProductID int = null,\n @IDProductType int = null,\n @ProductName varchar(50) = null,\n @ProductCode varchar(10) = null,\n ...\n @Volume int = null\n)\nAS\nSELECT ProductID, IDProductType, ProductName, ProductCode, Weight, Volume FROM tblProduct' \nWhere\n ((@ProductID is null) or (ProductID = @ProductID)) AND\n ((@ProductName is null) or (ProductName = @ProductName)) AND\n ...\n ((@Volume is null) or (Volume= @Volume))\n</code></pre>\n" }, { "answer_id": 247747, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 2, "selected": false, "text": "<p>I disagree that create Insert/Update/Select stored procedures are a \"best practice\". Unless your entire application is written in SPs, use a database layer in your application to handle these CRUD activities. Better yet, use an ORM technology to handle them for you.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20382/" ]
One of the "best practice" is accessing data via stored procedures. I understand why is this scenario good. My motivation is split database and application logic ( the tables can me changed, if the behaviour of stored procedures are same ), defence for SQL injection ( users can not execute "select \* from some\_tables", they can only call stored procedures ), and security ( in stored procedure can be "anything" which secure, that user can not select/insert/update/delete data, which is not for them ). What I don't know is how to access data with dynamic filters. I'm using MSSQL 2005. If I have table: ``` CREATE TABLE tblProduct ( ProductID uniqueidentifier -- PK , IDProductType uniqueidentifier -- FK to another table , ProductName nvarchar(255) -- name of product , ProductCode nvarchar(50) -- code of product for quick search , Weight decimal(18,4) , Volume decimal(18,4) ) ``` then I should create 4 stored procedures ( create / read / update / delete ). The stored procedure for "create" is easy. ``` CREATE PROC Insert_Product ( @ProductID uniqueidentifier, @IDProductType uniqueidentifier, ... etc ... ) AS BEGIN INSERT INTO tblProduct ( ProductID, IDProductType, ... etc .. ) VALUES ( @ProductID, @IDProductType, ... etc ... ) END ``` The stored procedure for "delete" is easy too. ``` CREATE PROC Delete_Product ( @ProductID uniqueidentifier, @IDProductType uniqueidentifier, ... etc ... ) AS BEGIN DELETE tblProduct WHERE ProductID = @ProductID AND IDProductType = @IDProductType AND ... etc ... END ``` The stored procedure for "update" is similar as for "delete", but I'm not sure this is the right way, how to do it. I think that updating all columns is not efficient. ``` CREATE PROC Update_Product( @ProductID uniqueidentifier, @Original_ProductID uniqueidentifier, @IDProductType uniqueidentifier, @Original_IDProductType uniqueidentifier, ... etc ... ) AS BEGIN UPDATE tblProduct SET ProductID = @ProductID, IDProductType = @IDProductType, ... etc ... WHERE ProductID = @Original_ProductID AND IDProductType = @Original_IDProductType AND ... etc ... END ``` And the last - stored procedure for "read" is littlebit mystery for me. How pass filter values for complex conditions? I have a few suggestion: Using XML parameter for passing where condition: ``` CREATE PROC Read_Product ( @WhereCondition XML ) AS BEGIN DECLARE @SELECT nvarchar(4000) SET @SELECT = 'SELECT ProductID, IDProductType, ProductName, ProductCode, Weight, Volume FROM tblProduct' DECLARE @WHERE nvarchar(4000) SET @WHERE = dbo.CreateSqlWherecondition( @WhereCondition ) --dbo.CreateSqlWherecondition is some function which returns text with WHERE condition from passed XML DECLARE @LEN_SELECT int SET @LEN_SELECT = LEN( @SELECT ) DECLARE @LEN_WHERE int SET @LEN_WHERE = LEN( @WHERE ) DECLARE @LEN_TOTAL int SET @LEN_TOTAL = @LEN_SELECT + @LEN_WHERE IF @LEN_TOTAL > 4000 BEGIN -- RAISE SOME CONCRETE ERROR, BECAUSE DYNAMIC SQL ACCEPTS MAX 4000 chars END DECLARE @SQL nvarchar(4000) SET @SQL = @SELECT + @WHERE EXEC sp_execsql @SQL END ``` But, I think the limitation of "4000" characters for one query is ugly. The next suggestion is using filter tables for every column. Insert filter values into the filter table and then call stored procedure with ID of filters: ``` CREATE TABLE tblFilter ( PKID uniqueidentifier -- PK , IDFilter uniqueidentifier -- identification of filter , FilterType tinyint -- 0 = ignore, 1 = equals, 2 = not equals, 3 = greater than, etc ... , BitValue bit , TinyIntValue tinyint , SmallIntValue smallint, IntValue int , BigIntValue bigint, DecimalValue decimal(19,4), NVarCharValue nvarchar(4000) , GuidValue uniqueidentifier, etc ... ) CREATE TABLE Read_Product ( @Filter_ProductID uniqueidentifier, @Filter_IDProductType uniqueidentifier, @Filter_ProductName uniqueidentifier, ... etc ... ) AS BEGIN SELECT ProductID, IDProductType, ProductName, ProductCode, Weight, Volume FROM tblProduct WHERE ( @Filter_ProductID IS NULL OR ( ( ProductID IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_ProductID AND FilterType = 1 ) AND NOT ( ProductID IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_ProductID AND FilterType = 2 ) ) AND ( @Filter_IDProductType IS NULL OR ( ( IDProductType IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_IDProductType AND FilterType = 1 ) AND NOT ( IDProductType IN ( SELECT GuidValue FROM tblFilter WHERE IDFilter = @Filter_IDProductType AND FilterType = 2 ) ) AND ( @Filter_ProductName IS NULL OR ( ... etc ... ) ) END ``` But this suggestion is littlebit complicated I think. Is there some "best practice" to do this type of stored procedures?
First: for your delete routine, your where clause should only include the primary key. Second: for your update routine, do not try to optimize before you have working code. In fact, do not try to optimize until you can profile your application and see where the bottlenecks are. I can tell you for sure that updating one column of one row and updating all columns of one row are nearly identical in speed. What takes time in a DBMS is (1) finding the disk block where you will write the data and (2) locking out other writers so that your write will be consistent. Finally, writing the code necessary to update only the columns that need to change will generally be harder to do and harder to maintain. If you really wanted to get picky, you'd have to compare the speed of figuring out which columns changed compared with just updating every column. If you update them all, you don't have to read any of them. Third: I tend to write one stored procedure for each retrieval path. In your example, I'd make one by primary key, one by each foreign key and then I'd add one for each new access path as I needed them in the application. Be agile; don't write code you don't need. I also agree with using views instead of stored procedures, however, you can use a stored procedure to return multiple result sets (in some version of MSSQL) or to change rows into columns, which can be useful. If you need to get, for example, 7 rows by primary key, you have some options. You can call the stored procedure that gets one row by primary key seven times. This may be fast enough if you keep the connection opened between all the calls. If you know you never need more than a certain number (say 10) of IDs at a time, you can write a stored procedure that includes a where clause like "and ID in (arg1, arg2, arg3...)" and make sure that unused arguments are set to NULL. If you decide you need to generate dynamic SQL, I wouldn't bother with a stored procedure because TSQL is just as easy to make a mistake as any other language. Also, you gain no benefit from using the database to do string manipulation -- it's almost always your bottleneck, so there is no point in giving the DB any more work than necessary.
247,284
<p>I have a form I am submitting using jQuery's ajaxSubmit function from the Forms plugin. I'm trying to add a form name/value pair to the form data just before submission occurs. My plan is to modify the form data in the beforeSubmit event handler.</p> <p>Given a function that looks like:</p> <pre><code>function handleActionFormBeforeSubmit(formData, form, options) { // Add a name/value pair here somehow to formData } </code></pre> <p>How do I add a simple pair to formData? It is an array in the form of:</p> <pre><code>[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] </code></pre> <p>Thanks, Brian</p>
[ { "answer_id": 247776, "author": "Brian Vallelunga", "author_id": 2656, "author_profile": "https://Stackoverflow.com/users/2656", "pm_score": 5, "selected": true, "text": "<p>After an hour of experimentation, I figured out a solution. To append a value to the form data, the following code will work.</p>\n\n<pre><code>function handleActionFormBeforeSubmit(formData, form, options) {\n\n // Add a name/value pair indicating this is an asynchronous call.\n // This works with the ASP.NET MVC framework's Request.IsMvcAjaxRequest() method.\n formData[formData.length] = { \"name\": \"__MVCASYNCPOST\", \"value\": \"true\" };\n}\n</code></pre>\n\n<p>You can also modify the data if you know the index of the value you want to change such as:</p>\n\n<pre><code>formData[0].value = 'new value';\n</code></pre>\n\n<p>I hope this helps someone else.</p>\n" }, { "answer_id": 1659333, "author": "tony", "author_id": 200723, "author_profile": "https://Stackoverflow.com/users/200723", "pm_score": 3, "selected": false, "text": "<p>This is fine:</p>\n\n<pre><code>formData.push({ \"name\": \"__MVCASYNCPOST\", \"value\": \"true\" });\n</code></pre>\n" }, { "answer_id": 2221596, "author": "SamBarnes", "author_id": 168632, "author_profile": "https://Stackoverflow.com/users/168632", "pm_score": 0, "selected": false, "text": "<p>For some reason changing the data in the beforeSubmit callback didn't work for me when I encountered this problem. </p>\n\n<p>However assigning an object to \"data\" in the form options caused this object to be appended to the serialised data. This is not documented explicitly on the jquery form website but is part of the underlying $.ajax method.</p>\n" }, { "answer_id": 21986134, "author": "Anshu Dahiya", "author_id": 2776730, "author_profile": "https://Stackoverflow.com/users/2776730", "pm_score": 1, "selected": false, "text": "<p>formData[0].value = 'new value'; is working fine in AjaxSubmit(). I had implemented same while upload file content dynamically. Earlier after so many time, form send blank data into server, so this code helpful to change before submit your form.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2656/" ]
I have a form I am submitting using jQuery's ajaxSubmit function from the Forms plugin. I'm trying to add a form name/value pair to the form data just before submission occurs. My plan is to modify the form data in the beforeSubmit event handler. Given a function that looks like: ``` function handleActionFormBeforeSubmit(formData, form, options) { // Add a name/value pair here somehow to formData } ``` How do I add a simple pair to formData? It is an array in the form of: ``` [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] ``` Thanks, Brian
After an hour of experimentation, I figured out a solution. To append a value to the form data, the following code will work. ``` function handleActionFormBeforeSubmit(formData, form, options) { // Add a name/value pair indicating this is an asynchronous call. // This works with the ASP.NET MVC framework's Request.IsMvcAjaxRequest() method. formData[formData.length] = { "name": "__MVCASYNCPOST", "value": "true" }; } ``` You can also modify the data if you know the index of the value you want to change such as: ``` formData[0].value = 'new value'; ``` I hope this helps someone else.
247,304
<p>I'm not sure how password hashing works (will be implementing it later), but need to create database schema now.</p> <p>I'm thinking of limiting passwords to 4-20 characters, but as I understand after encrypting hash string will be of different length.</p> <p>So, how to store these passwords in the database?</p>
[ { "answer_id": 247314, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 3, "selected": false, "text": "<p>As a fixed length string (VARCHAR(n) or however MySQL calls it).\nA hash has always a fixed length of for example 12 characters (depending on the hash algorithm you use). So a 20 char password would be reduced to a 12 char hash, and a 4 char password would also yield a 12 char hash.</p>\n" }, { "answer_id": 247320, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 2, "selected": false, "text": "<p>I've always tested to find the MAX string length of an encrypted string and set that as the character length of a VARCHAR type. Depending on how many records you're going to have, it could really help the database size.</p>\n" }, { "answer_id": 247328, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 4, "selected": false, "text": "<p>You might find this Wikipedia article on salting <a href=\"http://en.wikipedia.org/wiki/Password_salt\" rel=\"noreferrer\">worthwhile</a>. The idea is to add a set bit of data to randomize your hash value; this will protect your passwords from dictionary attacks if someone gets unauthorized access to the password hashes.</p>\n" }, { "answer_id": 247348, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 4, "selected": false, "text": "<p>You can actually use <code>CHAR</code><em>(length of hash)</em> to define your datatype for MySQL because each hashing algorithm will always evaluate out to the same number of characters. For example, <code>SHA1</code> always returns a 40-character hexadecimal number.</p>\n" }, { "answer_id": 247353, "author": "willasaywhat", "author_id": 12234, "author_profile": "https://Stackoverflow.com/users/12234", "pm_score": 2, "selected": false, "text": "<p>It really depends on the hashing algorithm you're using. The length of the password has little to do with the length of the hash, if I remember correctly. Look up the specs on the hashing algorithm you are using, run a few tests, and truncate just above that.</p>\n" }, { "answer_id": 247379, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "<p>Hashes are a sequence of bits (128 bits, 160 bits, 256 bits, etc., depending on the algorithm). Your column should be binary-typed, not text/character-typed, if MySQL allows it (SQL Server datatype is <code>binary(n)</code> or <code>varbinary(n)</code>). You should also salt the hashes. Salts may be text or binary, and you will need a corresponding column.</p>\n" }, { "answer_id": 247627, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 10, "selected": true, "text": "<p>Update: Simply using a hash function is not strong enough for storing passwords. You should read <a href=\"https://stackoverflow.com/a/55753734/20860\">the answer from Gilles on this thread</a> for a more detailed explanation.</p>\n\n<p>For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the <a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"noreferrer\">password_hash() function</a>, which uses Bcrypt by default.</p>\n\n<pre><code>$hash = password_hash(\"rasmuslerdorf\", PASSWORD_DEFAULT);\n</code></pre>\n\n<p>The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).</p>\n\n<pre><code>$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a\n</code></pre>\n\n<p>Use the SQL data type <code>CHAR(60)</code> to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.</p>\n\n<p>Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.</p>\n\n<hr>\n\n<p>It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the <a href=\"http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_unhex\" rel=\"noreferrer\"><code>UNHEX()</code></a> function to reduce a string of hex digits by half.</p>\n\n<ul>\n<li>MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16)</li>\n<li>SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20)</li>\n<li>SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28)</li>\n<li>SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32)</li>\n<li>SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48)</li>\n<li>SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64)</li>\n<li>BCrypt generates an implementation-dependent 448-bit hash value. <a href=\"https://stackoverflow.com/questions/5881169/storing-a-hashed-password-bcrypt-in-a-database-type-length-of-column\">You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)</a></li>\n</ul>\n\n<p>As of 2015, NIST <a href=\"https://csrc.nist.gov/Projects/Hash-Functions/NIST-Policy-on-Hash-Functions\" rel=\"noreferrer\">recommends using SHA-256 or higher</a> for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.</p>\n\n<p>Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are <a href=\"http://web.archive.org/web/20081222011930/http://www.larc.usp.br/~pbarreto/hflounge.html\" rel=\"noreferrer\">known to be crackable</a>.</p>\n" }, { "answer_id": 2934149, "author": "Hare Srinivasa", "author_id": 353456, "author_profile": "https://Stackoverflow.com/users/353456", "pm_score": -1, "selected": false, "text": "<p>for md5 vARCHAR(32) is appropriate. For those using AES better to use varbinary.</p>\n" }, { "answer_id": 45314547, "author": "bart", "author_id": 78297, "author_profile": "https://Stackoverflow.com/users/78297", "pm_score": 3, "selected": false, "text": "<p>You should use <code>TEXT</code> (storing unlimited number of characters) for the sake of forward compatibility. Hashing algorithms (need to) become stronger over time and thus this database field will need to support more characters over time. Additionally depending on your migration strategy you may need to store new and old hashes in the same field, so fixing the length to one type of hash is not recommended.</p>\n" }, { "answer_id": 55753734, "author": "Gilles 'SO- stop being evil'", "author_id": 387076, "author_profile": "https://Stackoverflow.com/users/387076", "pm_score": 5, "selected": false, "text": "<h1>Always use a password hashing algorithm: <a href=\"https://en.wikipedia.org/wiki/Argon2\" rel=\"noreferrer\">Argon2</a>, <a href=\"https://en.wikipedia.org/wiki/Scrypt\" rel=\"noreferrer\">scrypt</a>, <a href=\"https://en.wikipedia.org/wiki/Bcrypt\" rel=\"noreferrer\">bcrypt</a> or <a href=\"https://en.wikipedia.org/wiki/PBKDF2\" rel=\"noreferrer\">PBKDF2</a>.</h1>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Argon2\" rel=\"noreferrer\">Argon2</a> won the 2015 password hashing competition. <a href=\"https://en.wikipedia.org/wiki/Scrypt\" rel=\"noreferrer\">Scrypt</a>, <a href=\"https://en.wikipedia.org/wiki/Bcrypt\" rel=\"noreferrer\">bcrypt</a> and <a href=\"https://en.wikipedia.org/wiki/PBKDF2\" rel=\"noreferrer\">PBKDF2</a> are older algorithms that are considered less preferred now, but still fundamentally sound, so if your platform doesn't support Argon2 yet, it's ok to use another algorithm for now.</p>\n\n<p>Never store a password directly in a database. Don't encrypt it, either: otherwise, if your site gets breached, the attacker gets the decryption key and so can obtain all passwords. Passwords MUST be <em>hashed</em>.</p>\n\n<p>A <em>password hash</em> has different properties from a hash table hash or a cryptographic hash. Never use an ordinary cryptographic hash such as MD5, SHA-256 or SHA-512 on a password. A password hashing algorithm uses a <em>salt</em>, which is unique (not used for any other user or in anybody else's database). The salt is necessary so that attackers can't just pre-calculate the hashes of common passwords: with a salt, they have to restart the calculation for every account. A password hashing algorithm is <em>intrinsically slow</em> — as slow as you can afford. Slowness hurts the attacker a lot more than you because the attacker has to try many different passwords. For more information, see <a href=\"http://security.stackexchange.com/questions/211/how-to-securely-hash-passwords\">How to securely hash passwords</a>.</p>\n\n<p>A password hash encodes four pieces of information:</p>\n\n<ul>\n<li>An indicator of which algorithm is used. This is necessary for <a href=\"https://en.wikipedia.org/wiki/Crypto_agility\" rel=\"noreferrer\">agility</a>: cryptographic recommendations change over time. You need to be able to transition to a new algorithm.</li>\n<li>A difficulty or hardness indicator. The higher this value, the more computation is needed to calculate the hash. This should be a constant or a global configuration value in the password change function, but it should increase over time as computers get faster, so you need to remember the value for each account. Some algorithms have a single numerical value, others have more parameters there (for example to tune CPU usage and RAM usage separately).</li>\n<li>The salt. Since the salt must be globally unique, it has to be stored for each account. The salt should be generated randomly on each password change.</li>\n<li>The hash proper, i.e. the output of the mathematical calculation in the hashing algorithm.</li>\n</ul>\n\n<p>Many libraries include a pair functions that conveniently packages this information as a single string: one that takes the algorithm indicator, the hardness indicator and the password, generates a random salt and returns the full hash string; and one that takes a password and the full hash string as input and returns a boolean indicating whether the password was correct. There's no universal standard, but a common encoding is</p>\n\n<pre>$<em>algorithm</em>$<em>parameters</em>$<em>salt</em>$<em>output</em></pre>\n\n<p>where <code><em>algorithm</em></code> is a number or a short alphanumeric string encoding the choice of algorithm, <code><em>parameters</em></code> is a printable string, and <code><em>salt</em></code> and <code><em>output</em></code> are encoded in Base64 without terminating <code>=</code>.</p>\n\n<p>16 bytes are enough for the salt and the output. (See e.g. <a href=\"https://argon2-cffi.readthedocs.io/en/stable/parameters.html\" rel=\"noreferrer\">recommendations for Argon2</a>.) Encoded in Base64, that's 21 characters each. The other two parts depend on the algorithm and parameters, but 20–40 characters are typical. That's a total of <strong>about 82 ASCII characters</strong> (<code>CHAR(82)</code>, and no need for Unicode), to which you should add a safety margin if you think it's going to be difficult to enlarge the field later.</p>\n\n<p>If you encode the hash in a binary format, you can get it down to 1 byte for the algorithm, 1–4 bytes for the hardness (if you hard-code some of the parameters), and 16 bytes each for the salt and output, for a total of 37 bytes. Say <strong>40 bytes</strong> (<code>BINARY(40)</code>) to have at least a couple of spare bytes. Note that these are 8-bit bytes, not printable characters, in particular the field can include null bytes.</p>\n\n<p>Note that the length of the hash is completely unrelated to the length of the password.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
I'm not sure how password hashing works (will be implementing it later), but need to create database schema now. I'm thinking of limiting passwords to 4-20 characters, but as I understand after encrypting hash string will be of different length. So, how to store these passwords in the database?
Update: Simply using a hash function is not strong enough for storing passwords. You should read [the answer from Gilles on this thread](https://stackoverflow.com/a/55753734/20860) for a more detailed explanation. For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the [password\_hash() function](https://www.php.net/manual/en/function.password-hash.php), which uses Bcrypt by default. ``` $hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT); ``` The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt). ``` $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a ``` Use the SQL data type `CHAR(60)` to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary. Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008. --- It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the [`UNHEX()`](http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_unhex) function to reduce a string of hex digits by half. * MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16) * SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20) * SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28) * SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32) * SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48) * SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64) * BCrypt generates an implementation-dependent 448-bit hash value. [You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)](https://stackoverflow.com/questions/5881169/storing-a-hashed-password-bcrypt-in-a-database-type-length-of-column) As of 2015, NIST [recommends using SHA-256 or higher](https://csrc.nist.gov/Projects/Hash-Functions/NIST-Policy-on-Hash-Functions) for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely. Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are [known to be crackable](http://web.archive.org/web/20081222011930/http://www.larc.usp.br/~pbarreto/hflounge.html).
247,305
<p>I am using the jQuery tableSorter plugin on a page.</p> <p>Unfortunatley, the table that is being sorted is dynamically modified, and when I sort after adding an element, the element disappears, restoring the table to the state that it was in when the tableSorter was created.</p> <p>Is there any way that i can force tableSorter to rescan the page so that these new elements are sorted properly?</p>
[ { "answer_id": 247319, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 6, "selected": true, "text": "<p>I believe you can trigger an update using something like:</p>\n\n<pre><code>$(table).trigger(\"update\")\n</code></pre>\n" }, { "answer_id": 285037, "author": "Alex", "author_id": 32392, "author_profile": "https://Stackoverflow.com/users/32392", "pm_score": 4, "selected": false, "text": "<p>Seems you are correct.</p>\n\n<pre>\n$(table).trigger(\"update\");\n$(table).trigger(\"appendCache\");\n</pre>\n\n<p>does the trick.</p>\n\n<p>As a note, the tablesorter API changed at some point, so these things got changed, as well as the event binding. My biggest hangup was trying to figure out why some things worked and others did not, and it was due to having a wrong version of the plugin, despite there being no obvious distinction. </p>\n" }, { "answer_id": 11052245, "author": "Devaroop", "author_id": 909297, "author_profile": "https://Stackoverflow.com/users/909297", "pm_score": 2, "selected": false, "text": "<p>The <code>$(table).trigger(\"update\");</code> throws error </p>\n\n<pre><code> Uncaught TypeError: Cannot read property 'rows' of undefined \n</code></pre>\n\n<p>So, there is a jquery function <code>.ajaxStop()</code> where <code>tablesorter()</code> is called. Do not call tablesorter in <code>.ready()</code></p>\n\n<pre><code> jQuery(document).ajaxStop(function(){\n jQuery(\"#table_name\").tablesorter();\n })\n</code></pre>\n\n<p>which did the job</p>\n" }, { "answer_id": 42313521, "author": "Ishwar Rimal", "author_id": 5088262, "author_profile": "https://Stackoverflow.com/users/5088262", "pm_score": 2, "selected": false, "text": "<p>For those Newbies like me who are facing issue with sorting dynamic generated table, here is the solution.\nThe answer previously given are correct, but where do you place this command?</p>\n\n<pre><code>$('#tableId').tablesorter().trigger('update');\n</code></pre>\n\n<p>You need to place it as soon as you've appended the data to the table.\nEx in my case</p>\n\n<pre><code>var tableData = \"&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Age&lt;/th&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;Izaki&lt;/td&gt;&lt;td&gt;24&lt;/td&gt;&lt;tr&gt;&lt;tr&gt;&lt;td&gt;Serizawa&lt;/td&gt;&lt;td&gt;25&lt;/td&gt;&lt;/tr&gt;\";\n$('#tableId').html('tableData');\n$('#tableId').tablesorter().trigger('update');\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32392/" ]
I am using the jQuery tableSorter plugin on a page. Unfortunatley, the table that is being sorted is dynamically modified, and when I sort after adding an element, the element disappears, restoring the table to the state that it was in when the tableSorter was created. Is there any way that i can force tableSorter to rescan the page so that these new elements are sorted properly?
I believe you can trigger an update using something like: ``` $(table).trigger("update") ```
247,313
<p>If I had a phone number like this </p> <pre><code>string phone = "6365555796"; </code></pre> <p>Which I store with only numeric characters in my database <strong>(as a string)</strong>, is it possible to output the number like this: </p> <pre><code>"636-555-5796" </code></pre> <p>Similar to how I could if I were using a number: </p> <pre><code>long phone = 6365555796; string output = phone.ToString("000-000-0000"); </code></pre> <p>I've tried searching and all I could find online were numeric formatting documents.</p> <p>The reason I ask is because I think it would be an interesting idea to be able to store only the numeric values in the DB and allow for different formatting using a Constant string value to dictate how my phone numbers are formatted. Or am I better off using a number for this?</p> <p>EDIT: The question is to format a string that contains numbers, not a number itself.</p>
[ { "answer_id": 247332, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 1, "selected": false, "text": "<p>Why not just do something like this?</p>\n\n<pre><code>string phoneText = \"6365555796\";\nlong phoneNum = long.Parse(phoneText);\nstring output = phoneNum.ToString(\"000-000-0000\");\n</code></pre>\n" }, { "answer_id": 247337, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You could potentially do a string insert at a given character point. Kinda like: \nphone = phone.Insert(3, \"-\");\nphone = phone.Insert(7, \"-\");</p>\n" }, { "answer_id": 247393, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": -1, "selected": false, "text": "<p>To control string format of a number for display in an ASP.NET Gridview or another control, you can wrap your item in a helper class for display purposes:</p>\n\n<pre><code>public class PhoneDisplay\n{\n long phoneNum;\n public PhoneDisplay(long number)\n {\n phoneNum = number;\n }\n public override string ToString()\n {\n return string.Format(\"{0:###-###-####}\", phoneNum);\n }\n\n}\n</code></pre>\n\n<p>Then, define data or display fields as (e.g.):</p>\n\n<pre><code>PhoneDisplay MyPhone = new PhoneDisplay(6365555796);\n</code></pre>\n" }, { "answer_id": 247398, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 2, "selected": false, "text": "<p>I think this works </p>\n\n<pre><code>string s = string.Format(\"{0:###-###-####}\", ulong.Parse(phone));\n</code></pre>\n\n<p>In addtion, this <a href=\"http://blog.stevex.net/index.php/string-formatting-in-csharp/\" rel=\"nofollow noreferrer\">http://blog.stevex.net/index.php/string-formatting-in-csharp/</a> is a nice post on formatting strings in .NET. </p>\n\n<p>Thanks to @swilliams for clarifications. </p>\n" }, { "answer_id": 247417, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 4, "selected": true, "text": "<p>Best I can think of without having to convert to a long/number and so it fits one line is:</p>\n\n<pre><code>string number = \"1234567890\";\nstring formattedNumber = string.Format(\"{0}-{1}-{2}\", number.Substring(0,3), number.Substring(3,3), number.Substring(6));\n</code></pre>\n" }, { "answer_id": 247460, "author": "Dour High Arch", "author_id": 22437, "author_profile": "https://Stackoverflow.com/users/22437", "pm_score": 3, "selected": false, "text": "<p>Be aware that not everyone uses the North American 3-3-4 format for phone numbers. European phone numbers can be up to 15 digits long, with significant punctuation, e.g. +44-XXXX-XXXX-XXXX is different from 44+XXXX-XXXX-XXXX. You are also not considering PBXs and extensions, which can require over 30 digits.</p>\n\n<p>Military and radio phones can have alphabetic characters, no this is not the \"2\" = \"ABC\" you see on touch-tone phones.</p>\n" }, { "answer_id": 247526, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>The simple version:</p>\n\n<pre><code>string phone = \"6365555796\";\nConvert.ToInt64(phone).ToString(\"000-000-0000\");\n</code></pre>\n\n<p>To wrap some validation around that and put it in a nice method:</p>\n\n<pre><code>string FormatPhone(string phone)\n{\n /*assume the phone string came from the database, so we already know it's\n only digits. If this changes in the future a simple RegEx can validate \n (or correct) the digits requirement. */\n\n // still want to check the length:\n if (phone.Length != 10) throw new InvalidArgumentException();\n\n return Convert.ToInt64(phone).ToString(\"000-000-0000\");\n}\n</code></pre>\n" }, { "answer_id": 247671, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 1, "selected": false, "text": "<p>I loves me some extension method action:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Formats a string of nine digits into a U.S. phone number.\n /// &lt;/summary&gt;\n /// &lt;param name=\"value\"&gt;\n /// The string to format as a phone number.\n /// &lt;/param&gt;\n /// &lt;returns&gt;\n /// The numeric string as a U.S. phone number.\n /// &lt;/returns&gt;\n public static string\n ToUSPhone (this string value)\n {\n if (value == null)\n {\n return null;\n }\n\n long dummy;\n\n if ((value.Length != 10) ||\n !long.TryParse (\n value,\n NumberStyles.None,\n CultureInfo.CurrentCulture,\n out dummy))\n {\n return value;\n }\n\n return string.Format (\n CultureInfo.CurrentCulture,\n \"{0}-{1}-{2}\",\n value.Substring (0, 3),\n value.Substring (3, 3),\n value.Substring (6));\n }\n</code></pre>\n" }, { "answer_id": 248467, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>Sure:</p>\n\n<pre><code>Regex.Replace(phone, @\"^(\\d{3})(\\d{3})(\\d{4})$\", @\"$1-$2-$3\")\n</code></pre>\n\n<p>Of course, <a href=\"http://www.codinghorror.com/blog/archives/001016.html\" rel=\"nofollow noreferrer\">now you have 2 problems</a>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
If I had a phone number like this ``` string phone = "6365555796"; ``` Which I store with only numeric characters in my database **(as a string)**, is it possible to output the number like this: ``` "636-555-5796" ``` Similar to how I could if I were using a number: ``` long phone = 6365555796; string output = phone.ToString("000-000-0000"); ``` I've tried searching and all I could find online were numeric formatting documents. The reason I ask is because I think it would be an interesting idea to be able to store only the numeric values in the DB and allow for different formatting using a Constant string value to dictate how my phone numbers are formatted. Or am I better off using a number for this? EDIT: The question is to format a string that contains numbers, not a number itself.
Best I can think of without having to convert to a long/number and so it fits one line is: ``` string number = "1234567890"; string formattedNumber = string.Format("{0}-{1}-{2}", number.Substring(0,3), number.Substring(3,3), number.Substring(6)); ```
247,318
<p>Calling addChild with an empty string as the value (or even with whitespace) seems to cause a redundant SimpleXml node to be added inside the node instead of adding just the node with no value.</p> <p>Here's a quick demo of what happens:</p> <pre><code>[description] =&gt; !4jh5jh1uio4jh5ij14j34io5j! </code></pre> <p>And here's with an empty string:</p> <pre><code>[description] =&gt; SimpleXMLElement Object ( [0] =&gt; ) </code></pre> <p>The workaround I'm using at the moment is pretty horrible - I'm doing a str_replace on the final JSON to replace !4jh5jh1uio4jh5ij14j34io5j! with an empty string. Yuck. Perhaps the only answer at this point is 'submit a bug report to simplexml'...</p> <p>Does anyone have a better solution?</p>
[ { "answer_id": 247370, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 0, "selected": false, "text": "<p>Maybe I'm not understanding the question right but, it seems to me that when you use the addChild method, you're required to have a string as an argument for the name of the node regardless of what content is in the node. The value (second argument) is optional and can be left blank to add and empty node.</p>\n\n<p>Let me know if that helps.</p>\n" }, { "answer_id": 258352, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 1, "selected": false, "text": "<p>I think I figured out what is going on. Given code like this:</p>\n\n<pre><code>$xml = new SimpleXMLElement('&lt;xml&gt;&lt;/xml&gt;');\n$xml-&gt;addChild('node','value');\nprint_r($xml);\n\n$xml = new SimpleXMLElement('&lt;xml&gt;&lt;/xml&gt;');\n$xml-&gt;addChild('node','');\nprint_r($xml);\n\n$xml = new SimpleXMLElement('&lt;xml&gt;&lt;/xml&gt;');\n$xml-&gt;addChild('node');\nprint_r($xml);\n</code></pre>\n\n<p>The output is this:</p>\n\n<pre><code>SimpleXMLElement Object\n(\n [node] =&gt; value\n)\nSimpleXMLElement Object\n(\n [node] =&gt; SimpleXMLElement Object\n (\n [0] =&gt; \n )\n\n)\nSimpleXMLElement Object\n(\n [node] =&gt; SimpleXMLElement Object\n (\n )\n\n)\n</code></pre>\n\n<p>So, to make it so that in case #2 the empty element isn't created (i.e. if you don't know if the second argument is going to be an empty string or not), you could just do something like this:</p>\n\n<pre><code>$mystery_string = '';\n\n$xml = new SimpleXMLElement('&lt;xml&gt;&lt;/xml&gt;');\nif (preg_match('#\\S#', $mystery_string)) // Checks for non-whitespace character\n $xml-&gt;addChild('node', $mystery_string);\nelse\n $xml-&gt;addChild('node');\n\nprint_r($xml);\necho \"\\nOr in JSON:\\n\";\necho json_encode($xml);\n</code></pre>\n\n<p>To output:</p>\n\n<pre><code>SimpleXMLElement Object\n(\n [node] =&gt; SimpleXMLElement Object\n (\n )\n\n)\n\nOr in JSON:\n{\"node\":{}}\n</code></pre>\n\n<p>Is that what you want?</p>\n\n<p>Personally, I never use SimpleXML, and not only because of this sort of weird behavior -- it is still under major development and in PHP5 is missing like 2/3 of the methods you need to do DOM manipulation (like deleteChild, replaceChild etc).</p>\n\n<p>I use DOMDocument (which is standardized, fast and feature-complete, since it's an interface to libxml2).</p>\n" }, { "answer_id": 408622, "author": "null", "author_id": 25411, "author_profile": "https://Stackoverflow.com/users/25411", "pm_score": 0, "selected": false, "text": "<p>I've created an Xml library to which extends the simpleXml object to include all of the functionally that is present in the DOMDocument but is missing an interface from SimpleXml (as the two functions interact with the same underlying libxml2 object --by reference). It also has niceties such as AsArray() or AsJson() to output your object in one of those formats.</p>\n\n<p>I've just updated the library to work as you expect when outputting JSON. You can do the following:</p>\n\n<pre><code>$xml = new bXml('&lt;xml&gt;&lt;/xml&gt;');\n$xml-&gt;addChild('node', '');\n$json_w_root = $xml-&gt;asJson(); // is { 'xml': {'node':'' } }\n$json = $xml-&gt;children()-&gt;asJson(); // is { 'node' : '' } as expected.\n</code></pre>\n\n<p>The library is hosted on google code at <a href=\"http://code.google.com/p/blibrary/\" rel=\"nofollow noreferrer\">http://code.google.com/p/blibrary/</a></p>\n" }, { "answer_id": 732816, "author": "thomasrutter", "author_id": 53212, "author_profile": "https://Stackoverflow.com/users/53212", "pm_score": 1, "selected": false, "text": "<p>With SimpleXML, what you get if you use print_r(), or var_dump(), serialize(), or similar, does not correspond to what is stored internally in the object. It is a 'magical' object which overloads the way PHP interates its contents.</p>\n\n<p>You get the true representation of the element with AsXML() only.</p>\n\n<p>When something like print_r() iterates over a SimpleXML element or you access its properties using the -> operator, you get a munged version of the object. This munged version allows you to do things like \"echo $xml->surname\" or $xml->names[1] as if it really had these as properties, but is separate to the true XML contained within: in the munged representation elements are not necessarily in order, and elements whose names are PHP reserved words (like \"var\") aren't presented as properties, but can be accessed with code like $xml[\"var\"] - as if the object is an associative array. Where multiple sibling elements have the same name they are presented like arrays. I guess an empty string is also presented like an array for some reason. However, when output using AsXML() you get the real representation.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32300/" ]
Calling addChild with an empty string as the value (or even with whitespace) seems to cause a redundant SimpleXml node to be added inside the node instead of adding just the node with no value. Here's a quick demo of what happens: ``` [description] => !4jh5jh1uio4jh5ij14j34io5j! ``` And here's with an empty string: ``` [description] => SimpleXMLElement Object ( [0] => ) ``` The workaround I'm using at the moment is pretty horrible - I'm doing a str\_replace on the final JSON to replace !4jh5jh1uio4jh5ij14j34io5j! with an empty string. Yuck. Perhaps the only answer at this point is 'submit a bug report to simplexml'... Does anyone have a better solution?
I think I figured out what is going on. Given code like this: ``` $xml = new SimpleXMLElement('<xml></xml>'); $xml->addChild('node','value'); print_r($xml); $xml = new SimpleXMLElement('<xml></xml>'); $xml->addChild('node',''); print_r($xml); $xml = new SimpleXMLElement('<xml></xml>'); $xml->addChild('node'); print_r($xml); ``` The output is this: ``` SimpleXMLElement Object ( [node] => value ) SimpleXMLElement Object ( [node] => SimpleXMLElement Object ( [0] => ) ) SimpleXMLElement Object ( [node] => SimpleXMLElement Object ( ) ) ``` So, to make it so that in case #2 the empty element isn't created (i.e. if you don't know if the second argument is going to be an empty string or not), you could just do something like this: ``` $mystery_string = ''; $xml = new SimpleXMLElement('<xml></xml>'); if (preg_match('#\S#', $mystery_string)) // Checks for non-whitespace character $xml->addChild('node', $mystery_string); else $xml->addChild('node'); print_r($xml); echo "\nOr in JSON:\n"; echo json_encode($xml); ``` To output: ``` SimpleXMLElement Object ( [node] => SimpleXMLElement Object ( ) ) Or in JSON: {"node":{}} ``` Is that what you want? Personally, I never use SimpleXML, and not only because of this sort of weird behavior -- it is still under major development and in PHP5 is missing like 2/3 of the methods you need to do DOM manipulation (like deleteChild, replaceChild etc). I use DOMDocument (which is standardized, fast and feature-complete, since it's an interface to libxml2).
247,329
<p>Unfortunately on my project, we generate a lot of the HTML code in JavaScript like this:</p> <pre><code>var html = new StringBuffer(); html.append("&lt;td class=\"gr-my-deals\"&gt;&lt;a href=\"").append(deal.url).append("\" target=\"_blank\"&gt;").append(deal.description).append("&lt;/a&gt;&lt;/td&gt;"); </code></pre> <p>I have 2 specific complaints about this:</p> <ol> <li>The use of escaped double quotes (\”) within the HTML string. These should be replaced by single quotes (‘) to improve readability.</li> <li>The use of .append() instead of the JavaScript string concatentation operator “+”</li> </ol> <p>Applying both of these suggestions, produces the following equivalent line of code, which I consider to be much more readable:</p> <pre><code>var html = "&lt;td class=’gr-my-deals’&gt;&lt;a href=’" + deal.url + "’ target=’_blank’&gt;" + deal.description + "&lt;/a&gt;&lt;/td&gt;"; </code></pre> <p>I'm now looking for a way to automatically transform the first line of code into the second. All I've come up with so far is to run the following find and replace over all our Javascript code:</p> <pre><code>Find: ).append( Replace: + </code></pre> <p>This will convert the line of code shown above to:</p> <pre><code>html.append("&lt;td class=\"gr-my-deals\"&gt;&lt;a href=\"" + deal.url + "\" target=\"_blank\"&gt;" + deal.description + "&lt;/a&gt;&lt;/td&gt;)"; </code></pre> <p>This should safely remove all but the first 'append()' statement. Unfortunately, I can't think of any safe way to automatically convert the escaped double-quotes to single quotes. Bear in mind that I can't simply do a find/replace because in some cases you actually do need to use escaped double-quotes. Typically, this is when you're generating HTML that includes nested JS, and that JS contains string parameters, e.g.</p> <pre><code>function makeLink(stringParam) { var sb = new StringBuffer(); sb.append("&lt;a href=\"JavaScript:myFunc('" + stringParam + "');\"&gt;"); } </code></pre> <p>My questions (finally) are:</p> <ul> <li>Is there a better way to safely replace the calls to 'append()' with '+'</li> <li>Is there any way to safely replace the escaped double quotes with single quotes, regex?</li> </ul> <p>Cheers, Don</p>
[ { "answer_id": 247383, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "<p>Here is a stringFormat function that helps eliminate concatenation and ugly replacment values. </p>\n\n<pre><code>function stringFormat( str ) {\n\n for( i = 0; i &lt; arguments.length; i++ ) {\n var r = new RegExp( '\\\\{' + ( i ) + '\\\\}','gm' );\n\n str = str.replace( r, arguments[ i + 1 ] ); \n }\n return str;\n}\n</code></pre>\n\n<p>Use it like this:</p>\n\n<pre><code>var htmlMask = \"&lt;td class=’gr-my-deals’&gt;&lt;a href=’{0}’ target=’_blank’&gt;{1}&lt;/a&gt;&lt;/td&gt;\";\n\nvar x = stringFormat( htmlMask, deal.Url, deal.description ); \n</code></pre>\n" }, { "answer_id": 247392, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "<p>Consider switching to a <a href=\"https://stackoverflow.com/questions/tagged/javascript%20templates\">JavaScript template processor</a>. They're generally fairly light-weight, and can dramatically improve the clarity of your code... as well as the performance, if you have a lot of re-use and choose one that precompiles templates.</p>\n" }, { "answer_id": 248132, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 1, "selected": false, "text": "<p>As Shog9 implies, there are several good JavaScript templating engines out there. Here's an example of how you would use mine, <a href=\"http://plugins.jquery.com/project/simple-templates\" rel=\"nofollow noreferrer\">jQuery Simple Templates</a>:</p>\n\n<pre><code>var tmpl, vals, html;\n\ntmpl = '&lt;td class=\"gr-my-deals\"&gt;';\ntmpl += '&lt;a href=\"#{href}\"&gt;#{text}&lt;/a&gt;';\ntmpl += '&lt;/td&gt;';\n\nvals = {\n href : 'http://example.com/example',\n text : 'Click me!'\n};\n\nhtml = $.tmpl(tmpl, vals);\n</code></pre>\n" }, { "answer_id": 248953, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There is a good reason why you should be using the StringBuffer() instead of string concatenation in JavaScript. The StringBuffer() and its append() method use Array and Array's join() to bring the string together. If you have a significant number of partial strings you want to join, this is known to be a faster method of doing it.</p>\n" }, { "answer_id": 4559123, "author": "Michael Lorton", "author_id": 238884, "author_profile": "https://Stackoverflow.com/users/238884", "pm_score": 0, "selected": false, "text": "<p>Templating? Templating sucks! Here's the way I would write your code:</p>\n\n<pre><code>TD({ \"class\" : \"gr-my-deals\" },\n A({ href : deal.url,\n target : \"_blank\"},\n deal.description ))\n</code></pre>\n\n<p>I use a 20-line library called DOMination, which I will send to anyone who asks, to support such code. </p>\n\n<p>The advantages are manifold but some of the most obvious are:</p>\n\n<ul>\n<li>legible, intuitive code</li>\n<li>easy to learn and to write</li>\n<li>compact code (no close-tags, just close-parentheses)</li>\n<li>well-understood by JavaScript-aware editors, minifiers, and so on</li>\n<li>resolves some browser-specific issues (like the difference between rowSpan and rowspan on IE)</li>\n<li>integrates well with CSS</li>\n</ul>\n\n<p>(Your example, BTW, highlights the only disadvantage of DOMination: any HTML attributes that are also JavaScript reserved words, <code>class</code> in this case, have to be quoted, lest bad things happen.)</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/247329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
Unfortunately on my project, we generate a lot of the HTML code in JavaScript like this: ``` var html = new StringBuffer(); html.append("<td class=\"gr-my-deals\"><a href=\"").append(deal.url).append("\" target=\"_blank\">").append(deal.description).append("</a></td>"); ``` I have 2 specific complaints about this: 1. The use of escaped double quotes (\”) within the HTML string. These should be replaced by single quotes (‘) to improve readability. 2. The use of .append() instead of the JavaScript string concatentation operator “+” Applying both of these suggestions, produces the following equivalent line of code, which I consider to be much more readable: ``` var html = "<td class=’gr-my-deals’><a href=’" + deal.url + "’ target=’_blank’>" + deal.description + "</a></td>"; ``` I'm now looking for a way to automatically transform the first line of code into the second. All I've come up with so far is to run the following find and replace over all our Javascript code: ``` Find: ).append( Replace: + ``` This will convert the line of code shown above to: ``` html.append("<td class=\"gr-my-deals\"><a href=\"" + deal.url + "\" target=\"_blank\">" + deal.description + "</a></td>)"; ``` This should safely remove all but the first 'append()' statement. Unfortunately, I can't think of any safe way to automatically convert the escaped double-quotes to single quotes. Bear in mind that I can't simply do a find/replace because in some cases you actually do need to use escaped double-quotes. Typically, this is when you're generating HTML that includes nested JS, and that JS contains string parameters, e.g. ``` function makeLink(stringParam) { var sb = new StringBuffer(); sb.append("<a href=\"JavaScript:myFunc('" + stringParam + "');\">"); } ``` My questions (finally) are: * Is there a better way to safely replace the calls to 'append()' with '+' * Is there any way to safely replace the escaped double quotes with single quotes, regex? Cheers, Don
Here is a stringFormat function that helps eliminate concatenation and ugly replacment values. ``` function stringFormat( str ) { for( i = 0; i < arguments.length; i++ ) { var r = new RegExp( '\\{' + ( i ) + '\\}','gm' ); str = str.replace( r, arguments[ i + 1 ] ); } return str; } ``` Use it like this: ``` var htmlMask = "<td class=’gr-my-deals’><a href=’{0}’ target=’_blank’>{1}</a></td>"; var x = stringFormat( htmlMask, deal.Url, deal.description ); ```