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
285,521
<p>I am making a post from a .NET console app to a .NET web service. I know that the timeout on the server side is 20 min, but if my client takes more than 100 seconds to post my data to that service then I get a timeout exception. How would I tell my client to wait the available 20 min to timeout?</p>
[ { "answer_id": 285536, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 3, "selected": false, "text": "<p>on the client side, your webservice object has a timeout value. It should be pretty easy to set by going:</p>\n\n<pre><code>myServiceInstance.Timeout = 1200000\n</code></pre>\n\n<p>for 20 minutes</p>\n" }, { "answer_id": 285547, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 0, "selected": false, "text": "<p>Yup the <code>ServiceInstance.Timeout</code> is the property to set.</p>\n\n<p>I blogged about it here\n<a href=\"http://stackpanel.com/blog/2008/10/client-timeout-accessing-asmx-web-service/\" rel=\"nofollow noreferrer\">http://stackpanel.com/blog/2008/10/client-timeout-accessing-asmx-web-service/</a></p>\n" }, { "answer_id": 285558, "author": "wulimaster", "author_id": 21749, "author_profile": "https://Stackoverflow.com/users/21749", "pm_score": 2, "selected": false, "text": "<p>You need to verify that &lt;httpRuntime executionTimeout=\"1200\"/&gt; exists in the web.config on the webservice itself to confirm your 20 minutes.</p>\n\n<p>The service proxy class instance in your console app also needs to be set. There is a Timeout property to set (in milliseconds) so you would do something like this:</p>\n\n<p>MyServiceClass myService = new MyServiceClass();\nmyService.Timeout = 1200000;</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13593/" ]
I am making a post from a .NET console app to a .NET web service. I know that the timeout on the server side is 20 min, but if my client takes more than 100 seconds to post my data to that service then I get a timeout exception. How would I tell my client to wait the available 20 min to timeout?
on the client side, your webservice object has a timeout value. It should be pretty easy to set by going: ``` myServiceInstance.Timeout = 1200000 ``` for 20 minutes
285,522
<p>Let's say I have an html form. Each input/select/textarea will have a corresponding <code>&lt;label&gt;</code> with the <code>for</code> attribute set to the id of it's companion. In this case, I know that each input will only have a single label.</p> <p>Given an input element in javascript &mdash; via an onkeyup event, for example &mdash; what's the best way to find it's associated label?</p>
[ { "answer_id": 285560, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>Earlier...</p>\n\n<pre><code>var labels = document.getElementsByTagName(\"LABEL\"),\n lookup = {},\n i, label;\n\nfor (i = 0; i &lt; labels.length; i++) {\n label = labels[i];\n if (document.getElementById(label.htmlFor)) {\n lookup[label.htmlFor] = label;\n }\n}\n</code></pre>\n\n<p>Later...</p>\n\n<pre><code>var myLabel = lookup[myInput.id];\n</code></pre>\n\n<p>Snarky comment: Yes, you can also do it with JQuery. :-)</p>\n" }, { "answer_id": 285565, "author": "TonyB", "author_id": 3543, "author_profile": "https://Stackoverflow.com/users/3543", "pm_score": 7, "selected": false, "text": "<p>If you are using jQuery you can do something like this</p>\n\n<pre><code>$('label[for=\"foo\"]').hide ();\n</code></pre>\n\n<p>If you aren't using jQuery you'll have to search for the label. Here is a function that takes the element as an argument and returns the associated label</p>\n\n<pre><code>function findLableForControl(el) {\n var idVal = el.id;\n labels = document.getElementsByTagName('label');\n for( var i = 0; i &lt; labels.length; i++ ) {\n if (labels[i].htmlFor == idVal)\n return labels[i];\n }\n}\n</code></pre>\n" }, { "answer_id": 285575, "author": "AndreasKnudsen", "author_id": 36465, "author_profile": "https://Stackoverflow.com/users/36465", "pm_score": 3, "selected": false, "text": "<p>with jquery you could do something like </p>\n\n<pre><code>var nameOfLabel = someInput.attr('id');\nvar label = $(\"label[for='\" + nameOfLabel + \"']\");\n</code></pre>\n" }, { "answer_id": 285608, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 8, "selected": true, "text": "<p>First, scan the page for labels, and assign a reference to the label from the actual form element:</p>\n\n<pre><code>var labels = document.getElementsByTagName('LABEL');\nfor (var i = 0; i &lt; labels.length; i++) {\n if (labels[i].htmlFor != '') {\n var elem = document.getElementById(labels[i].htmlFor);\n if (elem)\n elem.label = labels[i]; \n }\n}\n</code></pre>\n\n<p>Then, you can simply go:</p>\n\n<pre><code>document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';\n</code></pre>\n\n<p>No need for a lookup array :)</p>\n" }, { "answer_id": 5641041, "author": "Mike McKay", "author_id": 266111, "author_profile": "https://Stackoverflow.com/users/266111", "pm_score": 0, "selected": false, "text": "<p>Use a JQuery selector:</p>\n\n<pre><code>$(\"label[for=\"+inputElement.id+\"]\")\n</code></pre>\n" }, { "answer_id": 7121904, "author": "ObjectType", "author_id": 83964, "author_profile": "https://Stackoverflow.com/users/83964", "pm_score": 0, "selected": false, "text": "<p>For future searchers... The following is a jQuery-ified version of FlySwat's accepted answer:</p>\n\n<pre><code>var labels = $(\"label\");\nfor (var i = 0; i &lt; labels.length; i++) {\n var fieldId = labels[i].htmlFor;\n if (fieldId != \"\") {\n var elem = $(\"#\" + fieldId);\n if (elem.length != 0) {\n elem.data(\"label\", $(labels[i])); \n }\n }\n}\n</code></pre>\n\n<p>Using:</p>\n\n<pre><code>$(\"#myFormElemId\").data(\"label\").css(\"border\",\"3px solid red\");\n</code></pre>\n" }, { "answer_id": 7304493, "author": "haifacarina", "author_id": 782125, "author_profile": "https://Stackoverflow.com/users/782125", "pm_score": 2, "selected": false, "text": "<pre><code>$(\"label[for='inputId']\").text()\n</code></pre>\n\n<p>This helped me to get the label of an input element using its ID. </p>\n" }, { "answer_id": 8913025, "author": "Gijs", "author_id": 713326, "author_profile": "https://Stackoverflow.com/users/713326", "pm_score": 5, "selected": false, "text": "<p>I am a bit surprised that nobody seems to know that you're <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1\" rel=\"noreferrer\">perfectly allowed</a> to do:</p>\n\n<pre><code>&lt;label&gt;Put your stuff here: &lt;input value=\"Stuff\"&gt;&lt;/label&gt;\n</code></pre>\n\n<p>Which won't get picked up by any of the suggested answers, but <strong>will</strong> label the input correctly.</p>\n\n<p>Here's some code that does take this case into account:</p>\n\n<pre><code>$.fn.getLabels = function() {\n return this.map(function() {\n var labels = $(this).parents('label');\n if (this.id) {\n labels.add('label[for=\"' + this.id + '\"]');\n }\n return labels.get();\n });\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$('#myfancyinput').getLabels();\n</code></pre>\n\n<p>Some notes:</p>\n\n<ul>\n<li>The code was written for clarity, not for performance. More performant alternatives may be available.</li>\n<li>This code supports getting the labels of multiple items in one go. If that's not what you want, adapt as necessary.</li>\n<li>This still doesn't take care of things like <a href=\"http://www.w3.org/TR/wai-aria/states_and_properties#aria-labelledby\" rel=\"noreferrer\"><code>aria-labelledby</code></a> if you were to use that (left as an exercise to the reader).</li>\n<li>Using multiple labels is a tricky business when it comes to support in different user agents and assistive technologies, so test well and use at your own risk, etc. etc.</li>\n<li>Yes, you could also implement this without using jQuery. :-)</li>\n</ul>\n" }, { "answer_id": 13047684, "author": "OzrenTkalcecKrznaric", "author_id": 1632534, "author_profile": "https://Stackoverflow.com/users/1632534", "pm_score": 2, "selected": false, "text": "<p>Answer from Gijs was most valuable for me, but unfortunately the extension does not work.</p>\n\n<p>Here's a rewritten extension that works, it may help someone:</p>\n\n<pre><code>jQuery.fn.getLabels = function () {\n return this.map(function () {\n var parentLabels = $(this).parents('label').get();\n var associatedLabels = this.id ? associatedLabels = $(\"label[for='\" + this.id + \"']\").get() : [];\n return parentLabels.concat(associatedLabels);\n });\n};\n</code></pre>\n" }, { "answer_id": 15061155, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 6, "selected": false, "text": "<p>There is a <code>labels</code> property in the <a href=\"http://www.w3.org/TR/2012/WD-html5-20121025/the-label-element.html#dom-lfe-labels\" rel=\"noreferrer\">HTML5 standard</a> which points to labels which are associated to an input element.</p>\n\n<p>So you could use something like this (support for native <code>labels</code> property but with a fallback for retrieving labels in case the browser doesn't support it)...</p>\n\n<pre><code>var getLabelsForInputElement = function(element) {\n var labels = [];\n var id = element.id;\n\n if (element.labels) {\n return element.labels;\n }\n\n id &amp;&amp; Array.prototype.push\n .apply(labels, document.querySelector(\"label[for='\" + id + \"']\"));\n\n while (element = element.parentNode) {\n if (element.tagName.toLowerCase() == \"label\") {\n labels.push(element);\n } \n }\n\n return labels;\n};\n\n// ES6\nvar getLabelsForInputElement = (element) =&gt; {\n let labels;\n let id = element.id;\n\n if (element.labels) {\n return element.labels;\n }\n\n if (id) {\n labels = Array.from(document.querySelector(`label[for='${id}']`)));\n }\n\n while (element = element.parentNode) {\n if (element.tagName.toLowerCase() == \"label\") {\n labels.push(element);\n } \n }\n\n return labels;\n};\n</code></pre>\n\n<p>Even easier if you're using jQuery...</p>\n\n<pre><code>var getLabelsForInputElement = function(element) {\n var labels = $();\n var id = element.id;\n\n if (element.labels) {\n return element.labels;\n }\n\n id &amp;&amp; (labels = $(\"label[for='\" + id + \"']\")));\n\n labels = labels.add($(element).parents(\"label\"));\n\n return labels;\n};\n</code></pre>\n" }, { "answer_id": 20225078, "author": "Martie Henry", "author_id": 3037784, "author_profile": "https://Stackoverflow.com/users/3037784", "pm_score": 1, "selected": false, "text": "<p>It is actually far easier to add an id to the label in the form itself, for example:</p>\n\n<pre><code>&lt;label for=\"firstName\" id=\"firstNameLabel\"&gt;FirstName:&lt;/label&gt;\n\n&lt;input type=\"text\" id=\"firstName\" name=\"firstName\" class=\"input_Field\" \n pattern=\"^[a-zA-Z\\s\\-]{2,25}$\" maxlength=\"25\"\n title=\"Alphabetic, Space, Dash Only, 2-25 Characters Long\" \n autocomplete=\"on\" required\n/&gt;\n</code></pre>\n\n<p>Then, you can simply use something like this:</p>\n\n<pre><code>if (myvariableforpagelang == 'es') {\n // set field label to spanish\n document.getElementById(\"firstNameLabel\").innerHTML = \"Primer Nombre:\";\n // set field tooltip (title to spanish\n document.getElementById(\"firstName\").title = \"Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud\";\n}\n</code></pre>\n\n<p>The javascript does have to be in a body onload function to work.</p>\n\n<p>Just a thought, works beautifully for me.</p>\n" }, { "answer_id": 20632804, "author": "kuroi neko", "author_id": 2960823, "author_profile": "https://Stackoverflow.com/users/2960823", "pm_score": 1, "selected": false, "text": "<p>As it has been already mentionned, the (currently) top-rated answer does not take into account the possibility to embed an input inside a label.</p>\n\n<p>Since nobody has posted a JQuery-free answer, here is mine :</p>\n\n<pre><code>var labels = form.getElementsByTagName ('label');\nvar input_label = {};\nfor (var i = 0 ; i != labels.length ; i++)\n{\n var label = labels[i];\n var input = label.htmlFor\n ? document.getElementById(label.htmlFor)\n : label.getElementsByTagName('input')[0];\n input_label[input.outerHTML] = \n (label.innerText || label.textContent); // innerText for IE8-\n}\n</code></pre>\n\n<p>In this example, for the sake of simplicity, the lookup table is directly indexed by the input HTML elements. This is hardly efficient and you can adapt it however you like.</p>\n\n<p>You can use a form as base element, or the whole document if you want to get labels for multiple forms at once.</p>\n\n<p>No checks are made for incorrect HTML (multiple or missing inputs inside labels, missing input with corresponding htmlFor id, etc), but feel free to add them.</p>\n\n<p>You might want to trim the label texts, since trailing spaces are often present when the input is embedded in the label.</p>\n" }, { "answer_id": 23790722, "author": "Peter Nosko", "author_id": 3361389, "author_profile": "https://Stackoverflow.com/users/3361389", "pm_score": 0, "selected": false, "text": "<p>I know this is old, but I had trouble with some solutions and pieced this together. I have tested this on Windows (Chrome, Firefox and MSIE) and OS X (Chrome and Safari) and believe this is the simplest solution. It works with these three style of attaching a label.</p>\n\n<pre><code>&lt;label&gt;&lt;input type=\"checkbox\" class=\"c123\" id=\"cb1\" name=\"item1\"&gt;item1&lt;/label&gt;\n\n&lt;input type=\"checkbox\" class=\"c123\" id=\"cb2\" name=\"item2\"&gt;item2&lt;/input&gt;\n\n&lt;input type=\"checkbox\" class=\"c123\" id=\"cb3\" name=\"item3\"&gt;&lt;label for=\"cb3\"&gt;item3&lt;/label&gt;\n</code></pre>\n\n<p>Using jQuery:</p>\n\n<pre><code>$(\".c123\").click(function() {\n $cb = $(this);\n $lb = $(this).parent();\n alert( $cb.attr('id') + ' = ' + $lb.text() );\n});\n</code></pre>\n\n<p>My JSFiddle: <a href=\"http://jsfiddle.net/pnosko/6PQCw/\" rel=\"nofollow\">http://jsfiddle.net/pnosko/6PQCw/</a></p>\n" }, { "answer_id": 27160272, "author": "itsazzad", "author_id": 540144, "author_profile": "https://Stackoverflow.com/users/540144", "pm_score": 0, "selected": false, "text": "<p>I have made for my own need, can be useful for somebody: <a href=\"http://jsfiddle.net/itsazzad/pq8w1e9p/1/\" rel=\"nofollow\">JSFIDDLE</a></p>\n\n<pre><code>$(\"input\").each(function () {\n if ($.trim($(this).prev('label').text()) != \"\") {\n console.log(\"\\nprev&gt;children:\");\n console.log($.trim($(this).prev('label').text()));\n } else {\n if ($.trim($(this).parent('label').text()) != \"\") {\n console.log(\"\\nparent&gt;children:\");\n console.log($.trim($(this).parent('label').text()));\n } else {\n if ($.trim($(this).parent().prev('label').text()) != \"\") {\n console.log(\"\\nparent&gt;prev&gt;children:\");\n console.log($.trim($(this).parent().prev('label').text()));\n } else {\n console.log(\"NOTFOUND! So set your own condition now\");\n }\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 31941735, "author": "Brendan", "author_id": 945370, "author_profile": "https://Stackoverflow.com/users/945370", "pm_score": 2, "selected": false, "text": "<p>If you're willing to use <a href=\"http://caniuse.com/#search=queryselector\" rel=\"nofollow\">querySelector</a> (and you can, even down to IE9 and sometimes IE8!), another method becomes viable.</p>\n\n<p>If your form field has an ID, and you use the label's <code>for</code> attribute, this becomes pretty simple in modern JavaScript:</p>\n\n<pre><code>var form = document.querySelector('.sample-form');\nvar formFields = form.querySelectorAll('.form-field');\n\n[].forEach.call(formFields, function (formField) {\n var inputId = formField.id;\n var label = form.querySelector('label[for=' + inputId + ']');\n console.log(label.textContent);\n});\n</code></pre>\n\n<p>Some have noted about multiple labels; if they all use the same value for the <code>for</code> attribute, just use <code>querySelectorAll</code> instead of <code>querySelector</code> and loop through to get everything you need.</p>\n" }, { "answer_id": 41756902, "author": "Gordon Rouse", "author_id": 2383941, "author_profile": "https://Stackoverflow.com/users/2383941", "pm_score": 0, "selected": false, "text": "<p>I am bit surprised no one is suggesting to use the CSS relationship method?</p>\n\n<p>in a style sheet you can reference a label from the element selector:</p>\n\n<pre><code>&lt;style&gt;\n\n//for input element with class 'YYY'\ninput.YYY + label {}\n\n&lt;/style&gt;\n</code></pre>\n\n<p>if the checkbox has an id of 'XXX'\nthen the label would be found through jQuery by:</p>\n\n<pre><code>$('#XXX + label');\n</code></pre>\n\n<p>You can also apply .find('+ label') to return the label from a jQuery checkbox element, ie useful when looping:</p>\n\n<pre><code>$('input[type=checkbox]').each( function(){\n $(this).find('+ label');\n});\n</code></pre>\n" }, { "answer_id": 45207860, "author": "Luigi D'Amico", "author_id": 4141943, "author_profile": "https://Stackoverflow.com/users/4141943", "pm_score": 5, "selected": false, "text": "<p>document.querySelector(\"label[for=\" + vHtmlInputElement.id + \"]\");</p>\n\n<p>This answers the question in the simplest and leanest manner.\nThis uses vanilla javascript and works on all main-stream proper browsers.</p>\n" }, { "answer_id": 47276699, "author": "davidnagli", "author_id": 4404040, "author_profile": "https://Stackoverflow.com/users/4404040", "pm_score": 4, "selected": false, "text": "<p>All the other answers are <strong>extremely</strong> outdated!!</p>\n\n<p>All you have to do is:</p>\n\n<pre><code>input.labels\n</code></pre>\n\n<p>HTML5 has been supported by all of the major browsers for many years already. There is absolutely no reason that you should have to make this from scratch on your own or polyfill it! Literally just use <code>input.labels</code> and it solves all of your problems.</p>\n" }, { "answer_id": 50145262, "author": "StateOfTheArtJonas", "author_id": 8571642, "author_profile": "https://Stackoverflow.com/users/8571642", "pm_score": 2, "selected": false, "text": "<p>A really concise solution using ES6 features like destructuring and implicit returns to turn it into a handy one liner would be: </p>\n\n<pre><code>const getLabels = ({ labels, id }) =&gt; labels || document.querySelectorAll(`label[for=${id}]`)\n</code></pre>\n\n<p>Or to simply get one label, not a NodeList: </p>\n\n<pre><code>const getFirstLabel = ({ labels, id }) =&gt; labels &amp;&amp; labels[0] || document.querySelector(`label[for=${id}]`)\n</code></pre>\n" }, { "answer_id": 51334543, "author": "Dan Bray", "author_id": 2452680, "author_profile": "https://Stackoverflow.com/users/2452680", "pm_score": 1, "selected": false, "text": "<p>The best answer works perfectly fine but in most cases, it is overkill and inefficient to loop through all the <code>label</code> elements.</p>\n\n<p>Here is an efficent function to get the <code>label</code> that goes with the <code>input</code> element:</p>\n\n<pre><code>function getLabelForInput(id)\n{\n var el = document.getElementById(id);\n if (!el)\n return null;\n var elPrev = el.previousElementSibling;\n var elNext = el.nextElementSibling;\n while (elPrev || elNext)\n {\n if (elPrev)\n {\n if (elPrev.htmlFor === id)\n return elPrev;\n elPrev = elPrev.previousElementSibling;\n }\n if (elNext)\n {\n if (elNext.htmlFor === id)\n return elNext;\n elNext = elNext.nextElementSibling;\n }\n }\n return null;\n}\n</code></pre>\n\n<p>For me, this one line of code was sufficient:</p>\n\n<pre><code>el = document.getElementById(id).previousElementSibling;\n</code></pre>\n\n<p>In most cases, the <code>label</code> will be very close or next to the input, which means the loop in the above function only needs to iterate a very small number of times.</p>\n" }, { "answer_id": 68764425, "author": "Rodolfo Bojo Pellegrino", "author_id": 16652712, "author_profile": "https://Stackoverflow.com/users/16652712", "pm_score": 2, "selected": false, "text": "<h2>Solution One <code>&lt;label&gt;</code>: One <code>&lt;input&gt;</code></h2>\n<p>Using <a href=\"https://www.w3.org/TR/html52/sec-forms.html#the-label-element\" rel=\"nofollow noreferrer\">HTML 5.2 reference</a>\nConsidering the <code>&lt;label&gt;</code> pointing to <code>&lt;input&gt;</code> using <code>for=</code>, the <em>labels</em> element will be a non empty array, and act as a link to the <code>&lt;label&gt;</code> element, accessing all properties of it, including its <code>id=</code>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function myFunction() {\n document.getElementById(\"p1\").innerHTML = \"The first label associated with input: &lt;b&gt;\" + document.getElementById(\"input4\").labels[0].id + \"&lt;/b&gt;\";\n\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form&gt;\n &lt;label id=\"theLabel\" for=\"input4\"&gt;my id is \"theLabel\"&lt;/label&gt;\n &lt;input name=\"name1\" id=\"input4\" value=\"my id is input4\"&gt;\n &lt;br&gt;\n&lt;/form&gt;\n\n&lt;p&gt;Click the \"click me\" button to see the label properties&lt;/p&gt;\n\n&lt;button onclick=\"myFunction()\"&gt;click me&lt;/button&gt;\n\n\n&lt;p id=\"p1\"&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>Solution Many <code>&lt;label&gt;</code>: One <code>&lt;input&gt;</code></h2>\n<p>With more than one <code>&lt;label&gt;</code> using <code>for=</code>, you can make a loop to show all of them, like this:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function myFunction2() {\n\nvar x = document.getElementById(\"input7\").labels;\nlet text = \"\";\nfor (let i = 0; i &lt; x.length; i++) {\n text += x[i].id + \"&lt;br&gt;\";\n}\ndocument.getElementById(\"p7\").innerHTML = text;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;b&gt;Three labels for one input&lt;/b&gt;&lt;br&gt;\n&lt;br&gt;\n&lt;form&gt;\n &lt;label id=\"theLabel2\" for=\"input7\"&gt;my id is \"theLabel2&lt;/label&gt;&lt;br&gt;\n &lt;label id=\"theLabel3\" for=\"input7\"&gt;my id is \"theLabel3&lt;/label&gt;&lt;br&gt;\n &lt;label id=\"theLabel4\" for=\"input7\"&gt;my id is \"theLabel4&lt;/label&gt;&lt;br&gt;\n &lt;input name=\"name1\" id=\"input7\" value=\"my id is input7\"&gt;\n &lt;br&gt;\n&lt;/form&gt;\n\n&lt;p&gt;Click the \"click me\" button to see the label properties&lt;/p&gt;\n&lt;button onclick=\"myFunction2()\"&gt;click me2&lt;/button&gt;\n\n&lt;p id=\"p7\"&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
Let's say I have an html form. Each input/select/textarea will have a corresponding `<label>` with the `for` attribute set to the id of it's companion. In this case, I know that each input will only have a single label. Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?
First, scan the page for labels, and assign a reference to the label from the actual form element: ``` var labels = document.getElementsByTagName('LABEL'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor != '') { var elem = document.getElementById(labels[i].htmlFor); if (elem) elem.label = labels[i]; } } ``` Then, you can simply go: ``` document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!'; ``` No need for a lookup array :)
285,523
<p>Is there a way to determine if the loop is iterating for the last time. My code looks something like this:</p> <pre><code>int[] array = {1, 2, 3...}; StringBuilder builder = new StringBuilder(); for(int i : array) { builder.append("" + i); if(!lastiteration) builder.append(","); } </code></pre> <p>Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.</p>
[ { "answer_id": 285530, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 5, "selected": false, "text": "<p>It might be easier to always append. And then, when you're done with your loop, just remove the final character. Tons less conditionals that way too.</p>\n\n<p>You can use <code>StringBuilder</code>'s <code>deleteCharAt(int index)</code> with index being <code>length() - 1</code></p>\n" }, { "answer_id": 285534, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>If you convert it to a classic index loop, yes.</p>\n\n<p>Or you could just delete the last comma after it's done. Like so:</p>\n\n<pre><code>int[] array = {1, 2, 3...};\nStringBuilder\n\nbuilder = new StringBuilder();\n\nfor(int i : array)\n{\n builder.append(i + \",\");\n}\n\nif(builder.charAt((builder.length() - 1) == ','))\n builder.deleteCharAt(builder.length() - 1);\n</code></pre>\n\n<p>Me, I just use <a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#join(java.util.Collection,%20char)\" rel=\"nofollow noreferrer\"><code>StringUtils.join()</code></a> from <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow noreferrer\">commons-lang</a>.</p>\n" }, { "answer_id": 285537, "author": "Gareth Davis", "author_id": 31480, "author_profile": "https://Stackoverflow.com/users/31480", "pm_score": 3, "selected": false, "text": "<p>keep it simple and use a standard for loop:</p>\n\n<pre><code>for(int i = 0 ; i &lt; array.length ; i ++ ){\n builder.append(array[i]);\n if( i != array.length - 1 ){\n builder.append(',');\n }\n}\n</code></pre>\n\n<p>or just use apache <a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#join(java.lang.Object[],%20char)\" rel=\"nofollow noreferrer\">commons-lang StringUtils.join()</a></p>\n" }, { "answer_id": 285543, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "<p>Explicit loops always work better than implicit ones.</p>\n\n<pre><code>builder.append( \"\" + array[0] );\nfor( int i = 1; i != array.length; i += 1 ) {\n builder.append( \", \" + array[i] );\n}\n</code></pre>\n\n<p>You should wrap the whole thing in an if-statement just in case you're dealing with a zero-length array.</p>\n" }, { "answer_id": 285544, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "<p>Another alternative is to append the comma before you append i, just not on the <em>first</em> iteration. (Please don't use <code>\"\" + i</code>, by the way - you don't really want concatenation here, and StringBuilder has a perfectly good append(int) overload.)</p>\n\n<pre><code>int[] array = {1, 2, 3...};\nStringBuilder builder = new StringBuilder();\n\nfor (int i : array) {\n if (builder.length() != 0) {\n builder.append(\",\");\n }\n builder.append(i);\n}\n</code></pre>\n\n<p>The nice thing about this is that it will work with any <code>Iterable</code> - you can't always index things. (The \"add the comma and then remove it at the end\" is a nice suggestion when you're really using StringBuilder - but it doesn't work for things like writing to streams. It's possibly the best approach for this exact problem though.)</p>\n" }, { "answer_id": 285546, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 0, "selected": false, "text": "<p>Another approach is to have the length of the array (if available) stored in a separate variable (more efficient than re-checking the length each time). You can then compare your index to that length to determine whether or not to add the final comma.</p>\n\n<p>EDIT: Another consideration is weighing the performance cost of removing a final character (which may cause a string copy) against having a conditional be checked in each iteration.</p>\n" }, { "answer_id": 285548, "author": "FallenAvatar", "author_id": 36965, "author_profile": "https://Stackoverflow.com/users/36965", "pm_score": 2, "selected": false, "text": "<p>Here is a solution:</p>\n\n<pre><code>int[] array = {1, 2, 3...};\nStringBuilder builder = new StringBuilder();\nbool firstiteration=true;\n\nfor(int i : array)\n{\n if(!firstiteration)\n builder.append(\",\");\n\n builder.append(\"\" + i);\n firstiteration=false;\n}\n</code></pre>\n\n<p>Look for the first iteration :)\n&nbsp;</p>\n" }, { "answer_id": 285552, "author": "Paul Brinkley", "author_id": 18160, "author_profile": "https://Stackoverflow.com/users/18160", "pm_score": 0, "selected": false, "text": "<p>Two alternate paths here:</p>\n\n<p>1: <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#join(java.lang.Object[],%20char)\" rel=\"nofollow noreferrer\">Apache Commons String Utils</a></p>\n\n<p>2: Keep a boolean called <code>first</code>, set to true. In each iteration, if <code>first</code> is false, append your comma; after that, set <code>first</code> to false.</p>\n" }, { "answer_id": 285571, "author": "Omar Kooheji", "author_id": 20400, "author_profile": "https://Stackoverflow.com/users/20400", "pm_score": 5, "selected": false, "text": "<p>Maybe you are using the wrong tool for the Job.</p>\n\n<p>This is more manual than what you are doing but it's in a way more elegant if not a bit \"old school\"</p>\n\n<pre><code> StringBuffer buffer = new StringBuffer();\n Iterator iter = s.iterator();\n while (iter.hasNext()) {\n buffer.append(iter.next());\n if (iter.hasNext()) {\n buffer.append(delimiter);\n }\n }\n</code></pre>\n" }, { "answer_id": 285592, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 4, "selected": false, "text": "<p>Another solution (perhaps the most efficient)</p>\n\n<pre><code> int[] array = {1, 2, 3};\n StringBuilder builder = new StringBuilder();\n\n if (array.length != 0) {\n builder.append(array[0]);\n for (int i = 1; i &lt; array.length; i++ )\n {\n builder.append(\",\");\n builder.append(array[i]);\n }\n }\n</code></pre>\n" }, { "answer_id": 285628, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 7, "selected": false, "text": "<p>Another way to do this:</p>\n\n<pre><code>String delim = \"\";\nfor (int i : ints) {\n sb.append(delim).append(i);\n delim = \",\";\n}\n</code></pre>\n\n<p>Update: For Java 8, you now have <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html\" rel=\"noreferrer\">Collectors</a></p>\n" }, { "answer_id": 285670, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 0, "selected": false, "text": "<p>If you're only turning an array into a comma delimited array, many languages have a join function for exactly this. It turns an array into a string with a delimiter between each element.</p>\n" }, { "answer_id": 289669, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 2, "selected": false, "text": "<p>You need <a href=\"http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Class_Separator\" rel=\"nofollow noreferrer\">Class Separator</a>.</p>\n\n<pre><code>Separator s = new Separator(\", \");\nfor(int i : array)\n{\n builder.append(s).append(i);\n}\n</code></pre>\n\n<p>The implementation of class <code>Separator</code> is straight forward. It wraps a string that is returned on every call of <code>toString()</code> except for the first call, which returns an empty string.</p>\n" }, { "answer_id": 669201, "author": "13ren", "author_id": 50979, "author_profile": "https://Stackoverflow.com/users/50979", "pm_score": 2, "selected": false, "text": "<p>Based on java.util.AbstractCollection.toString(), it exits early to avoid the delimiter.</p>\n\n<pre><code>StringBuffer buffer = new StringBuffer();\nIterator iter = s.iterator();\nfor (;;) {\n buffer.append(iter.next());\n if (! iter.hasNext())\n break;\n buffer.append(delimiter);\n}\n</code></pre>\n\n<p>It's efficient and elegant, but not as self-evident as some of the other answers.</p>\n" }, { "answer_id": 669221, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 1, "selected": false, "text": "<p>Yet another option.</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\nfor(int i : array)\n builder.append(',').append(i);\nString text = builder.toString();\nif (text.startsWith(\",\")) text=text.substring(1);\n</code></pre>\n" }, { "answer_id": 669233, "author": "Phil H", "author_id": 36537, "author_profile": "https://Stackoverflow.com/users/36537", "pm_score": 4, "selected": false, "text": "<p>This is almost a repeat of <a href=\"https://stackoverflow.com/questions/187676/string-operations-in-java/187738#187738\">this StackOverflow question</a>. What you want is <strong>StringUtils</strong>, and to call the <strong>join</strong> method.</p>\n\n<pre><code>StringUtils.join(strArr, ',');\n</code></pre>\n" }, { "answer_id": 669806, "author": "Julien Chastang", "author_id": 32174, "author_profile": "https://Stackoverflow.com/users/32174", "pm_score": 1, "selected": false, "text": "<p>Many of the solutions described here are a bit over the top, IMHO, especially those that rely on external libraries. There is a nice clean, clear idiom for achieving a comma separated list that I have always used. It relies on the conditional (?) operator:</p>\n\n<p><strong>Edit</strong>: Original solution correct, but non-optimal according to comments. Trying a second time:</p>\n\n<pre><code> int[] array = {1, 2, 3};\n StringBuilder builder = new StringBuilder();\n for (int i = 0 ; i &lt; array.length; i++)\n builder.append(i == 0 ? \"\" : \",\").append(array[i]); \n</code></pre>\n\n<p>There you go, in 4 lines of code including the declaration of the array and the StringBuilder.</p>\n" }, { "answer_id": 6106805, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 0, "selected": false, "text": "<p>In this case there is really no need to know if it is the last repetition.\nThere are many ways we can solve this. One way would be:</p>\n\n<pre><code>String del = null;\nfor(int i : array)\n{\n if (del != null)\n builder.append(del);\n else\n del = \",\";\n builder.append(i);\n}\n</code></pre>\n" }, { "answer_id": 25083058, "author": "Buffalo", "author_id": 688843, "author_profile": "https://Stackoverflow.com/users/688843", "pm_score": 1, "selected": false, "text": "<p>Here's a SSCCE benchmark I ran (related to what I had to implement) with these results: </p>\n\n<pre><code>elapsed time with checks at every iteration: 12055(ms)\nelapsed time with deletion at the end: 11977(ms)\n</code></pre>\n\n<p>On my example at least, skipping the check at every iteration isn't noticeably faster especially for sane volumes of data, but it <strong>is</strong> faster.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\n\n\npublic class TestCommas {\n\n public static String GetUrlsIn(int aProjectID, List&lt;String&gt; aUrls, boolean aPreferChecks)\n {\n\n if (aPreferChecks) {\n\n StringBuffer sql = new StringBuffer(\"select * from mytable_\" + aProjectID + \" WHERE hash IN \");\n\n StringBuffer inHashes = new StringBuffer(\"(\");\n StringBuffer inURLs = new StringBuffer(\"(\");\n\n if (aUrls.size() &gt; 0)\n {\n\n for (String url : aUrls)\n {\n\n if (inHashes.length() &gt; 0) {\n inHashes.append(\",\");\n inURLs.append(\",\");\n }\n\n inHashes.append(url.hashCode());\n\n inURLs.append(\"\\\"\").append(url.replace(\"\\\"\", \"\\\\\\\"\")).append(\"\\\"\");//.append(\",\");\n\n }\n\n }\n\n inHashes.append(\")\");\n inURLs.append(\")\");\n\n return sql.append(inHashes).append(\" AND url IN \").append(inURLs).toString();\n }\n\n else {\n\n StringBuffer sql = new StringBuffer(\"select * from mytable\" + aProjectID + \" WHERE hash IN \");\n\n StringBuffer inHashes = new StringBuffer(\"(\");\n StringBuffer inURLs = new StringBuffer(\"(\");\n\n if (aUrls.size() &gt; 0)\n {\n\n for (String url : aUrls)\n {\n inHashes.append(url.hashCode()).append(\",\"); \n\n inURLs.append(\"\\\"\").append(url.replace(\"\\\"\", \"\\\\\\\"\")).append(\"\\\"\").append(\",\");\n }\n\n }\n\n inHashes.deleteCharAt(inHashes.length()-1);\n inURLs.deleteCharAt(inURLs.length()-1);\n\n inHashes.append(\")\");\n inURLs.append(\")\");\n\n return sql.append(inHashes).append(\" AND url IN \").append(inURLs).toString();\n }\n\n }\n\n public static void main(String[] args) { \n List&lt;String&gt; urls = new ArrayList&lt;String&gt;();\n\n for (int i = 0; i &lt; 10000; i++) {\n urls.add(\"http://www.google.com/\" + System.currentTimeMillis());\n urls.add(\"http://www.yahoo.com/\" + System.currentTimeMillis());\n urls.add(\"http://www.bing.com/\" + System.currentTimeMillis());\n }\n\n\n long startTime = System.currentTimeMillis();\n for (int i = 0; i &lt; 300; i++) {\n GetUrlsIn(5, urls, true);\n }\n long endTime = System.currentTimeMillis();\n System.out.println(\"elapsed time with checks at every iteration: \" + (endTime-startTime) + \"(ms)\");\n\n startTime = System.currentTimeMillis();\n for (int i = 0; i &lt; 300; i++) {\n GetUrlsIn(5, urls, false);\n }\n endTime = System.currentTimeMillis();\n System.out.println(\"elapsed time with deletion at the end: \" + (endTime-startTime) + \"(ms)\");\n }\n}\n</code></pre>\n" }, { "answer_id": 40539794, "author": "b1tw153", "author_id": 2562562, "author_profile": "https://Stackoverflow.com/users/2562562", "pm_score": 3, "selected": false, "text": "<p>As toolkit mentioned, in Java 8 we now have <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html\" rel=\"noreferrer\">Collectors</a>. Here's what the code would look like:</p>\n\n<pre><code>String joined = array.stream().map(Object::toString).collect(Collectors.joining(\", \"));\n</code></pre>\n\n<p>I think that does exactly what you're looking for, and it's a pattern you could use for many other things.</p>\n" }, { "answer_id": 44557769, "author": "AnthonyJClink", "author_id": 1092670, "author_profile": "https://Stackoverflow.com/users/1092670", "pm_score": 0, "selected": false, "text": "<p>Since its a fixed array, it would be easier simply to avoid the enhanced for... If the Object is a collection an iterator would be easier.</p>\n\n<pre><code>int nums[] = getNumbersArray();\nStringBuilder builder = new StringBuilder();\n\n// non enhanced version\nfor(int i = 0; i &lt; nums.length; i++){\n builder.append(nums[i]);\n if(i &lt; nums.length - 1){\n builder.append(\",\");\n } \n}\n\n//using iterator\nIterator&lt;int&gt; numIter = Arrays.asList(nums).iterator();\n\nwhile(numIter.hasNext()){\n int num = numIter.next();\n builder.append(num);\n if(numIter.hasNext()){\n builder.append(\",\");\n }\n}\n</code></pre>\n" }, { "answer_id": 69911951, "author": "Hari Krishna", "author_id": 3302424, "author_profile": "https://Stackoverflow.com/users/3302424", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://self-learning-java-tutorial.blogspot.com/2015/12/stringjoiner-class.html\" rel=\"nofollow noreferrer\">StringJoiner</a>.</p>\n<pre><code>int[] array = { 1, 2, 3 };\nStringJoiner stringJoiner = new StringJoiner(&quot;,&quot;);\n\nfor (int i : array) {\n stringJoiner.add(String.valueOf(i));\n}\n\nSystem.out.println(stringJoiner);\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36858/" ]
Is there a way to determine if the loop is iterating for the last time. My code looks something like this: ``` int[] array = {1, 2, 3...}; StringBuilder builder = new StringBuilder(); for(int i : array) { builder.append("" + i); if(!lastiteration) builder.append(","); } ``` Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.
Another alternative is to append the comma before you append i, just not on the *first* iteration. (Please don't use `"" + i`, by the way - you don't really want concatenation here, and StringBuilder has a perfectly good append(int) overload.) ``` int[] array = {1, 2, 3...}; StringBuilder builder = new StringBuilder(); for (int i : array) { if (builder.length() != 0) { builder.append(","); } builder.append(i); } ``` The nice thing about this is that it will work with any `Iterable` - you can't always index things. (The "add the comma and then remove it at the end" is a nice suggestion when you're really using StringBuilder - but it doesn't work for things like writing to streams. It's possibly the best approach for this exact problem though.)
285,524
<p>With the following code:</p> <pre><code>Dim x As System.Xml.Linq.XElement = _ &lt;div&gt; &lt;%= message.ToString() %&gt; &lt;/div&gt; Dim m = x.ToString() </code></pre> <p>...if message is HTML, then the &lt; and > characters get converted to <code>&amp;lt;</code> and <code>&amp;rt;</code>. </p> <p>How can I force it to skip this encoding?</p>
[ { "answer_id": 286045, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 1, "selected": false, "text": "<p>You need to open the HTML snippit as an XML document and append the document node to the Div node you are creating.</p>\n\n<p>If you want to add XML (or HTML) to an existing XML document then you have to add it as XML and not as text (cause that gets encoded).</p>\n" }, { "answer_id": 805559, "author": "CoderDennis", "author_id": 69527, "author_profile": "https://Stackoverflow.com/users/69527", "pm_score": 4, "selected": true, "text": "<p>What is the type of your <code>message</code> variable? If <code>message</code> is an <code>XElement</code>, then just leave off the <code>.ToString</code> call like this:</p>\n\n<pre><code>Dim x As System.Xml.Linq.XElement = _\n &lt;div&gt;\n &lt;%= message %&gt;\n &lt;/div&gt;\nDim m = x.ToString()\n</code></pre>\n\n<p>If <code>message</code> is some other type (like <code>StringBuilder</code>), then do this:</p>\n\n<pre><code>Dim x As System.Xml.Linq.XElement = _\n &lt;div&gt;\n &lt;%= XElement.Parse(message.ToString()) %&gt;\n &lt;/div&gt;\nDim m = x.ToString()\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
With the following code: ``` Dim x As System.Xml.Linq.XElement = _ <div> <%= message.ToString() %> </div> Dim m = x.ToString() ``` ...if message is HTML, then the < and > characters get converted to `&lt;` and `&rt;`. How can I force it to skip this encoding?
What is the type of your `message` variable? If `message` is an `XElement`, then just leave off the `.ToString` call like this: ``` Dim x As System.Xml.Linq.XElement = _ <div> <%= message %> </div> Dim m = x.ToString() ``` If `message` is some other type (like `StringBuilder`), then do this: ``` Dim x As System.Xml.Linq.XElement = _ <div> <%= XElement.Parse(message.ToString()) %> </div> Dim m = x.ToString() ```
285,572
<p>I've previously encountered the suggestion to call System.Threading.Thread.Sleep(0); in tights loops in C# to prevent CPU hogging and used it to good effect.</p> <p>I have a PowerShell script that has a tight loop and I'm wondering whether I should be calling [Thread]::Sleep(0) or Start-Sleep 0 or whether the PS engine will yield for me occasionally.</p>
[ { "answer_id": 285831, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would recommend to use Thread.SpinWait(20). It works well on Intel HT boxes.\nThe advanced way is to check the number of CPU's and call either Sleep(0) for single CPU or SpitWait(20) otherwise</p>\n" }, { "answer_id": 288453, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": true, "text": "<p>I find there are a couple of problems with explicitly yielding a thread via .Sleep() or other means when you are just making sure it doesn't take over the processor. The first is that it just makes your code look poor as it's sprinkled with Thread.Sleep(0). You can comment every instance but it doesn't look great.</p>\n\n<p>The next problem is that you can only yield the code you control. This doesn't help at all if part of the long running script calls a long running function you have no control over. </p>\n\n<p>Instead I would alter the ThreadPriority during the long running operation to be BelowNormal or Lowest. This will solve both problems and likely will be more effecient as the OS can now make a more informed decision as to when to page you out. </p>\n\n<pre><code>[Thread]::CurrentThread.ThreadPriority = System.Threading.ThreadPriority.Lowest\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20819/" ]
I've previously encountered the suggestion to call System.Threading.Thread.Sleep(0); in tights loops in C# to prevent CPU hogging and used it to good effect. I have a PowerShell script that has a tight loop and I'm wondering whether I should be calling [Thread]::Sleep(0) or Start-Sleep 0 or whether the PS engine will yield for me occasionally.
I find there are a couple of problems with explicitly yielding a thread via .Sleep() or other means when you are just making sure it doesn't take over the processor. The first is that it just makes your code look poor as it's sprinkled with Thread.Sleep(0). You can comment every instance but it doesn't look great. The next problem is that you can only yield the code you control. This doesn't help at all if part of the long running script calls a long running function you have no control over. Instead I would alter the ThreadPriority during the long running operation to be BelowNormal or Lowest. This will solve both problems and likely will be more effecient as the OS can now make a more informed decision as to when to page you out. ``` [Thread]::CurrentThread.ThreadPriority = System.Threading.ThreadPriority.Lowest ```
285,579
<p>I'm fairly new to c# so that's why I'm asking this here.</p> <p>I am consuming a web service that returns a long string of XML values. Because this is a string all the attributes have escaped double quotes</p> <pre><code>string xmlSample = "&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;" </code></pre> <p>Here is my problem. I want to do a simple string.replace. If I was working in PHP I'd just run strip_slashes().</p> <p>However, I'm in C# and I can't for the life of me figure it out. I can't write out my expression to replace the double quotes (") because it terminates the string. If I escape it then it has incorrect results. What am I doing wrong?</p> <pre><code> string search = "\\\""; string replace = "\""; Regex rgx = new Regex(search); string strip = rgx.Replace(xmlSample, replace); //Actual Result &lt;root&gt;&lt;item att1=value att2=value2 /&gt;&lt;/root&gt; //Desired Result &lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <blockquote> <p>MizardX: To include a quote in a raw string you need to double it. </p> </blockquote> <p>That's important information, trying that approach now...No luck there either There is something going on here with the double quotes. The concepts you all are suggesting are solid, BUT the issue here is dealing with the double quotes and it looks like I'll need to do some additional research to solve this problem. If anyone comes up with something please post an answer.</p> <pre><code>string newC = xmlSample.Replace("\\\"", "\""); //Result &lt;root&gt;&lt;item att=\"value\" att2=\"value2\" /&gt;&lt;/root&gt; string newC = xmlSample.Replace("\"", "'"); //Result newC "&lt;root&gt;&lt;item att='value' att2='value2' /&gt;&lt;/root&gt;" </code></pre>
[ { "answer_id": 285603, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "<p>Both the string and the regex uses <code>\\</code> for escaping. The regex will see the character <code>\\</code> followed by <code>\"</code>, and think it's a literal escape. Try this:</p>\n\n<pre><code>Regex rgx = new Regex(\"\\\\\\\\\\\"\");\nstring strip = rgx.Replace(xmlSample, \"\\\"\");\n</code></pre>\n\n<p>You could also use raw strings (also known as veratim strings) in C#. They are prefixed with <code>@</code>, and all back-slashes are treated as normal characters. To include a quote in a raw string you need to double it.</p>\n\n<blockquote>\n <p><code>Regex rgx = new Regex(@\"\\\"\"\")</code><br>\n <code>string strip = rgx.Replace(xmlSample, @\"\"\"\");</code></p>\n</blockquote>\n" }, { "answer_id": 285624, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>There's no reason to use a Regular expression at all... that's a lot heavier than what you need.</p>\n\n<pre><code>string xmlSample = \"blah blah blah\";\n\nxmlSample = xmlSample.Replace(\"\\\\\\\", \"\\\"\");\n</code></pre>\n" }, { "answer_id": 285961, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 1, "selected": false, "text": "<p>If you are getting an XML string why not use XML instead strings?</p>\n\n<p>you will have access to all elements and attributes and it will be much easier and extremely fast if using the System.Xml namespace</p>\n\n<p>in your example you are getting this string:</p>\n\n<pre><code>string xmlSample = \"&lt;root&gt;&lt;item att1=\\\"value\\\" att2=\\\"value2\\\" /&gt;&lt;/root&gt;\";\n</code></pre>\n\n<p>All you need to do is convert that string into a XML Document and use it, like:</p>\n\n<pre><code>System.Xml.XmlDocument xml = new System.Xml.XmlDocument();\nxml.LoadXml(xmlSample);\n\nSystem.Xml.XmlElement _root = xml.DocumentElement;\n\nforeach (System.Xml.XmlNode _node in _root)\n{\n Literal1.Text = \"&lt;hr/&gt;\" + _node.Name + \"&lt;br/&gt;\";\n for (int iAtt = 0; iAtt &lt; _node.Attributes.Count; iAtt++)\n Literal1.Text += _node.Attributes[iAtt].Name + \" = \" + _node.Attributes[iAtt].Value + \"&lt;br/&gt;\";\n}\n</code></pre>\n\n<p>in ASP.NET this will output to the Literal1 something like:</p>\n\n<pre><code>item\natt1 = value\natt2 = value2\n</code></pre>\n\n<p>once you have the element in a XmlElement, it is very easy to search and get the values and names for what's in that element.</p>\n\n<p>give it a try, I use it a lot when retrieving WebServices responses and when I store something in a XML file as settings for a small application for example.</p>\n" }, { "answer_id": 286056, "author": "ala", "author_id": 37198, "author_profile": "https://Stackoverflow.com/users/37198", "pm_score": 6, "selected": true, "text": "<p>the following statement in C# </p>\n\n<pre><code>string xmlSample = \"&lt;root&gt;&lt;item att1=\\\"value\\\" att2=\\\"value2\\\" /&gt;&lt;/root&gt;\"\n</code></pre>\n\n<p>will actually store the value </p>\n\n<pre><code>&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;\n</code></pre>\n\n<p>whereas </p>\n\n<pre><code>string xmlSample = @\"&lt;root&gt;&lt;item att1=\\\"\"value\\\"\" att2=\\\"\"value2\\\"\" /&gt;&lt;/root&gt;\";\n</code></pre>\n\n<p>have the value of </p>\n\n<pre><code>&lt;root&gt;&lt;item att1=\\\"value\\\" att2=\\\"value2\\\" /&gt;&lt;/root&gt;\n</code></pre>\n\n<p>for the second case, you need to replace the slash () by empty string as follow</p>\n\n<pre><code>string test = xmlSample.Replace(@\"\\\", string.Empty);\n</code></pre>\n\n<p>the result will be </p>\n\n<pre><code>&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;\n</code></pre>\n\n<p>P.S. </p>\n\n<ol>\n<li>slash (<code>\\</code>) is default escape character in C#</li>\n<li>to ignore slashes, use @ at the beginning of string </li>\n<li>if @ is used, the escape character is double quote (\")</li>\n</ol>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30408/" ]
I'm fairly new to c# so that's why I'm asking this here. I am consuming a web service that returns a long string of XML values. Because this is a string all the attributes have escaped double quotes ``` string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>" ``` Here is my problem. I want to do a simple string.replace. If I was working in PHP I'd just run strip\_slashes(). However, I'm in C# and I can't for the life of me figure it out. I can't write out my expression to replace the double quotes (") because it terminates the string. If I escape it then it has incorrect results. What am I doing wrong? ``` string search = "\\\""; string replace = "\""; Regex rgx = new Regex(search); string strip = rgx.Replace(xmlSample, replace); //Actual Result <root><item att1=value att2=value2 /></root> //Desired Result <root><item att1="value" att2="value2" /></root> ``` > > MizardX: To include a quote in a raw string you need to double it. > > > That's important information, trying that approach now...No luck there either There is something going on here with the double quotes. The concepts you all are suggesting are solid, BUT the issue here is dealing with the double quotes and it looks like I'll need to do some additional research to solve this problem. If anyone comes up with something please post an answer. ``` string newC = xmlSample.Replace("\\\"", "\""); //Result <root><item att=\"value\" att2=\"value2\" /></root> string newC = xmlSample.Replace("\"", "'"); //Result newC "<root><item att='value' att2='value2' /></root>" ```
the following statement in C# ``` string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>" ``` will actually store the value ``` <root><item att1="value" att2="value2" /></root> ``` whereas ``` string xmlSample = @"<root><item att1=\""value\"" att2=\""value2\"" /></root>"; ``` have the value of ``` <root><item att1=\"value\" att2=\"value2\" /></root> ``` for the second case, you need to replace the slash () by empty string as follow ``` string test = xmlSample.Replace(@"\", string.Empty); ``` the result will be ``` <root><item att1="value" att2="value2" /></root> ``` P.S. 1. slash (`\`) is default escape character in C# 2. to ignore slashes, use @ at the beginning of string 3. if @ is used, the escape character is double quote (")
285,584
<p>I am currently stuck on an ASP.NET error when trying to access a .aspx page through localhost. This is the error:</p> <p><strong>OCIEnvCreate failed with return code -1 but error message text was not available.</strong></p> <p><strong>Description</strong>: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p> <p><strong>Exception Details</strong>: System.Exception: OCIEnvCreate failed with return code -1 but error message text was not available. </p> <p><strong>Stack Trace:</strong></p> <pre><code>[Exception: OCIEnvCreate failed with return code -1 but error message text was not available.] System.Data.OracleClient.OciHandle..ctor(OciHandle parentHandle, HTYPE handleType, MODE ocimode, HANDLEFLAG handleflags) +363 System.Data.OracleClient.OciEnvironmentHandle..ctor(MODE environmentMode, Boolean unicode) +23 System.Data.OracleClient.OracleInternalConnection.OpenOnLocalTransaction(String userName, String password, String serverName, Boolean integratedSecurity, Boolean unicode, Boolean omitOracleConnectionName) +122 System.Data.OracleClient.OracleInternalConnection..ctor(OracleConnectionString connectionOptions) +135 System.Data.OracleClient.OracleConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) +36 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +28 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +424 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +68 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +519 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +82 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +104 System.Data.OracleClient.OracleConnection.Open() +37 Wilson.ORMapper.Internals.Connection..ctor(String connectString, CustomProvider customProvider) +287 [ORMapperException: ObjectSpace: Connection String is Invalid - OCIEnvCreate failed with return code -1 but error message text was not available.] Wilson.ORMapper.Internals.Connection..ctor(String connectString, CustomProvider customProvider) +357 Wilson.ORMapper.Internals.Context.Init(XmlDocument xmlMappings, String connectString, CustomProvider customProvider, Int32 sessionMinutes, Int32 cleanupMinutes) +92 Wilson.ORMapper.Internals.Context..ctor(Stream mappingStream, String connectString, CustomProvider customProvider, Int32 sessionMinutes, Int32 cleanupMinutes) +171 Wilson.ORMapper.ObjectSpace..ctor(Stream mappingStream, String connectString, Provider providerType, Int32 sessionMinutes, Int32 cleanupMinutes) +66 zedi.DataManager.GetDefaultInstance() in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\Data\DataManager.cs:155 zedi.DataManager.get_ObjectSpaceGlobal() in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\Data\DataManager.cs:105 zedi.DataManager.get_ObjectSpace() in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\Data\DataManager.cs:129 zedi.DataObjects.CompanyBase.RetrieveQuery(ObjectQuery query) in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\DataObjects\Base\CompanyBase.cs:279 zedi.DataObjects.CompanyBase.RetrieveAll(String sortClause) in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\DataObjects\Base\CompanyBase.cs:78 maint_inetpub.siteTemplates.updateDeviceTemplate.Page_Load(Object sender, EventArgs e) in c:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\Websites\maint-inetpub\siteTemplates\updateDeviceTemplate.aspx.cs:47 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 </code></pre> <p>I notice it says the I have an invalid connection string but I have tested it and it works. I currently have Oracle 10g Express installed and before that I had Oracle 8i Client. It was working before I installed 10g Express. </p>
[ { "answer_id": 858581, "author": "Malcolm", "author_id": 73700, "author_profile": "https://Stackoverflow.com/users/73700", "pm_score": 2, "selected": false, "text": "<p>I've come across the same problem with oracle 10g, from what I've read this error seems to mean that the .Net oracle driver can't find the oracle client. </p>\n\n<p>There are various suggestions to fix this, including checking the PATH and ORACLE_HOME environment variables; re-installing the oracle client in the default location (C:\\oracle) if it isn't already there; or using oracle's Oracle Data Provider for .NET (ODP.NET) instead of the Microsoft oracle driver (System.Data.OracleClient).</p>\n\n<p>None of the above fixed my problem however, so if anyone has any more suggestions they would be most welcome!</p>\n" }, { "answer_id": 1526225, "author": "Nariman", "author_id": 175611, "author_profile": "https://Stackoverflow.com/users/175611", "pm_score": 2, "selected": false, "text": "<p>We've recently run into this as well; in our case, restoring the ORACLE_HOME environment variable did the trick (an incomplete installation of OMS10G that had left the system in an inconsistent state with the environment variable registering as null). </p>\n" }, { "answer_id": 3164578, "author": "Abilena", "author_id": 381916, "author_profile": "https://Stackoverflow.com/users/381916", "pm_score": 0, "selected": false, "text": "<p>I've experienced this on a windows 7 machine. Adding the ORACLE_HOME environment variable and running the executable that uses the oracle client in the \"windows xp sp3\" compatibility mode (file/properties/compatibility) solved the issue for me.</p>\n" }, { "answer_id": 6992311, "author": "Sebastian Edelmeier", "author_id": 249686, "author_profile": "https://Stackoverflow.com/users/249686", "pm_score": 0, "selected": false, "text": "<p>Although this issue is somewhat ancient, I'll throw in my five cents.\nFrom what I have read across the internet, this can occur even in an environment that's configured all the way through when the caller (the user logged on to windows) has no permissions to read/execute the Oracle binaries.</p>\n" }, { "answer_id": 36290730, "author": "AnisNoorAli", "author_id": 5977038, "author_profile": "https://Stackoverflow.com/users/5977038", "pm_score": 0, "selected": false, "text": "<p>Just remove the System.Data.OracleClient.dll from \n<code>\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.5</code> </p>\n\n<p><strong>make sure take the backup first in case of any other error</strong></p>\n\n<p>This works from me. </p>\n\n<p>Or Replace <code>System.Data.OracleClient.dll</code> from following folder\n<code>Windows\\Microsoft.NET\\assembly\\GAC_32\\System.Data.OracleClient\\v4.0_4.0.0.0__b77a5c561934e089</code></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37140/" ]
I am currently stuck on an ASP.NET error when trying to access a .aspx page through localhost. This is the error: **OCIEnvCreate failed with return code -1 but error message text was not available.** **Description**: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. **Exception Details**: System.Exception: OCIEnvCreate failed with return code -1 but error message text was not available. **Stack Trace:** ``` [Exception: OCIEnvCreate failed with return code -1 but error message text was not available.] System.Data.OracleClient.OciHandle..ctor(OciHandle parentHandle, HTYPE handleType, MODE ocimode, HANDLEFLAG handleflags) +363 System.Data.OracleClient.OciEnvironmentHandle..ctor(MODE environmentMode, Boolean unicode) +23 System.Data.OracleClient.OracleInternalConnection.OpenOnLocalTransaction(String userName, String password, String serverName, Boolean integratedSecurity, Boolean unicode, Boolean omitOracleConnectionName) +122 System.Data.OracleClient.OracleInternalConnection..ctor(OracleConnectionString connectionOptions) +135 System.Data.OracleClient.OracleConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) +36 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +28 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +424 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +68 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +519 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +82 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +104 System.Data.OracleClient.OracleConnection.Open() +37 Wilson.ORMapper.Internals.Connection..ctor(String connectString, CustomProvider customProvider) +287 [ORMapperException: ObjectSpace: Connection String is Invalid - OCIEnvCreate failed with return code -1 but error message text was not available.] Wilson.ORMapper.Internals.Connection..ctor(String connectString, CustomProvider customProvider) +357 Wilson.ORMapper.Internals.Context.Init(XmlDocument xmlMappings, String connectString, CustomProvider customProvider, Int32 sessionMinutes, Int32 cleanupMinutes) +92 Wilson.ORMapper.Internals.Context..ctor(Stream mappingStream, String connectString, CustomProvider customProvider, Int32 sessionMinutes, Int32 cleanupMinutes) +171 Wilson.ORMapper.ObjectSpace..ctor(Stream mappingStream, String connectString, Provider providerType, Int32 sessionMinutes, Int32 cleanupMinutes) +66 zedi.DataManager.GetDefaultInstance() in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\Data\DataManager.cs:155 zedi.DataManager.get_ObjectSpaceGlobal() in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\Data\DataManager.cs:105 zedi.DataManager.get_ObjectSpace() in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\Data\DataManager.cs:129 zedi.DataObjects.CompanyBase.RetrieveQuery(ObjectQuery query) in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\DataObjects\Base\CompanyBase.cs:279 zedi.DataObjects.CompanyBase.RetrieveAll(String sortClause) in C:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\DataAccess\ORClasses\DataObjects\Base\CompanyBase.cs:78 maint_inetpub.siteTemplates.updateDeviceTemplate.Page_Load(Object sender, EventArgs e) in c:\projects\FINE Application Interface\Production\On-site Backlog\Source\Code\Websites\maint-inetpub\siteTemplates\updateDeviceTemplate.aspx.cs:47 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 ``` I notice it says the I have an invalid connection string but I have tested it and it works. I currently have Oracle 10g Express installed and before that I had Oracle 8i Client. It was working before I installed 10g Express.
I've come across the same problem with oracle 10g, from what I've read this error seems to mean that the .Net oracle driver can't find the oracle client. There are various suggestions to fix this, including checking the PATH and ORACLE\_HOME environment variables; re-installing the oracle client in the default location (C:\oracle) if it isn't already there; or using oracle's Oracle Data Provider for .NET (ODP.NET) instead of the Microsoft oracle driver (System.Data.OracleClient). None of the above fixed my problem however, so if anyone has any more suggestions they would be most welcome!
285,586
<p>I have a script that constantly segfaults - the problem that I can't solve as segfault is in python libxml bindings - didn't write those. Ok, so in Linux I used to run an inf.loop so that when script dies - it restarts, like so:</p> <pre><code>#!/bin/bash while [ 1 ] do nice -n 19 python server.py sleep 1 done </code></pre> <p>Well, I can't seem to find /bin/bash in FreeBSD so that doesn't work. </p> <p>Any ideas? Consider that cron is not an option - allowed downtime is a few seconds.</p>
[ { "answer_id": 285605, "author": "Adam Jaskiewicz", "author_id": 35322, "author_profile": "https://Stackoverflow.com/users/35322", "pm_score": 0, "selected": false, "text": "<p>Not sure what shell FreeBSD uses by default, but it probably comes with a few. The man page for whatever shell you are using ought to tell you that shell's loop syntax. It's probably pretty similar.</p>\n" }, { "answer_id": 285609, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 1, "selected": false, "text": "<p>There will be some shell program on the system, and that script looks like it will run in pretty much any shell.</p>\n\n<p>Type <code>type bash</code> to see where bash is. If not, try sh. It should be there, and it should work. Take the result of <code>type bash</code> or <code>type sh</code>, and use in in the place of /bin/bash. Alternately, look at /etc/passwd, look for your account, and notice what the shell is. I believe it's the last field, and it will say something like /bin/sh or /usr/bin/bash or whatever. Use that instead of /bin/bash.</p>\n" }, { "answer_id": 285610, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": true, "text": "<p>/bin/sh almost certainly exists, but if you really need bash:</p>\n\n<pre><code>cd /usr/ports/*/bash\nmake install\n</code></pre>\n\n<p>that should install bash in /usr/local/bin/bash i believe</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37141/" ]
I have a script that constantly segfaults - the problem that I can't solve as segfault is in python libxml bindings - didn't write those. Ok, so in Linux I used to run an inf.loop so that when script dies - it restarts, like so: ``` #!/bin/bash while [ 1 ] do nice -n 19 python server.py sleep 1 done ``` Well, I can't seem to find /bin/bash in FreeBSD so that doesn't work. Any ideas? Consider that cron is not an option - allowed downtime is a few seconds.
/bin/sh almost certainly exists, but if you really need bash: ``` cd /usr/ports/*/bash make install ``` that should install bash in /usr/local/bin/bash i believe
285,587
<p>When i do </p> <pre><code>wnd = CreateWindow("EDIT", 0, WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN, x, y, w, h, parentWnd, NULL, NULL, NULL); </code></pre> <p>everything is fine, however if i remove the WS_VSCROLL and WS_HSCROLL then do the below, i do not get them thus have incorrect window. Why? Not only do i get an incorrect window it is unusable if both WS_VSCROLL and WS_HSCROLL are missing</p> <pre><code>style = WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN; SetWindowLong(wnd, GWL_STYLE, style); </code></pre>
[ { "answer_id": 285757, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 4, "selected": true, "text": "<p>Some control styles cannot be changed after window creation. The ES_AUTOHSCROLL style (which essentially controls word wrapping) is one of them; this is stated (somewhat indirectly) by the MSDN section on <a href=\"http://msdn.microsoft.com/en-us/library/bb775464.aspx\" rel=\"noreferrer\">Edit Control Styles</a>. You can set the bits using SetWindowLong(), but the control will either ignore them or behave erratically.</p>\n\n<p>The only way to do this cleanly is to recreate the edit control using the required styles. This is actually what Notepad does when you toggle the \"Word Wrap\" setting.</p>\n" }, { "answer_id": 5358808, "author": "Carlo Bramini", "author_id": 666834, "author_profile": "https://Stackoverflow.com/users/666834", "pm_score": 2, "selected": false, "text": "<p>You can do it with ShowScrollBar() function.\nYou may also find interesting the function EnableScrollBar() if you want to enable/disable scroll bars of a window.\nBest regards.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When i do ``` wnd = CreateWindow("EDIT", 0, WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN, x, y, w, h, parentWnd, NULL, NULL, NULL); ``` everything is fine, however if i remove the WS\_VSCROLL and WS\_HSCROLL then do the below, i do not get them thus have incorrect window. Why? Not only do i get an incorrect window it is unusable if both WS\_VSCROLL and WS\_HSCROLL are missing ``` style = WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN; SetWindowLong(wnd, GWL_STYLE, style); ```
Some control styles cannot be changed after window creation. The ES\_AUTOHSCROLL style (which essentially controls word wrapping) is one of them; this is stated (somewhat indirectly) by the MSDN section on [Edit Control Styles](http://msdn.microsoft.com/en-us/library/bb775464.aspx). You can set the bits using SetWindowLong(), but the control will either ignore them or behave erratically. The only way to do this cleanly is to recreate the edit control using the required styles. This is actually what Notepad does when you toggle the "Word Wrap" setting.
285,591
<p>Is it possible to use the __unused attribute macro on Objective-C object method parameters? I've tried placing it in various positions around the parameter declaration but it either causes a compilation error or seems to be ignored (i.e., the compiler still generates unused parameter warnings when compiling with -Wall -Wextra).</p> <p>Has anyone been able to do use this? Is it just unsupported with Objective-C? For reference, I'm currently using Apple's build of GCC 4.0.1.</p>
[ { "answer_id": 285702, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 2, "selected": false, "text": "<p>I can compile the following just fine:</p>\n\n<pre><code>- (NSString *) test:(__unused NSString *)test {\n return nil;\n}\n</code></pre>\n\n<p>Edit: Actually, that may not be strictly an arch thing:</p>\n\n<pre><code>Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror\nPhoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror -Wunused-parameter\ncc1obj: warnings being treated as errors\nPusher.m:40: warning: unused parameter ‘test’\nPhoenix-VI:CouchPusher louis$ \n</code></pre>\n\n<p>So -Wall does not include not include -Wunused-parameter....</p>\n" }, { "answer_id": 285750, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 5, "selected": true, "text": "<p>Okay, I found the answer... it appears to be a bug with the implementation of Apple's gcc 4.0. Using gcc 4.2 it works as expected and the proper placement is the following:</p>\n\n<pre><code>-(void)someMethod:(id) __unused someParam;\n</code></pre>\n\n<p>It's documented in the Objective-C release notes if anyone is interested: <a href=\"http://developer.apple.com/releasenotes/Cocoa/RN-ObjectiveC/index.html#//apple_ref/doc/uid/TP40004309-DontLinkElementID_6\" rel=\"noreferrer\">http://developer.apple.com/releasenotes/Cocoa/RN-ObjectiveC/index.html#//apple_ref/doc/uid/TP40004309-DontLinkElementID_6</a></p>\n\n<p>As a note, your answer will compile, Louis, but as I stated in my question it won't actually do anything or suppress the unused warning issued by the compiler.</p>\n\n<p>EDIT: I filed a bug report with apple for this <a href=\"http://rdar://6366051\" rel=\"noreferrer\">rdar://6366051</a>.</p>\n" }, { "answer_id": 285751, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 2, "selected": false, "text": "<p>I think you can use the #pragma unused to mark arguments as unused. Untested, but you can try something like</p>\n\n<pre><code>- (NSString *)test:(NSString *)test {\n#pragma unused (test);\n return nil;\n}\n</code></pre>\n" }, { "answer_id": 285785, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>A common idiom is to use the following:</p>\n\n<pre><code>#define UNUSED(x) (void)x\nvoid SomeFunction(int param1, int param2)\n{\n UNUSED(param2);\n // do stuff with param1\n}</code></pre>\n\n<p>The <code>UNUSED(param2)</code> statement doesn't generate any object code, eliminates warnings about unused variables, and clearly documents the code as not using the variable.</p>\n" }, { "answer_id": 1863688, "author": "alecf", "author_id": 204357, "author_profile": "https://Stackoverflow.com/users/204357", "pm_score": 1, "selected": false, "text": "<p>After fighting with the #pragma for a while, I discovered it's </p>\n\n<pre><code>+ (NSString*) runQuery:(id)query name:(NSString*)name options:(NSDictionary*)options\n{\n#pragma unused(name)\n ...\n\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34218/" ]
Is it possible to use the \_\_unused attribute macro on Objective-C object method parameters? I've tried placing it in various positions around the parameter declaration but it either causes a compilation error or seems to be ignored (i.e., the compiler still generates unused parameter warnings when compiling with -Wall -Wextra). Has anyone been able to do use this? Is it just unsupported with Objective-C? For reference, I'm currently using Apple's build of GCC 4.0.1.
Okay, I found the answer... it appears to be a bug with the implementation of Apple's gcc 4.0. Using gcc 4.2 it works as expected and the proper placement is the following: ``` -(void)someMethod:(id) __unused someParam; ``` It's documented in the Objective-C release notes if anyone is interested: <http://developer.apple.com/releasenotes/Cocoa/RN-ObjectiveC/index.html#//apple_ref/doc/uid/TP40004309-DontLinkElementID_6> As a note, your answer will compile, Louis, but as I stated in my question it won't actually do anything or suppress the unused warning issued by the compiler. EDIT: I filed a bug report with apple for this [rdar://6366051](http://rdar://6366051).
285,614
<p>Every night I need to trim back a table to only contain the latest 20,000 records. I could use a subquery:</p> <pre><code>delete from table WHERE id NOT IN (select TOP 20000 ID from table ORDER BY date_added DESC) </code></pre> <p>But that seems inefficient, especially if we later decide to keep 50,000 records. I'm using SQL 2005, and thought I could use ROW_NUMBER() OVER somehow to do it? Order them and delete all that have a ROW_NUMBER greater than 20,000? But I couldn't get it to work. Is the subquery my best bet or is there a better way?</p>
[ { "answer_id": 285622, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": true, "text": "<p>If it just <em>seems</em> inefficient, I would make sure it is inefficient before I start barking up the wrong tree.</p>\n\n<p>Measure the time, cpu usage, disk I/O, etc. to see how well it performs. I think you'll find it performs better than you think.</p>\n" }, { "answer_id": 285648, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 0, "selected": false, "text": "<p>Surely this is a prime case for wrapping up into a procedure and using two sql statements - the first to select the latest ID and subtract 20,000, then the second to delete all rows with ID's lower than this. </p>\n\n<p>However it does on the face of it sound like you're going to end up with a lot of fragmentation going with this approach and that might be a good argument for creating a new table, inserting the latest 20,000 records into it, deleting the old one and renaming the new. It might even be worthwhile putting the table in a different database and creating a view from your main database to facilitate access. Myself I generally tend to do this with tables used for data load and audit.</p>\n\n<p>It's very difficult to tell without knowing your actual data volumes and behavior, but it could well be that globally your inefficiencies will arise more from this than the delete method you use. If you're only collecting a thousand or less records a day then a delete is probably ok combined with running a data optimization maintenance plan, but more and I'd be looking at the more drastic approach.</p>\n" }, { "answer_id": 285851, "author": "Borzio", "author_id": 36215, "author_profile": "https://Stackoverflow.com/users/36215", "pm_score": 2, "selected": false, "text": "<p>Of course, your mileage will vary -- This will depend on how many real records you are scraping off the bottom of this table, but here's an alternative. <br/></p>\n\n<p>Side Note: Since you have a \"Date_Added\" field, would it be worth considering to simply keep the datetime of the last run and use that in your where clause to filter the records to be removed? Now, instead of 20,000 records, allow X number of days in the log ... Just a thought...<br/></p>\n\n<hr>\n\n<p>-- Get the records we want to KEEP into a temp.<br/>\n-- You can classify the keepers however you wish.<br/></p>\n\n<pre><code>select top 20000 * into #myTempTable from MyTable ORDER BY DateAdded DESC\n</code></pre>\n\n<p>-- Using truncate doesn't trash our log file and uses fewer sys resources...<br></p>\n\n<pre><code>truncate table MyTable \n</code></pre>\n\n<p>-- Bring our 'kept' records back into the fold ...<br/>\n-- This assumes that you are NOT using an identity column -- if you are, you should<br/>\n-- specify the field names instead of using the '*' and do something like <br/>\n-- SET IDENTITY_INSERT MyTable ON<br/>\n-- insert into MyTable select field1,field2,field3 from #myTempTable <br/>\n-- (I think that's right)<br/></p>\n\n<pre><code>insert into MyTable select * from #myTempTable\n</code></pre>\n\n<p>-- be a good citizen.</p>\n\n<pre><code>drop table #myTempTable\n</code></pre>\n\n<hr>\n\n<p><br/></p>\n\n<p>Hope it helps --</p>\n" }, { "answer_id": 285914, "author": "Haoest", "author_id": 10088, "author_profile": "https://Stackoverflow.com/users/10088", "pm_score": 2, "selected": false, "text": "<pre><code>DECLARE @limit INT\nSELECT @limit = min(id) FROM\n (SELECT TOP 20000 id FROM your_table ORDER BY id DESC)x\nDELETE FROM your_table where id &lt; @limit\n</code></pre>\n\n<p>The point was to avoid the nested query, which I may or may not be optimized (sorry not sql guru.)</p>\n" }, { "answer_id": 285968, "author": "John Dyer", "author_id": 2862, "author_profile": "https://Stackoverflow.com/users/2862", "pm_score": 0, "selected": false, "text": "<p>You question implies that you are trimming to get better daytime performance from the table. Are you getting table scans on the daytime queries? Wouldn't better indexes be the answer? Or are you in a situation where you are stuck with a \"crappy schema\"?</p>\n\n<p>Or do have some really strange situation where you indeed need to purge old records? Is 20,000 a hard and fast number? Or could a datetime work? Then and index on the datetime column would make trimming a bit easier.</p>\n" }, { "answer_id": 13904375, "author": "Santosh Dube", "author_id": 1908261, "author_profile": "https://Stackoverflow.com/users/1908261", "pm_score": 1, "selected": false, "text": "<p>insert 20000 into temp table then delete all records from main table then again insert\n20000 record from temp table to main table..,</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10876/" ]
Every night I need to trim back a table to only contain the latest 20,000 records. I could use a subquery: ``` delete from table WHERE id NOT IN (select TOP 20000 ID from table ORDER BY date_added DESC) ``` But that seems inefficient, especially if we later decide to keep 50,000 records. I'm using SQL 2005, and thought I could use ROW\_NUMBER() OVER somehow to do it? Order them and delete all that have a ROW\_NUMBER greater than 20,000? But I couldn't get it to work. Is the subquery my best bet or is there a better way?
If it just *seems* inefficient, I would make sure it is inefficient before I start barking up the wrong tree. Measure the time, cpu usage, disk I/O, etc. to see how well it performs. I think you'll find it performs better than you think.
285,617
<p>I'd like to call svn up from an asp.net page so people can hit the page to update a repository. (BTW: I'm using Beanstalk.com svn hosting which doesn't allow post-commit hooks, which is why I am doing it this way). </p> <p>See what I've got below. The process starts (it shows up in Processes in Task Manager) and exits after several seconds with no output message (at least none is outputted to the page). The repository does not get updated. But it does do something with the repository because the next time I try to manually update it from the command line it says the repo is locked. I have to run svn cleanup to get it to update. </p> <p>Ideas?</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) startInfo = New System.Diagnostics.ProcessStartInfo("svn") startInfo.RedirectStandardOutput = True startInfo.UseShellExecute = False startInfo.Arguments = "up " &amp; Request.QueryString("path") pStart.StartInfo = startInfo pStart.Start() pStart.WaitForExit() Response.Write(pStart.StandardOutput.ReadToEnd()) End Sub </code></pre>
[ { "answer_id": 286255, "author": "JTew", "author_id": 25372, "author_profile": "https://Stackoverflow.com/users/25372", "pm_score": 1, "selected": false, "text": "<p>You might be able to do this more effectively by using a .net SVN wrapper or library like this <a href=\"http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html\" rel=\"nofollow noreferrer\">one</a>. I'm sure there are others out there that would support the limitations of beanstalk as well.</p>\n" }, { "answer_id": 286989, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 0, "selected": false, "text": "<p>Using <a href=\"http://sharpsvn.net/\" rel=\"nofollow noreferrer\">SharpSvn</a>:</p>\n\n<pre><code>using(SvnClient client = new SvnClient())\n{\n client.Update(Request[\"path\"]);\n}\n</code></pre>\n\n<p>But I would recommend not to use a user passed variable directly for security reasons.</p>\n" }, { "answer_id": 287046, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>You can also use the Subversion library that comes with Ankh SVN.\nI used it in a project to manage files in a Subversion repository and it worked well.</p>\n\n<p>If you insist on using the command line client make sure you check the StandardError output for any error messages. Also make sure the user you run the process as has the appropriate rights.</p>\n" }, { "answer_id": 49434391, "author": "wojouk", "author_id": 9536082, "author_profile": "https://Stackoverflow.com/users/9536082", "pm_score": 0, "selected": false, "text": "<p>I have investigated this in detail. A loooong way to do it is to use Windows Messaging Subsystem (windows event log - you create your own log and write messages to it). Asp.Net creates a message. Then you need to write a windows service which reads the messages every 3 seconds or so. The moment it comes across an 'update svn please message', you run your cmd.exe /c svn.exe blah blah from your freshly created windows service...it works very well, buts its a lot of work...Then there is SharpSVN lib, but it requires a bit of setup and you can run into problems. Finally, most people seem to be trying to use ProcessStartInfo class, but few seem to get it right...Yes, its not easy and a long way around but here's the code......Here's code that will run svn.exe for you and log all the screen output to output buffer....</p>\n\n<pre><code> private static int lineCount = 0;\n private static StringBuilder outputBuffer = new StringBuilder();\n private void SvnOutputHandler(object sendingProcess,\n DataReceivedEventArgs e)\n {\n Process p = sendingProcess as Process;\n\n // Save the output lines here\n // Prepend line numbers to each line of the output.\n if (!String.IsNullOrEmpty(e.Data))\n {\n lineCount++;\n outputBuffer.Append(\"\\n[\" + lineCount + \"]: \" + e.Data);\n }\n }\n\n private void RunSVNCommand()\n {\n ProcessStartInfo psi = new ProcessStartInfo(\"cmd.exe\",\n string.Format(\"/c svn.exe --config-dir=%APPDATA%\\\\Subversion --username=yrname --password=yrpassword --trust-server-cert --non-interactive update d:\\\\inetpub\\\\wwwroot\\\\yourpath\"));\n\n psi.UseShellExecute = false;\n psi.CreateNoWindow = true;\n\n // Redirect the standard output of the sort command. \n // This stream is read asynchronously using an event handler.\n psi.RedirectStandardOutput = true;\n psi.RedirectStandardError = true;\n\n Process p = new Process();\n\n // Set our event handler to asynchronously read the sort output.\n p.OutputDataReceived += SvnOutputHandler;\n p.ErrorDataReceived += SvnOutputHandler;\n p.StartInfo = psi;\n\n p.Start();\n\n p.BeginOutputReadLine();\n p.BeginErrorReadLine();\n\n p.WaitForExit();\n }\n</code></pre>\n\n<p>Quick explanation on svn.exe arguments and why we do it...You need to specify config-dir to whatever account has checked out the svn dir. IIS runs under a different account. If it can't find the config file for svn, you will get a stop message. --Non-interactive and --trust-server-certificate is to basically skip the prompt to accept the security challenges. Finally, you will need to specify username and password as this for some reason does not get sent (with my version of svn.exe anyway). Now, on top of this, connecting via https to the svn server was giving me errors as the hostname reported by IIS is different to a desktop hostname (ssl cert mismatch), hence it does not like the hostname in the config file - go figure. So, I figured, that if I reverse proxy from http to https (so now I have two websites on one server, with one being reversesvn.domain.com:80 proxing to svn.domain.com:8443) This will skip on all the certificate issues and that was the final piece of the puzzle. Here's how to do it - simple : <a href=\"https://blog.ligos.net/2016-11-14/Reverse-Proxy-With-IIS-And-Lets-Encrypt.html\" rel=\"nofollow noreferrer\">https://blog.ligos.net/2016-11-14/Reverse-Proxy-With-IIS-And-Lets-Encrypt.html</a>.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd like to call svn up from an asp.net page so people can hit the page to update a repository. (BTW: I'm using Beanstalk.com svn hosting which doesn't allow post-commit hooks, which is why I am doing it this way). See what I've got below. The process starts (it shows up in Processes in Task Manager) and exits after several seconds with no output message (at least none is outputted to the page). The repository does not get updated. But it does do something with the repository because the next time I try to manually update it from the command line it says the repo is locked. I have to run svn cleanup to get it to update. Ideas? ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) startInfo = New System.Diagnostics.ProcessStartInfo("svn") startInfo.RedirectStandardOutput = True startInfo.UseShellExecute = False startInfo.Arguments = "up " & Request.QueryString("path") pStart.StartInfo = startInfo pStart.Start() pStart.WaitForExit() Response.Write(pStart.StandardOutput.ReadToEnd()) End Sub ```
You can also use the Subversion library that comes with Ankh SVN. I used it in a project to manage files in a Subversion repository and it worked well. If you insist on using the command line client make sure you check the StandardError output for any error messages. Also make sure the user you run the process as has the appropriate rights.
285,619
<p>I have an input String say <code>Please go to http://stackoverflow.com</code>. The url part of the String is detected and an anchor <code>&lt;a href=""&gt;&lt;/a&gt;</code> is automatically added by many browser/IDE/applications. So it becomes <code>Please go to &lt;a href='http://stackoverflow.com'&gt;http://stackoverflow.com&lt;/a&gt;</code>.</p> <p>I need to do the same using Java.</p>
[ { "answer_id": 285667, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 3, "selected": false, "text": "<p>You could do something like this (adjust the regex to suit your needs):</p>\n\n<pre><code>String originalString = \"Please go to http://www.stackoverflow.com\";\nString newString = originalString.replaceAll(\"http://.+?(com|net|org)/{0,1}\", \"&lt;a href=\\\"$0\\\"&gt;$0&lt;/a&gt;\");\n</code></pre>\n" }, { "answer_id": 285690, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Primitive:</p>\n\n<pre><code>String msg = \"Please go to http://stackoverflow.com\";\nString withURL = msg.replaceAll(\"(?:https?|ftps?)://[\\\\w/%.-]+\", \"&lt;a href='$0'&gt;$0&lt;/a&gt;\");\nSystem.out.println(withURL);\n</code></pre>\n\n<p>This needs refinement, to match proper URLs, and particularly GET parameters (?foo=bar&amp;x=25)</p>\n" }, { "answer_id": 285808, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 0, "selected": false, "text": "<p>Your are asking two separate questions.</p>\n\n<ol>\n<li>What is the best way to identify URLs in Strings?\nSee <a href=\"https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url\">this thread</a></li>\n<li>How to code the above solution in Java? other responses illustrating <code>String.replaceAll</code> usage have addressed this</li>\n</ol>\n" }, { "answer_id": 285865, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>While it's not Java specific, Jeff Atwood recently posted an article about the pitfalls you might run into when trying to locate and match URLs in arbitrary text:</p>\n\n<p><a href=\"http://blog.codinghorror.com/the-problem-with-urls/\" rel=\"nofollow noreferrer\">The Problem With URLs</a></p>\n\n<p>It gives a good regex that can be used along with the snippet of code that you need to use to properly (more or less) handle parens.</p>\n\n<p>The regex:</p>\n\n<pre><code>\\(?\\bhttp://[-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]\n</code></pre>\n\n<p>The paren cleanup:</p>\n\n<pre><code>if (s.StartsWith(\"(\") &amp;&amp; s.EndsWith(\")\"))\n{\n return s.Substring(1, s.Length - 2);\n}\n</code></pre>\n" }, { "answer_id": 285880, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 6, "selected": false, "text": "<h2>Use java.net.URL for that!!</h2>\n\n<p>Hey, why don't use the core class in java for this \"java.net.URL\" and let it validate the URL. </p>\n\n<p>While the following code violates the golden principle \"Use exception for exceptional conditions only\" it does not make sense to me to try to reinvent the wheel for something that is veeery mature on the java platform.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>import java.net.URL;\nimport java.net.MalformedURLException;\n\n// Replaces URLs with html hrefs codes\npublic class URLInString {\n public static void main(String[] args) {\n String s = args[0];\n // separate input by spaces ( URLs don't have spaces )\n String [] parts = s.split(\"\\\\s+\");\n\n // Attempt to convert each item into an URL. \n for( String item : parts ) try {\n URL url = new URL(item);\n // If possible then replace with anchor...\n System.out.print(\"&lt;a href=\\\"\" + url + \"\\\"&gt;\"+ url + \"&lt;/a&gt; \" ); \n } catch (MalformedURLException e) {\n // If there was an URL that was not it!...\n System.out.print( item + \" \" );\n }\n\n System.out.println();\n }\n}\n</code></pre>\n\n<p>Using the following input:</p>\n\n<pre><code>\"Please go to http://stackoverflow.com and then mailto:[email protected] to download a file from ftp://user:pass@someserver/someFile.txt\"\n</code></pre>\n\n<p>Produces the following output:</p>\n\n<pre><code>Please go to &lt;a href=\"http://stackoverflow.com\"&gt;http://stackoverflow.com&lt;/a&gt; and then &lt;a href=\"mailto:[email protected]\"&gt;mailto:[email protected]&lt;/a&gt; to download a file from &lt;a href=\"ftp://user:pass@someserver/someFile.txt\"&gt;ftp://user:pass@someserver/someFile.txt&lt;/a&gt;\n</code></pre>\n\n<p>Of course different protocols could be handled in different ways.\nYou can get all the info with the getters of URL class, for instance </p>\n\n<pre><code> url.getProtocol();\n</code></pre>\n\n<p>Or the rest of the attributes: spec, port, file, query, ref etc. etc</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/net/URL.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/net/URL.html</a></p>\n\n<p>Handles all the protocols ( at least all of those the java platform is aware ) and as an extra benefit, if there is any URL that java currently does not recognize and eventually gets incorporated into the URL class ( by library updating ) you'll get it transparently!</p>\n" }, { "answer_id": 7122165, "author": "Sérgio Nunes", "author_id": 452172, "author_profile": "https://Stackoverflow.com/users/452172", "pm_score": 0, "selected": false, "text": "<p>A good refinement to PhiLho's answer would be:\n<code>msg.replaceAll(\"(?:https?|ftps?)://[\\w/%.-][/\\??\\w=?\\w?/%.-]?[/\\?&amp;\\w=?\\w?/%.-]*\", \"$0\");</code></p>\n" }, { "answer_id": 9602832, "author": "Jacob Zwiers", "author_id": 228838, "author_profile": "https://Stackoverflow.com/users/228838", "pm_score": 2, "selected": false, "text": "<p>The following code makes these modifications to the \"Atwood Approach\":</p>\n\n<ol>\n<li>Detects https in addition to http (adding other schemes is trivial)</li>\n<li>The CASE_INSENSTIVE flag is used since HtTpS:// is valid.</li>\n<li>Matching sets of parentheses are peeled off (they can be nested to\nany level). Further, any remaining unmatched left parentheses are\nstripped, but trailing right parentheses are left intact (to respect\nwikipedia-style URLs) </li>\n<li>The URL is HTML Encoded in the link text.</li>\n<li>The target attribute is passed in via method parameter. Other attributes can be added as desired.</li>\n<li>It does not use \\b to identify a word break before matching a URL. URLs can begin with a left parenthesis or http[s]:// with no other requirement.</li>\n</ol>\n\n<p>Notes:</p>\n\n<ul>\n<li>Apache Commons Lang's StringUtils are used in the code below</li>\n<li>The call to HtmlUtil.encode() below is a util which ultimately calls\nsome Tomahawk code to HTML-encode the link text, but any similar utility will do.</li>\n<li>See the method comment for a usage in JSF or other environments where output is HTML Encoded by default.</li>\n</ul>\n\n<p>This was written in response to our client's requirements and we feel it represents a reasonable compromise between the allowable characters from the RFC and common usage. It is offered here in the hopes that it will be useful to others. </p>\n\n<p>Further expansion could be made which would allow for any Unicode characters to be entered (i.e. not escaped with %XX (two digit hex) and hyperlinked, but that would require accepting all Unicode letters plus limited punctuation and then splitting on the \"acceptable\" delimiters (eg. .,%,|,#, etc.), URL-encoding each part and then gluing back together. For example, <a href=\"http://en.wikipedia.org/wiki\" rel=\"nofollow\">http://en.wikipedia.org/wiki</a>/Björn_Andrésen (which the Stack Overflow generator does not detect) would be \"http://en.wikipedia.org/wiki/Bj%C3%B6rn_Andr%C3%A9sen\" in the href, but would contain Björn_Andrésen in the linked text on the page.</p>\n\n<pre><code>// NOTES: 1) \\w includes 0-9, a-z, A-Z, _\n// 2) The leading '-' is the '-' character. It must go first in character class expression\nprivate static final String VALID_CHARS = \"-\\\\w+&amp;@#/%=~()|\";\nprivate static final String VALID_NON_TERMINAL = \"?!:,.;\";\n\n// Notes on the expression:\n// 1) Any number of leading '(' (left parenthesis) accepted. Will be dealt with. \n// 2) s? ==&gt; the s is optional so either [http, https] accepted as scheme\n// 3) All valid chars accepted and then one or more\n// 4) Case insensitive so that the scheme can be hTtPs (for example) if desired\nprivate static final Pattern URI_FINDER_PATTERN = Pattern.compile(\"\\\\(*https?://[\"+ VALID_CHARS + VALID_NON_TERMINAL + \"]*[\" +VALID_CHARS + \"]\", Pattern.CASE_INSENSITIVE );\n\n/**\n * &lt;p&gt;\n * Finds all \"URL\"s in the given _rawText, wraps them in \n * HTML link tags and returns the result (with the rest of the text\n * html encoded).\n * &lt;/p&gt;\n * &lt;p&gt;\n * We employ the procedure described at:\n * http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html\n * which is a &lt;b&gt;must-read&lt;/b&gt;.\n * &lt;/p&gt;\n * Basically, we allow any number of left parenthesis (which will get stripped away)\n * followed by http:// or https://. Then any number of permitted URL characters\n * (based on http://www.ietf.org/rfc/rfc1738.txt) followed by a single character\n * of that set (basically, those minus typical punctuation). We remove all sets of \n * matching left &amp; right parentheses which surround the URL.\n *&lt;/p&gt;\n * &lt;p&gt;\n * This method *must* be called from a tag/component which will NOT\n * end up escaping the output. For example:\n * &lt;PRE&gt;\n * &lt;h:outputText ... escape=\"false\" value=\"#{core:hyperlinkText(textThatMayHaveURLs, '_blank')}\"/&gt;\n * &lt;/pre&gt;\n * &lt;/p&gt;\n * &lt;p&gt;\n * Reason: we are adding &lt;code&gt;&amp;lt;a href=\"...\"&amp;gt;&lt;/code&gt; tags to the output *and*\n * encoding the rest of the string. So, encoding the outupt will result in\n * double-encoding data which was already encoded - and encoding the &lt;code&gt;a href&lt;/code&gt;\n * (which will render it useless).\n * &lt;/p&gt;\n * &lt;p&gt;\n * \n * @param _rawText - if &lt;code&gt;null&lt;/code&gt;, returns &lt;code&gt;\"\"&lt;/code&gt; (empty string).\n * @param _target - if not &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;\"\"&lt;/code&gt;, adds a target attributed to the generated link, using _target as the attribute value.\n */\npublic static final String hyperlinkText( final String _rawText, final String _target ) {\n\n String returnValue = null;\n\n if ( !StringUtils.isBlank( _rawText ) ) {\n\n final Matcher matcher = URI_FINDER_PATTERN.matcher( _rawText );\n\n if ( matcher.find() ) {\n\n final int originalLength = _rawText.length();\n\n final String targetText = ( StringUtils.isBlank( _target ) ) ? \"\" : \" target=\\\"\" + _target.trim() + \"\\\"\";\n final int targetLength = targetText.length();\n\n // Counted 15 characters aside from the target + 2 of the URL (max if the whole string is URL)\n // Rough guess, but should keep us from expanding the Builder too many times.\n final StringBuilder returnBuffer = new StringBuilder( originalLength * 2 + targetLength + 15 );\n\n int currentStart;\n int currentEnd;\n int lastEnd = 0;\n\n String currentURL;\n\n do {\n currentStart = matcher.start();\n currentEnd = matcher.end();\n currentURL = matcher.group();\n\n // Adjust for URLs wrapped in ()'s ... move start/end markers\n // and substring the _rawText for new URL value.\n while ( currentURL.startsWith( \"(\" ) &amp;&amp; currentURL.endsWith( \")\" ) ) {\n currentStart = currentStart + 1;\n currentEnd = currentEnd - 1;\n\n currentURL = _rawText.substring( currentStart, currentEnd );\n }\n\n while ( currentURL.startsWith( \"(\" ) ) {\n currentStart = currentStart + 1;\n\n currentURL = _rawText.substring( currentStart, currentEnd );\n }\n\n // Text since last match\n returnBuffer.append( HtmlUtil.encode( _rawText.substring( lastEnd, currentStart ) ) );\n\n // Wrap matched URL\n returnBuffer.append( \"&lt;a href=\\\"\" + currentURL + \"\\\"\" + targetText + \"&gt;\" + currentURL + \"&lt;/a&gt;\" );\n\n lastEnd = currentEnd;\n\n } while ( matcher.find() );\n\n if ( lastEnd &lt; originalLength ) {\n returnBuffer.append( HtmlUtil.encode( _rawText.substring( lastEnd ) ) );\n }\n\n returnValue = returnBuffer.toString();\n }\n } \n\n if ( returnValue == null ) {\n returnValue = HtmlUtil.encode( _rawText );\n }\n\n return returnValue;\n\n}\n</code></pre>\n" }, { "answer_id": 11395769, "author": "Tixa", "author_id": 1499545, "author_profile": "https://Stackoverflow.com/users/1499545", "pm_score": -1, "selected": false, "text": "<p>To detect an URL you just need this:</p>\n\n<pre><code>if (yourtextview.getText().toString().contains(\"www\") || yourtextview.getText().toString().contains(\"http://\"){ your code here if contains URL;}\n</code></pre>\n" }, { "answer_id": 12330748, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 0, "selected": false, "text": "<p>I wrote my own URI/URL extractor and figured someone might find it useful considering it IMHO is better than the other answers because:</p>\n\n<ul>\n<li>Its Stream based and can be used on large documents</li>\n<li>Its extendable to handle all kinds of <a href=\"https://blog.codinghorror.com/the-problem-with-urls/\" rel=\"nofollow noreferrer\">\"Atwood Paren\"</a> problems through a strategy chain.</li>\n</ul>\n\n<p>Since the code is somewhat long for a post (albeit only one Java file) I have put it on <a href=\"https://gist.github.com/3674391\" rel=\"nofollow noreferrer\"><strong>gist github</strong></a>.</p>\n\n<p>Here is a signature of one of the main methods to call it to show how its the above bullet points:</p>\n\n<pre><code>public static Iterator&lt;ExtractedURI&gt; extractURIs(\n final Reader reader,\n final Iterable&lt;ToURIStrategy&gt; strategies,\n String ... schemes);\n</code></pre>\n\n<p>There is a default strategy chain which handle most of the Atwood problems.</p>\n\n<pre><code>public static List&lt;ToURIStrategy&gt; DEFAULT_STRATEGY_CHAIN = ImmutableList.of(\n new RemoveSurroundsWithToURIStrategy(\"'\"),\n new RemoveSurroundsWithToURIStrategy(\"\\\"\"),\n new RemoveSurroundsWithToURIStrategy(\"(\", \")\"),\n new RemoveEndsWithToURIStrategy(\".\"),\n DEFAULT_STRATEGY,\n REMOVE_LAST_STRATEGY);\n</code></pre>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 30829767, "author": "robinst", "author_id": 305973, "author_profile": "https://Stackoverflow.com/users/305973", "pm_score": 0, "selected": false, "text": "<p>I made a small library which does exactly this:</p>\n\n<p><a href=\"https://github.com/robinst/autolink-java\" rel=\"nofollow\">https://github.com/robinst/autolink-java</a></p>\n\n<p>Some tricky examples and the links that it detects:</p>\n\n<ul>\n<li><code>http://example.com.</code> → <a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>.</li>\n<li><code>http://example.com,</code> → <a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>,</li>\n<li><code>(http://example.com)</code> → (<a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>)</li>\n<li><code>(... (see http://example.com))</code> → (... (see <a href=\"http://example.com\" rel=\"nofollow\">http://example.com</a>))</li>\n<li><code>https://en.wikipedia.org/wiki/Link_(The_Legend_of_Zelda)</code> →\n<a href=\"https://en.wikipedia.org/wiki/Link_(The_Legend_of_Zelda)\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Link_(The_Legend_of_Zelda)</a></li>\n<li><code>http://üñîçøðé.com/</code> → <a href=\"http://example.com\" rel=\"nofollow\">http://üñîçøðé.com/</a></li>\n</ul>\n" }, { "answer_id": 43037736, "author": "Beeing Jk", "author_id": 4665578, "author_profile": "https://Stackoverflow.com/users/4665578", "pm_score": -1, "selected": false, "text": "<p>Suggesting a more convenient way of doing it in 2017:</p>\n\n<pre><code>&lt;TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:autoLink=\"web\"\n android:linksClickable=\"true\"/&gt;\n</code></pre>\n\n<p>or <code>android:autoLink=\"all\"</code> for all kinds of links.</p>\n" }, { "answer_id": 71198955, "author": "Bayram Binbir", "author_id": 11102299, "author_profile": "https://Stackoverflow.com/users/11102299", "pm_score": 0, "selected": false, "text": "<pre><code> public static List&lt;String&gt; extractURL(String text) {\n List&lt;String&gt; list = new ArrayList&lt;&gt;();\n Pattern pattern = Pattern\n .compile(\n &quot;(http://|https://){1}[\\\\w\\\\.\\\\-/:\\\\#\\\\?\\\\=\\\\&amp;\\\\;\\\\%\\\\~\\\\+]+&quot;,\n Pattern.CASE_INSENSITIVE);\n Matcher matcher = pattern.matcher(text);\n while (matcher.find()) {\n list.add(matcher.group());\n }\n return list;\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37144/" ]
I have an input String say `Please go to http://stackoverflow.com`. The url part of the String is detected and an anchor `<a href=""></a>` is automatically added by many browser/IDE/applications. So it becomes `Please go to <a href='http://stackoverflow.com'>http://stackoverflow.com</a>`. I need to do the same using Java.
Use java.net.URL for that!! --------------------------- Hey, why don't use the core class in java for this "java.net.URL" and let it validate the URL. While the following code violates the golden principle "Use exception for exceptional conditions only" it does not make sense to me to try to reinvent the wheel for something that is veeery mature on the java platform. Here's the code: ``` import java.net.URL; import java.net.MalformedURLException; // Replaces URLs with html hrefs codes public class URLInString { public static void main(String[] args) { String s = args[0]; // separate input by spaces ( URLs don't have spaces ) String [] parts = s.split("\\s+"); // Attempt to convert each item into an URL. for( String item : parts ) try { URL url = new URL(item); // If possible then replace with anchor... System.out.print("<a href=\"" + url + "\">"+ url + "</a> " ); } catch (MalformedURLException e) { // If there was an URL that was not it!... System.out.print( item + " " ); } System.out.println(); } } ``` Using the following input: ``` "Please go to http://stackoverflow.com and then mailto:[email protected] to download a file from ftp://user:pass@someserver/someFile.txt" ``` Produces the following output: ``` Please go to <a href="http://stackoverflow.com">http://stackoverflow.com</a> and then <a href="mailto:[email protected]">mailto:[email protected]</a> to download a file from <a href="ftp://user:pass@someserver/someFile.txt">ftp://user:pass@someserver/someFile.txt</a> ``` Of course different protocols could be handled in different ways. You can get all the info with the getters of URL class, for instance ``` url.getProtocol(); ``` Or the rest of the attributes: spec, port, file, query, ref etc. etc <http://java.sun.com/javase/6/docs/api/java/net/URL.html> Handles all the protocols ( at least all of those the java platform is aware ) and as an extra benefit, if there is any URL that java currently does not recognize and eventually gets incorporated into the URL class ( by library updating ) you'll get it transparently!
285,649
<p>I have a web application that is using a data store that has it's own built in paging. The PagedResult class tells me the number of total pages. What I would like to do it (after binding my ASP.NET GridView) do this:</p> <pre><code>MyGridView.PageCount = thePageCount; </code></pre> <p>And then have the GridView magically build the pagination links as it normally would if it was doing things itself.</p> <p>The problem is that "PageCount" is a read-only property... so, how can I do this simply?</p>
[ { "answer_id": 285746, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>You could create your own class that extends GridView and override the PageCount getter method to return the value from your PagedResult class.</p>\n" }, { "answer_id": 285826, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 3, "selected": true, "text": "<p>To use the built-in paging the GridView interacts with the data source. The GridView has a settable property for PageSize.</p>\n\n<p>If you use an ObjectDataSource, you configure both a SelectMethod and a SelectCountMethod. You could either modify your PagedResult class to return record count instead of page count, or wrap the PagedResult call in a method to convert page count to record count (PageCount * PageSize). </p>\n\n<p>If your PagedResult class only exists to support the web app, you should consider modifiying it to behave more like a typical paged data source.</p>\n" }, { "answer_id": 285833, "author": "Robert C. Barth", "author_id": 9209, "author_profile": "https://Stackoverflow.com/users/9209", "pm_score": 0, "selected": false, "text": "<p>Use the ObjectDataSource control, bind it to your GridView, and set up a handler for the SelectCoutnMethod property. You may have to write small wrapper object for your class that retrieves the data that interfaces with the ObjectDataSource control.</p>\n\n<p>Some links to help you out:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/9a4kyhcx.aspx\" rel=\"nofollow noreferrer\">ObjectDataSource Web Server Control Overview</a><br/>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx\" rel=\"nofollow noreferrer\">ObjectDataSource Class</a></p>\n" }, { "answer_id": 1725048, "author": "Randi", "author_id": 209916, "author_profile": "https://Stackoverflow.com/users/209916", "pm_score": 0, "selected": false, "text": "<pre><code> Dim myCount as Integer = 1 'this sets the page count to 1 \n While (oreader.Read())\n myCount += 1 'increments once for everytime a item is counted\n 'this sets an array for the items to go into\n idFname = oreader.GetOrdinal(\"workCenter\")\n 'this retrieves the values at those indices\n fName = oreader.GetValue(idFname)\n BulletedList1.Items.Add(fName)\n End While\n\n Catch ex As Exception\n BulletedList1.Items.Add(\"No Workcenters Found\")\n Finally\n oreader.Close()\n oconn.Close()\n End Try\nEnd If\nMe.insertItemForm.PagerSettings.PageButtonCount = myCount 'sets the page count to number of items in gridview or formview etc.\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11917/" ]
I have a web application that is using a data store that has it's own built in paging. The PagedResult class tells me the number of total pages. What I would like to do it (after binding my ASP.NET GridView) do this: ``` MyGridView.PageCount = thePageCount; ``` And then have the GridView magically build the pagination links as it normally would if it was doing things itself. The problem is that "PageCount" is a read-only property... so, how can I do this simply?
To use the built-in paging the GridView interacts with the data source. The GridView has a settable property for PageSize. If you use an ObjectDataSource, you configure both a SelectMethod and a SelectCountMethod. You could either modify your PagedResult class to return record count instead of page count, or wrap the PagedResult call in a method to convert page count to record count (PageCount \* PageSize). If your PagedResult class only exists to support the web app, you should consider modifiying it to behave more like a typical paged data source.
285,658
<p>Is there a way in FreeBSD to (being root) run a command as unprivileged user, like nobody? Kind of like reverse of sudo. Oh and considering that 'nobody' has /usr/sbin/nologin as shell - so <b>su</b> is not an option.</p>
[ { "answer_id": 285693, "author": "DrStalker", "author_id": 17007, "author_profile": "https://Stackoverflow.com/users/17007", "pm_score": 6, "selected": true, "text": "<p>sudo will allow you to run a command as another user.</p>\n\n<pre><code>sudo -u nobody &lt;command&gt;\n</code></pre>\n\n<p>will run as nobody, even if their login shell is not available.</p>\n" }, { "answer_id": 3234272, "author": "Brad Ackerman", "author_id": 113222, "author_profile": "https://Stackoverflow.com/users/113222", "pm_score": 6, "selected": false, "text": "<p>You can <code>su</code> to an account with the <code>nologin</code> shell if you use the <code>-m</code> option.</p>\n\n<p>Example:</p>\n\n<pre><code>su -m cthulhu -c '/usr/bin/scorpion-stare'\n</code></pre>\n\n<p>will run the SCORPION STARE command-line utility as the user <code>cthulhu</code>.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37141/" ]
Is there a way in FreeBSD to (being root) run a command as unprivileged user, like nobody? Kind of like reverse of sudo. Oh and considering that 'nobody' has /usr/sbin/nologin as shell - so **su** is not an option.
sudo will allow you to run a command as another user. ``` sudo -u nobody <command> ``` will run as nobody, even if their login shell is not available.
285,660
<p>In Vim I can <code>:set wrapscan</code> so that when I do an incremental search, the cursor jumps to the first match whether the first match is above or below the cursor.</p> <p>In Emacs, if I start a search via <code>C-s</code>, the search fails saying <em>Failing I-search</em> if the first match is above the cursor. If I hit <code>C-s</code> again it then wraps the search, saying <em>Wrapped I-search</em>. How do I wrap and jump the cursor by default as in Vim, without having to <code>C-s</code> a second time?</p>
[ { "answer_id": 287067, "author": "link0ff", "author_id": 23952, "author_profile": "https://Stackoverflow.com/users/23952", "pm_score": 5, "selected": true, "text": "<p>The easiest way to do this is to use the following defadvice:</p>\n\n<pre><code>(defadvice isearch-repeat (after isearch-no-fail activate)\n (unless isearch-success\n (ad-disable-advice 'isearch-repeat 'after 'isearch-no-fail)\n (ad-activate 'isearch-repeat)\n (isearch-repeat (if isearch-forward 'forward))\n (ad-enable-advice 'isearch-repeat 'after 'isearch-no-fail)\n (ad-activate 'isearch-repeat)))\n</code></pre>\n\n<p>When Isearch fails, it immediately tries again with wrapping. Note that it is important to temporarily disable this defadvice to prevent an infinite loop when there are no matches.</p>\n" }, { "answer_id": 36707038, "author": "Chris Martin", "author_id": 402884, "author_profile": "https://Stackoverflow.com/users/402884", "pm_score": 3, "selected": false, "text": "<p>Jurta's answer got most of the way there. This is the wanted behavior:</p>\n\n<pre><code>;; Prevents issue where you have to press backspace twice when\n;; trying to remove the first character that fails a search\n(define-key isearch-mode-map [remap isearch-delete-char] 'isearch-del-char)\n\n(defadvice isearch-search (after isearch-no-fail activate)\n (unless isearch-success\n (ad-disable-advice 'isearch-search 'after 'isearch-no-fail)\n (ad-activate 'isearch-search)\n (isearch-repeat (if isearch-forward 'forward))\n (ad-enable-advice 'isearch-search 'after 'isearch-no-fail)\n (ad-activate 'isearch-search)))\n</code></pre>\n" }, { "answer_id": 72900696, "author": "cabo", "author_id": 1163318, "author_profile": "https://Stackoverflow.com/users/1163318", "pm_score": 1, "selected": false, "text": "<p>Set <code>isearch-wrap-pause</code> to <code>no</code>.</p>\n<p><a href=\"https://www.gnu.org/software/emacs/manual/html_node/emacs/Repeat-Isearch.html\" rel=\"nofollow noreferrer\">https://www.gnu.org/software/emacs/manual/html_node/emacs/Repeat-Isearch.html</a></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23070/" ]
In Vim I can `:set wrapscan` so that when I do an incremental search, the cursor jumps to the first match whether the first match is above or below the cursor. In Emacs, if I start a search via `C-s`, the search fails saying *Failing I-search* if the first match is above the cursor. If I hit `C-s` again it then wraps the search, saying *Wrapped I-search*. How do I wrap and jump the cursor by default as in Vim, without having to `C-s` a second time?
The easiest way to do this is to use the following defadvice: ``` (defadvice isearch-repeat (after isearch-no-fail activate) (unless isearch-success (ad-disable-advice 'isearch-repeat 'after 'isearch-no-fail) (ad-activate 'isearch-repeat) (isearch-repeat (if isearch-forward 'forward)) (ad-enable-advice 'isearch-repeat 'after 'isearch-no-fail) (ad-activate 'isearch-repeat))) ``` When Isearch fails, it immediately tries again with wrapping. Note that it is important to temporarily disable this defadvice to prevent an infinite loop when there are no matches.
285,662
<pre><code>some_var = foo() another_var = bar() </code></pre> <p>or</p> <pre><code>some_var = foo() another_var = bar() </code></pre> <p>Including changing the whitespace as lines are added or removed to keep them lined up. Does this really look good? Is it worth the mucking up of the diff?</p>
[ { "answer_id": 285672, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 3, "selected": true, "text": "<p>From my time as VCS admin, darn few stylistic issues are worth mucking up the diff. We had a developer change names with his sex change procedure, and her new first name didn't have the same initial. She then changed her former initials to her new ones whenever she worked on a program, and that caused me a lot of annoyance.</p>\n" }, { "answer_id": 285678, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 1, "selected": false, "text": "<p>No, unless there is some vertical relationship between the variables, such as:</p>\n\n<pre><code>some_var[ 1] = \"foo\";\nsome_var[100] = \"bar\";\n</code></pre>\n\n<p>But the cases are very rare that I do this, especially when I only have a few variables. This is a bit more common in SQL, where I might have the parameter name, type, and default value (three parts) in one line, but even there I try avoid it--it isn't worth the hassle.</p>\n\n<pre><code>@some_var varchar(25) = NULL\n@another_var varchar(1000) = ''\n@one_more int = 0\n</code></pre>\n" }, { "answer_id": 285681, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>I don't think it's a good style because it makes it too hard to make changes (you have to do all the work of lining them up again), and for me it is perfectly readable without the extra whitespace.</p>\n\n<p>What's especially annoying about this is that when you change the left part of a line that is longer than all the other lines, you need to line up all the other lines all over again.</p>\n\n<p>Example:</p>\n\n<pre><code>some_var = foo()\nanother_var = bar()\n</code></pre>\n\n<p>Now I want to add a var called <code>another_another_var</code>:</p>\n\n<pre><code>some_var = foo()\nanother_var = bar()\nanother_another_var = baz()\n</code></pre>\n\n<p>Now I have to line them up again:</p>\n\n<pre><code>some_var = foo()\nanother_var = bar()\nanother_another_var = baz()\n</code></pre>\n\n<p>Very annoying.</p>\n" }, { "answer_id": 285688, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 1, "selected": false, "text": "<p>No.</p>\n\n<p>While some find this style ascetically pleasing, modern IDEs with syntax highlighting make aligning variables in this manner a waste of time, including the time it takes to reformat them when refactoring or modifying code.</p>\n\n<p>In addition I'm a firm believer in declaring variables as close to the scope where they are needed. Rarely does that result in a block of variable declarations that would even need to be aligned.</p>\n" }, { "answer_id": 285695, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>With Perl, you can just set your preferences and run perl-tidy over your code every now and then.</p>\n\n<p>It gives the nicety of the aligned = 's, in the right contexts, without the worry to need to think about how best to align them and remember to do it yourself. </p>\n\n<p>Also, whatever coding style you have used for your project, you should maintain it vehemently.</p>\n\n<p>The more consistent and strictly enforced the style, the easier it will be to discover oddities and programming errors amongst your code. </p>\n\n<p>Also, some enforcements on coding style <em>reduce</em> diff collision based problems in the long term by enforcing good line-breaking rules.</p>\n" }, { "answer_id": 285724, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 1, "selected": false, "text": "<p>Styles like that cause the eye to travel vertically; however, the code should be reading horizontally. A coding style should complement what the eye does instead of fighting with it.</p>\n" }, { "answer_id": 285749, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 1, "selected": false, "text": "<p>Also, in extreme cases it becomes hard to casually see which assignment goes where because of large gaps. It is something I see too often in header files.</p>\n\n<pre><code>...\nsome_important_number = 348273;\ninitial_message_prefix = \"foo\";\nanother_important_number = 348711;\nmax_bucket_sz = 456;\n...\n</code></pre>\n\n<p>With dozens of these in a block, it becomes hard to read.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19687/" ]
``` some_var = foo() another_var = bar() ``` or ``` some_var = foo() another_var = bar() ``` Including changing the whitespace as lines are added or removed to keep them lined up. Does this really look good? Is it worth the mucking up of the diff?
From my time as VCS admin, darn few stylistic issues are worth mucking up the diff. We had a developer change names with his sex change procedure, and her new first name didn't have the same initial. She then changed her former initials to her new ones whenever she worked on a program, and that caused me a lot of annoyance.
285,666
<p>I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value. </p> <p>Edit: This would be SQL Server. </p>
[ { "answer_id": 285699, "author": "Jason Anderson", "author_id": 1530166, "author_profile": "https://Stackoverflow.com/users/1530166", "pm_score": 1, "selected": false, "text": "<p>Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?</p>\n\n<p>Depending on your requirements, you might do something like this:</p>\n\n<p>1) run the query and put results in a temp table (or table variable)\n2) check to see if the temp table has results\n3) if not, return an empty row by performing a select statement similar to this (in SQL Server):</p>\n\n<pre><code>select '' as columnA, '' as columnB, '' as columnC from #tempTable\n</code></pre>\n\n<p>Where columnA, columnB and columnC are your actual column names.</p>\n" }, { "answer_id": 285701, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 7, "selected": true, "text": "<p>One approach for Oracle:</p>\n\n<pre><code>SELECT val\nFROM myTable\nUNION ALL\nSELECT 'DEFAULT'\nFROM dual\nWHERE NOT EXISTS (SELECT * FROM myTable)\n</code></pre>\n\n<p>Or alternatively in Oracle:</p>\n\n<pre><code>SELECT NVL(MIN(val), 'DEFAULT')\nFROM myTable\n</code></pre>\n\n<p>Or alternatively in SqlServer:</p>\n\n<pre><code>SELECT ISNULL(MIN(val), 'DEFAULT')\nFROM myTable\n</code></pre>\n\n<p>These use the fact that <code>MIN()</code> returns <code>NULL</code> when there are no rows.</p>\n" }, { "answer_id": 285722, "author": "John Baughman", "author_id": 26923, "author_profile": "https://Stackoverflow.com/users/26923", "pm_score": 2, "selected": false, "text": "<p>I figured it out, and it should also work for other systems too. It's a variation of WW's answer.</p>\n\n<pre><code>select rate \nfrom d_payment_index\nwhere fy = 2007\n and payment_year = 2008\n and program_id = 18\nunion\nselect 0 as rate \nfrom d_payment_index \nwhere not exists( select rate \n from d_payment_index\n where fy = 2007\n and payment_year = 2008\n and program_id = 18 )\n</code></pre>\n" }, { "answer_id": 285823, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 3, "selected": false, "text": "<p>This would be eliminate the select query from running twice and be better for performance:</p>\n\n<pre><code>Declare @rate int\n\nselect \n @rate = rate \nfrom \n d_payment_index\nwhere \n fy = 2007\n and payment_year = 2008\n and program_id = 18\n\nIF @@rowcount = 0\n Set @rate = 0\n\nSelect @rate 'rate'\n</code></pre>\n" }, { "answer_id": 285871, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>One table scan method using a left join from defaults to actuals:</p>\n\n<pre><code>CREATE TABLE [stackoverflow-285666] (k int, val varchar(255))\n\nINSERT INTO [stackoverflow-285666]\nVALUES (1, '1-1')\nINSERT INTO [stackoverflow-285666]\nVALUES (1, '1-2')\nINSERT INTO [stackoverflow-285666]\nVALUES (1, '1-3')\nINSERT INTO [stackoverflow-285666]\nVALUES (2, '2-1')\nINSERT INTO [stackoverflow-285666]\nVALUES (2, '2-2')\n\nDECLARE @k AS int\nSET @k = 0\n\nWHILE @k &lt; 3\n BEGIN\n SELECT @k AS k\n ,COALESCE(ActualValue, DefaultValue) AS [Value]\n FROM (\n SELECT 'DefaultValue' AS DefaultValue\n ) AS Defaults\n LEFT JOIN (\n SELECT val AS ActualValue\n FROM [stackoverflow-285666]\n WHERE k = @k\n ) AS [Values]\n ON 1 = 1\n\n SET @k = @k + 1\n END\n\nDROP TABLE [stackoverflow-285666]\n</code></pre>\n\n<p>Gives output:</p>\n\n<pre><code>k Value\n----------- ------------\n0 DefaultValue\n\nk Value\n----------- ------------\n1 1-1\n1 1-2\n1 1-3\n\nk Value\n----------- ------------\n2 2-1\n2 2-2\n</code></pre>\n" }, { "answer_id": 288185, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 4, "selected": false, "text": "<p>If your base query is expected to return only one row, then you could use this trick:</p>\n\n<pre><code>select NVL( MIN(rate), 0 ) AS rate \nfrom d_payment_index\nwhere fy = 2007\n and payment_year = 2008\n and program_id = 18\n</code></pre>\n\n<p>(Oracle code, not sure if NVL is the right function for SQL Server.)</p>\n" }, { "answer_id": 534178, "author": "beach", "author_id": 53892, "author_profile": "https://Stackoverflow.com/users/53892", "pm_score": 3, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate\nFROM \n (SELECT 0) DEF (Rate) -- This is your default rate\nLEFT JOIN (\n select rate \n from d_payment_index\n --WHERE 1=2 -- Uncomment this line to simulate a missing value\n\n --...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes...\n --where fy = 2007\n -- and payment_year = 2008\n -- and program_id = 18\n) ACTUAL (Rate) ON 1=1\n</code></pre>\n\n<p><strong>Results</strong></p>\n\n<p><em>Valid Rate Exists</em></p>\n\n<pre><code>Rate Rate UseThisRate\n----------- ----------- -----------\n0 1 1\n</code></pre>\n\n<p><em>Default Rate Used</em></p>\n\n<pre><code>Rate Rate UseThisRate\n----------- ----------- -----------\n0 NULL 0\n</code></pre>\n\n<p><strong>Test DDL</strong></p>\n\n<pre><code>CREATE TABLE d_payment_index (rate int NOT NULL)\nINSERT INTO d_payment_index VALUES (1)\n</code></pre>\n" }, { "answer_id": 37454970, "author": "Y-Mi Wong", "author_id": 6384946, "author_profile": "https://Stackoverflow.com/users/6384946", "pm_score": 0, "selected": false, "text": "<p>Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.</p>\n\n<pre><code> ---=== The table &amp; its data\n CREATE TABLE dbo.Rates (\n PkId int,\n name varchar(10),\n rate decimal(10,2)\n )\n INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)\n INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)\n</code></pre>\n\n<p>Here's the solution:</p>\n\n<pre><code>---=== The solution \nCREATE PROCEDURE dbo.GetRate \n @PkId int\nAS\nBEGIN\n DECLARE @tempTable TABLE (\n PkId int, \n name varchar(10), \n rate decimal(10,2)\n )\n\n --- [1] Insert default values into @tempTable. PkId=0 is dummy value \n INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)\n\n --- [2] Update the single row in @tempTable with the actual value.\n --- This only happens if a match is found\n UPDATE @tempTable\n SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate\n FROM @tempTable t INNER JOIN dbo.Rates x\n ON t.PkId = 0\n WHERE x.PkId = @PkId\n\n SELECT * FROM @tempTable\nEND\n</code></pre>\n\n<p>Test the code:</p>\n\n<pre><code>EXEC dbo.GetRate @PkId=1 --- returns values for PkId=1\nEXEC dbo.GetRate @PkId=12314 --- returns default values\n</code></pre>\n" }, { "answer_id": 51160249, "author": "Eike", "author_id": 388845, "author_profile": "https://Stackoverflow.com/users/388845", "pm_score": 3, "selected": false, "text": "<p>This snippet uses Common Table Expressions to reduce redundant code and to improve readability. It is a variation of John Baughman's answer. </p>\n\n<p>The syntax is for SQL Server. </p>\n\n<pre><code>WITH products AS (\n SELECT prod_name,\n price\n FROM Products_Table\n WHERE prod_name LIKE '%foo%'\n ),\n defaults AS (\n SELECT '-' AS prod_name,\n 0 AS price\n )\n\nSELECT * FROM products\nUNION ALL\nSELECT * FROM defaults\n WHERE NOT EXISTS ( SELECT * FROM products );\n</code></pre>\n" }, { "answer_id": 62469335, "author": "Deepak Vaishnav", "author_id": 6854712, "author_profile": "https://Stackoverflow.com/users/6854712", "pm_score": 2, "selected": false, "text": "<p>*SQL solution</p>\n<p>Suppose you have a review table which has primary key &quot;id&quot;.</p>\n<pre><code>SELECT * FROM review WHERE id = 1555\nUNION ALL\nSELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1\n</code></pre>\n<p>if table doesn't have review with 1555 id then this query will provide a review of id 1.</p>\n" }, { "answer_id": 63174302, "author": "Serge Bugera", "author_id": 3289809, "author_profile": "https://Stackoverflow.com/users/3289809", "pm_score": 2, "selected": false, "text": "<p>Assuming there is a table <code>config</code> with unique index on <code>config_code</code> column:</p>\n<pre><code>CONFIG_CODE PARAM1 PARAM2\n--------------- -------- --------\ndefault_config def 000\nconfig1 abc 123\nconfig2 def 456\n</code></pre>\n<p>This query returns line for <code>config1</code> values, because it exists in the table:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\n FROM (SELECT *\n FROM config\n WHERE config_code = 'config1'\n OR config_code = 'default_config'\n ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)\n WHERE rownum = 1;\n</code></pre>\n<pre><code>CONFIG_CODE PARAM1 PARAM2\n--------------- -------- --------\nconfig1 abc 123\n</code></pre>\n<p>This one returns default record as <code>config3</code> doesn't exist in the table:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\n FROM (SELECT *\n FROM config\n WHERE config_code = 'config3'\n OR config_code = 'default_config'\n ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)\n WHERE rownum = 1;\n</code></pre>\n<pre><code>CONFIG_CODE PARAM1 PARAM2\n--------------- -------- --------\ndefault_config def 000\n</code></pre>\n<p>In comparison with other solutions this one queries table <code>config</code> only once.</p>\n" }, { "answer_id": 68619854, "author": "Shanmukhi Goli", "author_id": 9479518, "author_profile": "https://Stackoverflow.com/users/9479518", "pm_score": 0, "selected": false, "text": "<p>This is what I used for getting a default value if no values are present.</p>\n<PRE><CODE>\n SELECT IF (\n (SELECT COUNT(*) FROM tbs.replication_status) > 0, \n (SELECT rs.last_replication_end_date FROM tbs.replication_status AS rs \n WHERE rs.last_replication_start_date IS NOT NULL \n AND rs.last_replication_end_date IS NOT NULL \n AND rs.table = '%s' ORDER BY id DESC LIMIT 1), \n (SELECT CAST(UNIX_TIMESTAMP (CURRENT_TIMESTAMP(6)) AS UNSIGNED))\n ) AS ts;\n</PRE></CODE>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26923/" ]
I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value. Edit: This would be SQL Server.
One approach for Oracle: ``` SELECT val FROM myTable UNION ALL SELECT 'DEFAULT' FROM dual WHERE NOT EXISTS (SELECT * FROM myTable) ``` Or alternatively in Oracle: ``` SELECT NVL(MIN(val), 'DEFAULT') FROM myTable ``` Or alternatively in SqlServer: ``` SELECT ISNULL(MIN(val), 'DEFAULT') FROM myTable ``` These use the fact that `MIN()` returns `NULL` when there are no rows.
285,674
<p>In firefox, the error messages display as should. Just to the right of the element being validated. In IE. No matter what I do with the sizing of the labels/elements/errors, the error is always posted below the element, causing every other element to be pushed down.</p> <pre><code>&lt;p&gt; &lt;label for="handle"&gt;&lt;strong&gt;User Name&lt;/strong&gt;&lt;/label&gt; &lt;INPUT NAME="handle" id="handle" VALUE="#attributes.getUser.handle#"&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="password"&gt;&lt;strong&gt;Password&lt;/strong&gt;&lt;/label&gt; &lt;INPUT TYPE="TEXT" id="password" NAME="password" MAXLENGTH=50 VALUE="#attributes.getUser.password#"&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="confirmPassword"&gt;&lt;strong&gt;Confirm Password&lt;/strong&gt;&lt;/label&gt; &lt;INPUT TYPE="TEXT" id="confirmPassword" NAME="confirmPassword" MAXLENGTH=50 VALUE="#attributes.getUser.password#"&gt; &lt;/p&gt; </code></pre> <p>If anyone else has had this issue, i'd be very grateful for any help.</p>
[ { "answer_id": 285699, "author": "Jason Anderson", "author_id": 1530166, "author_profile": "https://Stackoverflow.com/users/1530166", "pm_score": 1, "selected": false, "text": "<p>Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?</p>\n\n<p>Depending on your requirements, you might do something like this:</p>\n\n<p>1) run the query and put results in a temp table (or table variable)\n2) check to see if the temp table has results\n3) if not, return an empty row by performing a select statement similar to this (in SQL Server):</p>\n\n<pre><code>select '' as columnA, '' as columnB, '' as columnC from #tempTable\n</code></pre>\n\n<p>Where columnA, columnB and columnC are your actual column names.</p>\n" }, { "answer_id": 285701, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 7, "selected": true, "text": "<p>One approach for Oracle:</p>\n\n<pre><code>SELECT val\nFROM myTable\nUNION ALL\nSELECT 'DEFAULT'\nFROM dual\nWHERE NOT EXISTS (SELECT * FROM myTable)\n</code></pre>\n\n<p>Or alternatively in Oracle:</p>\n\n<pre><code>SELECT NVL(MIN(val), 'DEFAULT')\nFROM myTable\n</code></pre>\n\n<p>Or alternatively in SqlServer:</p>\n\n<pre><code>SELECT ISNULL(MIN(val), 'DEFAULT')\nFROM myTable\n</code></pre>\n\n<p>These use the fact that <code>MIN()</code> returns <code>NULL</code> when there are no rows.</p>\n" }, { "answer_id": 285722, "author": "John Baughman", "author_id": 26923, "author_profile": "https://Stackoverflow.com/users/26923", "pm_score": 2, "selected": false, "text": "<p>I figured it out, and it should also work for other systems too. It's a variation of WW's answer.</p>\n\n<pre><code>select rate \nfrom d_payment_index\nwhere fy = 2007\n and payment_year = 2008\n and program_id = 18\nunion\nselect 0 as rate \nfrom d_payment_index \nwhere not exists( select rate \n from d_payment_index\n where fy = 2007\n and payment_year = 2008\n and program_id = 18 )\n</code></pre>\n" }, { "answer_id": 285823, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 3, "selected": false, "text": "<p>This would be eliminate the select query from running twice and be better for performance:</p>\n\n<pre><code>Declare @rate int\n\nselect \n @rate = rate \nfrom \n d_payment_index\nwhere \n fy = 2007\n and payment_year = 2008\n and program_id = 18\n\nIF @@rowcount = 0\n Set @rate = 0\n\nSelect @rate 'rate'\n</code></pre>\n" }, { "answer_id": 285871, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>One table scan method using a left join from defaults to actuals:</p>\n\n<pre><code>CREATE TABLE [stackoverflow-285666] (k int, val varchar(255))\n\nINSERT INTO [stackoverflow-285666]\nVALUES (1, '1-1')\nINSERT INTO [stackoverflow-285666]\nVALUES (1, '1-2')\nINSERT INTO [stackoverflow-285666]\nVALUES (1, '1-3')\nINSERT INTO [stackoverflow-285666]\nVALUES (2, '2-1')\nINSERT INTO [stackoverflow-285666]\nVALUES (2, '2-2')\n\nDECLARE @k AS int\nSET @k = 0\n\nWHILE @k &lt; 3\n BEGIN\n SELECT @k AS k\n ,COALESCE(ActualValue, DefaultValue) AS [Value]\n FROM (\n SELECT 'DefaultValue' AS DefaultValue\n ) AS Defaults\n LEFT JOIN (\n SELECT val AS ActualValue\n FROM [stackoverflow-285666]\n WHERE k = @k\n ) AS [Values]\n ON 1 = 1\n\n SET @k = @k + 1\n END\n\nDROP TABLE [stackoverflow-285666]\n</code></pre>\n\n<p>Gives output:</p>\n\n<pre><code>k Value\n----------- ------------\n0 DefaultValue\n\nk Value\n----------- ------------\n1 1-1\n1 1-2\n1 1-3\n\nk Value\n----------- ------------\n2 2-1\n2 2-2\n</code></pre>\n" }, { "answer_id": 288185, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 4, "selected": false, "text": "<p>If your base query is expected to return only one row, then you could use this trick:</p>\n\n<pre><code>select NVL( MIN(rate), 0 ) AS rate \nfrom d_payment_index\nwhere fy = 2007\n and payment_year = 2008\n and program_id = 18\n</code></pre>\n\n<p>(Oracle code, not sure if NVL is the right function for SQL Server.)</p>\n" }, { "answer_id": 534178, "author": "beach", "author_id": 53892, "author_profile": "https://Stackoverflow.com/users/53892", "pm_score": 3, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate\nFROM \n (SELECT 0) DEF (Rate) -- This is your default rate\nLEFT JOIN (\n select rate \n from d_payment_index\n --WHERE 1=2 -- Uncomment this line to simulate a missing value\n\n --...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes...\n --where fy = 2007\n -- and payment_year = 2008\n -- and program_id = 18\n) ACTUAL (Rate) ON 1=1\n</code></pre>\n\n<p><strong>Results</strong></p>\n\n<p><em>Valid Rate Exists</em></p>\n\n<pre><code>Rate Rate UseThisRate\n----------- ----------- -----------\n0 1 1\n</code></pre>\n\n<p><em>Default Rate Used</em></p>\n\n<pre><code>Rate Rate UseThisRate\n----------- ----------- -----------\n0 NULL 0\n</code></pre>\n\n<p><strong>Test DDL</strong></p>\n\n<pre><code>CREATE TABLE d_payment_index (rate int NOT NULL)\nINSERT INTO d_payment_index VALUES (1)\n</code></pre>\n" }, { "answer_id": 37454970, "author": "Y-Mi Wong", "author_id": 6384946, "author_profile": "https://Stackoverflow.com/users/6384946", "pm_score": 0, "selected": false, "text": "<p>Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.</p>\n\n<pre><code> ---=== The table &amp; its data\n CREATE TABLE dbo.Rates (\n PkId int,\n name varchar(10),\n rate decimal(10,2)\n )\n INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)\n INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)\n</code></pre>\n\n<p>Here's the solution:</p>\n\n<pre><code>---=== The solution \nCREATE PROCEDURE dbo.GetRate \n @PkId int\nAS\nBEGIN\n DECLARE @tempTable TABLE (\n PkId int, \n name varchar(10), \n rate decimal(10,2)\n )\n\n --- [1] Insert default values into @tempTable. PkId=0 is dummy value \n INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)\n\n --- [2] Update the single row in @tempTable with the actual value.\n --- This only happens if a match is found\n UPDATE @tempTable\n SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate\n FROM @tempTable t INNER JOIN dbo.Rates x\n ON t.PkId = 0\n WHERE x.PkId = @PkId\n\n SELECT * FROM @tempTable\nEND\n</code></pre>\n\n<p>Test the code:</p>\n\n<pre><code>EXEC dbo.GetRate @PkId=1 --- returns values for PkId=1\nEXEC dbo.GetRate @PkId=12314 --- returns default values\n</code></pre>\n" }, { "answer_id": 51160249, "author": "Eike", "author_id": 388845, "author_profile": "https://Stackoverflow.com/users/388845", "pm_score": 3, "selected": false, "text": "<p>This snippet uses Common Table Expressions to reduce redundant code and to improve readability. It is a variation of John Baughman's answer. </p>\n\n<p>The syntax is for SQL Server. </p>\n\n<pre><code>WITH products AS (\n SELECT prod_name,\n price\n FROM Products_Table\n WHERE prod_name LIKE '%foo%'\n ),\n defaults AS (\n SELECT '-' AS prod_name,\n 0 AS price\n )\n\nSELECT * FROM products\nUNION ALL\nSELECT * FROM defaults\n WHERE NOT EXISTS ( SELECT * FROM products );\n</code></pre>\n" }, { "answer_id": 62469335, "author": "Deepak Vaishnav", "author_id": 6854712, "author_profile": "https://Stackoverflow.com/users/6854712", "pm_score": 2, "selected": false, "text": "<p>*SQL solution</p>\n<p>Suppose you have a review table which has primary key &quot;id&quot;.</p>\n<pre><code>SELECT * FROM review WHERE id = 1555\nUNION ALL\nSELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1\n</code></pre>\n<p>if table doesn't have review with 1555 id then this query will provide a review of id 1.</p>\n" }, { "answer_id": 63174302, "author": "Serge Bugera", "author_id": 3289809, "author_profile": "https://Stackoverflow.com/users/3289809", "pm_score": 2, "selected": false, "text": "<p>Assuming there is a table <code>config</code> with unique index on <code>config_code</code> column:</p>\n<pre><code>CONFIG_CODE PARAM1 PARAM2\n--------------- -------- --------\ndefault_config def 000\nconfig1 abc 123\nconfig2 def 456\n</code></pre>\n<p>This query returns line for <code>config1</code> values, because it exists in the table:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\n FROM (SELECT *\n FROM config\n WHERE config_code = 'config1'\n OR config_code = 'default_config'\n ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)\n WHERE rownum = 1;\n</code></pre>\n<pre><code>CONFIG_CODE PARAM1 PARAM2\n--------------- -------- --------\nconfig1 abc 123\n</code></pre>\n<p>This one returns default record as <code>config3</code> doesn't exist in the table:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\n FROM (SELECT *\n FROM config\n WHERE config_code = 'config3'\n OR config_code = 'default_config'\n ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)\n WHERE rownum = 1;\n</code></pre>\n<pre><code>CONFIG_CODE PARAM1 PARAM2\n--------------- -------- --------\ndefault_config def 000\n</code></pre>\n<p>In comparison with other solutions this one queries table <code>config</code> only once.</p>\n" }, { "answer_id": 68619854, "author": "Shanmukhi Goli", "author_id": 9479518, "author_profile": "https://Stackoverflow.com/users/9479518", "pm_score": 0, "selected": false, "text": "<p>This is what I used for getting a default value if no values are present.</p>\n<PRE><CODE>\n SELECT IF (\n (SELECT COUNT(*) FROM tbs.replication_status) > 0, \n (SELECT rs.last_replication_end_date FROM tbs.replication_status AS rs \n WHERE rs.last_replication_start_date IS NOT NULL \n AND rs.last_replication_end_date IS NOT NULL \n AND rs.table = '%s' ORDER BY id DESC LIMIT 1), \n (SELECT CAST(UNIX_TIMESTAMP (CURRENT_TIMESTAMP(6)) AS UNSIGNED))\n ) AS ts;\n</PRE></CODE>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
In firefox, the error messages display as should. Just to the right of the element being validated. In IE. No matter what I do with the sizing of the labels/elements/errors, the error is always posted below the element, causing every other element to be pushed down. ``` <p> <label for="handle"><strong>User Name</strong></label> <INPUT NAME="handle" id="handle" VALUE="#attributes.getUser.handle#"> </p> <p> <label for="password"><strong>Password</strong></label> <INPUT TYPE="TEXT" id="password" NAME="password" MAXLENGTH=50 VALUE="#attributes.getUser.password#"> </p> <p> <label for="confirmPassword"><strong>Confirm Password</strong></label> <INPUT TYPE="TEXT" id="confirmPassword" NAME="confirmPassword" MAXLENGTH=50 VALUE="#attributes.getUser.password#"> </p> ``` If anyone else has had this issue, i'd be very grateful for any help.
One approach for Oracle: ``` SELECT val FROM myTable UNION ALL SELECT 'DEFAULT' FROM dual WHERE NOT EXISTS (SELECT * FROM myTable) ``` Or alternatively in Oracle: ``` SELECT NVL(MIN(val), 'DEFAULT') FROM myTable ``` Or alternatively in SqlServer: ``` SELECT ISNULL(MIN(val), 'DEFAULT') FROM myTable ``` These use the fact that `MIN()` returns `NULL` when there are no rows.
285,700
<p>i'm looking for a way to programatically convert word documents in docx format to doc format without using ole automation. i already have a windows service that does this but it means installing office on a server and it is a little unreliable and not supported. i am aware of the aspose.words product, and i will try it out, but has anyone any recommendations for how to do this as simply, reliably, and cheaply as possible?</p>
[ { "answer_id": 320854, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 4, "selected": false, "text": "<p>One option without using OLE automation would be to wrap the converter dlls coming with compatibility pack in order to convert from docx to doc without automating Office.</p>\n\n<p>This requires only that the Compatibility Pack of Office is installed on the machine.</p>\n\n<p>The Office converter dlls convert from the document format that they support to RTF and/or from RTF to their document format using the interface ForeignToRtf/RtfToForeign. You can chain converters as you wish to convert from one format to another, e.g. to do a conversion DOCX -> RTF -> DOC.</p>\n\n<p>You can get the <a href=\"http://support.microsoft.com/?scid=kb%3Ben-us%3B111716&amp;x=16&amp;y=7\" rel=\"nofollow noreferrer\">SDK from Microsoft</a>, which includes several samples on how to use existing converters. If I remember correctly there is already a command line wrapper sample included. Everything is C/C++ stuff.</p>\n\n<p>You can find out which of the converter dlls are responsible for OpenXML conversion by looking at the following registry key: </p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Shared Tools\\Text Converters\\Import\\Word12 \n</code></pre>\n\n<p>Let me know if you need further details on this.</p>\n" }, { "answer_id": 688274, "author": "JasonPlutext", "author_id": 1031689, "author_profile": "https://Stackoverflow.com/users/1031689", "pm_score": 0, "selected": false, "text": "<p>You could use <a href=\"http://dev.plutext.org\" rel=\"nofollow noreferrer\">docx4j</a> (or indeed, just poi) to read the docx, and poi to write it out as a .doc</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3142/" ]
i'm looking for a way to programatically convert word documents in docx format to doc format without using ole automation. i already have a windows service that does this but it means installing office on a server and it is a little unreliable and not supported. i am aware of the aspose.words product, and i will try it out, but has anyone any recommendations for how to do this as simply, reliably, and cheaply as possible?
One option without using OLE automation would be to wrap the converter dlls coming with compatibility pack in order to convert from docx to doc without automating Office. This requires only that the Compatibility Pack of Office is installed on the machine. The Office converter dlls convert from the document format that they support to RTF and/or from RTF to their document format using the interface ForeignToRtf/RtfToForeign. You can chain converters as you wish to convert from one format to another, e.g. to do a conversion DOCX -> RTF -> DOC. You can get the [SDK from Microsoft](http://support.microsoft.com/?scid=kb%3Ben-us%3B111716&x=16&y=7), which includes several samples on how to use existing converters. If I remember correctly there is already a command line wrapper sample included. Everything is C/C++ stuff. You can find out which of the converter dlls are responsible for OpenXML conversion by looking at the following registry key: ``` HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Text Converters\Import\Word12 ``` Let me know if you need further details on this.
285,710
<p>Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.</p> <p>The target language is C++.</p> <p>I am interested in what you have personally used.</p>
[ { "answer_id": 285732, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 2, "selected": false, "text": "<p>In essence, if a profiling tool is not available, you emulate what a profiler would have done. You insert counters into functions you think are interesting and count how many times, and potentially with what size/sort of arguments they're called.</p>\n\n<p>If you have access to any timers on your platform, you may start/stop these at the beginning/end of said functions to get execution time information as well, if this is unclear from the code. This is going to give you the biggest bang for your buck in complex code, as there will usually be too many functions to instrument them all. Instead, you can obtain the time spent in certain sections of code by dedicating a timer to each one.</p>\n\n<p>These two techniques in tandem can form an iterative approach, where you find the broad section of code that consumes the majority of your cycles using timers, then instrument individual functions at a finer granularity to hone in on the problem.</p>\n" }, { "answer_id": 285765, "author": "Celestial M Weasel", "author_id": 4125, "author_profile": "https://Stackoverflow.com/users/4125", "pm_score": 2, "selected": false, "text": "<p>If it is something sufficiently long in duration (e.g. a minute or more), I run the software in a debugger then break a few times and see where the debugger breaks, this gives a very rough idea of what the software is up to (e.g. if you break 10 times and they are all in the same place, this tells you something interesting!). \nVery rough and ready but doesn't require any tools, instrumentation etc. </p>\n" }, { "answer_id": 285926, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 4, "selected": true, "text": "<p>I've found the following quite useful:</p>\n\n<pre><code>#ifdef PROFILING\n# define PROFILE_CALL(x) do{ \\\n const DWORD t1 = timeGetTime(); \\\n x; \\\n const DWORD t2 = timeGetTime(); \\\n std::cout &lt;&lt; \"Call to '\" &lt;&lt; #x &lt;&lt; \"' took \" &lt;&lt; (t2 - t1) &lt;&lt; \" ms.\\n\"; \\\n }while(false)\n#else\n# define PROFILE_CALL(x) x\n#endif\n</code></pre>\n\n<p>Which can be used in the calling function as such:</p>\n\n<pre><code>PROFILE_CALL(renderSlow(world));\nint r = 0;\nPROFILE_CALL(r = readPacketSize());\n</code></pre>\n" }, { "answer_id": 285940, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>No joke: In addition to dumping timings to std::cout and other text/data oriented approaches I also use the Beep() function. There's something about hearing the gap of silence between two \"Beep\" checkpoints that makes a different kind of impression.</p>\n\n<p>It's like the difference between looking at a written sheet music, and actually HEARING the music. It's like the difference between reading rgb(255,0,0) and seeing fire-engine red.</p>\n\n<p>So, right now, I have a client/server app and with Beeps of different frequencies, marking where the client sends the message, where the server starts its reply, finishes its reply, where reply first enters the client, etc, I can very naturally get a feel for where the time is spent.</p>\n" }, { "answer_id": 285946, "author": "PiNoYBoY82", "author_id": 13646, "author_profile": "https://Stackoverflow.com/users/13646", "pm_score": 1, "selected": false, "text": "<p>I would use the 80/20 rule and put timers around hotspots or interesting call paths. You should have a general idea where the bottlenecks will be (or at least a majority of the execution paths) and use the appropriate platform dependent high resolution timer (QueryPerformanceCounters, gettimeofday, etc.).</p>\n\n<p>I usually don't bother with anything at startup or shutdown (unless needed) and will have well defined \"choke points\", usually message passing or some sort of algorithmic calculation. I've generally found that message sinks/srcs (sinks moreso), queues, mutexes, and just plain mess-ups (algorithms, loops) usually account for most of the latency in an execution path.</p>\n" }, { "answer_id": 286216, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what platforms you had in mind, but on embedded microcontrollers, it's sometimes helpful to twiddle a spare digital output line and measure the pulse width using an oscilloscope, counter/timer, or logic analyzer.</p>\n" }, { "answer_id": 289164, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "<p>Are you using Visual Studio?</p>\n\n<p>The you can use the /Gh and /GH switches. <a href=\"http://www.codeproject.com/KB/tips/stackdumper.aspx\" rel=\"nofollow noreferrer\">Here's an example involving stack inspection</a></p>\n\n<p>These flags allow you, by a file-by-file basis, to register undecorated functions that are called every time a method is entered and/or left in runtime.</p>\n\n<p>You can then register all times of profiling information, not just timing information. Stack-dumps, calling address, return address, etc. Which is important, because you may want to know that 'function X used Y time under function Z' and not just the total time spent in function X.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler. The target language is C++. I am interested in what you have personally used.
I've found the following quite useful: ``` #ifdef PROFILING # define PROFILE_CALL(x) do{ \ const DWORD t1 = timeGetTime(); \ x; \ const DWORD t2 = timeGetTime(); \ std::cout << "Call to '" << #x << "' took " << (t2 - t1) << " ms.\n"; \ }while(false) #else # define PROFILE_CALL(x) x #endif ``` Which can be used in the calling function as such: ``` PROFILE_CALL(renderSlow(world)); int r = 0; PROFILE_CALL(r = readPacketSize()); ```
285,712
<p>I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.</p> <p>The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?</p> <p>Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?</p> <p>I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?</p>
[ { "answer_id": 285745, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 6, "selected": false, "text": "<p>Here is some example code to help you get started:</p>\n\n<pre><code>package com.acme;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class FileArrayProvider {\n\n public String[] readLines(String filename) throws IOException {\n FileReader fileReader = new FileReader(filename);\n BufferedReader bufferedReader = new BufferedReader(fileReader);\n List&lt;String&gt; lines = new ArrayList&lt;String&gt;();\n String line = null;\n while ((line = bufferedReader.readLine()) != null) {\n lines.add(line);\n }\n bufferedReader.close();\n return lines.toArray(new String[lines.size()]);\n }\n}\n</code></pre>\n\n<p>And an example unit test:</p>\n\n<pre><code>package com.acme;\n\nimport java.io.IOException;\n\nimport org.junit.Test;\n\npublic class FileArrayProviderTest {\n\n @Test\n public void testFileArrayProvider() throws IOException {\n FileArrayProvider fap = new FileArrayProvider();\n String[] lines = fap\n .readLines(\"src/main/java/com/acme/FileArrayProvider.java\");\n for (String line : lines) {\n System.out.println(line);\n }\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 285771, "author": "Ryan Thames", "author_id": 1459442, "author_profile": "https://Stackoverflow.com/users/1459442", "pm_score": 0, "selected": false, "text": "<p>You should be able to use forward slashes in Java to refer to file locations.</p>\n\n<p>The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the <a href=\"http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html\" rel=\"nofollow noreferrer\">Java APIs</a>.</p>\n\n<p>Toolkit's use of BufferedReader is probably what you need.</p>\n" }, { "answer_id": 6064722, "author": "Tony Nassar", "author_id": 761762, "author_profile": "https://Stackoverflow.com/users/761762", "pm_score": 2, "selected": false, "text": "<p>Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: <a href=\"http://commons.apache.org/io/api-release/index.html\" rel=\"nofollow\">http://commons.apache.org/io/api-release/index.html</a>. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities. </p>\n" }, { "answer_id": 12592835, "author": "Hélio Santos", "author_id": 1698797, "author_profile": "https://Stackoverflow.com/users/1698797", "pm_score": 5, "selected": false, "text": "<pre><code>import java.io.File;\n\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\nimport java.util.List;\n\n// ...\n\nPath filePath = new File(\"fileName\").toPath();\nCharset charset = Charset.defaultCharset(); \nList&lt;String&gt; stringList = Files.readAllLines(filePath, charset);\nString[] stringArray = stringList.toArray(new String[]{});\n</code></pre>\n" }, { "answer_id": 69270638, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 0, "selected": false, "text": "<p>For completeness, another way to read all lines of a file<sup>1</sup> as <code>String[]</code> is to use the Java 8+ <code>BufferedReader.lines()</code> method. Like this:</p>\n<pre><code>BufferedReader br ...\nString[] lines = br.lines().toArray(String[]::new);\n</code></pre>\n<p>Note that since the <code>lines()</code> stream cannot tell the downstream methods how many lines there will be ahead of time, some temporary <code>String</code> arrays will need to be created. However, the implementation is designed to avoid unnecessary copying.</p>\n<hr />\n<p><sup>1 - You can use this approach with anything that you can wrap with a <code>BufferedReader</code>.</sup></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37161/" ]
I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers. The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary? Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i? I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?
Here is some example code to help you get started: ``` package com.acme; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileArrayProvider { public String[] readLines(String filename) throws IOException { FileReader fileReader = new FileReader(filename); BufferedReader bufferedReader = new BufferedReader(fileReader); List<String> lines = new ArrayList<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } bufferedReader.close(); return lines.toArray(new String[lines.size()]); } } ``` And an example unit test: ``` package com.acme; import java.io.IOException; import org.junit.Test; public class FileArrayProviderTest { @Test public void testFileArrayProvider() throws IOException { FileArrayProvider fap = new FileArrayProvider(); String[] lines = fap .readLines("src/main/java/com/acme/FileArrayProvider.java"); for (String line : lines) { System.out.println(line); } } } ``` Hope this helps.
285,715
<h2>Background</h2> <p>We are developing some in-house utilities using ASP.NET 2.0. One of which is extracting some information from databases and building an Excel workbook containing a number of spreadsheets with data based on queries into the database.</p> <h2>Problem</h2> <p>The proof-of-concept prototype (a simple ASP.NET page that queries a single item from the database and opens Excel to add data to a worksheet) is working well when run locally on the development machines, happily creating and displaying an Excel spreadsheet as requested. However, when run on our server, we get the following error upon trying to instantiate Excel .</p> <p>Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).</p> <h2>Solution?</h2> <p>We are using the PIA for Excel 2003 and we have Excel 2003 and the PIA installed on the server. Can anyone explain why this isn't working or give us some tips on how we might track the problem down?</p> <p>Thanks for any assistance you can provide.</p>
[ { "answer_id": 285745, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 6, "selected": false, "text": "<p>Here is some example code to help you get started:</p>\n\n<pre><code>package com.acme;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class FileArrayProvider {\n\n public String[] readLines(String filename) throws IOException {\n FileReader fileReader = new FileReader(filename);\n BufferedReader bufferedReader = new BufferedReader(fileReader);\n List&lt;String&gt; lines = new ArrayList&lt;String&gt;();\n String line = null;\n while ((line = bufferedReader.readLine()) != null) {\n lines.add(line);\n }\n bufferedReader.close();\n return lines.toArray(new String[lines.size()]);\n }\n}\n</code></pre>\n\n<p>And an example unit test:</p>\n\n<pre><code>package com.acme;\n\nimport java.io.IOException;\n\nimport org.junit.Test;\n\npublic class FileArrayProviderTest {\n\n @Test\n public void testFileArrayProvider() throws IOException {\n FileArrayProvider fap = new FileArrayProvider();\n String[] lines = fap\n .readLines(\"src/main/java/com/acme/FileArrayProvider.java\");\n for (String line : lines) {\n System.out.println(line);\n }\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 285771, "author": "Ryan Thames", "author_id": 1459442, "author_profile": "https://Stackoverflow.com/users/1459442", "pm_score": 0, "selected": false, "text": "<p>You should be able to use forward slashes in Java to refer to file locations.</p>\n\n<p>The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the <a href=\"http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html\" rel=\"nofollow noreferrer\">Java APIs</a>.</p>\n\n<p>Toolkit's use of BufferedReader is probably what you need.</p>\n" }, { "answer_id": 6064722, "author": "Tony Nassar", "author_id": 761762, "author_profile": "https://Stackoverflow.com/users/761762", "pm_score": 2, "selected": false, "text": "<p>Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: <a href=\"http://commons.apache.org/io/api-release/index.html\" rel=\"nofollow\">http://commons.apache.org/io/api-release/index.html</a>. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities. </p>\n" }, { "answer_id": 12592835, "author": "Hélio Santos", "author_id": 1698797, "author_profile": "https://Stackoverflow.com/users/1698797", "pm_score": 5, "selected": false, "text": "<pre><code>import java.io.File;\n\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\nimport java.util.List;\n\n// ...\n\nPath filePath = new File(\"fileName\").toPath();\nCharset charset = Charset.defaultCharset(); \nList&lt;String&gt; stringList = Files.readAllLines(filePath, charset);\nString[] stringArray = stringList.toArray(new String[]{});\n</code></pre>\n" }, { "answer_id": 69270638, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 0, "selected": false, "text": "<p>For completeness, another way to read all lines of a file<sup>1</sup> as <code>String[]</code> is to use the Java 8+ <code>BufferedReader.lines()</code> method. Like this:</p>\n<pre><code>BufferedReader br ...\nString[] lines = br.lines().toArray(String[]::new);\n</code></pre>\n<p>Note that since the <code>lines()</code> stream cannot tell the downstream methods how many lines there will be ahead of time, some temporary <code>String</code> arrays will need to be created. However, the implementation is designed to avoid unnecessary copying.</p>\n<hr />\n<p><sup>1 - You can use this approach with anything that you can wrap with a <code>BufferedReader</code>.</sup></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23234/" ]
Background ---------- We are developing some in-house utilities using ASP.NET 2.0. One of which is extracting some information from databases and building an Excel workbook containing a number of spreadsheets with data based on queries into the database. Problem ------- The proof-of-concept prototype (a simple ASP.NET page that queries a single item from the database and opens Excel to add data to a worksheet) is working well when run locally on the development machines, happily creating and displaying an Excel spreadsheet as requested. However, when run on our server, we get the following error upon trying to instantiate Excel . Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel.\_Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E\_NOINTERFACE)). Solution? --------- We are using the PIA for Excel 2003 and we have Excel 2003 and the PIA installed on the server. Can anyone explain why this isn't working or give us some tips on how we might track the problem down? Thanks for any assistance you can provide.
Here is some example code to help you get started: ``` package com.acme; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileArrayProvider { public String[] readLines(String filename) throws IOException { FileReader fileReader = new FileReader(filename); BufferedReader bufferedReader = new BufferedReader(fileReader); List<String> lines = new ArrayList<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } bufferedReader.close(); return lines.toArray(new String[lines.size()]); } } ``` And an example unit test: ``` package com.acme; import java.io.IOException; import org.junit.Test; public class FileArrayProviderTest { @Test public void testFileArrayProvider() throws IOException { FileArrayProvider fap = new FileArrayProvider(); String[] lines = fap .readLines("src/main/java/com/acme/FileArrayProvider.java"); for (String line : lines) { System.out.println(line); } } } ``` Hope this helps.
285,716
<p>I have written a program that gets input from a usb second keyboard (actually a barcode scanner). The problem is that if another window is active the data is input there rather than in my program. Could someone give me advice on what I'm doing wrong?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main(int argc, char * argv[]){ FILE * fp_in; char * data; fp_in = fopen("/dev/input/by-id/usb-04d9_1400-event-kbd","r"); if(fp_in == NULL){ fprintf(stderr,"Failed to open input by id\n"); } fp_in = fopen("/dev/input/by-path/pci-0000:00:1d.1-usb-0:2:1.0-event-kbd","r"); if(fp_in == NULL){ fprintf(stderr,"Failed to open input by path\n"); return 1; } while(1){ fscanf(fp_in,data,"%s"); fprintf(stderr,"%s",data); } return 0; } </code></pre> <p>thanks <hr> If I may be so bold as to rephrase the question on Confuzzled's behalf:</p> <p>How can I write a program under Linux that attaches itself to an input device, in this case a barcode scanner, so that the input does not go to the program that has the keyboard focus?</p>
[ { "answer_id": 285876, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>I'll get started with a list of common problems surrounding your task, I don't have the answer, but I can at least provide some light on <strong>why</strong> you are having problems. </p>\n\n<ol>\n<li><p>Keyboard devices, for obvious security reasons, have access control restrictions on them. For obvious reasons, if arbitrary applications could sniff/hook the keyboard without the right permission, it could have fatal consequences, AKA: Keyboard Logger. </p></li>\n<li><p>Sometimes, when one application ( in your case X ) has gained control of an input device, it eats up all the bytes being sent to it. So if you managed to get around the permissions problem, you still have a problem in that some other software is consuming the datastream before you. </p></li>\n</ol>\n" }, { "answer_id": 2049058, "author": "rgngl", "author_id": 190381, "author_profile": "https://Stackoverflow.com/users/190381", "pm_score": 2, "selected": false, "text": "<p>It's been a while since this question has been asked :) Anyway, I think what you should do is to use the linux input device subsystem API.</p>\n\n<p><a href=\"http://www.linuxjournal.com/article/6429\" rel=\"nofollow noreferrer\">http://www.linuxjournal.com/article/6429</a> here's a good introduction.</p>\n" }, { "answer_id": 7867363, "author": "Devesh", "author_id": 771650, "author_profile": "https://Stackoverflow.com/users/771650", "pm_score": 1, "selected": false, "text": "<p>If I have understood your question correctly, there may be a few problems corresponding to what you want to do.</p>\n\n<p>1) In order to read from these files in /dev folder you need to have root permissions.</p>\n\n<p>2) (I am not too sure about this) but I believe these are special files and hence you cannot read them as you would a normal file.</p>\n\n<p>Assuming you took care of these two problems , it will still not solve your problem because X events are handled by the X sever, which you can think of as simultaneously reading the same file. It is the one which captures these events and handles them accordingly by calling the relevant event handlers, if any, for a particular event in the topmost active window. All the windows talk to the X server which tells if something has been typed. So even if you have a terminal window open with a program running, first the X server must tell the window about the key presses which will then be passed to the program running in the terminal.</p>\n\n<p>Another code which does similar work can be found <a href=\"http://www.thelinuxdaily.com/2010/05/grab-raw-keyboard-input-from-event-device-node-devinputevent/\" rel=\"nofollow\" title=\"here\">here</a>.</p>\n" }, { "answer_id": 21819422, "author": "admiralswan", "author_id": 3317403, "author_profile": "https://Stackoverflow.com/users/3317403", "pm_score": 2, "selected": false, "text": "<p>I was trying to do the same thing, What I did was to \"float\" that device using xinput. In my case, <code>xinput list</code> shows (among other things)</p>\n\n<p><code>HID Keyboard Device HID Keyboard Device id=13 [slave keyboard (3)]</code></p>\n\n<p>This is the device the corresponds to the barcode scanner. You can then simply type</p>\n\n<p><code>xinput float 13</code></p>\n\n<p>into a terminal. Keystrokes from the scanner will no longer get entered into the focused window, but they can still be read from the device file. However, you will need to decode the events you read from the file to get the information you want(the barcode). See <a href=\"https://stackoverflow.com/questions/5060710/format-of-dev-input-event\">format of /dev/input/event*?</a> for some information on how to do this.</p>\n\n<p>Finally, to read the device file without root privileges, just add a udev rule for the scanner. For me, it's something like this:</p>\n\n<p><code>SUBSYSTEM==\"input\", ATTRS{idVendor}==\"1d57\", ATTRS{idProduct}==\"001c\" MODE=\"0644\"</code></p>\n\n<p>The idVendor and idProduct for your scanner can be found by examining the output of <code>dmesg</code> after plugging the scanner in.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37163/" ]
I have written a program that gets input from a usb second keyboard (actually a barcode scanner). The problem is that if another window is active the data is input there rather than in my program. Could someone give me advice on what I'm doing wrong? ``` #include <stdio.h> #include <string.h> int main(int argc, char * argv[]){ FILE * fp_in; char * data; fp_in = fopen("/dev/input/by-id/usb-04d9_1400-event-kbd","r"); if(fp_in == NULL){ fprintf(stderr,"Failed to open input by id\n"); } fp_in = fopen("/dev/input/by-path/pci-0000:00:1d.1-usb-0:2:1.0-event-kbd","r"); if(fp_in == NULL){ fprintf(stderr,"Failed to open input by path\n"); return 1; } while(1){ fscanf(fp_in,data,"%s"); fprintf(stderr,"%s",data); } return 0; } ``` thanks --- If I may be so bold as to rephrase the question on Confuzzled's behalf: How can I write a program under Linux that attaches itself to an input device, in this case a barcode scanner, so that the input does not go to the program that has the keyboard focus?
It's been a while since this question has been asked :) Anyway, I think what you should do is to use the linux input device subsystem API. <http://www.linuxjournal.com/article/6429> here's a good introduction.
285,717
<p>What's the best way to run scheduled tasks in a Rails environment? Script/runner? Rake? I would like to run the task every few minutes.</p>
[ { "answer_id": 285870, "author": "Freakent", "author_id": 32747, "author_profile": "https://Stackoverflow.com/users/32747", "pm_score": 4, "selected": false, "text": "<p>Assuming your tasks don't take too long to complete, just create a new controller with an action for each task. Implement the logic of the task as controller code, Then set up a cronjob at the OS level that uses wget to invoke the URL of this controller and action at the appropriate time intervals. The advantages of this method are you:</p>\n\n<ol>\n<li>Have full access to all your Rails objects just as in a normal controller.</li>\n<li>Can develop and test just as you do normal actions. </li>\n<li>Can also invoke your tasks adhoc from a simple web page.</li>\n<li>Don't consume any more memory by firing up additional ruby/rails processes.</li>\n</ol>\n" }, { "answer_id": 285898, "author": "salt.racer", "author_id": 757, "author_profile": "https://Stackoverflow.com/users/757", "pm_score": 3, "selected": false, "text": "<p>I use backgroundrb.</p>\n\n<p><a href=\"http://backgroundrb.rubyforge.org/\" rel=\"noreferrer\">http://backgroundrb.rubyforge.org/</a></p>\n\n<p>I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.</p>\n" }, { "answer_id": 286489, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 1, "selected": false, "text": "<p>I'm not really sure, I guess it depends on the task: how often to run, how much complicated and how much direct communication with the rails project is needed etc. I guess if there was just <em>\"One Best Way\"</em> to do something, there wouldn't be so many different ways to do it.</p>\n\n<p>At my last job in a Rails project, we needed to make a batch invitation mailer (survey invitations, not spamming) which should send the planned mails whenever the server had time. I think we were going to use <a href=\"http://en.wikipedia.org/wiki/Daemontools\" rel=\"nofollow noreferrer\">daemon tools</a> to run the rake tasks I had created. </p>\n\n<p>Unfortunately, our company had some money problems and was \"bought\" by the main rival so the project was never completed, so I don't know what we would eventually have used.</p>\n" }, { "answer_id": 287107, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 4, "selected": false, "text": "<p>script/runner and rake tasks are perfectly fine to run as cron jobs.</p>\n\n<p>Here's one very important thing you must remember when running cron jobs. They probably won't be called from the root directory of your app. This means all your requires for files (as opposed to libraries) should be done with the explicit path: e.g. File.dirname(__FILE__) + \"/other_file\". This also means you have to know how to explicitly call them from another directory :-)</p>\n\n<p>Check if your code supports being run from another directory with </p>\n\n<pre><code># from ~\n/path/to/ruby /path/to/app/script/runner -e development \"MyClass.class_method\"\n/path/to/ruby /path/to/rake -f /path/to/app/Rakefile rake:task RAILS_ENV=development\n</code></pre>\n\n<p>Also, cron jobs probably don't run as you, so don't depend on any shortcut you put in .bashrc. But that's just a standard cron tip ;-)</p>\n" }, { "answer_id": 290935, "author": "Luke Francl", "author_id": 17965, "author_profile": "https://Stackoverflow.com/users/17965", "pm_score": 3, "selected": false, "text": "<p>Both will work fine. I usually use script/runner. </p>\n\n<p>Here's an example:</p>\n\n<p><code>0 6 * * * cd /var/www/apps/your_app/current; ./script/runner --environment production 'EmailSubscription.send_email_subscriptions' &gt;&gt; /var/www/apps/your_app/shared/log/send_email_subscriptions.log 2&gt;&amp;1</code></p>\n\n<p>You can also write a pure-Ruby script to do this if you load the right config files to connect to your database.</p>\n\n<p>One thing to keep in mind if memory is precious is that script/runner (or a Rake task that depends on 'environment') will load the entire Rails environment. If you only need to insert some records into the database, this will use memory you don't really have to. If you write your own script, you can avoid this. I haven't actually needed to do this yet, but I am considering it.</p>\n" }, { "answer_id": 396688, "author": "Thibaut Barrère", "author_id": 20302, "author_profile": "https://Stackoverflow.com/users/20302", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"http://dougmcinnes.com/2008/07/14/craken/\" rel=\"noreferrer\">Craken</a> (rake centric cron jobs)</p>\n" }, { "answer_id": 480255, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here's how I have setup my cron tasks. I have one to make daily backups of SQL database (using rake) and another to expire cache once a month. Any output is logged in a file log/cron_log. My crontab looks like this:</p>\n\n<pre><code>crontab -l # command to print all cron tasks\ncrontab -e # command to edit/add cron tasks\n\n# Contents of crontab\n0 1 * * * cd /home/lenart/izziv. whiskas.si/current; /bin/sh cron_tasks &gt;&gt; log/cron_log 2&gt;&amp;1\n0 0 1 * * cd /home/lenart/izziv.whiskas.si/current; /usr/bin/env /usr/local/bin/ruby script/runner -e production lib/monthly_cron.rb &gt;&gt; log/cron_log 2&gt;&amp;1\n</code></pre>\n\n<p>The first cron task makes daily db backups. The contents of cron_tasks are the following:</p>\n\n<pre><code>/usr/local/bin/rake db:backup RAILS_ENV=production; date; echo \"END OF OUTPUT ----\";\n</code></pre>\n\n<p>The second task was setup later and uses script/runner to expire cache once a month (lib/monthly_cron.rb):</p>\n\n<pre><code>#!/usr/local/bin/ruby\n# Expire challenge cache\nChallenge.force_expire_cache\nputs \"Expired cache for Challenges (Challenge.force_expire_cache) #{Time.now}\"\n</code></pre>\n\n<p>I guess I could backup database some other way but so far it works for me :)</p>\n\n<p>The <strong>paths</strong> to rake and ruby can vary on different servers. You can see where they are by using:</p>\n\n<pre><code>whereis ruby # -&gt; ruby: /usr/local/bin/ruby\nwhereis rake # -&gt; rake: /usr/local/bin/rake\n</code></pre>\n" }, { "answer_id": 995643, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 8, "selected": true, "text": "<p>I'm using the rake approach (as supported by <a href=\"https://devcenter.heroku.com/articles/scheduler\" rel=\"noreferrer\">heroku</a>)</p>\n\n<p>With a file called lib/tasks/cron.rake ..</p>\n\n<pre><code>task :cron =&gt; :environment do\n puts \"Pulling new requests...\"\n EdiListener.process_new_messages\n puts \"done.\"\nend\n</code></pre>\n\n<p>To execute from the command line, this is just \"rake cron\". This command can then be put on the operating system cron/task scheduler as desired.</p>\n\n<p><strong>Update</strong> this is quite an old question and answer! Some new info:</p>\n\n<ul>\n<li>the heroku cron service I referenced has since been replaced by <a href=\"https://devcenter.heroku.com/articles/scheduler\" rel=\"noreferrer\">Heroku Scheduler</a></li>\n<li>for frequent tasks (esp. where you want to avoid the Rails environment startup cost) my preferred approach is to use system cron to call a script that will either (a) poke a secure/private webhook API to invoke the required task in the background or (b) directly enqueue a task on your queuing system of choice </li>\n</ul>\n" }, { "answer_id": 6377867, "author": "Jim Garvin", "author_id": 66145, "author_profile": "https://Stackoverflow.com/users/66145", "pm_score": 8, "selected": false, "text": "<p>I've used the extremely popular <a href=\"https://github.com/javan/whenever\" rel=\"noreferrer\">Whenever</a> on projects that rely heavily on scheduled tasks, and it's great. It gives you a nice DSL to define your scheduled tasks instead of having to deal with crontab format. From the README:</p>\n\n<blockquote>\n <p>Whenever is a Ruby gem that provides a\n clear syntax for writing and deploying\n cron jobs.</p>\n</blockquote>\n\n<p>Example from the README:</p>\n\n<pre><code>every 3.hours do\n runner \"MyModel.some_process\" \n rake \"my:rake:task\" \n command \"/usr/bin/my_great_command\"\nend\n\nevery 1.day, :at =&gt; '4:30 am' do \n runner \"MyModel.task_to_run_at_four_thirty_in_the_morning\"\nend\n</code></pre>\n" }, { "answer_id": 14883296, "author": "Adrià Cidre", "author_id": 1067821, "author_profile": "https://Stackoverflow.com/users/1067821", "pm_score": 2, "selected": false, "text": "<p>Probably the best way to do it is using rake to write the tasks you need and the just execute it via command line.</p>\n\n<p>You can see a very helpful <a href=\"http://railscasts.com/episodes/66-custom-rake-tasks\" rel=\"nofollow\">video at railscasts</a></p>\n\n<p>Also take a look at this other resources:</p>\n\n<ul>\n<li><a href=\"http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial\" rel=\"nofollow\">Rails Rake Tutorial</a></li>\n</ul>\n" }, { "answer_id": 15013117, "author": "Abdo", "author_id": 226255, "author_profile": "https://Stackoverflow.com/users/226255", "pm_score": 4, "selected": false, "text": "<p>The problem with whenever (and cron) is that it reloads the rails environment every time it's executed, which is a real problem when your tasks are frequent or have a lot of initialization work to do. I have had issues in production because of this and must warn you.</p>\n\n<p>Rufus scheduler does it for me ( <a href=\"https://github.com/jmettraux/rufus-scheduler\">https://github.com/jmettraux/rufus-scheduler</a> )</p>\n\n<p>When I have long jobs to run, I use it with delayed_job ( <a href=\"https://github.com/collectiveidea/delayed_job\">https://github.com/collectiveidea/delayed_job</a> )</p>\n\n<p>I hope this helps!</p>\n" }, { "answer_id": 17036643, "author": "Tyler Morgan", "author_id": 2047664, "author_profile": "https://Stackoverflow.com/users/2047664", "pm_score": 4, "selected": false, "text": "<p>I'm a big fan of <a href=\"https://github.com/resque/resque\">resque</a>/<a href=\"https://github.com/bvandenbos/resque-scheduler\">resque scheduler</a>. You can not only run repeating cron-like tasks but also tasks at specific times. The downside is, it requires a Redis server.</p>\n" }, { "answer_id": 18159262, "author": "Pankhuri", "author_id": 2669893, "author_profile": "https://Stackoverflow.com/users/2669893", "pm_score": 5, "selected": false, "text": "<p>In our project we first used whenever gem, but confronted some problems.</p>\n\n<p>We then switched to <strong><a href=\"https://github.com/jmettraux/rufus-scheduler\" rel=\"noreferrer\">RUFUS SCHEDULER</a></strong> gem, which turned out to be very easy and reliable for scheduling tasks in Rails.</p>\n\n<p>We have used it for sending weekly &amp; daily mails, and even for running some periodic rake tasks or any method.</p>\n\n<p>The code used in this is like:</p>\n\n<pre><code> require 'rufus-scheduler'\n\n scheduler = Rufus::Scheduler.new\n\n scheduler.in '10d' do\n # do something in 10 days\n end\n\n scheduler.at '2030/12/12 23:30:00' do\n # do something at a given point in time\n end\n\n scheduler.every '3h' do\n # do something every 3 hours\n end\n\n scheduler.cron '5 0 * * *' do\n # do something every day, five minutes after midnight\n # (see \"man 5 crontab\" in your terminal)\n end\n</code></pre>\n\n<p>To learn more: <a href=\"https://github.com/jmettraux/rufus-scheduler\" rel=\"noreferrer\">https://github.com/jmettraux/rufus-scheduler</a></p>\n" }, { "answer_id": 22795854, "author": "Caner", "author_id": 2424542, "author_profile": "https://Stackoverflow.com/users/2424542", "pm_score": 2, "selected": false, "text": "<p>Once I had to make the same decision and I'm really happy with that decision today. Use <strong>resque scheduler</strong> because not only a seperate redis will take out the load from your db, you will also have access to many plugins like resque-web which provides a great user interface. As your system develops you will have more and more tasks to schedule so you will be able to control them from a single place. </p>\n" }, { "answer_id": 24544045, "author": "nnattawat", "author_id": 3749163, "author_profile": "https://Stackoverflow.com/users/3749163", "pm_score": 2, "selected": false, "text": "<p>I used <a href=\"https://github.com/tomykaira/clockwork\" rel=\"nofollow\">clockwork</a> gem and it works pretty well for me. There is also <code>clockworkd</code> gem that allows a script to run as a daemon.</p>\n" }, { "answer_id": 25512430, "author": "Israel Barba", "author_id": 1904975, "author_profile": "https://Stackoverflow.com/users/1904975", "pm_score": 2, "selected": false, "text": "<p>you can use <code>resque</code> and <code>resque-schedular</code> gem for creating cron, this is very easy to do.</p>\n\n<p><a href=\"https://github.com/resque/resque\" rel=\"nofollow noreferrer\">https://github.com/resque/resque</a></p>\n\n<p><a href=\"https://github.com/resque/resque-scheduler\" rel=\"nofollow noreferrer\">https://github.com/resque/resque-scheduler</a></p>\n" }, { "answer_id": 26555653, "author": "jaysqrd", "author_id": 1137353, "author_profile": "https://Stackoverflow.com/users/1137353", "pm_score": 3, "selected": false, "text": "<p>Using something Sidekiq or Resque is a far more robust solution. They both support retrying jobs, exclusivity with a REDIS lock, monitoring, and scheduling.</p>\n\n<p>Keep in mind that Resque is a dead project (not actively maintained), so Sidekiq is a way better alternative. It also is more performant: Sidekiq runs several workers on a single, multithread process while Resque runs each worker in a separate process.</p>\n" }, { "answer_id": 33107035, "author": "Alexander Paramonov", "author_id": 598386, "author_profile": "https://Stackoverflow.com/users/598386", "pm_score": 4, "selected": false, "text": "<p>That is interesting no one mentioned the <a href=\"https://github.com/tobiassvn/sidetiq\">Sidetiq</a>.\nIt is nice addition if you already using Sidekiq.</p>\n\n<blockquote>\n <p>Sidetiq provides a simple API for defining recurring workers for\n Sidekiq.</p>\n</blockquote>\n\n<p>Job will look like this:</p>\n\n<pre><code>class MyWorker\n include Sidekiq::Worker\n include Sidetiq::Schedulable\n\n recurrence { hourly.minute_of_hour(15, 45) }\n\n def perform\n # do stuff ...\n end\nend\n</code></pre>\n" }, { "answer_id": 33540967, "author": "Vipul Lawande", "author_id": 4486025, "author_profile": "https://Stackoverflow.com/users/4486025", "pm_score": 2, "selected": false, "text": "<p>I have recently created some cron jobs for the projects I have been working on.</p>\n\n<p>I found that the gem <strong>Clockwork</strong> very useful.</p>\n\n<pre><code>require 'clockwork'\n\nmodule Clockwork\n every(10.seconds, 'frequent.job')\nend\n</code></pre>\n\n<p>You can even schedule your background job using this gem.\nFor documentation and further help refer <a href=\"https://github.com/Rykian/clockwork\" rel=\"nofollow noreferrer\">https://github.com/Rykian/clockwork</a></p>\n" }, { "answer_id": 46341534, "author": "Ami", "author_id": 5681693, "author_profile": "https://Stackoverflow.com/users/5681693", "pm_score": 1, "selected": false, "text": "<p>I Use script to run cron, that is the best way to run a cron.\nHere is some example for cron,</p>\n\n<p>Open CronTab —> sudo crontab -e</p>\n\n<p>And Paste Bellow lines:</p>\n\n<p>00 00 * * * wget <a href=\"https://your_host/some_API_end_point\" rel=\"nofollow noreferrer\">https://your_host/some_API_end_point</a></p>\n\n<p>Here is some cron format, will help you</p>\n\n<pre><code>::CRON FORMAT::\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/ut6wO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ut6wO.png\" alt=\"cron format table\"></a></p>\n\n<pre><code>Examples Of crontab Entries\n15 6 2 1 * /home/melissa/backup.sh\nRun the shell script /home/melissa/backup.sh on January 2 at 6:15 A.M.\n\n15 06 02 Jan * /home/melissa/backup.sh\nSame as the above entry. Zeroes can be added at the beginning of a number for legibility, without changing their value.\n\n0 9-18 * * * /home/carl/hourly-archive.sh\nRun /home/carl/hourly-archive.sh every hour, on the hour, from 9 A.M. through 6 P.M., every day.\n\n0 9,18 * * Mon /home/wendy/script.sh\nRun /home/wendy/script.sh every Monday, at 9 A.M. and 6 P.M.\n\n30 22 * * Mon,Tue,Wed,Thu,Fri /usr/local/bin/backup\nRun /usr/local/bin/backup at 10:30 P.M., every weekday. \n</code></pre>\n\n<p>Hope this will help you :)</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13195/" ]
What's the best way to run scheduled tasks in a Rails environment? Script/runner? Rake? I would like to run the task every few minutes.
I'm using the rake approach (as supported by [heroku](https://devcenter.heroku.com/articles/scheduler)) With a file called lib/tasks/cron.rake .. ``` task :cron => :environment do puts "Pulling new requests..." EdiListener.process_new_messages puts "done." end ``` To execute from the command line, this is just "rake cron". This command can then be put on the operating system cron/task scheduler as desired. **Update** this is quite an old question and answer! Some new info: * the heroku cron service I referenced has since been replaced by [Heroku Scheduler](https://devcenter.heroku.com/articles/scheduler) * for frequent tasks (esp. where you want to avoid the Rails environment startup cost) my preferred approach is to use system cron to call a script that will either (a) poke a secure/private webhook API to invoke the required task in the background or (b) directly enqueue a task on your queuing system of choice
285,718
<p>I'm using MediaTemple's (dv) hosting service. How do I determine what mail-server is installed? Should I use the shell? If so, what command would be used?</p>
[ { "answer_id": 285739, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "<p>Go to the shell and type this command:</p>\n\n<pre><code>telnet &lt;hostname&gt; 25\n</code></pre>\n\n<p>This will come back with a line like so:</p>\n\n<pre><code>220 example.com ESMTP Exim 4.69 Thu, 13 Nov 2008 10:06:01 +1100\n</code></pre>\n\n<p>as you can see, this sever is running EXIM.</p>\n\n<p>Then type QUIT to exit back to the shell.</p>\n\n<hr>\n\n<p><strong>UPDATE:</strong> Some hosts use a different address for their email server, if you are on Linux, you can type the following command to get a list of mail servers for a given domain:</p>\n\n<pre><code>dig -t MX example.com\n</code></pre>\n" }, { "answer_id": 285918, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 3, "selected": false, "text": "<p>Try</p>\n\n<pre><code>$ nmap -p 25 -A -T polite &lt;hostname&gt;\n</code></pre>\n\n<p>from a Linux box with nmap installed.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using MediaTemple's (dv) hosting service. How do I determine what mail-server is installed? Should I use the shell? If so, what command would be used?
Go to the shell and type this command: ``` telnet <hostname> 25 ``` This will come back with a line like so: ``` 220 example.com ESMTP Exim 4.69 Thu, 13 Nov 2008 10:06:01 +1100 ``` as you can see, this sever is running EXIM. Then type QUIT to exit back to the shell. --- **UPDATE:** Some hosts use a different address for their email server, if you are on Linux, you can type the following command to get a list of mail servers for a given domain: ``` dig -t MX example.com ```
285,723
<p>I'm a .NET developer, and worked with VB6 before that. I've become very familiar with those environments, and working in the context of garbage collected languages. However, I now wish to bolster my skillset with native C++ and find myself a bit overwhelmed. Ironically, it's not what I'd imagine is the usual stumbling blocks for beginners as I feel that I've got the grasp of pointers and memory management fairly well. The thing that's a bit confusing for me is more along the lines of:</p> <ul> <li>Referencing/using other libraries</li> <li>Exposing <em>my</em> libraries for others to use</li> <li>String handling</li> <li>Data type conversions</li> <li>Good project structure</li> <li>Data structures to use (ie. in C#, I use <code>List&lt;T&gt;</code> a lot, what do I use in C++ that works simiarly?)</li> </ul> <p>It almost feels like depending on the IDE you use, the guidelines are different, so I was really looking for something that's perhaps a bit more universal. Or at worst, focused on using Microsoft's compiler/IDE. Also, just to be clear, I'm not looking for anything about general programming practices (Design Patterns, Code Complete, etc.) as I feel I'm pretty well versed in those topics.</p>
[ { "answer_id": 285753, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 2, "selected": false, "text": "<p>You've got some toolkits available. For example, there are STL (Standard Template Library) and Boost/TR1 (extensions to STL) that are considered industry standards (well, STL is, at least). These provide lists, maps, sets, shared pointers, strings, streams, and all sorts of other handy tools. Best of all, they're widely supported across compilers.</p>\n\n<p>As for data conversions, you can either do casts or create explicit converter functions.</p>\n\n<p>Libraries - You can either create static libraries (get absorbed into the final executable) or DLLs (you're familiar with these, already). MSDN is an awesome resource for DLLs. Static libraries depend on your build environment.</p>\n\n<p>In general, this is my advice:\n - Get to know your IDE of choice very well\n - Purchase \"C++ The Complete Reference\" by Herbert Schildt, which I consider to be an excellent tome on all things C++ (includes STL)</p>\n\n<p>Considering your background, you should be well set once you do both of those.</p>\n" }, { "answer_id": 285755, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 1, "selected": false, "text": "<p>Referencing and using other libraries, if you're including the source, is accomplished simply by #including the header files for the library into whatever .cpp file you need them in (and then compile the source for the library along with your project). Most of the time, however, you'll probably be using a .lib (static library) or .dll (dynamic library). Most (all?) DLLs come with a .lib file, so the procedure for both types is the same: include the appropriate header files where you need them, then add the associated .lib file during the linking step (in visual studio, I think you can just add the file to the project).</p>\n\n<p>It's been a long time since I've created my own libraries for others to use, so I'll let someone else answer that part. Or I'll come back and edit this answer tomorrow, since I'm going to have to create a .lib for work tomorrow :)</p>\n\n<p>String stuff is usually accomplished with std::string. Under special circumstances, you may also use the old C-style sprintf() function, but that's generally discouraged.</p>\n\n<p>As far as the data structures you're looking for, check out the STL (Standard Template Library). It includes List, Vector, Map, String, etc that should be familiar to you.\nI'm not sure what you mean by type conversions... I assume you know about casting, so you must mean something more complex than that, in which case it's probably specific to the types you're trying to convert. Maybe someone else can offer more info.</p>\n" }, { "answer_id": 285819, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 9, "selected": true, "text": "<p>I know you say you've got a good grasp of pointers and memory management, but I'd still like to explain an important trick.\nAs a general rule of thumb, <em>never</em> have new/delete in your user code.</p>\n\n<p>Every resource acquisition (whether it's a synchronization lock, a database connection or a chunk of memory or anything else that must be acquired and released) should be wrapped in an object so that the constructor performs the acquisition, and the destructor releases the resource. The technique is known as <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"noreferrer\">RAII</a>, and is basically <em>the</em> way to avoid memory leaks. Get used to it.\nThe C++ standard library obviously uses this extensively, so you can get a feel for how it works there. Jumping a bit in your questions, the equivalent of <code>List&lt;T&gt;</code> is <code>std::vector&lt;T&gt;</code>, and it uses RAII to manage its memory. You'd use it something like this:</p>\n\n<pre><code>void foo() {\n\n // declare a vector *without* using new. We want it allocated on the stack, not\n // the heap. The vector can allocate data on the heap if and when it feels like\n // it internally. We just don't need to see it in our user code\n std::vector&lt;int&gt; v;\n v.push_back(4);\n v.push_back(42); // Add a few numbers to it\n\n // And that is all. When we leave the scope of this function, the destructors \n // of all local variables, in this case our vector, are called - regardless of\n // *how* we leave the function. Even if an exception is thrown, v still goes \n // out of scope, so its destructor is called, and it cleans up nicely. That's \n // also why C++ doesn't have a finally clause for exception handling, but only \n // try/catch. Anything that would otherwise go in the finally clause can be put\n // in the destructor of a local object.\n} \n</code></pre>\n\n<p>If I had to pick one single principle that a C++ programmer must learn and embrace, it's the above. Let the scoping rules and the destructors work for you. They offer all the guarantees you need to write safe code.</p>\n\n<h2>String handling:</h2>\n\n<p><code>std::string</code> is your friend there. In C, you'd use arrays of char's (or char pointers), but those are nasty, because they don't behave as strings. In C++, you have a std::string class, which behaves as you'd expect. The only thing to keep in mind is that \"hello world\" is of type char[12] and NOT std::string. (for C compatibility), so sometimes you have to explicitly convert your string literal (something enclosed in quotes, like \"hello world\") to a std::string to get the behavior you want:\nYou can still write</p>\n\n<pre><code>std::string s = \"hello world\";\n</code></pre>\n\n<p>because C-style strings (such as literals, like \"hello world\") are implicitly convertible to std::string, but it doesn't always work:\n\"hello\" + \" world\" won't compile, because the + operator isn't defined for two pointers.\n\"hello worl\" + 'd' however, <em>will</em> compile, but it won't do anything sensible.\nInstead of appending a char to a string, it will take the integral value of the char (which gets promoted to an int), and add that to the value of the pointer.</p>\n\n<p>std::string(\"hello worl\") + \"d\" does as you'd expect however, because the left hand side is already a std::string, and the addition operator is overloaded for std::string to do as you'd expect, even when the right hand side is a char* or a single character.</p>\n\n<p>One final note on strings:\nstd::string uses char, which is a single-byte datatype. That is, it is not suitable for unicode text.\nC++ provides the wide character type wchar_t which is 2 or 4 bytes, depending on platform, and is typically used for unicode text (although in neither case does the C++ standard really specify the character set). And a string of wchar_t's is called std::wstring.</p>\n\n<h2>Libraries:</h2>\n\n<p>They don't exist, fundamentally.\nThe C++ language has no notion of libraries, and this takes some getting used to.\nIt allows you to #include another file (typically a header file with the extension .h or .hpp), but this is simply a verbatim copy/paste. The preprocessor simply combines the two files resulting in what is called a translation unit. Multiple source files will typically include the same headers, and that only works under certain specific circumstances, so this bit is key to understanding the C++ compilation model, which is notoriously quirky. Instead of compiling a bunch of separate modules, and exhanging some kind of metadata between them, as a C# compiler would, each translation unit is compiled in isolation, and the resulting object files are passed to a linker which then tries to merge the common bits back together (if multiple translation units included the same header, you essentially have code duplicated across translation units, so the linker merges them back into a single definition) ;)</p>\n\n<p>Of course there are platform-specific ways to write libraries. On Windows, you can make .dll's or .libs, with the difference that a .lib is linked into your application, while a .dll is a separate file you have to bundle with your app, just like in .NET. On Linux, the equivalent filetypes are .so and .a, and in all cases, you have to supply the relevant header files as well, for people to be able to develop against your libraries.</p>\n\n<h2>Data type conversions:</h2>\n\n<p>I'm not sure exactly what you're looking for there, but one point I feel is significant is that the \"traditional\" cast as in the following, is bad:</p>\n\n<pre><code>int i = (int)42.0f; \n</code></pre>\n\n<p>There are several reasons for this.\nFirst, it attempts to perform several different types of casts in order, and you may be surprised by which one the compiler ends up applying. Second, it's hard to find in a search, and third, it's not ugly enough. Casts are generally best avoided, and in C++, they're made a bit ugly to remind you of this. ;)</p>\n\n<pre><code>// The most common cast, when the types are known at compile-time. That is, if \n// inheritance isn't involved, this is generally the one to use\nstatic_cast&lt;U&gt;(T); \n\n// The equivalent for polymorphic types. Does the same as above, but performs a \n// runtime typecheck to ensure that the cast is actually valid\ndynamic_cast&lt;U&gt;(T); \n\n// Is mainly used for converting pointer types. Basically, it says \"don't perform\n// an actual conversion of the data (like from 42.0f to 42), but simply take the\n// same bit pattern and reinterpret it as if it had been something else). It is\n// usually not portable, and in fact, guarantees less than I just said.\nreinterpret_cast&lt;U&gt;(T); \n\n// For adding or removing const-ness. You can't call a non-const member function\n// of a const object, but with a const-cast you can remove the const-ness from \n// the object. Generally a bad idea, but can be necessary.\nconst_cast&lt;U&gt;(T);\n</code></pre>\n\n<p>As you'll note, these casts are much more specific, which means the compiler can give you an error if the cast is invalid (unlike the traditional syntax, where it'd just try any of the above casts until it finds one that works), and it's big and verbose, allowing you to search for it, and reminds you that they should be avoided when possible. ;)</p>\n\n<h2>The standard library:</h2>\n\n<p>Finally, getting back to data structures, put some effort into understanding the standard library. It is small, but amazingly versatile, and once you learn how to use it, you'll be in a far better position.</p>\n\n<p>The standard library consists of several pretty distinct building blocks (the library has kind of accumulated over time. Parts of it were ported from C. The I/O streams library are adopted from one place, and the container classes and their associated functionality are adopted from a completely different library, and are designed noticeably different. The latter are part of what is often referred to as the STL (Standard Template Library). Strictly speaking, that is the name of the library that, slightly modified, got adopted into the C++ Standard Library.</p>\n\n<p>The STL is key to understanding \"modern C++\". It is composed of three pillars, containers, iterators and algorithms.\nIn a nutshell, containers expose iterators, and algorithms work on iterator pairs.</p>\n\n<p>The following example takes a vector of int's, adds 1 to each element, and copies it to a linked list, just for the sake of example:</p>\n\n<pre><code>int add1(int i) { return i+1; } // The function we wish to apply\n\nvoid foo() {\n std::vector&lt;int&gt; v;\n v.push_back(1);\n v.push_back(2);\n v.push_back(3);\n v.push_back(4);\n v.push_back(5); // Add the numbers 1-5 to the vector\n\n std::list&lt;int&gt; l;\n\n // Transform is an algorithm which applies some transformation to every element\n // in an iterator range, and stores the output to a separate iterator\n std::transform ( \n v.begin(),\n v.end(), // Get an iterator range spanning the entire vector\n // Create a special iterator which, when you move it forward, adds a new \n // element to the container it points to. The output will be assigned to this\n std::back_inserter(l) \n add1); // And finally, the function we wish to apply to each element\n}\n</code></pre>\n\n<p>The above style takes some getting used to, but it is extremely powerful and concise.\nBecause the transform function is templated, it can accept <em>any</em> types as input, as long as they behave as iterators. This means that the function can be used to combine any type of containers, or even streams or anything else that can be iterated through, as long as the iterator is designed to be compatible with the STL. We also don't have to use the begin/end pair. Instead of the end iterator, we could have passed one pointing to the third element, and the algorithm would then have stopped there. Or we could have written custom iterators which skipped every other elements, or whatever else we liked.\nThe above is a basic example of each of the three pillars. We use a container to store our data, but the algorithm we use to process it doesn't actually have to know about the container. It just has to know about the iterator range on which it has to work. And of course each of these three pillars can be extended by writing new classes, which will then work smoothly together with the rest of the STL.</p>\n\n<p>In a sense, this is very similar to LINQ, so since you're coming from .NET, you can probably see some analogies. The STL counterpart is a bit more flexible though, at the cost of slightly weirder syntax. :)\n(As mentioned in comments, it is also more efficient. In general, there is <em>zero</em> overhead to STL algorithms, they can be just as efficient as hand-coded loops. This is often surprising, but is possible because all relevant types are known at compile-time (which is a requirement for templates to work), and C++ compilers tend to inline aggressively.)</p>\n" }, { "answer_id": 285863, "author": "Electrons_Ahoy", "author_id": 19074, "author_profile": "https://Stackoverflow.com/users/19074", "pm_score": 2, "selected": false, "text": "<p>I'll not repeat what others have said about libraries and such, but if you're serious about C++, do yourself a favor and pick up Bjarne Stroustrup's \"The C++ Programming Language.\"</p>\n\n<p>It took me years of working in C++ to finally pick up a copy, and once I did, I spent an afternoon slapping my forehead saying \"of course! I should have realized! etc.\"</p>\n\n<p>(Ironically, I had EXACTLY the same experience with K&amp;R's \"The C Programming Language.\" Someday, I'll learn to just go get \"The Book\" on day 1.)</p>\n" }, { "answer_id": 380019, "author": "cweston", "author_id": 37966, "author_profile": "https://Stackoverflow.com/users/37966", "pm_score": 1, "selected": false, "text": "<p><em>In response to \"Referencing/using other libraries\"</em></p>\n\n<p>Information regarding explicit loading of DLL's in C/C++ for both windows and linux include...</p>\n\n<p><strong>Windows:</strong></p>\n\n<p><a href=\"http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c9855#more\" rel=\"nofollow noreferrer\">Windows DLL Tutorial</a> </p>\n\n<p>Functions: <em>LoadLibrary, GetProcAddress, FreeLibrary</em></p>\n\n<p><strong>Linux:</strong></p>\n\n<p>Functions: <em>dlopen, dlsym, dlerror, dlclose</em></p>\n\n<p><a href=\"http://www.ibm.com/developerworks/library/l-dll.html\" rel=\"nofollow noreferrer\">Linux DLL Tutorial</a></p>\n" }, { "answer_id": 487892, "author": "Tamir", "author_id": 30879, "author_profile": "https://Stackoverflow.com/users/30879", "pm_score": -1, "selected": false, "text": "<p>I <a href=\"http://khason.net/blog/pinvoke-cheat-sheet/\" rel=\"nofollow noreferrer\">wrote small cheat sheet</a> for such programmers. You also might be interested with more complicated cases, such <a href=\"http://khason.net/blog/how-to-pinvoke-varargs-variable-arguments-in-c-or-hidden-junk-in-clr/\" rel=\"nofollow noreferrer\">as varargs</a></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
I'm a .NET developer, and worked with VB6 before that. I've become very familiar with those environments, and working in the context of garbage collected languages. However, I now wish to bolster my skillset with native C++ and find myself a bit overwhelmed. Ironically, it's not what I'd imagine is the usual stumbling blocks for beginners as I feel that I've got the grasp of pointers and memory management fairly well. The thing that's a bit confusing for me is more along the lines of: * Referencing/using other libraries * Exposing *my* libraries for others to use * String handling * Data type conversions * Good project structure * Data structures to use (ie. in C#, I use `List<T>` a lot, what do I use in C++ that works simiarly?) It almost feels like depending on the IDE you use, the guidelines are different, so I was really looking for something that's perhaps a bit more universal. Or at worst, focused on using Microsoft's compiler/IDE. Also, just to be clear, I'm not looking for anything about general programming practices (Design Patterns, Code Complete, etc.) as I feel I'm pretty well versed in those topics.
I know you say you've got a good grasp of pointers and memory management, but I'd still like to explain an important trick. As a general rule of thumb, *never* have new/delete in your user code. Every resource acquisition (whether it's a synchronization lock, a database connection or a chunk of memory or anything else that must be acquired and released) should be wrapped in an object so that the constructor performs the acquisition, and the destructor releases the resource. The technique is known as [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization), and is basically *the* way to avoid memory leaks. Get used to it. The C++ standard library obviously uses this extensively, so you can get a feel for how it works there. Jumping a bit in your questions, the equivalent of `List<T>` is `std::vector<T>`, and it uses RAII to manage its memory. You'd use it something like this: ``` void foo() { // declare a vector *without* using new. We want it allocated on the stack, not // the heap. The vector can allocate data on the heap if and when it feels like // it internally. We just don't need to see it in our user code std::vector<int> v; v.push_back(4); v.push_back(42); // Add a few numbers to it // And that is all. When we leave the scope of this function, the destructors // of all local variables, in this case our vector, are called - regardless of // *how* we leave the function. Even if an exception is thrown, v still goes // out of scope, so its destructor is called, and it cleans up nicely. That's // also why C++ doesn't have a finally clause for exception handling, but only // try/catch. Anything that would otherwise go in the finally clause can be put // in the destructor of a local object. } ``` If I had to pick one single principle that a C++ programmer must learn and embrace, it's the above. Let the scoping rules and the destructors work for you. They offer all the guarantees you need to write safe code. String handling: ---------------- `std::string` is your friend there. In C, you'd use arrays of char's (or char pointers), but those are nasty, because they don't behave as strings. In C++, you have a std::string class, which behaves as you'd expect. The only thing to keep in mind is that "hello world" is of type char[12] and NOT std::string. (for C compatibility), so sometimes you have to explicitly convert your string literal (something enclosed in quotes, like "hello world") to a std::string to get the behavior you want: You can still write ``` std::string s = "hello world"; ``` because C-style strings (such as literals, like "hello world") are implicitly convertible to std::string, but it doesn't always work: "hello" + " world" won't compile, because the + operator isn't defined for two pointers. "hello worl" + 'd' however, *will* compile, but it won't do anything sensible. Instead of appending a char to a string, it will take the integral value of the char (which gets promoted to an int), and add that to the value of the pointer. std::string("hello worl") + "d" does as you'd expect however, because the left hand side is already a std::string, and the addition operator is overloaded for std::string to do as you'd expect, even when the right hand side is a char\* or a single character. One final note on strings: std::string uses char, which is a single-byte datatype. That is, it is not suitable for unicode text. C++ provides the wide character type wchar\_t which is 2 or 4 bytes, depending on platform, and is typically used for unicode text (although in neither case does the C++ standard really specify the character set). And a string of wchar\_t's is called std::wstring. Libraries: ---------- They don't exist, fundamentally. The C++ language has no notion of libraries, and this takes some getting used to. It allows you to #include another file (typically a header file with the extension .h or .hpp), but this is simply a verbatim copy/paste. The preprocessor simply combines the two files resulting in what is called a translation unit. Multiple source files will typically include the same headers, and that only works under certain specific circumstances, so this bit is key to understanding the C++ compilation model, which is notoriously quirky. Instead of compiling a bunch of separate modules, and exhanging some kind of metadata between them, as a C# compiler would, each translation unit is compiled in isolation, and the resulting object files are passed to a linker which then tries to merge the common bits back together (if multiple translation units included the same header, you essentially have code duplicated across translation units, so the linker merges them back into a single definition) ;) Of course there are platform-specific ways to write libraries. On Windows, you can make .dll's or .libs, with the difference that a .lib is linked into your application, while a .dll is a separate file you have to bundle with your app, just like in .NET. On Linux, the equivalent filetypes are .so and .a, and in all cases, you have to supply the relevant header files as well, for people to be able to develop against your libraries. Data type conversions: ---------------------- I'm not sure exactly what you're looking for there, but one point I feel is significant is that the "traditional" cast as in the following, is bad: ``` int i = (int)42.0f; ``` There are several reasons for this. First, it attempts to perform several different types of casts in order, and you may be surprised by which one the compiler ends up applying. Second, it's hard to find in a search, and third, it's not ugly enough. Casts are generally best avoided, and in C++, they're made a bit ugly to remind you of this. ;) ``` // The most common cast, when the types are known at compile-time. That is, if // inheritance isn't involved, this is generally the one to use static_cast<U>(T); // The equivalent for polymorphic types. Does the same as above, but performs a // runtime typecheck to ensure that the cast is actually valid dynamic_cast<U>(T); // Is mainly used for converting pointer types. Basically, it says "don't perform // an actual conversion of the data (like from 42.0f to 42), but simply take the // same bit pattern and reinterpret it as if it had been something else). It is // usually not portable, and in fact, guarantees less than I just said. reinterpret_cast<U>(T); // For adding or removing const-ness. You can't call a non-const member function // of a const object, but with a const-cast you can remove the const-ness from // the object. Generally a bad idea, but can be necessary. const_cast<U>(T); ``` As you'll note, these casts are much more specific, which means the compiler can give you an error if the cast is invalid (unlike the traditional syntax, where it'd just try any of the above casts until it finds one that works), and it's big and verbose, allowing you to search for it, and reminds you that they should be avoided when possible. ;) The standard library: --------------------- Finally, getting back to data structures, put some effort into understanding the standard library. It is small, but amazingly versatile, and once you learn how to use it, you'll be in a far better position. The standard library consists of several pretty distinct building blocks (the library has kind of accumulated over time. Parts of it were ported from C. The I/O streams library are adopted from one place, and the container classes and their associated functionality are adopted from a completely different library, and are designed noticeably different. The latter are part of what is often referred to as the STL (Standard Template Library). Strictly speaking, that is the name of the library that, slightly modified, got adopted into the C++ Standard Library. The STL is key to understanding "modern C++". It is composed of three pillars, containers, iterators and algorithms. In a nutshell, containers expose iterators, and algorithms work on iterator pairs. The following example takes a vector of int's, adds 1 to each element, and copies it to a linked list, just for the sake of example: ``` int add1(int i) { return i+1; } // The function we wish to apply void foo() { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); // Add the numbers 1-5 to the vector std::list<int> l; // Transform is an algorithm which applies some transformation to every element // in an iterator range, and stores the output to a separate iterator std::transform ( v.begin(), v.end(), // Get an iterator range spanning the entire vector // Create a special iterator which, when you move it forward, adds a new // element to the container it points to. The output will be assigned to this std::back_inserter(l) add1); // And finally, the function we wish to apply to each element } ``` The above style takes some getting used to, but it is extremely powerful and concise. Because the transform function is templated, it can accept *any* types as input, as long as they behave as iterators. This means that the function can be used to combine any type of containers, or even streams or anything else that can be iterated through, as long as the iterator is designed to be compatible with the STL. We also don't have to use the begin/end pair. Instead of the end iterator, we could have passed one pointing to the third element, and the algorithm would then have stopped there. Or we could have written custom iterators which skipped every other elements, or whatever else we liked. The above is a basic example of each of the three pillars. We use a container to store our data, but the algorithm we use to process it doesn't actually have to know about the container. It just has to know about the iterator range on which it has to work. And of course each of these three pillars can be extended by writing new classes, which will then work smoothly together with the rest of the STL. In a sense, this is very similar to LINQ, so since you're coming from .NET, you can probably see some analogies. The STL counterpart is a bit more flexible though, at the cost of slightly weirder syntax. :) (As mentioned in comments, it is also more efficient. In general, there is *zero* overhead to STL algorithms, they can be just as efficient as hand-coded loops. This is often surprising, but is possible because all relevant types are known at compile-time (which is a requirement for templates to work), and C++ compilers tend to inline aggressively.)
285,730
<p>I'm attempting to bind a <code>DependancyProperty</code> in one of my usercontrols to the <code>Width</code> property of a <code>Column</code> in a <code>Grid</code>. </p> <p>I have code similar to this:</p> <pre><code>&lt;Grid x:Name="MyGridName"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition x:Name="TitleSection" Width="100" /&gt; &lt;ColumnDefinition Width="*" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt;...&lt;/Grid.RowDefinitions&gt; &lt;GridSplitter x:Name="MyGridSplitter" Grid.Row="0" Grid.Column="0" ... /&gt; &lt;/Grid&gt; </code></pre> <p>In a separate Usercontrol I have the following<code>DependancyProperty</code> defined.</p> <pre><code>public static readonly DependencyProperty TitleWidthProperty = DependencyProperty.Register("TitleWidth", typeof(int), typeof(MyUserControl)); public int TitleWidth { get { return (int)base.GetValue(TitleWidthProperty); } set { base.SetValue(TitleWidthProperty, value); } } </code></pre> <p>I am creating instances of the Usercontrol in code, hence I have a binding statement similar to this :</p> <pre><code>MyUserControl Cntrl = new MyUserControl(/* Construction Params */); BindingOperations.SetBinding(Cntrl , MyUserControl.AnotherProperty, new Binding { ElementName = "objZoomSlider", Path = new PropertyPath("Value"), Mode = BindingMode.OneWay }); BindingOperations.SetBinding(Cntrl , MyUserControl.TitleWidthProperty, new Binding { ElementName = "TitleSection", Path = new PropertyPath("ActualWidth"), Mode = BindingMode.OneWay }); /* Other operations on Cntrl */ </code></pre> <p>The first binding defined works fantastically, although that is binding to an actual UIElement (in this case a Slider), but the Binding to "TitleSection" (which is the ColumnDefinition defined in the Grid) fails. Putting a breakpoint in the code and doing a watch on "TitleSection" returns the expected object. </p> <p>I am beginning to suspect that a x:Name'd ColumnDefinition can't be bound to. <strong>Can anyone suggest how I might be able to bind to the changing width of the first column in my grid?</strong></p> <p><strong>EDIT #1 - To answer comments</strong></p> <p>The databinding 'fails' in the sense that with a breakpoint set on the setter for the <code>TitleWidth</code> property, and using the GridSplitter control to resize the first column, the breakpoint is never hit. Additionally, code I would expect to be fired when the DependancyProperty <code>TitleWidth</code> changes does not get executed.</p> <p>The usercontrol is being created and added to a Stackpanel within the Grid in the <code>Window_Loaded</code> function. I would expect that the Grid has been rendered by the time the Usercontrols are being constructed. Certainly the x:Name'd Element <code>TitleSection</code> is watchable and has a value of <code>100</code> when they are being constructed / before the binding is happening.</p> <p><strong>EDIT #2 - Possibly something to do with this?</strong></p> <p>I've been having a sniff round the MSDN pages for the Grid ColumnDefinition documentation and have come across <a href="http://msdn.microsoft.com/en-us/library/system.windows.gridlength.aspx" rel="nofollow noreferrer">GridLength()</a> but I can't get my head around how I can use this in a binding expression. I cannot use the associated GridLengthConverter as a converter in the binding code as it does not derive from IValueConverter. </p> <p>I am leaning towards somehow binding to the ActualWidth property of one of the cells in the Grid object. It doesn't seem as clean as binding to the column definition, but at the moment I cannot get that to work.</p>
[ { "answer_id": 286695, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 2, "selected": false, "text": "<p>Have you tried setting up the binding in xaml, the following should work for you.</p>\n\n<pre><code>&lt;ColumnDefinition \n x:Name=\"TitleSection\" \n Width=\"{Binding \n Path=TitleWidth, \n RelativeSource={RelativeSource AncestorType=MyUserControl}}\" \n /&gt;\n</code></pre>\n\n<p>Otherwise, looking at the binding code you've supplied, it looks the wrong way around to me, the target of the binding should be the grid column and the source should be your dependency property. </p>\n\n<p>The equivalent code for the above xaml is</p>\n\n<pre><code>BindingOperations.SetBinding(TitleSection, ColumnDefinition.WidthProperty,\n new Binding()\n {\n RelativeSource= new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MyUserControl),1),\n Path = new PropertyPath(\"TitleWidth\"),\n });\n</code></pre>\n\n<p>On a related note, using a GridSplitter and binding the Width property are mutally exclusive. As soon as you resize the column using the splitter, your binding will be replaced with the value from the splitter. </p>\n\n<p>This is similar to what you would experience by updating any property that is the target of a binding. When you set the targets value directly in code, you are esentially replacing the binding object with the value you supply.</p>\n" }, { "answer_id": 286737, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 5, "selected": true, "text": "<p>Well I have got a bit of a kludge working, I'll explain how for future generations:</p>\n\n<p>Essentially I have a 2 column, multi row grid with a splitter right aligned in the first column so it can be resized by the user if the content it contains requires more space. To complicate things I have a user control being loaded programatically into some of the rows which has a columnSpan of 2 for rendering purposes (content 'bleeds' from one cell into the next).</p>\n\n<p>When the first column is resized I need this to be reflected in the usercontrol. Firstly I tried binding to the ColumnDefinition but it really wasn't playing ball.</p>\n\n<p><strong>How I fixed/Kludged it</strong></p>\n\n<p>In a spare cell in the first column I added a <code>&lt;Label&gt;</code> with an x:Name to make it accessible. As it is in a cell it has default properties of 'Stretch' and fills the cell completely. It gets resized as the column is resized using the splitter. Binding to the Label's <code>ActualWidth</code> property means that changes to the size of the column are communicated to the DependancyProperty in my columnSpanned usercontrol correctly.</p>\n\n<p><strong>Thoughts</strong></p>\n\n<p>Obviously, despite ColumnDefinition having an <code>ActualWidth</code> property when it changes it doesn't appear to fire the <code>PropertyChanged</code> event internally (or thats my best guess). This may be a bug, or by design, but for me it means I've had to use a less clean solution.</p>\n" }, { "answer_id": 26785462, "author": "JCH2k", "author_id": 1070906, "author_profile": "https://Stackoverflow.com/users/1070906", "pm_score": 2, "selected": false, "text": "<p>ColumnDefinition.Width is not an integer - it is a GridLength.\nYou can't bind the GridLength directly to the Integer, you need a converter.</p>\n\n<p>This is also the reason, why you can't bind any Control's Width property (double) to a ColumnDefinition's Width property (GridLength) without a converter.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31128/" ]
I'm attempting to bind a `DependancyProperty` in one of my usercontrols to the `Width` property of a `Column` in a `Grid`. I have code similar to this: ``` <Grid x:Name="MyGridName"> <Grid.ColumnDefinitions> <ColumnDefinition x:Name="TitleSection" Width="100" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions>...</Grid.RowDefinitions> <GridSplitter x:Name="MyGridSplitter" Grid.Row="0" Grid.Column="0" ... /> </Grid> ``` In a separate Usercontrol I have the following`DependancyProperty` defined. ``` public static readonly DependencyProperty TitleWidthProperty = DependencyProperty.Register("TitleWidth", typeof(int), typeof(MyUserControl)); public int TitleWidth { get { return (int)base.GetValue(TitleWidthProperty); } set { base.SetValue(TitleWidthProperty, value); } } ``` I am creating instances of the Usercontrol in code, hence I have a binding statement similar to this : ``` MyUserControl Cntrl = new MyUserControl(/* Construction Params */); BindingOperations.SetBinding(Cntrl , MyUserControl.AnotherProperty, new Binding { ElementName = "objZoomSlider", Path = new PropertyPath("Value"), Mode = BindingMode.OneWay }); BindingOperations.SetBinding(Cntrl , MyUserControl.TitleWidthProperty, new Binding { ElementName = "TitleSection", Path = new PropertyPath("ActualWidth"), Mode = BindingMode.OneWay }); /* Other operations on Cntrl */ ``` The first binding defined works fantastically, although that is binding to an actual UIElement (in this case a Slider), but the Binding to "TitleSection" (which is the ColumnDefinition defined in the Grid) fails. Putting a breakpoint in the code and doing a watch on "TitleSection" returns the expected object. I am beginning to suspect that a x:Name'd ColumnDefinition can't be bound to. **Can anyone suggest how I might be able to bind to the changing width of the first column in my grid?** **EDIT #1 - To answer comments** The databinding 'fails' in the sense that with a breakpoint set on the setter for the `TitleWidth` property, and using the GridSplitter control to resize the first column, the breakpoint is never hit. Additionally, code I would expect to be fired when the DependancyProperty `TitleWidth` changes does not get executed. The usercontrol is being created and added to a Stackpanel within the Grid in the `Window_Loaded` function. I would expect that the Grid has been rendered by the time the Usercontrols are being constructed. Certainly the x:Name'd Element `TitleSection` is watchable and has a value of `100` when they are being constructed / before the binding is happening. **EDIT #2 - Possibly something to do with this?** I've been having a sniff round the MSDN pages for the Grid ColumnDefinition documentation and have come across [GridLength()](http://msdn.microsoft.com/en-us/library/system.windows.gridlength.aspx) but I can't get my head around how I can use this in a binding expression. I cannot use the associated GridLengthConverter as a converter in the binding code as it does not derive from IValueConverter. I am leaning towards somehow binding to the ActualWidth property of one of the cells in the Grid object. It doesn't seem as clean as binding to the column definition, but at the moment I cannot get that to work.
Well I have got a bit of a kludge working, I'll explain how for future generations: Essentially I have a 2 column, multi row grid with a splitter right aligned in the first column so it can be resized by the user if the content it contains requires more space. To complicate things I have a user control being loaded programatically into some of the rows which has a columnSpan of 2 for rendering purposes (content 'bleeds' from one cell into the next). When the first column is resized I need this to be reflected in the usercontrol. Firstly I tried binding to the ColumnDefinition but it really wasn't playing ball. **How I fixed/Kludged it** In a spare cell in the first column I added a `<Label>` with an x:Name to make it accessible. As it is in a cell it has default properties of 'Stretch' and fills the cell completely. It gets resized as the column is resized using the splitter. Binding to the Label's `ActualWidth` property means that changes to the size of the column are communicated to the DependancyProperty in my columnSpanned usercontrol correctly. **Thoughts** Obviously, despite ColumnDefinition having an `ActualWidth` property when it changes it doesn't appear to fire the `PropertyChanged` event internally (or thats my best guess). This may be a bug, or by design, but for me it means I've had to use a less clean solution.
285,733
<p>I've tried the following, but I was unsuccessful:</p> <pre><code>ALTER TABLE person ALTER COLUMN dob POSITION 37; </code></pre>
[ { "answer_id": 285740, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 8, "selected": true, "text": "<p>\"<a href=\"http://wiki.postgresql.org/wiki/Alter_column_position\" rel=\"noreferrer\">Alter column position</a>\" in the PostgreSQL Wiki says:</p>\n\n<blockquote>\n <p>PostgreSQL currently defines column\n order based on the <code>attnum</code> column of\n the <code>pg_attribute</code> table. The only way\n to change column order is either by\n recreating the table, or by adding\n columns and rotating data until you\n reach the desired layout.</p>\n</blockquote>\n\n<p>That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.</p>\n\n<p>One other idea occurs to me: you can define a <code>VIEW</code> that specifies the order of columns how you like it, without changing the physical position of the column in the base table.</p>\n" }, { "answer_id": 285747, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 4, "selected": false, "text": "<p>I don't think you can at present: see <a href=\"http://wiki.postgresql.org/wiki/Alter_column_position\" rel=\"noreferrer\">this article on the Postgresql wiki</a>.</p>\n\n<p>The three workarounds from this article are: </p>\n\n<ol>\n<li>Recreate the table</li>\n<li>Add columns and move data</li>\n<li>Hide the differences with a view.</li>\n</ol>\n" }, { "answer_id": 21028894, "author": "Ken", "author_id": 1188033, "author_profile": "https://Stackoverflow.com/users/1188033", "pm_score": 5, "selected": false, "text": "<p>This post is old and probably solved but I had the same issue. I resolved it by creating a view of the original table specifying the new column order. </p>\n\n<p>From here I could either use the view or create a new table from the view. </p>\n\n<pre>\n CREATE VIEW original_tab_vw AS\n SELECT a.col1, a.col3, a.col4, a.col2\n FROM original_tab a\n WHERE a.col1 IS NOT NULL --or whatever\n</pre>\n\n<pre>\n SELECT * INTO new_table FROM original_tab_vw\n</pre>\n\n<p>Rename or drop the original table and set the name of the new table to the old table.</p>\n" }, { "answer_id": 27886259, "author": "marcopolo", "author_id": 4442083, "author_profile": "https://Stackoverflow.com/users/4442083", "pm_score": 3, "selected": false, "text": "<p>Open the table in PGAdmin and in the SQL pane at the bottom copy the SQL Create Table statement. Then open the Query Tool and paste. If the table has data, change the table name to 'new_name', if not, delete the comment \"--\" in the Drop Table line. Edit the column sequence as required. Mind the missing/superfluous comma in the last column in case you have moved it. Execute the new SQL Create Table command. Refresh and ... voilà.</p>\n\n<p>For empty tables in the design stage this method is quite practical.</p>\n\n<p>In case the table has data, we need to rearrange the column sequence of the data as well. This is easy: use <code>INSERT</code> to import the old table into its new version with:</p>\n\n<pre><code>INSERT INTO new ( c2, c3, c1 ) SELECT * from old;\n</code></pre>\n\n<p>... where <code>c2</code>, <code>c3</code>, <code>c1</code> are the columns <code>c1</code>, <code>c2</code>, <code>c3</code> of the old table in their new positions. Please note that in this case you <strong>must use a 'new' name</strong> for the edited 'old' table, or <strong>you will lose your data</strong>. In case the column names are many, long and/or complex use the same method as above to copy the new table structure into a text editor, and create the new column list there before copying it into the <code>INSERT</code> statement.</p>\n\n<p>After checking that all is well, <code>DROP</code> the old table and change the the 'new' name to 'old' using <code>ALTER TABLE new RENAME TO old;</code> and you are done.</p>\n" }, { "answer_id": 34411880, "author": "Ville", "author_id": 134536, "author_profile": "https://Stackoverflow.com/users/134536", "pm_score": 5, "selected": false, "text": "<p>One, albeit a clumsy option to rearrange the columns when the column order must absolutely be changed, and foreign keys are in use, is to first dump the entire database with data, then dump just the schema (<code>pg_dump -s databasename &gt; databasename_schema.sql</code>). Next edit the schema file to rearrange the columns as you would like, then recreate the database from the schema, and finally restore the data into the newly created database.</p>\n" }, { "answer_id": 39781155, "author": "Allwin", "author_id": 2000649, "author_profile": "https://Stackoverflow.com/users/2000649", "pm_score": 7, "selected": false, "text": "<p>In PostgreSQL, while adding a field it would be added at the end of the table.\nIf we need to insert into particular position then</p>\n<pre><code> alter table tablename rename to oldtable;\n create table tablename (column defs go here); ### with all the constraints\n insert into tablename (col1, col2, col3) select col1, col2, col3 from oldtable;\n</code></pre>\n" }, { "answer_id": 57519646, "author": "Orlov Const", "author_id": 9506423, "author_profile": "https://Stackoverflow.com/users/9506423", "pm_score": 1, "selected": false, "text": "<p>I use Django and it requires id column in each table if you don't want to have a headache.\nUnfortunately, I was careless and my table bp.geo_location_vague didn't contain this field.\nI initialed little trick.\nStep 1:</p>\n\n<pre><code>CREATE VIEW bp.geo_location_vague_vw AS\n SELECT \n a.id, -- I change order of id column here. \n a.in_date,\n etc\n FROM bp.geo_location_vague a\n</code></pre>\n\n<p>Step 2: (without create table - table will create automaticaly!) </p>\n\n<pre><code>SELECT * into bp.geo_location_vague_cp2 FROM bp.geo_location_vague_vw\n</code></pre>\n\n<p>Step 3:</p>\n\n<pre><code>CREATE SEQUENCE bp.tbl_tbl_id_seq;\nALTER TABLE bp.geo_location_vague_cp2 ALTER COLUMN id SET DEFAULT nextval('tbl_tbl_id_seq');\nALTER SEQUENCE bp.tbl_tbl_id_seq OWNED BY bp.geo_location_vague_cp2.id;\nSELECT setval('tbl_tbl_id_seq', COALESCE(max(id), 0)) FROM bp.geo_location_vague_cp2;\n</code></pre>\n\n<p>Because I need have bigserial pseudotype in the table. After SELECT * into pg will create bigint type insetad bigserial.</p>\n\n<p>step 4: \nNow we can drop the view, drop source table and rename the new table in the old name.\nThe trick was ended successfully.</p>\n" }, { "answer_id": 60277710, "author": "almoglan", "author_id": 11921280, "author_profile": "https://Stackoverflow.com/users/11921280", "pm_score": 0, "selected": false, "text": "<p>There are some workarounds to make it possible:</p>\n\n<ol>\n<li><p>Recreating the whole table</p></li>\n<li><p>Create new columns within the current table</p></li>\n<li><p>Create a view</p></li>\n</ol>\n\n<p><a href=\"https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html\" rel=\"nofollow noreferrer\">https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html</a></p>\n" }, { "answer_id": 61924470, "author": "GammaGames", "author_id": 3903479, "author_profile": "https://Stackoverflow.com/users/3903479", "pm_score": 2, "selected": false, "text": "<p>I was working on re-ordering a lot of tables and didn't want to have to write the same queries over and over so I made a script to do it all for me. Essentially, it:</p>\n\n<ol>\n<li>Gets the table creation SQL from <code>pg_dump</code></li>\n<li>Gets all available columns from the dump</li>\n<li>Puts the columns in the desired order</li>\n<li>Modifies the original <code>pg_dump</code> query to create a re-ordered table with data</li>\n<li>Drops old table</li>\n<li>Renames new table to match old table</li>\n</ol>\n\n<p>It can be used by running the following simple command: </p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>./reorder.py -n schema -d database table \\\n first_col second_col ... penultimate_col ultimate_col --migrate\n</code></pre>\n\n<p>It prints out the sql so you can verify and test it, that was a big reason I based it on <code>pg_dump</code>. You can find the <a href=\"https://github.com/TriangleCommunications/reorder-table-columns\" rel=\"nofollow noreferrer\">github repo here</a>.</p>\n" }, { "answer_id": 74453351, "author": "Ondrej Valenta", "author_id": 5556714, "author_profile": "https://Stackoverflow.com/users/5556714", "pm_score": 0, "selected": false, "text": "<p>For those tempted to change column order like this, just know it won't work because whole table gets messed up. You'll receive an error like this: <em>[XX000] ERROR: invalid memory alloc request size 18446744073709551613</em></p>\n<p>Unfortunately, it seems like the <em>attnum</em> is not only used for retrieval of data but for storage as well.</p>\n<p>The idea to drop whole table is all good and fine but you also have to drop all FKs, IXs and so on. I'll probably learn to live with my column being at back.</p>\n<pre><code>select *\nfrom information_schema.columns\nwhere table_name = 'table1';\n\nupdate pg_catalog.pg_attribute\nset attnum = 10 where attname = 'column_on_9_position_to_move_to_7';\n\nupdate pg_catalog.pg_attribute\nset attnum = 9 where attname = 'column_on_7_position_to_move_to_9';\n\nupdate pg_catalog.pg_attribute\nset attnum = 7 where attname = 'column_on_9_position_to_move_to_7';\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
I've tried the following, but I was unsuccessful: ``` ALTER TABLE person ALTER COLUMN dob POSITION 37; ```
"[Alter column position](http://wiki.postgresql.org/wiki/Alter_column_position)" in the PostgreSQL Wiki says: > > PostgreSQL currently defines column > order based on the `attnum` column of > the `pg_attribute` table. The only way > to change column order is either by > recreating the table, or by adding > columns and rotating data until you > reach the desired layout. > > > That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax. One other idea occurs to me: you can define a `VIEW` that specifies the order of columns how you like it, without changing the physical position of the column in the base table.
285,754
<p>So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.</p> <p>I would like to use generics to create a general class for this scenario. Something like:</p> <pre><code> Adder&lt;Double&gt; adder = new Adder&lt;Double&gt;(); adder.add(10.0d, 10.0d); // = 20.0d </code></pre> <p>But, I cannot instantiate the generic type I pass in to my Adder class! So -- what to do?</p>
[ { "answer_id": 285773, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "<p>Uh oh---generics are not C++ templates. Because of type erasure, the <code>Double</code> in your example won't even show through to the runtime system.</p>\n\n<p>In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., <code>double add(double, double)</code>, <code>float add(float, fload)</code>, <code>BigDecimal add(BigDecimal, BigDecimal)</code>, etc.</p>\n" }, { "answer_id": 285812, "author": "Paul Brinkley", "author_id": 18160, "author_profile": "https://Stackoverflow.com/users/18160", "pm_score": 2, "selected": false, "text": "<p>I <em>think</em> you can do what you want, but I'm not sure, given the information you provided. It sounds as if you want some variation of the following:</p>\n\n<pre><code>public class Foob&lt;T extends Number&gt; {\n\n public T doSomething(T t1, T t2) {\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 285917, "author": "Ken Paul", "author_id": 26671, "author_profile": "https://Stackoverflow.com/users/26671", "pm_score": 0, "selected": false, "text": "<p>If you don't know what kinds of numbers you'll be operating on, then you probably won't be using instance variables of your own. In that case, you can write static methods and never need to instantiate your class.</p>\n\n<p>If you really need your own intermediate variables, then you will likely need to define them differently for each class of user variables you're working with. For instance, if someone tries to use your class to operate on <strong>BigDecimal</strong> variables, you probably won't be using <strong>int</strong> variables for intermediate results.</p>\n" }, { "answer_id": 285919, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 0, "selected": false, "text": "<p>I'm not sure generics is what you want here. Generics in java are for enforcing <strong>compile-time</strong> constraints, not runtime polymorphism. I think what you really want is to use overloading. Using generics, you would have something like:</p>\n\n<pre><code>interface Adder&lt;T&gt; {\n T add(T arg1, arg3);\n}\n</code></pre>\n\n<p>and a bunch of:</p>\n\n<pre><code>class DoubleAdder implements Adder&lt;Double&gt; {\n Double add(Double arg1, Double arg2) {\n return arg1.add(arg2);\n }\n}\n</code></pre>\n\n<p>and then a bunch of:</p>\n\n<pre><code>if (arg1 instanceof Double) {\n Adder&lt;Double&gt; adder = new DoubleAdder();\n}\n</code></pre>\n\n<p>Using generics doesn't save you anything.</p>\n" }, { "answer_id": 287614, "author": "Parag", "author_id": 34956, "author_profile": "https://Stackoverflow.com/users/34956", "pm_score": 0, "selected": false, "text": "<p>I agree with Laplie. Overloading is what will help you. The closest you can come using generics is something like this:</p>\n\n<p>public class NumericOps<br>\n{<br>\n&nbsp;&nbsp;public T add(T n1, T n2) {<br>\n&nbsp;&nbsp;&nbsp;&nbsp;//n1.add(n2);<br>\n&nbsp;&nbsp;&nbsp;&nbsp;//This is not possible because Number does not have an add method, hence<br>\n&nbsp;&nbsp;&nbsp;&nbsp;//you will have to determine the type of n1.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;//We cannot determine the type of U because it will not exist at runtime<br>\n&nbsp;&nbsp;&nbsp;&nbsp;//due to type erasure<br>\n&nbsp;&nbsp;&nbsp;&nbsp;if(n1 instanceof Integer) {<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//add the Integers...<br>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br>\n&nbsp;&nbsp;&nbsp;&nbsp;else if(n1 instanceof Double) {<br>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//add the doubles<br>\n&nbsp;&nbsp;&nbsp;&nbsp;}<br>\n&nbsp;&nbsp;&nbsp;&nbsp;return null;<br>\n&nbsp;&nbsp;}<br>\n}<br></p>\n\n<p>But this does not help very much because there is no benefit of using generics.</p>\n" }, { "answer_id": 1261665, "author": "Graphics Noob", "author_id": 127669, "author_profile": "https://Stackoverflow.com/users/127669", "pm_score": 0, "selected": false, "text": "<p>If you could live with converting everything to a double for the computation you could use polymorphism</p>\n\n<pre><code>Number someNumberFunction(Number n1, Number n2) \n{\n double\n d1 = n1.doubleValue(),\n d2 = n2.doubleValue();\n\n /* perform computations on d1 &amp; d2 */\n}\n</code></pre>\n\n<p>Unfortunately this won't work well on BigInteger or BigDecimal</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on. I would like to use generics to create a general class for this scenario. Something like: ``` Adder<Double> adder = new Adder<Double>(); adder.add(10.0d, 10.0d); // = 20.0d ``` But, I cannot instantiate the generic type I pass in to my Adder class! So -- what to do?
Uh oh---generics are not C++ templates. Because of type erasure, the `Double` in your example won't even show through to the runtime system. In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., `double add(double, double)`, `float add(float, fload)`, `BigDecimal add(BigDecimal, BigDecimal)`, etc.
285,760
<p>I need to spawn a child process that is a console application, and capture its output.</p> <p>I wrote up the following code for a method:</p> <pre><code>string retMessage = String.Empty; ProcessStartInfo startInfo = new ProcessStartInfo(); Process p = new Process(); startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardInput = true; startInfo.UseShellExecute = false; startInfo.Arguments = command; startInfo.FileName = exec; p.StartInfo = startInfo; p.Start(); p.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { using (StreamReader output = p.StandardOutput) { retMessage = output.ReadToEnd(); } } ); p.WaitForExit(); return retMessage; </code></pre> <p>However, this does not return anything. I don't believe the <code>OutputDataReceived</code> event is being called back, or the <code>WaitForExit()</code> command may be blocking the thread so it will never callback.</p> <p>Any advice?</p> <p><strong>EDIT:</strong> Looks like I was trying too hard with the callback. Doing:</p> <pre><code>return p.StandardOutput.ReadToEnd(); </code></pre> <p>Appears to work fine.</p>
[ { "answer_id": 285786, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 2, "selected": false, "text": "<p>You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.</p>\n" }, { "answer_id": 285841, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 8, "selected": false, "text": "<p>Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:</p>\n\n<pre><code>process.StartInfo.UseShellExecute = false;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.OutputDataReceived += (sender, args) =&gt; Console.WriteLine(\"received output: {0}\", args.Data);\nprocess.Start();\nprocess.BeginOutputReadLine();\n</code></pre>\n" }, { "answer_id": 285929, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "<p>It looks like two of your lines are out of order. You start the process before setting up an event handler to capture the output. It's possible the process is just finishing before the event handler is added.</p>\n\n<p>Switch the lines like so.</p>\n\n<pre><code>p.OutputDataReceived += ...\np.Start(); \n</code></pre>\n" }, { "answer_id": 9730455, "author": "Umar Farooq Khawaja", "author_id": 151742, "author_profile": "https://Stackoverflow.com/users/151742", "pm_score": 5, "selected": false, "text": "<p>I just tried this very thing and the following worked for me:</p>\n\n<pre><code>StringBuilder outputBuilder;\nProcessStartInfo processStartInfo;\nProcess process;\n\noutputBuilder = new StringBuilder();\n\nprocessStartInfo = new ProcessStartInfo();\nprocessStartInfo.CreateNoWindow = true;\nprocessStartInfo.RedirectStandardOutput = true;\nprocessStartInfo.RedirectStandardInput = true;\nprocessStartInfo.UseShellExecute = false;\nprocessStartInfo.Arguments = \"&lt;insert command line arguments here&gt;\";\nprocessStartInfo.FileName = \"&lt;insert tool path here&gt;\";\n\nprocess = new Process();\nprocess.StartInfo = processStartInfo;\n// enable raising events because Process does not raise events by default\nprocess.EnableRaisingEvents = true;\n// attach the event handler for OutputDataReceived before starting the process\nprocess.OutputDataReceived += new DataReceivedEventHandler\n(\n delegate(object sender, DataReceivedEventArgs e)\n {\n // append the new data to the data already read-in\n outputBuilder.Append(e.Data);\n }\n);\n// start the process\n// then begin asynchronously reading the output\n// then wait for the process to exit\n// then cancel asynchronously reading the output\nprocess.Start();\nprocess.BeginOutputReadLine();\nprocess.WaitForExit();\nprocess.CancelOutputRead();\n\n// use the output\nstring output = outputBuilder.ToString();\n</code></pre>\n" }, { "answer_id": 14932218, "author": "Beatles1692", "author_id": 111469, "author_profile": "https://Stackoverflow.com/users/111469", "pm_score": -1, "selected": false, "text": "<p>Here's a method that I use to run a process and gets its output and errors :</p>\n\n<pre><code>public static string ShellExecute(this string path, string command, TextWriter writer, params string[] arguments)\n {\n using (var process = Process.Start(new ProcessStartInfo { WorkingDirectory = path, FileName = command, Arguments = string.Join(\" \", arguments), UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }))\n {\n using (process.StandardOutput)\n {\n writer.WriteLine(process.StandardOutput.ReadToEnd());\n }\n using (process.StandardError)\n {\n writer.WriteLine(process.StandardError.ReadToEnd());\n }\n }\n\n return path;\n }\n</code></pre>\n\n<p>For example :</p>\n\n<pre><code>@\"E:\\Temp\\MyWorkingDirectory\".ShellExecute(@\"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Bin\\svcutil.exe\", Console.Out);\n</code></pre>\n" }, { "answer_id": 18529868, "author": "Sam", "author_id": 238753, "author_profile": "https://Stackoverflow.com/users/238753", "pm_score": 5, "selected": false, "text": "<p>Here's some full and simple code to do this. This worked fine when I used it.</p>\n\n<pre><code>var processStartInfo = new ProcessStartInfo\n{\n FileName = @\"C:\\SomeProgram\",\n Arguments = \"Arguments\",\n RedirectStandardOutput = true,\n UseShellExecute = false\n};\nvar process = Process.Start(processStartInfo);\nvar output = process.StandardOutput.ReadToEnd();\nprocess.WaitForExit();\n</code></pre>\n\n<p>Note that this only captures standard <em>output</em>; it doesn't capture standard <em>error</em>. If you want both, use <a href=\"https://stackoverflow.com/a/285841/238753\">this technique</a> for each stream.</p>\n" }, { "answer_id": 21482452, "author": "jws", "author_id": 2183035, "author_profile": "https://Stackoverflow.com/users/2183035", "pm_score": 2, "selected": false, "text": "<p>Redirecting the stream is asynchronous and will potentially continue after the process has terminated. It is mentioned by Umar to cancel after process termination <code>process.CancelOutputRead()</code>. However that has data loss potential.</p>\n\n<p>This is working reliably for me:</p>\n\n<pre><code>process.WaitForExit(...);\n...\nwhile (process.StandardOutput.EndOfStream == false)\n{\n Thread.Sleep(100);\n}\n</code></pre>\n\n<p>I didn't try this approach but I like the suggestion from Sly:</p>\n\n<pre><code>if (process.WaitForExit(timeout))\n{\n process.WaitForExit();\n}\n</code></pre>\n" }, { "answer_id": 31702940, "author": "Robb Sadler", "author_id": 540061, "author_profile": "https://Stackoverflow.com/users/540061", "pm_score": 5, "selected": false, "text": "<p>I needed to capture both stdout and stderr and have it timeout if the process didn't exit when expected. I came up with this:</p>\n\n<pre><code>Process process = new Process();\nStringBuilder outputStringBuilder = new StringBuilder();\n\ntry\n{\nprocess.StartInfo.FileName = exeFileName;\nprocess.StartInfo.WorkingDirectory = args.ExeDirectory;\nprocess.StartInfo.Arguments = args;\nprocess.StartInfo.RedirectStandardError = true;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nprocess.StartInfo.CreateNoWindow = true;\nprocess.StartInfo.UseShellExecute = false;\nprocess.EnableRaisingEvents = false;\nprocess.OutputDataReceived += (sender, eventArgs) =&gt; outputStringBuilder.AppendLine(eventArgs.Data);\nprocess.ErrorDataReceived += (sender, eventArgs) =&gt; outputStringBuilder.AppendLine(eventArgs.Data);\nprocess.Start();\nprocess.BeginOutputReadLine();\nprocess.BeginErrorReadLine();\nvar processExited = process.WaitForExit(PROCESS_TIMEOUT);\n\nif (processExited == false) // we timed out...\n{\n process.Kill();\n throw new Exception(\"ERROR: Process took too long to finish\");\n}\nelse if (process.ExitCode != 0)\n{\n var output = outputStringBuilder.ToString();\n var prefixMessage = \"\";\n\n throw new Exception(\"Process exited with non-zero exit code of: \" + process.ExitCode + Environment.NewLine + \n \"Output from process: \" + outputStringBuilder.ToString());\n}\n}\nfinally\n{ \nprocess.Close();\n}\n</code></pre>\n\n<p>I am piping the stdout and stderr into the same string, but you could keep it separate if needed. It uses events, so it should handle them as they come (I believe). I have run this successfully, and will be volume testing it soon.</p>\n" }, { "answer_id": 33610114, "author": "Craig", "author_id": 2645643, "author_profile": "https://Stackoverflow.com/users/2645643", "pm_score": 2, "selected": false, "text": "<p>The answer from Judah did not work for me (or is not complete) as the application was exiting after the first <code>BeginOutputReadLine();</code></p>\n\n<p>This works for me as a complete snippet, reading the constant output of a ping:</p>\n\n<pre><code> var process = new Process();\n process.StartInfo.FileName = \"ping\";\n process.StartInfo.Arguments = \"google.com -t\";\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.UseShellExecute = false;\n process.OutputDataReceived += (sender, a) =&gt; Console.WriteLine(a.Data);\n process.Start();\n process.BeginOutputReadLine();\n process.WaitForExit();\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I need to spawn a child process that is a console application, and capture its output. I wrote up the following code for a method: ``` string retMessage = String.Empty; ProcessStartInfo startInfo = new ProcessStartInfo(); Process p = new Process(); startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardInput = true; startInfo.UseShellExecute = false; startInfo.Arguments = command; startInfo.FileName = exec; p.StartInfo = startInfo; p.Start(); p.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { using (StreamReader output = p.StandardOutput) { retMessage = output.ReadToEnd(); } } ); p.WaitForExit(); return retMessage; ``` However, this does not return anything. I don't believe the `OutputDataReceived` event is being called back, or the `WaitForExit()` command may be blocking the thread so it will never callback. Any advice? **EDIT:** Looks like I was trying too hard with the callback. Doing: ``` return p.StandardOutput.ReadToEnd(); ``` Appears to work fine.
Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output: ``` process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data); process.Start(); process.BeginOutputReadLine(); ```
285,775
<p>One of my columns is called <code>from</code>. I can't change the name because I didn't make it. Am I allowed to do something like <code>SELECT from FROM TableName</code> or is there a special syntax to avoid the SQL Server being confused?</p>
[ { "answer_id": 285777, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 10, "selected": true, "text": "<p>Wrap the column name in brackets like so, <code>from</code> becomes [from].</p>\n\n<pre><code>select [from] from table;\n</code></pre>\n\n<p>It is also possible to use the following (useful when querying multiple tables):</p>\n\n<pre><code>select table.[from] from table;\n</code></pre>\n" }, { "answer_id": 285783, "author": "John Baughman", "author_id": 26923, "author_profile": "https://Stackoverflow.com/users/26923", "pm_score": 3, "selected": false, "text": "<p>If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name. </p>\n\n<pre><code>select [select]\nfrom [table]\n</code></pre>\n" }, { "answer_id": 285795, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": false, "text": "<p>While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).</p>\n\n<pre><code>SELECT [from] AS TransferFrom -- Or something else more suitable\nFROM TableName\n</code></pre>\n" }, { "answer_id": 285913, "author": "Eigir", "author_id": 37007, "author_profile": "https://Stackoverflow.com/users/37007", "pm_score": 4, "selected": false, "text": "<p>Your question seems to be well answered here, but I just want to add one more comment to this subject.</p>\n\n<p>Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is <em>reserved</em> word.</p>\n\n<p>More information:</p>\n\n<blockquote>\n <p>\"Reserved keywords should not be used\n as object names. Databases upgraded\n from earlier versions of SQL Server\n may contain identifiers that include\n words not reserved in the earlier\n version, but that are reserved words\n for the current version of SQL Server.\n You can refer to the object by using\n delimited identifiers until the name\n can be changed.\"\n <a href=\"http://msdn.microsoft.com/en-us/library/ms176027.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms176027.aspx</a></p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>\"If your database does contain names\n that match reserved keywords, you must\n use delimited identifiers when you\n refer to those objects. For more\n information, see Identifiers (DMX).\"\n <a href=\"http://msdn.microsoft.com/en-us/library/ms132178.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms132178.aspx</a></p>\n</blockquote>\n" }, { "answer_id": 293009, "author": "some", "author_id": 36866, "author_profile": "https://Stackoverflow.com/users/36866", "pm_score": 5, "selected": false, "text": "<p>If it had been in PostgreSQL, use double quotes around the name, like:</p>\n\n<pre><code>select \"from\" from \"table\";\n</code></pre>\n\n<p>Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. <strong>sEleCt * from tAblE;</strong> is interpreted as <strong>select * from table;</strong>. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: <strong>select * from \"table\";</strong> and <strong>select * from \"Table\";</strong> gets the result from two different tables. </p>\n" }, { "answer_id": 8871217, "author": "user247487", "author_id": 247487, "author_profile": "https://Stackoverflow.com/users/247487", "pm_score": 1, "selected": false, "text": "<p>You can put your column name in bracket like:</p>\n\n<pre><code>Select [from] from &lt; ur_tablename&gt;\n</code></pre>\n\n<p>Or</p>\n\n<p>Put in a temprary table then use as you like.<br>\nExample:</p>\n\n<pre><code>Declare @temp_table table(temp_from varchar(max))\n\nInsert into @temp_table\nSelect * from your_tablename\n</code></pre>\n\n<p>Here I just assume that your_tablename contains only one column (i.e. from).</p>\n" }, { "answer_id": 12340258, "author": "preyingrazor", "author_id": 1658315, "author_profile": "https://Stackoverflow.com/users/1658315", "pm_score": 2, "selected": false, "text": "<p>Hi I work on Teradata systems that is completely ANSI compliant. Use double quotes \" \" to name such columns. </p>\n\n<p>E.g. <code>type</code> is a SQL reserved keyword, and when used within quotes, <code>type</code> is treated as a user specified name.</p>\n\n<p>See below code example:</p>\n\n<pre><code>CREATE TABLE alpha1\nAS\n(\nSEL\nproduct1\ntype_of_product AS \"type\"\nFROM beta1\n) WITH DATA\nPRIMARY INDEX (product1)\n\n--type is a SQL reserved keyword\n\nTYPE\n\n--see? now to retrieve the column you would use:\n\nSEL \"type\" FROM alpha1\n</code></pre>\n" }, { "answer_id": 12354437, "author": "Rudolf Real", "author_id": 1242821, "author_profile": "https://Stackoverflow.com/users/1242821", "pm_score": 2, "selected": false, "text": "<p>I ran in the same issue when trying to <strong>update</strong> a column which name was a <strong>keyword</strong>. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:</p>\n\n<pre><code>UPDATE `survey`\nSET survey.values='yes,no'\nWHERE (question='Did you agree?')\n</code></pre>\n" }, { "answer_id": 19891609, "author": "Muneeb Hassan", "author_id": 775393, "author_profile": "https://Stackoverflow.com/users/775393", "pm_score": 2, "selected": false, "text": "<p>I have also faced this issue. \nAnd the solution for this is to put [Column_Name] like this in the query.</p>\n\n<pre><code>string query= \"Select [Name],[Email] from Person\";\n</code></pre>\n\n<p>So it will work perfectly well.</p>\n" }, { "answer_id": 24532098, "author": "user3797709", "author_id": 3797709, "author_profile": "https://Stackoverflow.com/users/3797709", "pm_score": 2, "selected": false, "text": "<p>The following will work perfectly:</p>\n\n<pre><code>SELECT DISTINCT table.from AS a FROM table\n</code></pre>\n" }, { "answer_id": 29441254, "author": "Sunil Kapil", "author_id": 1801075, "author_profile": "https://Stackoverflow.com/users/1801075", "pm_score": 5, "selected": false, "text": "<p>These are the two ways to do it:</p>\n\n<ol>\n<li>Use back quote as here: </li>\n</ol>\n\n<blockquote>\n <p>SELECT `from` FROM TableName</p>\n</blockquote>\n\n<ol start=\"2\">\n<li>You can mention with table name as: </li>\n</ol>\n\n<blockquote>\n <p><code>SELECT TableName.from FROM TableName</code></p>\n</blockquote>\n" }, { "answer_id": 36354231, "author": "Kun Wu", "author_id": 894557, "author_profile": "https://Stackoverflow.com/users/894557", "pm_score": 3, "selected": false, "text": "<p>In Apache Drill, use backquotes:</p>\n\n<pre><code>select `from` from table;\n</code></pre>\n" }, { "answer_id": 44162398, "author": "cacti5", "author_id": 5839007, "author_profile": "https://Stackoverflow.com/users/5839007", "pm_score": 1, "selected": false, "text": "<p>In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit. </p>\n\n<pre><code>select [from] from &lt;table&gt;\n</code></pre>\n\n<p>As a note, the above does not work in MySQL</p>\n" }, { "answer_id": 48694279, "author": "David Bradley", "author_id": 1378018, "author_profile": "https://Stackoverflow.com/users/1378018", "pm_score": 1, "selected": false, "text": "<p>Judging from the answers here and my own experience. The only acceptable answer, if you're planning on being portable is don't use SQL keywords for table, column, or other names.</p>\n\n<p>All these answers work in the various databases but apparently a lot don't support the ANSI solution.</p>\n" }, { "answer_id": 68912765, "author": "steve363", "author_id": 10261876, "author_profile": "https://Stackoverflow.com/users/10261876", "pm_score": 0, "selected": false, "text": "<p>In Oracle SQL Developer, pl/sql you can do this with double quotes but if you use double quotes you must type the column names in upper case. For example, SELECT &quot;FROM&quot; FROM MY_TABLE</p>\n" }, { "answer_id": 71177522, "author": "Nishant Shah", "author_id": 1256210, "author_profile": "https://Stackoverflow.com/users/1256210", "pm_score": 1, "selected": false, "text": "<p>Simple solution</p>\n<p>Lets say the column name is <strong>from</strong> ; So the column name in query can be referred by table alias</p>\n<pre><code>Select * from user u where u.from=&quot;US&quot;\n</code></pre>\n" }, { "answer_id": 72699536, "author": "Jo van Schalkwyk", "author_id": 5422001, "author_profile": "https://Stackoverflow.com/users/5422001", "pm_score": 2, "selected": false, "text": "<p>Some solid answers—but the most-upvoted one is parochial, only dealing with SQL Server. In summary:</p>\n<ul>\n<li>If you have source control, the best solution is to stick to the rules, and avoid using reserved words. <a href=\"https://www.drupal.org/docs/develop/coding-standards/list-of-sql-reserved-words\" rel=\"nofollow noreferrer\">This list</a> has been around for ages, and covers most of the peculiarities. One tip is that reserved words are rarely plural—so you're usually safe using plural names. Exceptions are DIAGNOSTICS, SCHEMAS, OCTETS, OFFSETS, OPTIONS, VALUES, PARAMETERS, PRIVILEGES and also verb-like words that also appear plural: OVERLAPS, READS, RETURNS, TRANSFORMS.</li>\n<li>Many of us don't have the luxury of changing the field names. There, you'll need to know the details of the RDBM you're accessing:</li>\n<li>For <em>SQL Server</em> use [square_braces] around the name. This works in an ODBC connection too.</li>\n<li>For <em>MySQL</em> use `back_ticks`.</li>\n<li>Postgres, Oracle and several other RDBMs will apparently allow &quot;double_quotes&quot; to be used.</li>\n</ul>\n<p>Dotting the offending word onto the table name may also work.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25645/" ]
One of my columns is called `from`. I can't change the name because I didn't make it. Am I allowed to do something like `SELECT from FROM TableName` or is there a special syntax to avoid the SQL Server being confused?
Wrap the column name in brackets like so, `from` becomes [from]. ``` select [from] from table; ``` It is also possible to use the following (useful when querying multiple tables): ``` select table.[from] from table; ```
285,790
<pre><code>while (xxx) { timeout.tv_sec=TIMEOUT; timeout.tv_usec=0; FD_ZERO(&amp;set); FD_SET(sd,&amp;set); switch (select(FD_SETSIZE,&amp;set,NULL,NULL,&amp;timeout)) xxxxx } </code></pre> <p>works fine, however</p> <pre><code>FD_ZERO(&amp;set); FD_SET(sd,&amp;set); while (xxx) { timeout.tv_sec=TIMEOUT; timeout.tv_usec=0; switch (select(FD_SETSIZE,&amp;set,NULL,NULL,&amp;timeout)) xxxxx } </code></pre> <p>doesn't. It works the first time around, but the next time it runs through the while loop it gets a timeout even if the sd socket receives data. It seems to me to be a waste of resources to have to empty and fill set every time.</p> <p>Anybody have a good explanation why this is, and even better, perhaps a suggestion how to avoid it?</p>
[ { "answer_id": 285801, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "<p>Read the select man page. The returned set is only the file descriptors that are ready to be used. You are supposed to use FD_ISSET to check each one if it is set or not.</p>\n\n<p>Always initialize the fd_set right before using it.</p>\n" }, { "answer_id": 285807, "author": "John Safranek", "author_id": 30524, "author_profile": "https://Stackoverflow.com/users/30524", "pm_score": 0, "selected": false, "text": "<p>That's the way select works. It works best, and makes more sense, if you have more than one socket. That's kind of the point: you are selecting across many sockets. If you want to read from one socket, just read or recv it.</p>\n" }, { "answer_id": 286231, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 5, "selected": true, "text": "<p>select modifies its arguments. You really do have to re-initialize it each time.</p>\n\n<p>If you're concerned about overhead, the cost of processing the complete FD_SET in the kernel is somewhat more significant than the cost of FD_ZERO. You'd want to only pass in your maximum fd, not FD_SETSZIZE, to minimize the kernel processing. In your example:</p>\n\n<pre><code>switch (select((sd + 1),&amp;set,NULL,NULL,&amp;timeout))\n</code></pre>\n\n<p>For a more complex case with multiple fds, you typically end up maintaining a max variable:</p>\n\n<pre><code>FD_SET(sd,&amp;set);\nif (sd &gt; max) max = sd;\n... repeat many times...\n\nswitch (select((max + 1),&amp;set,NULL,NULL,&amp;timeout))\n</code></pre>\n\n<p><br>\nIf you will have a large number of file descriptors and are concerned about the overhead of schlepping them about, you should look at some of the alternatives to select(). You don't mention the OS you're using, but for Unix-like OSes there are a few:</p>\n\n<ul>\n<li>for Linux, epoll()</li>\n<li>for FreeBSD/NetBSD/OpenBSD/MacOS X, kqueue()</li>\n<li>for Solaris, /dev/poll</li>\n</ul>\n\n<p>The APIs are different, but they are all essentially a stateful kernel interface to maintain a set of active file descriptions. Once an fd is added to the set, you will be notified of events on that fd without having to continually pass it in again.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37169/" ]
``` while (xxx) { timeout.tv_sec=TIMEOUT; timeout.tv_usec=0; FD_ZERO(&set); FD_SET(sd,&set); switch (select(FD_SETSIZE,&set,NULL,NULL,&timeout)) xxxxx } ``` works fine, however ``` FD_ZERO(&set); FD_SET(sd,&set); while (xxx) { timeout.tv_sec=TIMEOUT; timeout.tv_usec=0; switch (select(FD_SETSIZE,&set,NULL,NULL,&timeout)) xxxxx } ``` doesn't. It works the first time around, but the next time it runs through the while loop it gets a timeout even if the sd socket receives data. It seems to me to be a waste of resources to have to empty and fill set every time. Anybody have a good explanation why this is, and even better, perhaps a suggestion how to avoid it?
select modifies its arguments. You really do have to re-initialize it each time. If you're concerned about overhead, the cost of processing the complete FD\_SET in the kernel is somewhat more significant than the cost of FD\_ZERO. You'd want to only pass in your maximum fd, not FD\_SETSZIZE, to minimize the kernel processing. In your example: ``` switch (select((sd + 1),&set,NULL,NULL,&timeout)) ``` For a more complex case with multiple fds, you typically end up maintaining a max variable: ``` FD_SET(sd,&set); if (sd > max) max = sd; ... repeat many times... switch (select((max + 1),&set,NULL,NULL,&timeout)) ``` If you will have a large number of file descriptors and are concerned about the overhead of schlepping them about, you should look at some of the alternatives to select(). You don't mention the OS you're using, but for Unix-like OSes there are a few: * for Linux, epoll() * for FreeBSD/NetBSD/OpenBSD/MacOS X, kqueue() * for Solaris, /dev/poll The APIs are different, but they are all essentially a stateful kernel interface to maintain a set of active file descriptions. Once an fd is added to the set, you will be notified of events on that fd without having to continually pass it in again.
285,793
<p>Eclipse issues warnings when a <code>serialVersionUID</code> is missing. </p> <blockquote> <p>The serializable class Foo does not declare a static final serialVersionUID field of type long</p> </blockquote> <p>What is <code>serialVersionUID</code> and why is it important? Please show an example where missing <code>serialVersionUID</code> will cause a problem.</p>
[ { "answer_id": 285809, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 12, "selected": true, "text": "<p>The docs for <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html\" rel=\"noreferrer\"><code>java.io.Serializable</code></a> are probably about as good an explanation as you'll get:</p>\n<blockquote>\n<p>The serialization runtime associates with each serializable class a version number, called a <code>serialVersionUID</code>, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different <code>serialVersionUID</code> than that of the corresponding sender's class, then deserialization will result in an\n<a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InvalidClassException.html\" rel=\"noreferrer\"><code>InvalidClassException</code></a>. A serializable class can declare its own <code>serialVersionUID</code> explicitly by declaring a field named <code>serialVersionUID</code> that must be static, final, and of type <code>long</code>:</p>\n</blockquote>\n<blockquote>\n<pre><code>ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;\n</code></pre>\n</blockquote>\n<blockquote>\n<p>If a serializable class does not explicitly declare a <code>serialVersionUID</code>, then the serialization runtime will calculate a default <code>serialVersionUID</code> value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is <em>strongly recommended</em> that all serializable classes explicitly declare <code>serialVersionUID</code> values, since the default <code>serialVersionUID</code> computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected <code>InvalidClassExceptions</code> during deserialization. Therefore, to guarantee a consistent <code>serialVersionUID</code> value across different java compiler implementations, a serializable class must declare an explicit <code>serialVersionUID</code> value. It is also strongly advised that explicit <code>serialVersionUID</code> declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class — <code>serialVersionUID</code> fields are not useful as inherited members.</p>\n</blockquote>\n" }, { "answer_id": 285811, "author": "eishay", "author_id": 16201, "author_profile": "https://Stackoverflow.com/users/16201", "pm_score": 5, "selected": false, "text": "<p>If you will never need to serialize your objects to byte array and send/store them, then you don't need to worry about it. If you do, then you must consider your serialVersionUID since the deserializer of the object will match it to the version of object its classloader has. Read more about it in the Java Language Specification.</p>\n" }, { "answer_id": 285827, "author": "Scott Bale", "author_id": 2495576, "author_profile": "https://Stackoverflow.com/users/2495576", "pm_score": 8, "selected": false, "text": "<p>I can't pass up this opportunity to plug Josh Bloch's book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321356683\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java</a> (2nd Edition). Chapter 10 is an indispensible resource on Java serialization.</p>\n<p>Per Josh, the automatically-generated UID is generated based on a class name, implemented interfaces, and all public and protected members. Changing any of these in any way will change the <code>serialVersionUID</code>. So you don't need to mess with them only if you are certain that no more than one version of the class will ever be serialized (either across processes or retrieved from storage at a later time).</p>\n<p>If you ignore them for now, and find later that you need to change the class in some way but maintain compatibility w/ old version of the class, you can use the JDK tool <strong>serialver</strong> to generate the <code>serialVersionUID</code> on the <em>old</em> class, and explicitly set that on the new class. (Depending on your changes you may need to also implement custom serialization by adding <code>writeObject</code> and <code>readObject</code> methods - see <code>Serializable</code> javadoc or aforementioned chapter 10.)</p>\n" }, { "answer_id": 286006, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 7, "selected": false, "text": "<p>You can tell Eclipse to ignore these serialVersionUID warnings:</p>\n\n<blockquote>\n <p>Window > Preferences > Java > Compiler > Errors / Warnings > Potential Programming Problems</p>\n</blockquote>\n\n<p>In case you didn't know, there are a lot of other warnings you can enable in this section (or even have some reported as errors), many are very useful:</p>\n\n<ul>\n<li>Potential Programming Problems: Possible accidental boolean assignment</li>\n<li>Potential Programming Problems: Null pointer access</li>\n<li>Unnecessary code: Local variable is never read</li>\n<li>Unnecessary code: Redundant null check</li>\n<li>Unnecessary code: Unnecessary cast or 'instanceof'</li>\n</ul>\n\n<p>and many more.</p>\n" }, { "answer_id": 286254, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 9, "selected": false, "text": "<p>If you're serializing just because you have to serialize for the implementation's sake (who cares if you serialize for an <code>HTTPSession</code>, for instance...if it's stored or not, you probably don't care about <code>de-serializing</code> a form object), then you can ignore this.</p>\n\n<p>If you're actually using serialization, it only matters if you plan on storing and retrieving objects using serialization directly. The <code>serialVersionUID</code> represents your class version, and you should increment it if the current version of your class is not backwards compatible with its previous version.</p>\n\n<p>Most of the time, you will probably not use serialization directly. If this is the case, generate a default <code>SerialVersionUID</code> by clicking the quick fix option and don't worry about it.</p>\n" }, { "answer_id": 337345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>It would be nice if CheckStyle could verify that the serialVersionUID on a class that implements Serializable has a good value, i.e. that it matches what the serial version id generator would produce. If you have a project with lots of serializable DTOs, for example, remembering to delete the existing serialVersionUID and regenerate it is a pain, and currently the only way (that I know of) to verify this is to regenerate for each class and compare to the old one. This is very very painful.</p>\n" }, { "answer_id": 4881563, "author": "Paŭlo Ebermann", "author_id": 600500, "author_profile": "https://Stackoverflow.com/users/600500", "pm_score": 5, "selected": false, "text": "<p>If you get this warning on a class you don't ever think about serializing, and that you didn't declare yourself <code>implements Serializable</code>, it is often because you inherited from a superclass, which implements Serializable. Often then it would be better to delegate to such a object instead of using inheritance.</p>\n\n<p>So, instead of </p>\n\n<pre><code>public class MyExample extends ArrayList&lt;String&gt; {\n\n public MyExample() {\n super();\n }\n ...\n}\n</code></pre>\n\n<p>do</p>\n\n<pre><code>public class MyExample {\n private List&lt;String&gt; myList;\n\n public MyExample() {\n this.myList = new ArrayList&lt;String&gt;();\n }\n ...\n}\n</code></pre>\n\n<p>and in the relevant methods call <code>myList.foo()</code> instead of <code>this.foo()</code> (or <code>super.foo()</code>). (This does not fit in all cases, but still quite often.)</p>\n\n<p>I often see people extending JFrame or such, when they really only need to delegate to this. (This also helps for auto-completing in a IDE, since JFrame has hundreds of methods, which you don't need when you want to call your custom ones on your class.)</p>\n\n<p>One case where the warning (or the serialVersionUID) is unavoidable is when you extend from AbstractAction, normally in a anonymous class, only adding the actionPerformed-method. I think there shouldn't be a warning in this case (since you normally can't reliable serialize and deserialize such anonymous classes anyway accross different versions of your class), but I'm not sure how the compiler could recognize this.</p>\n" }, { "answer_id": 10373579, "author": "grand johnson", "author_id": 1364371, "author_profile": "https://Stackoverflow.com/users/1364371", "pm_score": 4, "selected": false, "text": "<p>Don't bother, the default calculation is really good and suffice for 99,9999% of the cases. And if you run into problems, you can - as already stated - introduce UID's as the need arrise (which is highly unlikely)</p>\n" }, { "answer_id": 12702699, "author": "Alexander Torstling", "author_id": 83741, "author_profile": "https://Stackoverflow.com/users/83741", "pm_score": 7, "selected": false, "text": "<p><code>serialVersionUID</code> facilitates versioning of serialized data. Its value is stored with the data when serializing. When de-serializing, the same version is checked to see how the serialized data matches the current code. </p>\n\n<p>If you want to version your data, you normally start with a <code>serialVersionUID</code> of 0, and bump it with every structural change to your class which alters the serialized data (adding or removing non-transient fields). </p>\n\n<p>The built-in de-serialization mechanism (<code>in.defaultReadObject()</code>) will refuse to de-serialize from old versions of the data. But if you want to you can define your own <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/input.html#2971\" rel=\"noreferrer\">readObject()</a>-function which can read back old data. This custom code can then check the <code>serialVersionUID</code> in order to know which version the data is in and decide how to de-serialize it. This versioning technique is useful if you store serialized data which survives several versions of your code.</p>\n\n<p>But storing serialized data for such a long time span is not very common. It is far more common to use the serialization mechanism to temporarily write data to for instance a cache or send it over the network to another program with the same version of the relevant parts of the codebase. </p>\n\n<p>In this case you are not interested in maintaining backwards compatibility. You are only concerned with making sure that the code bases which are communicating indeed have the same versions of relevant classes. In order to facilitate such a check, you must maintain the <code>serialVersionUID</code> just like before and not forget to update it when making changes to your classes. </p>\n\n<p>If you do forget to update the field, you might end up with two different versions of a class with different structure but with the same <code>serialVersionUID</code>. If this happens, the default mechanism (<code>in.defaultReadObject()</code>) will not detect any difference, and try to de-serialize incompatible data. Now you might end up with a cryptic runtime error or silent failure (null fields). These types of errors might be hard to find.</p>\n\n<p>So to help this usecase, the Java platform offers you a choice of not setting the <code>serialVersionUID</code> manually. Instead, a hash of the class structure will be generated at compile-time and used as id. This mechanism will make sure that you never have different class structures with the same id, and so you will not get these hard-to-trace runtime serialization failures mentioned above.</p>\n\n<p>But there is a backside to the auto-generated id strategy. Namely that the generated ids for the same class might differ between compilers (as mentioned by Jon Skeet above). So if you communicate serialized data between code compiled with different compilers, it is recommended to maintain the ids manually anyway. </p>\n\n<p>And if you are backwards-compatible with your data like in the first use case mentioned, you also probably want to maintain the id yourself. This in order to get readable ids and have greater control over when and how they change.</p>\n" }, { "answer_id": 15388086, "author": "Mukti", "author_id": 2165875, "author_profile": "https://Stackoverflow.com/users/2165875", "pm_score": 4, "selected": false, "text": "<p>Field data represents some information stored in the class.\nClass implements the <code>Serializable</code> interface, \nso eclipse automatically offered to declare the <code>serialVersionUID</code> field. Lets start with value 1 set there.</p>\n\n<p>If you don't want that warning to come, use this:</p>\n\n<pre><code>@SuppressWarnings(\"serial\")\n</code></pre>\n" }, { "answer_id": 15861472, "author": "Rupesh", "author_id": 1270989, "author_profile": "https://Stackoverflow.com/users/1270989", "pm_score": 6, "selected": false, "text": "<p>Original question has asked for 'why is it important' and 'example' where this <code>Serial Version ID</code> would be useful. Well I have found one.</p>\n\n<p>Say you create a <code>Car</code> class, instantiate it, and write it out to an object stream. The flattened car object sits in the file system for some time. Meanwhile, if the <code>Car</code> class is modified by adding a new field. Later on, when you try to read (i.e. deserialize) the flattened <code>Car</code> object, you get the <code>java.io.InvalidClassException</code> – because all serializable classes are automatically given a unique identifier. This exception is thrown when the identifier of the class is not equal to the identifier of the flattened object. If you really think about it, the exception is thrown because of the addition of the new field. You can avoid this exception being thrown by controlling the versioning yourself by declaring an explicit serialVersionUID. There is also a small performance benefit in explicitly declaring your <code>serialVersionUID</code> (because does not have to be calculated). So, it is best practice to add your own serialVersionUID to your Serializable classes as soon as you create them as shown below:</p>\n\n<pre><code>public class Car {\n static final long serialVersionUID = 1L; //assign a long value\n}\n</code></pre>\n" }, { "answer_id": 16656980, "author": "Henrique Ordine", "author_id": 1264138, "author_profile": "https://Stackoverflow.com/users/1264138", "pm_score": 4, "selected": false, "text": "<p>As for an example where the missing serialVersionUID might cause a problem:</p>\n\n<p>I'm working on this Java EE application that is composed of a Web module that uses an <code>EJB</code> module. The web module calls the <code>EJB</code> module remotely and passes a <code>POJO</code> that implements <code>Serializable</code> as an argument.</p>\n\n<p>This <code>POJO's</code> class was packaged inside the EJB jar and inside it's own jar in the WEB-INF/lib of the web module. They're actually the same class, but when I package the EJB module I unpack this POJO's jar to pack it together with the EJB module.</p>\n\n<p>The call to the <code>EJB</code> was failing with the Exception below because I hadn't declared its <code>serialVersionUID</code>:</p>\n\n<pre><code>Caused by: java.io.IOException: Mismatched serialization UIDs : Source\n (Rep.\n IDRMI:com.hordine.pedra.softbudget.domain.Budget:5CF7CE11E6810A36:04A3FEBED5DA4588)\n = 04A3FEBED5DA4588 whereas Target (Rep. ID RMI:com.hordine.pedra.softbudget.domain.Budget:7AF5ED7A7CFDFF31:6227F23FA74A9A52)\n = 6227F23FA74A9A52\n</code></pre>\n" }, { "answer_id": 16880322, "author": "Nitesh Soni", "author_id": 2444506, "author_profile": "https://Stackoverflow.com/users/2444506", "pm_score": 5, "selected": false, "text": "<p>To understand the significance of field serialVersionUID, one should understand how Serialization/Deserialization works.</p>\n\n<p>When a Serializable class object is serialized Java Runtime associates a serial version no.(called as serialVersionUID) with this serialized object. At the time when you deserialize this serialized object Java Runtime matches the serialVersionUID of serialized object with the serialVersionUID of the class. If both are equal then only it proceeds with the further process of deserialization else throws InvalidClassException.</p>\n\n<p>So we conclude that to make Serialization/Deserialization process successful the serialVersionUID of serialized object must be equivalent to the serialVersionUID of the class. In case if programmer specifies the serialVersionUID value explicitly in the program then the same value will be associated with the serialized object and the class, irrespective of the serialization and deserialzation platform(for ex. serialization might be done on platform like windows by using sun or MS JVM and Deserialization might be on different platform Linux using Zing JVM).</p>\n\n<p>But in case if serialVersionUID is not specified by programmer then while doing Serialization\\DeSerialization of any object, Java runtime uses its own algorithm to calculate it. This serialVersionUID calculation algorithm varies from one JRE to another. It is also possible that the environment where the object is serialized is using one JRE (ex: SUN JVM) and the environment where deserialzation happens is using Linux Jvm(zing). In such cases serialVersionUID associated with serialized object will be different than the serialVersionUID of class calculated at deserialzation environment. In turn deserialization will not be successful. So to avoid such situations/issues programmer must always specify serialVersionUID of Serializable class.</p>\n" }, { "answer_id": 19418317, "author": "Thalaivar", "author_id": 337128, "author_profile": "https://Stackoverflow.com/users/337128", "pm_score": 6, "selected": false, "text": "<blockquote>\n <p>What is a <strong>serialVersionUID</strong> and why should I use it?</p>\n</blockquote>\n\n<p><code>SerialVersionUID</code> is a unique identifier for each class, <code>JVM</code> uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization.</p>\n\n<p>Specifying one gives more control, though JVM does generate one if you don't specify. The value generated can differ between different compilers. Furthermore, sometimes you just want for some reason to forbid deserialization of old serialized objects [<code>backward incompatibility</code>], and in this case you just have to change the serialVersionUID. </p>\n\n<p><strong>The <a href=\"https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html\" rel=\"noreferrer\">javadocs for <code>Serializable</code></a> say</strong>:</p>\n\n<blockquote>\n <p>the default serialVersionUID computation is highly sensitive to class\n details that may vary depending on compiler implementations, and can\n thus result in unexpected <code>InvalidClassException</code>s during\n deserialization.</p>\n</blockquote>\n\n<p><strong>Therefore, you must declare serialVersionUID because it give us more control</strong>.</p>\n\n<p><a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=45\" rel=\"noreferrer\">This article</a> has some good points on the topic.</p>\n" }, { "answer_id": 22177263, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 4, "selected": false, "text": "<p>I generally use <code>serialVersionUID</code> in one context: When I know it will be leaving the context of the Java VM. </p>\n\n<p>I would know this when I to use <code>ObjectInputStream</code> and <code>ObjectOutputStream</code> for my application or if I know a library/framework I use will use it. The serialVersionID ensures different Java VMs of varying versions or vendors will inter-operate correctly or if it is stored and retrieved outside the VM for example <code>HttpSession</code> the session data can remain even during a restart and upgrade of the application server.</p>\n\n<p>For all other cases, I use </p>\n\n<pre><code>@SuppressWarnings(\"serial\")\n</code></pre>\n\n<p>since most of the time the default <code>serialVersionUID</code> is sufficient. This includes <code>Exception</code>, <code>HttpServlet</code>.</p>\n" }, { "answer_id": 29266546, "author": "Neethu Lalitha", "author_id": 3357735, "author_profile": "https://Stackoverflow.com/users/3357735", "pm_score": 4, "selected": false, "text": "<p>SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch</p>\n\n<p>Read more: <a href=\"http://javarevisited.blogspot.com/2011/04/top-10-java-serialization-interview.html#ixzz3VQxnpOPZ\">http://javarevisited.blogspot.com/2011/04/top-10-java-serialization-interview.html#ixzz3VQxnpOPZ</a></p>\n" }, { "answer_id": 31088833, "author": "schnell18", "author_id": 3061706, "author_profile": "https://Stackoverflow.com/users/3061706", "pm_score": 3, "selected": false, "text": "<p>If you want to amend a huge number of classes which had no serialVersionUID set in the first place while maintain the compatibility with the old classes, tools like IntelliJ Idea, Eclipse fall short as they generate random numbers and does not work on a bunch of files in one go. I come up the following bash script(I'm sorry for Windows users, consider buy a Mac or convert to Linux) to make amending serialVersionUID issue with ease:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>base_dir=$(pwd) \nsrc_dir=$base_dir/src/main/java \nic_api_cp=$base_dir/target/classes \n\nwhile read f \ndo \n clazz=${f//\\//.} \n clazz=${clazz/%.java/} \n seruidstr=$(serialver -classpath $ic_api_cp $clazz | cut -d ':' -f 2 | sed -e 's/^\\s\\+//')\n perl -ni.bak -e \"print $_; printf qq{%s\\n}, q{ private $seruidstr} if /public class/\" $src_dir/$f\ndone\n</code></pre>\n\n<p>you save the this script, say add_serialVersionUID.sh to you ~/bin. Then you run it in the root directory of your Maven or Gradle project like:</p>\n\n<pre><code>add_serialVersionUID.sh &lt; myJavaToAmend.lst\n</code></pre>\n\n<p>This .lst includes the list of java files to add the serialVersionUID in the following format:</p>\n\n<pre><code>com/abc/ic/api/model/domain/item/BizOrderTransDO.java\ncom/abc/ic/api/model/domain/item/CardPassFeature.java\ncom/abc/ic/api/model/domain/item/CategoryFeature.java\ncom/abc/ic/api/model/domain/item/GoodsFeature.java\ncom/abc/ic/api/model/domain/item/ItemFeature.java\ncom/abc/ic/api/model/domain/item/ItemPicUrls.java\ncom/abc/ic/api/model/domain/item/ItemSkuDO.java\ncom/abc/ic/api/model/domain/serve/ServeCategoryFeature.java\ncom/abc/ic/api/model/domain/serve/ServeFeature.java\ncom/abc/ic/api/model/param/depot/DepotItemDTO.java\ncom/abc/ic/api/model/param/depot/DepotItemQueryDTO.java\ncom/abc/ic/api/model/param/depot/InDepotDTO.java\ncom/abc/ic/api/model/param/depot/OutDepotDTO.java\n</code></pre>\n\n<p>This script uses the JDK serialVer tool under hood. So make sure your $JAVA_HOME/bin is in the PATH.</p>\n" }, { "answer_id": 31795462, "author": "Geek", "author_id": 102040, "author_profile": "https://Stackoverflow.com/users/102040", "pm_score": 3, "selected": false, "text": "<p>This question is very well documented in Effective Java by Joshua Bloch. A very good book and a must read. I will outline some of the reasons below :</p>\n\n<p>The serialization runtime comes up with a number called Serial version for each serializable class. This number is called serialVersionUID. Now there is some Math behind this number and it comes out based on the fields/methods that are defined in the class. For the same class the same version is generated every time. This number is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.</p>\n\n<p>If the class is serializable you can also declare your own serialVersionUID explicitly by declaring a field named \"serialVersionUID\" that must be static, final, and of type long. Most IDE's like Eclipse help you generate that long string.</p>\n" }, { "answer_id": 36681325, "author": "Naved Ali", "author_id": 4142806, "author_profile": "https://Stackoverflow.com/users/4142806", "pm_score": 3, "selected": false, "text": "<p>Each time an object is serialized the object is stamped with a version ID number for the object's class.This ID is called <a href=\"https://stackoverflow.com/q/285793/1387612\">serialVersionUID</a> and it is computed based on information about the class structure. Suppose you made an Employee class and it has version id #333 (assigned by JVM),Now when you will serialize the object of that class (Suppose Employee object), JVM will assign UID to it as #333.</p>\n\n<p>Consider a situation - in the future you need to edit or change your class and in that case when you modify it, JVM will assign it a new UID (Suppose #444).\nNow when you try to deserialize the employee object, JVM will compare serialized object's (Employee object) version ID(#333) with that of the class i.e #444(Since it was changed). On comparison JVM will find both version UID are different and hence Deserialization will fail.\nHence if serialVersionID for each class is defined by programmer itself. It will be same even if the class is evolved in future and hence JVM will always find that class is compatible with serialized object even though the class is changed. For more Info you can refer chapter 14 of HEAD FIRST JAVA.</p>\n" }, { "answer_id": 42641080, "author": "roottraveller", "author_id": 5167682, "author_profile": "https://Stackoverflow.com/users/5167682", "pm_score": 4, "selected": false, "text": "<p><strong>Why use <code>SerialVersionUID</code> inside <code>Serializable</code> class in Java?</strong></p>\n\n<p>During <code>serialization</code>, Java runtime creates a version number for a class, so that it can de-serialize it later. This version number is known as <code>SerialVersionUID</code> in Java.</p>\n\n<p><code>SerialVersionUID</code> is used to version serialized data. You can only de-serialize a class if it's <code>SerialVersionUID</code> matches with the serialized instance. When we don't declare <code>SerialVersionUID</code> in our class, Java runtime generates it for us but its not recommended. It's recommended to declare <code>SerialVersionUID</code> as <code>private static final long</code> variable to avoid default mechanism. </p>\n\n<p>When you declare a class as <code>Serializable</code> by implementing marker interface <code>java.io.Serializable</code>, Java runtime persist instance of that class into disk by using default Serialization mechanism, provided you have not customized the process using <code>Externalizable</code> interface.</p>\n\n<p>see also <a href=\"http://javarevisited.blogspot.com/2014/05/why-use-serialversionuid-inside-serializable-class-in-java.html\" rel=\"nofollow noreferrer\">Why use SerialVersionUID inside Serializable class in Java</a></p>\n" }, { "answer_id": 48374672, "author": "JegsVala", "author_id": 3230563, "author_profile": "https://Stackoverflow.com/users/3230563", "pm_score": 6, "selected": false, "text": "<p>First I need to explain what serialization is.</p>\n<p><strong>Serialization</strong> allows to convert an object to a stream, for sending that object over the network OR Save to file OR save into DB for letter usage.</p>\n<p><em><strong>There are some rules for serialization</strong></em>.</p>\n<ul>\n<li><p>An object is serializable only if its class or its superclass implements the Serializable interface</p>\n</li>\n<li><p>An object is serializable (itself implements the Serializable interface) even if its superclass is not. However, the first superclass in the hierarchy of the serializable class, that does not implements Serializable interface, MUST have a no-arg constructor. If this is violated, readObject() will produce a java.io.InvalidClassException in runtime</p>\n</li>\n<li><p>All primitive types are serializable.</p>\n</li>\n<li><p>Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializable must mark transient fields of classes that do not support serialization (e.g., a file stream).</p>\n</li>\n<li><p>Static fields (with static modifier) are not serialized.</p>\n</li>\n</ul>\n<p>When <code>Object</code> is serialized, Java Runtime associates the serial version number aka, the <code>serialVersionID</code>.</p>\n<p><em><strong>Where we need serialVersionID:</strong></em></p>\n<p>During the deserialization to verify that sender and receiver are compatible with respect to serialization. If the receiver loaded the class with a different <code>serialVersionID</code> then deserialization will end with <code>InvalidClassCastException</code>.<br />\nA serializable class can declare its own <code>serialVersionUID</code> explicitly by declaring a field named <code>serialVersionUID</code> that must be static, final, and of type long.</p>\n<p>Let's try this with an example.</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.Serializable;\n\npublic class Employee implements Serializable {\n private static final long serialVersionUID = 1L;\n private String empname;\n private byte empage;\n\n public String getEmpName() {\n return name;\n }\n\n public void setEmpName(String empname) {\n this.empname = empname;\n }\n\n public byte getEmpAge() {\n return empage;\n }\n\n public void setEmpAge(byte empage) {\n this.empage = empage;\n }\n\n public String whoIsThis() {\n return getEmpName() + &quot; is &quot; + getEmpAge() + &quot;years old&quot;;\n }\n}\n</code></pre>\n<p>Create Serialize Object</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectOutputStream;\n\npublic class Writer {\n public static void main(String[] args) throws IOException {\n Employee employee = new Employee();\n employee.setEmpName(&quot;Jagdish&quot;);\n employee.setEmpAge((byte) 30);\n\n FileOutputStream fout = new\n FileOutputStream(&quot;/users/Jagdish.vala/employee.obj&quot;);\n ObjectOutputStream oos = new ObjectOutputStream(fout);\n oos.writeObject(employee);\n oos.close();\n System.out.println(&quot;Process complete&quot;);\n }\n}\n</code></pre>\n<p>Deserialize the object</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\n\npublic class Reader {\n public static void main(String[] args) throws ClassNotFoundException, IOException {\n Employee employee = new Employee();\n FileInputStream fin = new FileInputStream(&quot;/users/Jagdish.vala/employee.obj&quot;);\n ObjectInputStream ois = new ObjectInputStream(fin);\n employee = (Employee) ois.readObject();\n ois.close();\n System.out.println(employee.whoIsThis());\n }\n}\n</code></pre>\n<p>NOTE: Now change the serialVersionUID of the Employee class and save:</p>\n<pre><code>private static final long serialVersionUID = 4L;\n</code></pre>\n<p>And execute the Reader class. Not to execute the Writer class and you will get the exception.</p>\n<pre><code>Exception in thread &quot;main&quot; java.io.InvalidClassException: \ncom.jagdish.vala.java.serialVersion.Employee; local class incompatible: \nstream classdesc serialVersionUID = 1, local class serialVersionUID = 4\nat java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)\nat java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)\nat java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)\nat java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)\nat java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)\nat java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)\nat com.krishantha.sample.java.serialVersion.Reader.main(Reader.java:14)\n</code></pre>\n" }, { "answer_id": 54226923, "author": "gagarwa", "author_id": 3862024, "author_profile": "https://Stackoverflow.com/users/3862024", "pm_score": 2, "selected": false, "text": "<p>A Simple Explanation:</p>\n\n<ol>\n<li><p>Are you serializing data?</p>\n\n<p>Serialization is basically writing class data to a file/stream/etc. De-serialization is reading that data back to a class. </p></li>\n<li><p>Do you intend to go into production?</p>\n\n<p>If you are just testing something with unimportant/fake data, then don't worry about it (unless you are testing serialization directly). </p></li>\n<li><p>Is this the first version?</p>\n\n<p>If so, set <code>serialVersionUID=1L</code>. </p></li>\n<li><p>Is this the second, third, etc. prod version?</p>\n\n<p>Now you need to worry about <code>serialVersionUID</code>, and should look into it in depth.</p></li>\n</ol>\n\n<p>Basically, if you don't update the version correctly when you update a class you need to write/read, you will get an error when you try to read old data.</p>\n" }, { "answer_id": 55693983, "author": "Stanislav Orlov", "author_id": 5580567, "author_profile": "https://Stackoverflow.com/users/5580567", "pm_score": 2, "selected": false, "text": "<p>To tell the long story short this field is used to check if serialized data can be deserialized correctly. Serialization and deserialization are often made by different copies of program - for example server converts object to string and client converts received string to object. This field tells that both operates with same idea about what this object is. This field helps when:</p>\n\n<ul>\n<li><p>you have many different copies of your program in different places (like 1 server and 100 clients). If you will change your object, alter your version number and forget to update one this clients, it will know that he is not capable of deserialization</p></li>\n<li><p>you have stored your data in some file and later on you try to open it with updated version of your program with modified object - you will know that this file is not compatible if you keep your version right</p></li>\n</ul>\n\n<p>When is it important? </p>\n\n<p>Most obvious - if you add some fields to your object, older versions will not be able to use them because they do not have these fields in their object structure.</p>\n\n<p>Less obvious - When you deserialize object, fields that where not present in string will be kept as NULL. If you have removed field from your object, older versions will keep this field as allways-NULL that can lead to misbehavior if older versions rely on data in this field (anyway you have created it for something, not just for fun :-) ) </p>\n\n<p>Least obvious - Sometimes you change the idea you put in some field's meaning. For example when you are 12 years old you mean \"bicycle\" under \"bike\", but when you are 18 you mean \"motorcycle\" - if your friends will invite you to \"bike ride across city\" and you will be the only one who came on bicycle, you will undestand how important it is to keep same meaning across fields :-)</p>\n" }, { "answer_id": 55897241, "author": "Shanks D Shiva", "author_id": 11004892, "author_profile": "https://Stackoverflow.com/users/11004892", "pm_score": 2, "selected": false, "text": "<p>Firstly to answer your question, when we don't declare SerialVersionUID in our class, Java runtime generates it for us, but that process is sensitive to many class meta data including number of fields, type of fields, access modifier of fields, interface implemented by class etc. Therefore it is recommended to declare it ourselves and Eclipse is warning you about the same.</p>\n\n<p>Serialization:\nWe often work with important objects whose state (data in the variables of the object) is so important that we can not risk to lose it due to power/system failures (or) network failures in case of sending the object state to other machine. The solution for this problem is named \"Persistence\" which simply means persisting (holding/saving) the data. Serialization is one of many other ways to achieve persistence (by saving data to disk/memory). When saving the state of the object, it is important to create an identity for the object, to be able to properly read it back (de-serialization). This unique identification is ID is SerialVersionUID. </p>\n" }, { "answer_id": 59826166, "author": "Hari Krishna", "author_id": 3302424, "author_profile": "https://Stackoverflow.com/users/3302424", "pm_score": 2, "selected": false, "text": "<p>'serialVersionUID' is a 64 bit number used to uniquely identify a class during deserialization process. When you serialize an object, serialVersionUID of the class also written to the file. Whenever you deserialize this object, java run time extract this serialVersionUID value from the serialized data and compare the same value associate with the class. If both do not match, then 'java.io.InvalidClassException' will be thrown.</p>\n\n<p>If a serializable class do not explicitly declare a serialVersionUID, then serialization runtime will calculate serialVersionUID value for that class based on various aspects of the class like fields, methods etc.,, You can refer this <a href=\"https://self-learning-java-tutorial.blogspot.com/2014/09/serialversionuid.html\" rel=\"nofollow noreferrer\">link</a> for demo application.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
Eclipse issues warnings when a `serialVersionUID` is missing. > > The serializable class Foo does not declare a static final > serialVersionUID field of type long > > > What is `serialVersionUID` and why is it important? Please show an example where missing `serialVersionUID` will cause a problem.
The docs for [`java.io.Serializable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html) are probably about as good an explanation as you'll get: > > The serialization runtime associates with each serializable class a version number, called a `serialVersionUID`, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different `serialVersionUID` than that of the corresponding sender's class, then deserialization will result in an > [`InvalidClassException`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InvalidClassException.html). A serializable class can declare its own `serialVersionUID` explicitly by declaring a field named `serialVersionUID` that must be static, final, and of type `long`: > > > > > > ``` > ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; > > ``` > > > > If a serializable class does not explicitly declare a `serialVersionUID`, then the serialization runtime will calculate a default `serialVersionUID` value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is *strongly recommended* that all serializable classes explicitly declare `serialVersionUID` values, since the default `serialVersionUID` computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected `InvalidClassExceptions` during deserialization. Therefore, to guarantee a consistent `serialVersionUID` value across different java compiler implementations, a serializable class must declare an explicit `serialVersionUID` value. It is also strongly advised that explicit `serialVersionUID` declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class — `serialVersionUID` fields are not useful as inherited members. > > >
285,816
<p>I want to add items in a LaTeX-document. Say for example, that I want add hints to the document. I create a command, so I can call something similar to this:</p> <pre><code>\hint{foocareful}{Be careful with foo!}{foo is a very precious item and can easily be broken. Be careful, especially don't throw foo.} </code></pre> <p>This will be formatted in special way, to make it easy for the reader to recognize it as a hint. It gets a label, that can be referenced in the example with 'foocareful'.</p> <p>In the appendix I want to add a list of all hints with references to them. Something like:</p> <pre><code>\begin{enumerate} ... \item Be careful with foo! (\pageref{foocareful}) ... \end{enumerate} </code></pre> <p>But naturally I don't want to maintain this list by hand. How can I create automatically such a list?</p>
[ { "answer_id": 285998, "author": "coryan", "author_id": 33325, "author_profile": "https://Stackoverflow.com/users/33325", "pm_score": 2, "selected": false, "text": "<p>Have not done this in years, but I would look at the LaTeX source code for \\tableofcontents and \\listoffigures. I think the mechanism is generic and you can expand it to include your own lists.</p>\n" }, { "answer_id": 286165, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 4, "selected": true, "text": "<p>One way to do it is to use the <code>float</code> package. I think that, at least, the <code>floatrow</code> package can also do what you want, and may also be more flexible. See you go, though.</p>\n\n<p>Here's an example of something like you're trying to do using <code>float</code>:</p>\n\n<pre><code>\\documentclass{article}\n\\usepackage{float}\n\n\\floatstyle{boxed}\n\\newfloat{hintbox}{H}{hnt}\n\\floatname{hintbox}{Hint}\n\n\\newcommand\\hint[2]{%\n \\begin{hintbox}\n #2\n \\caption{#1}\n \\end{hintbox}}\n\n\\begin{document}\n\\section{Hello}\n\n\\hint{Be careful with foo!\\label{foocareful}}{%\n foo is a very precious item and can easily be broken. \n Be careful, especially don't throw foo.}\n\n\\hint{Don't worry about bar!\\label{foocareful}}{%\n Unlike foo, bar is pretty easily to get along with.}\n\n\\section{End}\n\n\\listof{hintbox}{List of Hints}\n\n\\end{document}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
I want to add items in a LaTeX-document. Say for example, that I want add hints to the document. I create a command, so I can call something similar to this: ``` \hint{foocareful}{Be careful with foo!}{foo is a very precious item and can easily be broken. Be careful, especially don't throw foo.} ``` This will be formatted in special way, to make it easy for the reader to recognize it as a hint. It gets a label, that can be referenced in the example with 'foocareful'. In the appendix I want to add a list of all hints with references to them. Something like: ``` \begin{enumerate} ... \item Be careful with foo! (\pageref{foocareful}) ... \end{enumerate} ``` But naturally I don't want to maintain this list by hand. How can I create automatically such a list?
One way to do it is to use the `float` package. I think that, at least, the `floatrow` package can also do what you want, and may also be more flexible. See you go, though. Here's an example of something like you're trying to do using `float`: ``` \documentclass{article} \usepackage{float} \floatstyle{boxed} \newfloat{hintbox}{H}{hnt} \floatname{hintbox}{Hint} \newcommand\hint[2]{% \begin{hintbox} #2 \caption{#1} \end{hintbox}} \begin{document} \section{Hello} \hint{Be careful with foo!\label{foocareful}}{% foo is a very precious item and can easily be broken. Be careful, especially don't throw foo.} \hint{Don't worry about bar!\label{foocareful}}{% Unlike foo, bar is pretty easily to get along with.} \section{End} \listof{hintbox}{List of Hints} \end{document} ```
285,818
<p>With Java Version 1.5.0_06 on both Windows and Ubuntu Linux :</p> <p>Whenever I add minutes to the date "2008/10/05 00:00:00" , it seems that an extra hour is wrongly added.</p> <p>ie: adding 360 minutes to 2008/10/05 00:00:00 at midnight should arrive at 2008/10/05 06:00:00</p> <p>But it is arriving at 2008/10/05 07:00:00</p> <p>The totally perplexing thing is that this <strong>ONLY</strong> happens when the day is 2008/10/05, all other days that I try perform the minutes addition correctly. </p> <p>Am I going crazy or is this a bug in Java ?</p> <pre><code> SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { String date = "2008/10/05 00:00:00"; int minutesToAdd = 360; // 6 hrs Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(date)); cal.add(Calendar.MINUTE, minutesToAdd); System.out.println(cal.getTime()); } catch (ParseException e) {} </code></pre>
[ { "answer_id": 285822, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p>There's a crossover to daylight savings on that day.</p>\n\n<p>Are you in New Zealand? If so, that means your timezone files are out of date. Better go to the Java download site and download new ones; look for \"JDK DST Timezone Update Tool\".</p>\n" }, { "answer_id": 285825, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>Could this be daylight savings kicking in?</p>\n" }, { "answer_id": 286498, "author": "DaWilli", "author_id": 33974, "author_profile": "https://Stackoverflow.com/users/33974", "pm_score": 1, "selected": false, "text": "<p>Take a look at <a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow noreferrer\">Joda-Time</a>.</p>\n\n<p>From the Documentation:</p>\n\n<p><em>\"Joda-Time has been created to radically change date and time handling in Java. The JDK classes Date and Calendar are very badly designed, have had numerous bugs and have odd performance effects.\"</em></p>\n" }, { "answer_id": 68963768, "author": "Ole V.V.", "author_id": 5772882, "author_profile": "https://Stackoverflow.com/users/5772882", "pm_score": 0, "selected": false, "text": "<h2>java.time</h2>\n<p>I recommend that you use java.time, the modern Java date and time API, for your date and time work (you reported using Java 1.5 back in 2008, before the advent of java.time, but I hope that you aren’t anymore). java.time can be considered the successor of the Joda-Time library that Willi aus Rohr mentions in his answer.</p>\n<p>Let’s first define a formatter for parsing:</p>\n<pre><code>private static final DateTimeFormatter PARSER\n = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm:ss&quot;, Locale.ROOT);\n</code></pre>\n<p>Now to parse your string and add 360 minutes:</p>\n<pre><code> String date = &quot;2008/10/05 00:00:00&quot;;\n int minutesToAdd = 360; // 6 hrs\n \n ZonedDateTime originalTime = LocalDateTime.parse(date, PARSER)\n .atZone(ZoneId.of(&quot;Pacific/Auckland&quot;));\n ZonedDateTime newTime = originalTime.plusMinutes(minutesToAdd);\n \n System.out.println(newTime);\n</code></pre>\n<p>Output on my Java 11:</p>\n<blockquote>\n<p>2008-10-05T06:00+13:00[Pacific/Auckland]</p>\n</blockquote>\n<p>6 hours have been correctly added. You notice that a <code>ZonedDateTime</code> also print its UTC offset, here +13:00, so should you have an out-of-date time zone database in your Java installation, you also have a chance of seeing that the offset was not as expected.</p>\n<p>If you want to add whole hours, prefer the <code>plusHours</code> method over <code>plusMinutes</code>.</p>\n<h2>Link</h2>\n<p><a href=\"https://docs.oracle.com/javase/tutorial/datetime/\" rel=\"nofollow noreferrer\">Oracle tutorial: Date Time</a> explaining how to use java.time.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27262/" ]
With Java Version 1.5.0\_06 on both Windows and Ubuntu Linux : Whenever I add minutes to the date "2008/10/05 00:00:00" , it seems that an extra hour is wrongly added. ie: adding 360 minutes to 2008/10/05 00:00:00 at midnight should arrive at 2008/10/05 06:00:00 But it is arriving at 2008/10/05 07:00:00 The totally perplexing thing is that this **ONLY** happens when the day is 2008/10/05, all other days that I try perform the minutes addition correctly. Am I going crazy or is this a bug in Java ? ``` SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { String date = "2008/10/05 00:00:00"; int minutesToAdd = 360; // 6 hrs Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(date)); cal.add(Calendar.MINUTE, minutesToAdd); System.out.println(cal.getTime()); } catch (ParseException e) {} ```
There's a crossover to daylight savings on that day. Are you in New Zealand? If so, that means your timezone files are out of date. Better go to the Java download site and download new ones; look for "JDK DST Timezone Update Tool".
285,829
<p>I'd like to use the DataGridView control as a list with columns. Sort of like ListView in Details mode but I want to keep the DataGridView flexibility.</p> <p><strong>ListView</strong> (with <em>Details</em> view and <em>FullRowSelect</em> enabled) highlights the whole line and shows the focus mark around the whole line:<br> <img src="https://i361.photobucket.com/albums/oo51/Stark3000/ListView_row.png" alt="selected row in ListView control"></p> <p><strong>DataGridView</strong> (with <em>SelectionMode</em> = <em>FullRowSelect</em>) displays focus mark only around a single cell:<br> <img src="https://i361.photobucket.com/albums/oo51/Stark3000/DataGridView_row.png" alt="selected row in DataGridView"></p> <p>So, does anyone know of some (ideally) easy way to make the DataGridView row selection look like the ListView one?<br> I'm not looking for a changed behaviour of the control - I only want it to look the same.<br> Ideally, without messing up with the methods that do the actual painting.</p>
[ { "answer_id": 331438, "author": "Tomas Sedovic", "author_id": 2239, "author_profile": "https://Stackoverflow.com/users/2239", "pm_score": 7, "selected": true, "text": "<p>Put this code either into your form's constructor or set it in datagridview's <em>Properties</em> using the IDE.</p>\n\n<pre><code>dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\ndgv.MultiSelect = false;\ndgv.RowPrePaint +=new DataGridViewRowPrePaintEventHandler(dgv_RowPrePaint);\n</code></pre>\n\n<p>Then paste the following event into the form code:</p>\n\n<pre><code>private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)\n{\n e.PaintParts &amp;= ~DataGridViewPaintParts.Focus;\n}\n</code></pre>\n\n<p>And it works! :-) </p>\n\n<p>\"dgv\" is the <em>DataGridView</em> in question and \"form\" is the <em>Form</em> that contains it.</p>\n\n<p>Note, that this soulution doesn't display the dotted rectangle around the whole row. Instead, it removes the focus dots entirely.</p>\n" }, { "answer_id": 8304512, "author": "L.E.", "author_id": 205291, "author_profile": "https://Stackoverflow.com/users/205291", "pm_score": 5, "selected": false, "text": "<p>How about</p>\n\n<pre><code>SelectionMode == FullRowSelect\n</code></pre>\n\n<p>and </p>\n\n<pre><code>ReadOnly == true\n</code></pre>\n\n<p>It works for me.</p>\n" }, { "answer_id": 67304346, "author": "igorsp7", "author_id": 8239268, "author_profile": "https://Stackoverflow.com/users/8239268", "pm_score": 0, "selected": false, "text": "<p>If you want the focus rectangle to be around the entire row rather than the single cell, you can use the below code.\nIt assumes that your DataGridView is named gvMain and that it has SelectionMode set to FullRowSelect and MultiSelect set to False.</p>\n<pre><code>private void gvMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)\n{\n // Draw our own focus rectangle around the entire row\n if (gvMain.Rows[e.RowIndex].Selected &amp;&amp; gvMain.Focused) \n ControlPaint.DrawFocusRectangle(e.Graphics, e.RowBounds, Color.Empty, gvMain.DefaultCellStyle.SelectionBackColor);\n}\n\nprivate void gvMain_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)\n{\n // Disable the original focus rectangle around the cell\n e.PaintParts &amp;= ~DataGridViewPaintParts.Focus;\n}\n\nprivate void gvMain_LeaveAndEnter(object sender, EventArgs e)\n{\n // Redraw our focus rectangle every time our DataGridView receives and looses focus (same event handler for both events)\n gvMain.InvalidateRow(gvMain.CurrentRow.Index);\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2239/" ]
I'd like to use the DataGridView control as a list with columns. Sort of like ListView in Details mode but I want to keep the DataGridView flexibility. **ListView** (with *Details* view and *FullRowSelect* enabled) highlights the whole line and shows the focus mark around the whole line: ![selected row in ListView control](https://i361.photobucket.com/albums/oo51/Stark3000/ListView_row.png) **DataGridView** (with *SelectionMode* = *FullRowSelect*) displays focus mark only around a single cell: ![selected row in DataGridView](https://i361.photobucket.com/albums/oo51/Stark3000/DataGridView_row.png) So, does anyone know of some (ideally) easy way to make the DataGridView row selection look like the ListView one? I'm not looking for a changed behaviour of the control - I only want it to look the same. Ideally, without messing up with the methods that do the actual painting.
Put this code either into your form's constructor or set it in datagridview's *Properties* using the IDE. ``` dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dgv.MultiSelect = false; dgv.RowPrePaint +=new DataGridViewRowPrePaintEventHandler(dgv_RowPrePaint); ``` Then paste the following event into the form code: ``` private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) { e.PaintParts &= ~DataGridViewPaintParts.Focus; } ``` And it works! :-) "dgv" is the *DataGridView* in question and "form" is the *Form* that contains it. Note, that this soulution doesn't display the dotted rectangle around the whole row. Instead, it removes the focus dots entirely.
285,860
<p>Using Java, how can I test that a URL is contactable, and returns a valid response?</p> <pre><code>http://stackoverflow.com/about </code></pre>
[ { "answer_id": 285862, "author": "brasskazoo", "author_id": 6340, "author_profile": "https://Stackoverflow.com/users/6340", "pm_score": 7, "selected": true, "text": "<p>The solution as a unit test:</p>\n\n<pre><code>public void testURL() throws Exception {\n String strUrl = \"http://stackoverflow.com/about\";\n\n try {\n URL url = new URL(strUrl);\n HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();\n urlConn.connect();\n\n assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());\n } catch (IOException e) {\n System.err.println(\"Error creating HTTP connection\");\n e.printStackTrace();\n throw e;\n }\n}\n</code></pre>\n" }, { "answer_id": 285872, "author": "John T", "author_id": 36457, "author_profile": "https://Stackoverflow.com/users/36457", "pm_score": 3, "selected": false, "text": "<p>Since java 5 if i recall, the InetAdress class contains a method called isReachable(); so you can use it to make a ping implementation in java. You can also specify a timeout for this method. This is just another alternative to the unit test method posted above, which is probably more efficient.</p>\n" }, { "answer_id": 6452098, "author": "Charif", "author_id": 811943, "author_profile": "https://Stackoverflow.com/users/811943", "pm_score": -1, "selected": false, "text": "<pre><code>import org.apache.commons.validator.UrlValidator;\n\npublic class ValidateUrlExample {\n\n public static void main(String[] args) {\n\n UrlValidator urlValidator = new UrlValidator();\n\n //valid URL\n if (urlValidator.isValid(\"http://www.mkyong.com\")) {\n System.out.println(\"url is valid\");\n } else {\n System.out.println(\"url is invalid\");\n }\n\n //invalid URL\n if (urlValidator.isValid(\"http://invalidURL^$&amp;%$&amp;^\")) {\n System.out.println(\"url is valid\");\n } else {\n System.out.println(\"url is invalid\");\n }\n }\n}\n</code></pre>\n\n<p>Output: </p>\n\n<pre>\nurl is valid\nurl is invalid\n</pre>\n\n<p>source : <a href=\"http://www.mkyong.com/java/how-to-validate-url-in-java/\" rel=\"nofollow\">http://www.mkyong.com/java/how-to-validate-url-in-java/</a></p>\n" }, { "answer_id": 61655279, "author": "Sam Ginrich", "author_id": 9437799, "author_profile": "https://Stackoverflow.com/users/9437799", "pm_score": 0, "selected": false, "text": "<pre><code>System.out.println(new InetSocketAddress(\"http://stackoverflow.com/about\", 80).isUnresolved());\n</code></pre>\n\n<p>delivers <em>false</em> if page is reachable, which is a precondition.</p>\n\n<p>In order to cover initial question completely, you need to implement a <em>http get</em> or <em>post</em>.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
Using Java, how can I test that a URL is contactable, and returns a valid response? ``` http://stackoverflow.com/about ```
The solution as a unit test: ``` public void testURL() throws Exception { String strUrl = "http://stackoverflow.com/about"; try { URL url = new URL(strUrl); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode()); } catch (IOException e) { System.err.println("Error creating HTTP connection"); e.printStackTrace(); throw e; } } ```
285,866
<p>I want to create an Ant buildfile, that includes some files as a sort of plugin.</p> <p>So if I want to activate a feature in a project - say pmd-checking - I copy a pmd.xml in a directory and the build.xml get on the start the idea, that pmd.xml exists and imports it, so that new targets can be available to the build.</p> <p>But the 'import' task can only be used as a top-level task, so I have no idea how to relize this functionality. Is this possible with Ant and if so, how can I do it?</p> <p>EDIT: I would prefer a solution, that allows new targets to show up in the listing presented by <code>ant -p</code>.</p>
[ { "answer_id": 285951, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"http://ant.apache.org/manual/Tasks/ant.html\" rel=\"nofollow noreferrer\"><strong>ant</strong></a> task and even parameterize the target name. Here's an example:</p>\n\n<pre><code>&lt;ant antfile=\"plugins/pmd.xml\" target=\"${pmd-target}\"/&gt;\n</code></pre>\n\n<p>If you want more flexibility, I recommend checking <a href=\"http://gant.codehaus.org/\" rel=\"nofollow noreferrer\">gant</a> or <a href=\"http://www.gradle.org/\" rel=\"nofollow noreferrer\">gradle</a>.</p>\n" }, { "answer_id": 286008, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>I'm not sure want you want is conceptually possible. The <code>-p</code> command-line argument doesn't execute any tasks, it just parses the file. What you want would require something to be executed.</p>\n\n<p>But, I'd give the <a href=\"http://ant-contrib.sourceforge.net/\" rel=\"nofollow noreferrer\">ant-contrib</a> project a look. It has a conditional <a href=\"http://ant-contrib.sourceforge.net/tasks/tasks/if.html\" rel=\"nofollow noreferrer\"><code>&lt;if&gt;</code></a> task, which might make the top-level import work only when you want it to.</p>\n" }, { "answer_id": 286106, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>In the documentation for the <a href=\"http://ant.apache.org/manual/Tasks/import.html\" rel=\"nofollow noreferrer\">import</a> task, note the <code>optional</code> attribute. Set this to <code>true</code> and missing includes won't break the build.</p>\n\n<p>So <code>pmd.xml</code> is included if found, but won't break the build if it isn't.</p>\n\n<p>Not tested, so I'm not positive about <code>ant -p</code> including targets in the imported file if it is found.</p>\n" }, { "answer_id": 4639766, "author": "martin clayton", "author_id": 183172, "author_profile": "https://Stackoverflow.com/users/183172", "pm_score": 3, "selected": true, "text": "<p>It's not explicitly stated in the import task documentation, but the task accepts a fileset as an alternative to a single file.\nHence this, at the top level, should do the trick, and targets created are listed by <code>ant -p</code>:</p>\n\n<pre><code>&lt;property name=\"plugins.dir\" value=\"plugins\" /&gt;\n&lt;fileset id=\"plugin.modules\" dir=\"${plugins.dir}\"&gt;\n &lt;include name=\"**/*.xml\" /&gt;\n&lt;/fileset&gt;\n\n&lt;import&gt;\n &lt;fileset refid=\"plugin.modules\" /&gt;\n&lt;/import&gt;\n</code></pre>\n\n<p>One wrinkle with this is that there must be at least one plug-in in the 'plugins' directory, or the import will fail.\nYou can just create a placeholder file - say called <code>empty.xml</code>:</p>\n\n<pre><code> &lt;project /&gt;\n</code></pre>\n\n<p>Once that's there, you just need to put any new plug-ins in the plugin directory, and they will be imported by future builds.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
I want to create an Ant buildfile, that includes some files as a sort of plugin. So if I want to activate a feature in a project - say pmd-checking - I copy a pmd.xml in a directory and the build.xml get on the start the idea, that pmd.xml exists and imports it, so that new targets can be available to the build. But the 'import' task can only be used as a top-level task, so I have no idea how to relize this functionality. Is this possible with Ant and if so, how can I do it? EDIT: I would prefer a solution, that allows new targets to show up in the listing presented by `ant -p`.
It's not explicitly stated in the import task documentation, but the task accepts a fileset as an alternative to a single file. Hence this, at the top level, should do the trick, and targets created are listed by `ant -p`: ``` <property name="plugins.dir" value="plugins" /> <fileset id="plugin.modules" dir="${plugins.dir}"> <include name="**/*.xml" /> </fileset> <import> <fileset refid="plugin.modules" /> </import> ``` One wrinkle with this is that there must be at least one plug-in in the 'plugins' directory, or the import will fail. You can just create a placeholder file - say called `empty.xml`: ``` <project /> ``` Once that's there, you just need to put any new plug-ins in the plugin directory, and they will be imported by future builds.
285,869
<p>Does anyone know how to use the <a href="http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx" rel="nofollow noreferrer">Raw Input</a> facility on Windows from a WX Python application?</p> <p>What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.</p>
[ { "answer_id": 307018, "author": "joeforker", "author_id": 36330, "author_profile": "https://Stackoverflow.com/users/36330", "pm_score": 3, "selected": true, "text": "<p>Have you tried using ctypes?</p>\n\n<pre><code>&gt;&gt;&gt; import ctypes\n&gt;&gt;&gt; ctypes.windll.user32.RegisterRawInputDevices\n&lt;_FuncPtr object at 0x01FCFDC8&gt;\n</code></pre>\n\n<p>It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.</p>\n" }, { "answer_id": 467729, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Theres a nice looking library here\n<a href=\"http://code.google.com/p/pymultimouse/\" rel=\"nofollow noreferrer\">http://code.google.com/p/pymultimouse/</a></p>\n\n<p>It's not wx-python specific - but it does use raw input in python with ctypes (and worked in my test with 2 mice)</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/285869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10286/" ]
Does anyone know how to use the [Raw Input](http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx) facility on Windows from a WX Python application? What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.
Have you tried using ctypes? ``` >>> import ctypes >>> ctypes.windll.user32.RegisterRawInputDevices <_FuncPtr object at 0x01FCFDC8> ``` It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.
285,889
<p>I want to create a file on the webserver dynamically in PHP.</p> <p>First I create a directory to store the file. THIS WORKS</p> <pre><code>// create the users directory and index page $dirToCreate = "..".$_SESSION['s_USER_URL']; mkdir($dirToCreate, 0777, TRUE); // create the directory for the user </code></pre> <p>Now I want to create a file called index.php and write out some content into it.</p> <p>I am trying:</p> <pre><code>$ourFileName = $_SESSION['s_USER_URL']."/"."index.php"; $ourFileHandle = fopen($ourFileName, 'x') or die("can't open file"); fclose($ourFileHandle); // append data to it $ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file"); $stringData = "Hi"; fwrite($ourFileHandle, $stringData); </code></pre> <p>But it never gets past the <code>$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");</code> Saying the file does not exist, but that is the point. I want to create it.</p> <p>I did some echoing and the path (/people/jason) exists and I am trying to write to /people/jason/index.php</p> <p>Does anyone have any thoughts on what I am doing wrong? </p> <p>PHP 5 on a linux server I believe.</p> <p>-Jason</p>
[ { "answer_id": 285900, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<p>It could be a result of one of your php ini settings, or possibly an apache security setting. </p>\n\n<p>Try creating the dir as only rwxr-x--- and see how that goes. </p>\n\n<p>I recall a shared hosting setup where \"safemode\" was compiled in and this behaviour tended to occur, basically, if the files/dirs were writable by too many people they would magically stop being acessible. </p>\n\n<p>Its probably doc'd in php, but ill have to check.</p>\n" }, { "answer_id": 285905, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 4, "selected": true, "text": "<p>First you do :</p>\n\n<pre><code>$dirToCreate = \"..\".$_SESSION['s_USER_URL']; \n</code></pre>\n\n<p>But the filename you try to write to is not prefixed with the '..', so try changing</p>\n\n<pre><code>$ourFileName = $_SESSION['s_USER_URL'].\"/\".\"index.php\";\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';\n</code></pre>\n\n<p>or probably tidier:</p>\n\n<pre><code>$ourFileName = $dirToCreate . '/index.php';\n</code></pre>\n\n<p>You are probably getting the warning because the directory you are trying to write the file into does not exist</p>\n" }, { "answer_id": 285906, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "<p>why not use:</p>\n\n<pre><code>file_put_contents( $filename, $content )\n</code></pre>\n\n<p>or you could <code>touch</code> the file before writing to it.</p>\n" }, { "answer_id": 285909, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 0, "selected": false, "text": "<p>Does the file 'index.php' already exist? When you fopen with the 'x' mode, if the file exists fopen will return FALSE and trigger a warning.</p>\n" }, { "answer_id": 286114, "author": "John T", "author_id": 36457, "author_profile": "https://Stackoverflow.com/users/36457", "pm_score": 0, "selected": false, "text": "<p>What i first noticed is you are making a directory higher in the tree, then attempting to make the php file in the current folder. Correct me if i'm wrong, but aren't you trying to make the file in the new created folder? if i recall php correctly (pardon me it's been a while, i'll probably add something from another language in here not noticing) here is an easier to understand way for a beginner, of course change the values accordingly, this simply makes a directory and makes a file then sets permissions.</p>\n\n<pre><code>&lt;?php\n\n$path = \"..\".$_SESSION['s_USER_URL']; \n// may want to add a tilde (~) to user directory\n// path, unixy thing to do ;D\n\nmkdir($path, 0777); // make directory, set perms.\n\n$file = \"index.php\"; // declare a file name\n\n/* here you could use the chdir() command, if you wanted to go to the \ndirectory where you created the file, this will help you understand the \nrest of your code as you will have to perform less concatenation on\n directories such as below */\n\n$handle = fopen($path.\"/\".$file, 'w') or die(\"can't open file\");\n// open file for writing, create if it doesn't exist\n\n$info = \"Stack Overflow was here!\"; // string to input\n\nfwrite($handle, $info); // perform the write operation\n\nfclose($handle); // close the handle\n\n?&gt;\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/285889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to create a file on the webserver dynamically in PHP. First I create a directory to store the file. THIS WORKS ``` // create the users directory and index page $dirToCreate = "..".$_SESSION['s_USER_URL']; mkdir($dirToCreate, 0777, TRUE); // create the directory for the user ``` Now I want to create a file called index.php and write out some content into it. I am trying: ``` $ourFileName = $_SESSION['s_USER_URL']."/"."index.php"; $ourFileHandle = fopen($ourFileName, 'x') or die("can't open file"); fclose($ourFileHandle); // append data to it $ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file"); $stringData = "Hi"; fwrite($ourFileHandle, $stringData); ``` But it never gets past the `$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");` Saying the file does not exist, but that is the point. I want to create it. I did some echoing and the path (/people/jason) exists and I am trying to write to /people/jason/index.php Does anyone have any thoughts on what I am doing wrong? PHP 5 on a linux server I believe. -Jason
First you do : ``` $dirToCreate = "..".$_SESSION['s_USER_URL']; ``` But the filename you try to write to is not prefixed with the '..', so try changing ``` $ourFileName = $_SESSION['s_USER_URL']."/"."index.php"; ``` to ``` $ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php'; ``` or probably tidier: ``` $ourFileName = $dirToCreate . '/index.php'; ``` You are probably getting the warning because the directory you are trying to write the file into does not exist
285,928
<pre><code> private void activateRecords(long[] stuff) { ... api.activateRecords(Arrays.asList(specIdsToActivate)); } </code></pre> <p>Shouldn't this call to Arrays.asList return a list of <code>Long</code>s? Instead it is returning a <code>List&lt;long[]&gt;</code></p> <pre><code>public static &lt;T&gt; List&lt;T&gt; asList(T... a) </code></pre> <p>The method signature is consistent with the results, the varargs throws the entire array into the list. It's the same as <code>new ArrayList(); list.add(myArray)</code> And yes, I know it's meant to be used like this: <code>Arrays.asList(T t1, T t2, T t3)</code></p> <p>I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list? Any other <strong>clean</strong> way of doing this?</p>
[ { "answer_id": 285947, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 4, "selected": true, "text": "<p>That's because long[] and Long[] are different types.</p>\n\n<p>In the first case T is long[], in the second T is Long.</p>\n\n<p>How to fix this? Don't use long[] in the first place?</p>\n" }, { "answer_id": 285969, "author": "Stephen", "author_id": 37193, "author_profile": "https://Stackoverflow.com/users/37193", "pm_score": 3, "selected": false, "text": "<p>Autoboxing cannot be done on arrays. You are allowed to do:</p>\n\n<pre><code>private List&lt;Long&gt; array(final long[] lngs) {\n List&lt;Long&gt; list = new ArrayList&lt;Long&gt;();\n for (long l : lngs) {\n list.add(l);\n }\n return list;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>private List&lt;Long&gt; array(final long[] lngs) {\n List&lt;Long&gt; list = new ArrayList&lt;Long&gt;();\n for (Long l : lngs) {\n list.add(l);\n }\n return list;\n}\n</code></pre>\n\n<p>(notice that the iterable types are different)</p>\n\n<p>e.g.</p>\n\n<pre><code>Long l = 1l;\n</code></pre>\n\n<p>but not</p>\n\n<pre><code>Long[] ls = new long[]{1l}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/285928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402777/" ]
``` private void activateRecords(long[] stuff) { ... api.activateRecords(Arrays.asList(specIdsToActivate)); } ``` Shouldn't this call to Arrays.asList return a list of `Long`s? Instead it is returning a `List<long[]>` ``` public static <T> List<T> asList(T... a) ``` The method signature is consistent with the results, the varargs throws the entire array into the list. It's the same as `new ArrayList(); list.add(myArray)` And yes, I know it's meant to be used like this: `Arrays.asList(T t1, T t2, T t3)` I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list? Any other **clean** way of doing this?
That's because long[] and Long[] are different types. In the first case T is long[], in the second T is Long. How to fix this? Don't use long[] in the first place?
285,937
<p>Is it possible to insert a row, but only if one of the values already in the table does not exist?</p> <p>I'm creating a <em>Tell A Friend</em> with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.</p> <p>I'm using PHP 4 and MySql 4.1.</p>
[ { "answer_id": 285953, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if I got it, but what about a</p>\n\n<pre><code>try {\n mysql_query($sql);\n}\ncatch(Exception $e) {\n\n}\n</code></pre>\n\n<p>combined with an unique field index in MySQL?</p>\n\n<p>if it throws an exception then you know that you got a duplicated field.\nSorry if that don't answer your question..</p>\n" }, { "answer_id": 285954, "author": "Feet", "author_id": 18340, "author_profile": "https://Stackoverflow.com/users/18340", "pm_score": 0, "selected": false, "text": "<p>If the email field was the primary key then the constraints on the table would stop a duplicate from being entered.</p>\n" }, { "answer_id": 285957, "author": "victoriah", "author_id": 37014, "author_profile": "https://Stackoverflow.com/users/37014", "pm_score": 5, "selected": true, "text": "<p>If the column is a primary key or a unique index:</p>\n\n<pre><code>INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE\nemail=email_address\n</code></pre>\n\n<p>Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of \"ON DUPLICATE KEY DO NOTHING\" in MySQL. I'm not sure about the email=email_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.</p>\n" }, { "answer_id": 285964, "author": "Gene", "author_id": 35630, "author_profile": "https://Stackoverflow.com/users/35630", "pm_score": 3, "selected": false, "text": "<p>Most likely something like:</p>\n\n<pre><code>IF NOT EXISTS(SELECT * FROM myTable WHERE Email=@Email) THEN INSERT INTO blah blah\n</code></pre>\n\n<p>That can be rolled into one database query.</p>\n" }, { "answer_id": 285980, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 5, "selected": false, "text": "<p>This works if you have a unique index or primary key on the column (EmailAddr in this example):</p>\n\n<pre><code>INSERT IGNORE INTO Table (EmailAddr) VALUES ('[email protected]')\n</code></pre>\n\n<p>Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.</p>\n\n<p>See the <a href=\"http://dev.mysql.com/doc/refman/4.1/en/insert.html\" rel=\"noreferrer\">MySql docs</a> for more information.</p>\n" }, { "answer_id": 287049, "author": "Peter Howe", "author_id": 24106, "author_profile": "https://Stackoverflow.com/users/24106", "pm_score": 1, "selected": false, "text": "<p>MySQL offers <a href=\"http://dev.mysql.com/doc/refman/5.0/en/replace.html\" rel=\"nofollow noreferrer\">REPLACE INTO http://dev.mysql.com/doc/refman/5.0/en/replace.html</a>:</p>\n\n<blockquote>\n <p>REPLACE works exactly like INSERT,\n except that if an old row in the table\n has the same value as a new row for a\n PRIMARY KEY or a UNIQUE index, the\n old row is deleted before the new row\n is inserted.</p>\n</blockquote>\n" }, { "answer_id": 903006, "author": "mttmllns", "author_id": 110926, "author_profile": "https://Stackoverflow.com/users/110926", "pm_score": 2, "selected": false, "text": "<p>A slight modification/addition to naeblis's answer:</p>\n\n<pre><code>INSERT INTO table (email) VALUES (email_address)\nON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)\n</code></pre>\n\n<p>This way you don't have to throw <code>email=email_address</code> in there <strong>and</strong> you get the correct value for <code>LAST_INSERT_ID()</code> if the statement updates.</p>\n\n<p><em>Source:</em> MySQL Docs: 12.2.5.3</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/285937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
Is it possible to insert a row, but only if one of the values already in the table does not exist? I'm creating a *Tell A Friend* with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table. I'm using PHP 4 and MySql 4.1.
If the column is a primary key or a unique index: ``` INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE email=email_address ``` Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email\_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.
285,938
<p>Given an HTML link like</p> <pre><code>&lt;a href="urltxt" class="someclass" close="true"&gt;texttxt&lt;/a&gt; </code></pre> <p>how can I isolate the url and the text? </p> <p><strong>Updates</strong></p> <p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p> <p>I did </p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs </code></pre> <p>i get </p> <pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... </code></pre> <p>Why am i missing the content? </p> <p>edit: elaborated on 'stuck' as advised :)</p>
[ { "answer_id": 285941, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 4, "selected": true, "text": "<p>Use <a href=\"http://crummy.com/software/BeautifulSoup\" rel=\"noreferrer\">Beautiful Soup</a>. Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I think you want:</p>\n\n<pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())\n</code></pre>\n\n<p>By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.</p>\n\n<p><strong>EDIT 2:</strong></p>\n\n<p>This should show you all the links in a page:</p>\n\n<pre><code>import urlparse, urllib\nfrom BeautifulSoup import BeautifulSoup\n\nurl = \"http://www.example.com/index.html\"\nsource = urllib.urlopen(url).read()\n\nsoup = BeautifulSoup(source)\n\nfor item in soup.fetchall('a'):\n try:\n link = urlparse.urlparse(item['href'].lower())\n except:\n # Not a valid link\n pass\n else:\n print link\n</code></pre>\n" }, { "answer_id": 285959, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "<p>Here's a code example, showing getting the attributes and contents of the links:</p>\n\n<pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))\nfor link in soup.findAll('a'):\n print link.attrs, link.contents\n</code></pre>\n" }, { "answer_id": 285963, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Though I suppose the others <em>might</em> be correct in pointing you to using Beautiful Soup, they <em>might</em> not, and using an external library might be massively over-the-top for your purposes. Here's a regex which will do what you ask.</p>\n\n<pre><code>/&lt;a\\s+[^&gt;]*?href=\"([^\"]*)\".*?&gt;(.*?)&lt;\\/a&gt;/\n</code></pre>\n\n<p>Here's what it matches:</p>\n\n<pre><code>'&lt;a href=\"url\" close=\"true\"&gt;text&lt;/a&gt;'\n// Parts: \"url\", \"text\"\n\n'&lt;a href=\"url\" close=\"true\"&gt;text&lt;span&gt;something&lt;/span&gt;&lt;/a&gt;'\n// Parts: \"url\", \"text&lt;span&gt;something&lt;/span&gt;\"\n</code></pre>\n\n<p>If you wanted to get <em>just</em> the text (eg: \"textsomething\" in the second example above), I'd just run another regex over it to strip anything between pointed brackets.</p>\n" }, { "answer_id": 286019, "author": "Tom", "author_id": 7376, "author_profile": "https://Stackoverflow.com/users/7376", "pm_score": 2, "selected": false, "text": "<p>Looks like you have two issues there:</p>\n\n<ol>\n<li>link.content<strong>s</strong>, not link.content</li>\n<li>attrs is a dictionary, not a string. It holds key value pairs for each attribute in an HTML element. link.attrs['href'] will get you what you appear to be looking for, but you'd want to wrap that in a check in case you come across an a tag without an href attribute.</li>\n</ol>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/285938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19731/" ]
Given an HTML link like ``` <a href="urltxt" class="someclass" close="true">texttxt</a> ``` how can I isolate the url and the text? **Updates** I'm using Beautiful Soup, and am unable to figure out how to do that. I did ``` soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs ``` i get ``` *link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... ``` Why am i missing the content? edit: elaborated on 'stuck' as advised :)
Use [Beautiful Soup](http://crummy.com/software/BeautifulSoup). Doing it yourself is harder than it looks, you'll be better off using a tried and tested module. **EDIT:** I think you want: ``` soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read()) ``` By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly. **EDIT 2:** This should show you all the links in a page: ``` import urlparse, urllib from BeautifulSoup import BeautifulSoup url = "http://www.example.com/index.html" source = urllib.urlopen(url).read() soup = BeautifulSoup(source) for item in soup.fetchall('a'): try: link = urlparse.urlparse(item['href'].lower()) except: # Not a valid link pass else: print link ```
285,955
<p>Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?</p>
[ { "answer_id": 285987, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "<p>Something like:</p>\n\n<pre><code>import java.io.File;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n\npublic class Newest {\n public static void main(String[] args) {\n File dir = new File(\"C:\\\\your\\\\dir\");\n File [] files = dir.listFiles();\n Arrays.sort(files, new Comparator(){\n public int compare(Object o1, Object o2) {\n return compare( (File)o1, (File)o2);\n }\n private int compare( File f1, File f2){\n long result = f2.lastModified() - f1.lastModified();\n if( result &gt; 0 ){\n return 1;\n } else if( result &lt; 0 ){\n return -1;\n } else {\n return 0;\n }\n }\n });\n System.out.println( Arrays.asList(files ));\n }\n}\n</code></pre>\n" }, { "answer_id": 286001, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 6, "selected": false, "text": "<p>The following code returns the last modified file or folder:</p>\n\n<pre><code>public static File getLastModified(String directoryFilePath)\n{\n File directory = new File(directoryFilePath);\n File[] files = directory.listFiles(File::isFile);\n long lastModifiedTime = Long.MIN_VALUE;\n File chosenFile = null;\n\n if (files != null)\n {\n for (File file : files)\n {\n if (file.lastModified() &gt; lastModifiedTime)\n {\n chosenFile = file;\n lastModifiedTime = file.lastModified();\n }\n }\n }\n\n return chosenFile;\n}\n</code></pre>\n\n<p>Note that it required <code>Java 8</code> or newer due to the lambda expression.</p>\n" }, { "answer_id": 12337559, "author": "John Jintire", "author_id": 1657856, "author_profile": "https://Stackoverflow.com/users/1657856", "pm_score": 4, "selected": false, "text": "<p>This works perfectly fine for me:</p>\n\n<pre><code>import org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.comparator.LastModifiedFileComparator;\nimport org.apache.commons.io.filefilter.WildcardFileFilter;\n\n...\n\n/* Get the newest file for a specific extension */\npublic File getTheNewestFile(String filePath, String ext) {\n File theNewestFile = null;\n File dir = new File(filePath);\n FileFilter fileFilter = new WildcardFileFilter(\"*.\" + ext);\n File[] files = dir.listFiles(fileFilter);\n\n if (files.length &gt; 0) {\n /** The newest file comes first **/\n Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);\n theNewestFile = files[0];\n }\n\n return theNewestFile;\n}\n</code></pre>\n" }, { "answer_id": 30892976, "author": "Almaz", "author_id": 4989585, "author_profile": "https://Stackoverflow.com/users/4989585", "pm_score": 5, "selected": false, "text": "<p>In Java 8:</p>\n\n<pre><code>Path dir = Paths.get(\"./path/somewhere\"); // specify your directory\n\nOptional&lt;Path&gt; lastFilePath = Files.list(dir) // here we get the stream with full directory listing\n .filter(f -&gt; !Files.isDirectory(f)) // exclude subdirectories from listing\n .max(Comparator.comparingLong(f -&gt; f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field\n\nif ( lastFilePath.isPresent() ) // your folder may be empty\n{\n // do your code here, lastFilePath contains all you need\n} \n</code></pre>\n" }, { "answer_id": 45711591, "author": "Prasanth V", "author_id": 6370767, "author_profile": "https://Stackoverflow.com/users/6370767", "pm_score": 2, "selected": false, "text": "<pre><code>private File getLatestFilefromDir(String dirPath){\n File dir = new File(dirPath);\n File[] files = dir.listFiles();\n if (files == null || files.length == 0) {\n return null;\n }\n\n File lastModifiedFile = files[0];\n for (int i = 1; i &lt; files.length; i++) {\n if (lastModifiedFile.lastModified() &lt; files[i].lastModified()) {\n lastModifiedFile = files[i];\n }\n }\n return lastModifiedFile;\n}\n</code></pre>\n" }, { "answer_id": 45996832, "author": "Tested", "author_id": 8547291, "author_profile": "https://Stackoverflow.com/users/8547291", "pm_score": 1, "selected": false, "text": "<pre><code>public File getLastDownloadedFile() {\n File choice = null;\n try {\n File fl = new File(\"C:/Users/\" + System.getProperty(\"user.name\")\n + \"/Downloads/\");\n File[] files = fl.listFiles(new FileFilter() {\n public boolean accept(File file) {\n return file.isFile();\n }\n });\n//Sleep to download file if not required can be removed\n Thread.sleep(30000);\n long lastMod = Long.MIN_VALUE;\n\n for (File file : files) {\n if (file.lastModified() &gt; lastMod) {\n choice = file;\n lastMod = file.lastModified();\n }\n }\n } catch (Exception e) {\n System.out.println(\"Exception while getting the last download file :\"\n + e.getMessage());\n }\n System.out.println(\"The last downloaded file is \" + choice.getPath());\n System.out.println(\"The last downloaded file is \" + choice.getPath(),true);\n return choice;\n}\n</code></pre>\n" }, { "answer_id": 51330320, "author": "Asheron", "author_id": 10027688, "author_profile": "https://Stackoverflow.com/users/10027688", "pm_score": 0, "selected": false, "text": "<p>Here's a small modification to Jose's code which makes sure the folder has at least 1 file in it. Work's great in my app!</p>\n\n<pre><code>public static File lastFileModified(String dir) {\n File fl = new File(dir);\n File choice = null;\n if (fl.listFiles().length&gt;0) {\n File[] files = fl.listFiles(new FileFilter() {\n public boolean accept(File file) {\n return file.isFile();\n }\n });\n long lastMod = Long.MIN_VALUE;\n\n for (File file : files) {\n if (file.lastModified() &gt; lastMod) {\n choice = file;\n lastMod = file.lastModified();\n }\n }\n }\n return choice;\n}\n</code></pre>\n" }, { "answer_id": 55561917, "author": "theeman05", "author_id": 10711647, "author_profile": "https://Stackoverflow.com/users/10711647", "pm_score": 1, "selected": false, "text": "<p>This will return the most recent created file, I made this because when you create a file in some situations, it may not always have the correct modified date.</p>\n\n<pre><code>import java.nio.file.Files;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.nio.file.attribute.FileTime;\n\nprivate File lastFileCreated(String dir) {\n File fl = new File(dir);\n File[] files = fl.listFiles(new FileFilter() {\n public boolean accept(File file) {\n return true;\n }\n });\n\n FileTime lastCreated = null;\n File choice = null;\n\n for (File file : files) {\n BasicFileAttributes attr=null;\n try {\n attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);\n }catch (Exception e){\n System.out.println(e);\n }\n\n if(lastCreated ==null)\n lastCreated = attr.creationTime();\n\n if (attr!=null&amp;&amp;attr.creationTime().compareTo(lastCreated)==0) {\n choice = file;\n }\n }\n return choice;\n}\n</code></pre>\n" }, { "answer_id": 56402466, "author": "SaurabhGuptaAricent", "author_id": 11585199, "author_profile": "https://Stackoverflow.com/users/11585199", "pm_score": 0, "selected": false, "text": "<p>This code works for me well:</p>\n\n<pre><code>public String pickLatestFileFromDownloads() {\n\n String currentUsersHomeDir = System.getProperty(\"user.home\");\n\n String downloadFolder = currentUsersHomeDir + File.separator + \"Downloads\" + File.separator;\n\n File dir = new File(downloadFolder);\n File[] files = dir.listFiles();\n if (files == null || files.length == 0) {\n testLogger.info(\"There is no file in the folder\");\n }\n\n File lastModifiedFile = files[0];\n for (int i = 1; i &lt; files.length; i++) {\n if (lastModifiedFile.lastModified() &lt; files[i].lastModified()) {\n lastModifiedFile = files[i];\n }\n }\n String k = lastModifiedFile.toString();\n\n System.out.println(lastModifiedFile);\n Path p = Paths.get(k);\n String file = p.getFileName().toString();\n return file;\n\n }\n\n//PostedBy: saurabh Gupta Aricent-provar\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/285955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?
The following code returns the last modified file or folder: ``` public static File getLastModified(String directoryFilePath) { File directory = new File(directoryFilePath); File[] files = directory.listFiles(File::isFile); long lastModifiedTime = Long.MIN_VALUE; File chosenFile = null; if (files != null) { for (File file : files) { if (file.lastModified() > lastModifiedTime) { chosenFile = file; lastModifiedTime = file.lastModified(); } } } return chosenFile; } ``` Note that it required `Java 8` or newer due to the lambda expression.
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack" rel="noreferrer">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
[ { "answer_id": 286094, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a> is a good Python library for dealing with messy HTML in clean ways.</p>\n" }, { "answer_id": 286222, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 2, "selected": false, "text": "<p>It seems the question could be more precisely stated as \"<em>How to convert HTML to XML so that XPath expressions can be evaluated against it</em>\".</p>\n\n<p>Here are two good tools:</p>\n\n<ol>\n<li><p><a href=\"http://home.ccil.org/~cowan/XML/tagsoup/\" rel=\"nofollow noreferrer\"><strong>TagSoup</strong></a>, an open-source program, is a Java and SAX - based tool, developed by <a href=\"http://home.ccil.org/~cowan/\" rel=\"nofollow noreferrer\"><strong>John Cowan</strong></a>. This is \na SAX-compliant parser written in Java that, instead of parsing well-formed or valid XML, parses HTML as it is found in the wild: poor, nasty and brutish, though quite often far from short. TagSoup is designed for people who have to process this stuff using some semblance of a rational application design. By providing a SAX interface, it allows standard XML tools to be applied to even the worst HTML. TagSoup also includes a command-line processor that reads HTML files and can generate either clean HTML or well-formed XML that is a close approximation to XHTML.<br>\n<a href=\"http://www.jezuk.co.uk/arabica/log?id=3591\" rel=\"nofollow noreferrer\">Taggle</a> is a commercial C++ port of TagSoup.</p></li>\n<li><p><a href=\"http://code.msdn.microsoft.com/SgmlReader\" rel=\"nofollow noreferrer\"><strong>SgmlReader</strong></a> is a tool developed by Microsoft's <a href=\"http://www.lovettsoftware.com/\" rel=\"nofollow noreferrer\"><strong>Chris Lovett</strong></a>.<br />\nSgmlReader is an XmlReader API over any SGML document (including built in support for HTML). A command line utility is also provided which outputs the well formed XML result.<br />\nDownload the zip file including the standalone executable and the full source code: <a href=\"http://code.msdn.microsoft.com/SgmlReader/Release/ProjectReleases.aspx?ReleaseId=1442\" rel=\"nofollow noreferrer\"><strong>SgmlReader.zip</strong></a></p></li>\n</ol>\n" }, { "answer_id": 288976, "author": "Chu Yeow", "author_id": 25226, "author_profile": "https://Stackoverflow.com/users/25226", "pm_score": 2, "selected": false, "text": "<p>For Ruby, I highly recommend Hpricot that Jb Evain pointed out. If you're looking for a faster libxml-based competitor, Nokogiri (see <a href=\"http://tenderlovemaking.com/2008/10/30/nokogiri-is-released/\" rel=\"nofollow noreferrer\">http://tenderlovemaking.com/2008/10/30/nokogiri-is-released/</a>) is pretty good too (it supports both XPath and CSS searches like Hpricot but is faster). There's a basic <a href=\"http://github.com/tenderlove/nokogiri/wikis\" rel=\"nofollow noreferrer\">wiki</a> and some <a href=\"http://gist.github.com/22176\" rel=\"nofollow noreferrer\">benchmarks</a>.</p>\n" }, { "answer_id": 288994, "author": "Klathzazt", "author_id": 35223, "author_profile": "https://Stackoverflow.com/users/35223", "pm_score": 1, "selected": false, "text": "<p>There is a free C implementation for XML called libxml2 which has some api bits for XPath which I have used with great success which you can specify HTML as the document being loaded. This had worked for me for some less than perfect HTML documents.. </p>\n\n<p>For the most part, XPath is most useful when the inbound HTML is properly coded and can be read 'like an xml document'. You may want to consider using a utility that is specific to this purpose for cleaning up HTML documents. Here is one example: <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\">http://tidy.sourceforge.net/</a></p>\n\n<p>As far as these XPath tools go- you will likely find that most implementations are actually based on pre-existing C or C++ libraries such as libxml2.</p>\n" }, { "answer_id": 289167, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 4, "selected": true, "text": "<p>In python, <a href=\"http://pypi.python.org/pypi/elementtidy/1.0-20050212\" rel=\"noreferrer\">ElementTidy</a> parses tag soup and produces an element tree, which allows querying using XPath:</p>\n\n<pre><code>&gt;&gt;&gt; from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB\n&gt;&gt;&gt; tb = TB()\n&gt;&gt;&gt; tb.feed(\"&lt;p&gt;Hello world\")\n&gt;&gt;&gt; e= tb.close()\n&gt;&gt;&gt; e.find(\".//{http://www.w3.org/1999/xhtml}p\")\n&lt;Element {http://www.w3.org/1999/xhtml}p at 264eb8&gt;\n</code></pre>\n" }, { "answer_id": 4747067, "author": "Jagtesh Chadha", "author_id": 129912, "author_profile": "https://Stackoverflow.com/users/129912", "pm_score": 6, "selected": false, "text": "<p>I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries.</p>\n\n<p>Here's how <a href=\"http://codespeak.net/lxml/xpathxslt.html\" rel=\"noreferrer\">you can parse HTML via XPATH using lxml</a>.</p>\n\n<pre><code>&gt;&gt;&gt; from lxml import etree\n&gt;&gt;&gt; doc = '&lt;foo&gt;&lt;bar&gt;&lt;/bar&gt;&lt;/foo&gt;'\n&gt;&gt;&gt; tree = etree.HTML(doc)\n\n&gt;&gt;&gt; r = tree.xpath('/foo/bar')\n&gt;&gt;&gt; len(r)\n1\n&gt;&gt;&gt; r[0].tag\n'bar'\n\n&gt;&gt;&gt; r = tree.xpath('bar')\n&gt;&gt;&gt; r[0].tag\n'bar'\n</code></pre>\n" }, { "answer_id": 9441191, "author": "Gareth Davidson", "author_id": 146642, "author_profile": "https://Stackoverflow.com/users/146642", "pm_score": 3, "selected": false, "text": "<p>The most stable results I've had have been using lxml.html's soupparser. You'll need to install python-lxml and python-beautifulsoup, then you can do the following:</p>\n\n<pre><code>from lxml.html.soupparser import fromstring\ntree = fromstring('&lt;mal form=\"ed\"&gt;&lt;html/&gt;here!')\nmatches = tree.xpath(\"./mal[@form=ed]\")\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/285990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
In .Net, I found this great library, [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?
In python, [ElementTidy](http://pypi.python.org/pypi/elementtidy/1.0-20050212) parses tag soup and produces an element tree, which allows querying using XPath: ``` >>> from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB >>> tb = TB() >>> tb.feed("<p>Hello world") >>> e= tb.close() >>> e.find(".//{http://www.w3.org/1999/xhtml}p") <Element {http://www.w3.org/1999/xhtml}p at 264eb8> ```
286,004
<p>There seem to be a decent number of <code>mod_rewrite</code> threads floating around lately with a bit of confusion over how certain aspects of it work. As a result I've compiled a few notes on common functionality, and perhaps a few annoying nuances.</p> <p>What other features / common issues have you run across using <code>mod_rewrite</code>?</p>
[ { "answer_id": 286005, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 8, "selected": false, "text": "<h2>Where to place mod_rewrite rules</h2>\n\n<p><code>mod_rewrite</code> rules may be placed within the <code>httpd.conf</code> file, or within the <code>.htaccess</code> file. if you have access to <code>httpd.conf</code>, placing rules here will offer a performance benefit (as the rules are processed once, as opposed to each time the <code>.htaccess</code> file is called).</p>\n\n<h2>Logging mod_rewrite requests</h2>\n\n<p>Logging may be enabled from within the <code>httpd.conf</code> file (including <code>&lt;Virtual Host&gt;</code>):</p>\n\n<pre><code># logs can't be enabled from .htaccess\n# loglevel &gt; 2 is really spammy!\nRewriteLog /path/to/rewrite.log\nRewriteLogLevel 2\n</code></pre>\n\n<h2>Common use cases</h2>\n\n<ol>\n<li><p>To funnel all requests to a single point:</p>\n\n<pre><code>RewriteEngine on\n# ignore existing files\nRewriteCond %{REQUEST_FILENAME} !-f \n# ignore existing directories\nRewriteCond %{REQUEST_FILENAME} !-d \n# map requests to index.php and append as a query string\nRewriteRule ^(.*)$ index.php?query=$1 \n</code></pre>\n\n<p>Since Apache 2.2.16 you can also use <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource\" rel=\"noreferrer\"><code>FallbackResource</code></a>.</p></li>\n<li><p>Handling 301/302 redirects:</p>\n\n<pre><code>RewriteEngine on\n# 302 Temporary Redirect (302 is the default, but can be specified for clarity)\nRewriteRule ^oldpage\\.html$ /newpage.html [R=302] \n# 301 Permanent Redirect\nRewriteRule ^oldpage2\\.html$ /newpage.html [R=301] \n</code></pre>\n\n<p><em>Note</em>: external redirects are implicitly 302 redirects:</p>\n\n<pre><code># this rule:\nRewriteRule ^somepage\\.html$ http://google.com\n# is equivalent to:\nRewriteRule ^somepage\\.html$ http://google.com [R]\n# and:\nRewriteRule ^somepage\\.html$ http://google.com [R=302]\n</code></pre></li>\n<li><p>Forcing SSL</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://example.com/$1 [R,L]\n</code></pre></li>\n<li><p>Common flags:</p>\n\n<ul>\n<li><code>[R]</code> or <code>[redirect]</code> - force a redirect (defaults to a 302 temporary redirect)</li>\n<li><code>[R=301]</code> or <code>[redirect=301]</code> - force a 301 permanent redirect</li>\n<li><code>[L]</code> or <code>[last]</code> - stop rewriting process (see note below in common pitfalls)</li>\n<li><code>[NC]</code> or <code>[nocase]</code> - specify that matching should be case insensitive </li>\n</ul>\n\n<p><br>\nUsing the long-form of flags is often more readable and will help others who come to read your code later.</p>\n\n<p>You can separate multiple flags with a comma:</p>\n\n<pre><code>RewriteRule ^olddir(.*)$ /newdir$1 [L,NC]\n</code></pre></li>\n</ol>\n\n<h2>Common pitfalls</h2>\n\n<ol>\n<li><p>Mixing <code>mod_alias</code> style redirects with <code>mod_rewrite</code></p>\n\n<pre><code># Bad\nRedirect 302 /somepage.html http://example.com/otherpage.html\nRewriteEngine on\nRewriteRule ^(.*)$ index.php?query=$1\n\n# Good (use mod_rewrite for both)\nRewriteEngine on\n# 302 redirect and stop processing\nRewriteRule ^somepage.html$ /otherpage.html [R=302,L] \nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n# handle other redirects\nRewriteRule ^(.*)$ index.php?query=$1 \n</code></pre>\n\n<p><em>Note</em>: you can mix <code>mod_alias</code> with <code>mod_rewrite</code>, but it involves more work than just handling basic redirects as above.</p></li>\n<li><p>Context affects syntax</p>\n\n<p>Within <code>.htaccess</code> files, a leading slash is not used in the RewriteRule pattern:</p>\n\n<pre><code># given: GET /directory/file.html\n\n# .htaccess\n# result: /newdirectory/file.html\nRewriteRule ^directory(.*)$ /newdirectory$1\n\n# .htaccess\n# result: no match!\nRewriteRule ^/directory(.*)$ /newdirectory$1\n\n# httpd.conf\n# result: /newdirectory/file.html\nRewriteRule ^/directory(.*)$ /newdirectory$1\n\n# Putting a \"?\" after the slash will allow it to work in both contexts:\nRewriteRule ^/?directory(.*)$ /newdirectory$1\n</code></pre></li>\n<li><p>[L] is not last! (sometimes)</p>\n\n<p>The <code>[L]</code> flag stops processing any further rewrite rules <em>for that pass through the rule set</em>. However, if the URL was modified in that pass and you're in the <code>.htaccess</code> context or the <code>&lt;Directory&gt;</code> section, then your modified request is going to be passed back through the URL parsing engine again. And on the next pass, it may match a different rule this time. If you don't understand this, it often looks like your <code>[L]</code> flag had no effect.</p>\n\n<pre><code># processing does not stop here\nRewriteRule ^dirA$ /dirB [L] \n# /dirC will be the final result\nRewriteRule ^dirB$ /dirC \n</code></pre>\n\n<p>Our rewrite log shows that the rules are run twice and the URL is updated twice:</p>\n\n<pre><code>rewrite 'dirA' -&gt; '/dirB'\ninternal redirect with /dirB [INTERNAL REDIRECT]\nrewrite 'dirB' -&gt; '/dirC'\n</code></pre>\n\n<p>The best way around this is to use the <code>[END]</code> flag (<a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_end\" rel=\"noreferrer\">see Apache docs</a>) instead of the <code>[L]</code> flag, if you truly want to stop all further processing of rules (and subsequent passes). However, the <code>[END]</code> flag is only available for <strong>Apache v2.3.9+</strong>, so if you have v2.2 or lower, you're stuck with just the <code>[L]</code> flag. </p>\n\n<p>For earlier versions, you must rely on <code>RewriteCond</code> statements to prevent matching of rules on subsequent passes of the URL parsing engine. </p>\n\n<pre><code># Only process the following RewriteRule if on the first pass\nRewriteCond %{ENV:REDIRECT_STATUS} ^$\nRewriteRule ...\n</code></pre>\n\n<p>Or you must ensure that your RewriteRule's are in a context (i.e. <code>httpd.conf</code>) that will not cause your request to be re-parsed.</p></li>\n</ol>\n" }, { "answer_id": 1298917, "author": "Michael Ekoka", "author_id": 56974, "author_profile": "https://Stackoverflow.com/users/56974", "pm_score": 4, "selected": false, "text": "<p><strong>Other Pitfalls:</strong></p>\n\n<p>1- Sometimes it's a good idea to disable MultiViews</p>\n\n<pre><code>Options -MultiViews\n</code></pre>\n\n<p>I'm not well verse on all of MultiViews capabilities, but I know that it messes up my mod_rewrite rules when active, because one of its properties is to try and 'guess' an extension to a file that it thinks I'm looking for.</p>\n\n<p>I'll explain:\nSuppose you have 2 php files in your web dir, file1.php and file2.php and you add these conditions and rule to your .htaccess :</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)$ file1.php/$1 \n</code></pre>\n\n<p>You assume that all urls that do not match a file or a directory will be grabbed by file1.php. Surprise! This rule is not being honored for the url <a href=\"http://myhost/file2/somepath\" rel=\"noreferrer\">http://myhost/file2/somepath</a>. Instead you're taken inside file2.php. </p>\n\n<p>What's going on is that MultiViews automagically guessed that the url that you actually wanted was <a href=\"http://myhost/file2.php/somepath\" rel=\"noreferrer\">http://myhost/file2.php/somepath</a> and gladly took you there. </p>\n\n<p>Now, you have no clue what just happened and you're at that point questioning everything that you thought you knew about mod_rewrite. You then start playing around with rules to try to make sense of the logic behind this new situation, but the more you're testing the less sense it makes. </p>\n\n<p>Ok, In short if you want mod_rewrite to work in a way that approximates logic, turning off MultiViews is a step in the right direction.</p>\n\n<p>2- enable FollowSymlinks</p>\n\n<pre><code>Options +FollowSymLinks \n</code></pre>\n\n<p>That one, I don't really know the details of, but I've seen it mentioned many times, so just do it.</p>\n" }, { "answer_id": 1298953, "author": "B.E.", "author_id": 94162, "author_profile": "https://Stackoverflow.com/users/94162", "pm_score": 2, "selected": false, "text": "<p>Another great feature are rewrite-map-expansions. They're especially useful if you have a massive amout of hosts / rewrites to handle:</p>\n\n<p>They are like a key-value-replacement:</p>\n\n<pre><code>RewriteMap examplemap txt:/path/to/file/map.txt\n</code></pre>\n\n<p>Then you can use a mapping in your rules like:</p>\n\n<pre><code>RewriteRule ^/ex/(.*) ${examplemap:$1}\n</code></pre>\n\n<p>More information on this topic can be found here:</p>\n\n<p><a href=\"http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#mapfunc\" rel=\"nofollow noreferrer\">http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#mapfunc</a></p>\n" }, { "answer_id": 1338657, "author": "Sean McMillan", "author_id": 117587, "author_profile": "https://Stackoverflow.com/users/117587", "pm_score": 4, "selected": false, "text": "<p>The deal with RewriteBase:</p>\n\n<p>You almost always need to set RewriteBase. If you don't, apache guesses that your base is the physical disk path to your directory. So start with this:</p>\n\n<pre><code>RewriteBase /\n</code></pre>\n" }, { "answer_id": 2097329, "author": "DrDol", "author_id": 254234, "author_profile": "https://Stackoverflow.com/users/254234", "pm_score": 3, "selected": false, "text": "<p><strong>Equation can be done with following example:</strong></p>\n\n<pre><code>RewriteCond %{REQUEST_URI} ^/(server0|server1).*$ [NC]\n# %1 is the string that was found above\n# %1&lt;&gt;%{HTTP_COOKIE} concatenates first macht with mod_rewrite variable -&gt; \"test0&lt;&gt;foo=bar;\"\n#RewriteCond search for a (.*) in the second part -&gt; \\1 is a reference to (.*)\n# &lt;&gt; is used as an string separator/indicator, can be replaced by any other character\nRewriteCond %1&lt;&gt;%{HTTP_COOKIE} !^(.*)&lt;&gt;.*stickysession=\\1.*$ [NC]\nRewriteRule ^(.*)$ https://notmatch.domain.com/ [R=301,L]\n</code></pre>\n\n<p><strong>Dynamic Load Balancing:</strong></p>\n\n<p>If you use the mod_proxy to balance your system, it's possible to add a dynamic range of worker server.</p>\n\n<pre><code>RewriteCond %{HTTP_COOKIE} ^.*stickysession=route\\.server([0-9]{1,2}).*$ [NC]\nRewriteRule (.*) https://worker%1.internal.com/$1 [P,L]\n</code></pre>\n" }, { "answer_id": 2688558, "author": "mromaine", "author_id": 228162, "author_profile": "https://Stackoverflow.com/users/228162", "pm_score": 5, "selected": false, "text": "<p>if you need to 'block' internal redirects / rewrites from happening in the .htaccess, take a look at the</p>\n\n<pre><code>RewriteCond %{ENV:REDIRECT_STATUS} ^$\n</code></pre>\n\n<p>condition, as <a href=\"http://sltaylor.co.uk/blog/ignoring-internal-rewrites-in-htaccess/\" rel=\"noreferrer\">discussed here</a>.</p>\n" }, { "answer_id": 21733589, "author": "cweekly", "author_id": 385848, "author_profile": "https://Stackoverflow.com/users/385848", "pm_score": 2, "selected": false, "text": "<p>mod_rewrite can modify aspects of request handling without altering the URL, e.g. setting environment variables, setting cookies, etc. This is incredibly useful.</p>\n\n<p>Conditionally set an environment variable:</p>\n\n<pre><code>RewriteCond %{HTTP_COOKIE} myCookie=(a|b) [NC]\nRewriteRule .* - [E=MY_ENV_VAR:%b]\n</code></pre>\n\n<p>Return a 503 response:\n<code>RewriteRule</code>'s <code>[R]</code> flag can take a non-3xx value and return a non-redirecting response, e.g. for managed downtime/maintenance:</p>\n\n<pre><code>RewriteRule .* - [R=503,L]\n</code></pre>\n\n<p>will return a 503 response (not a <em>redirect</em> per se).</p>\n\n<p>Also, mod_rewrite can act like a super-powered interface to mod_proxy, so you can do this instead of writing <code>ProxyPass</code> directives:</p>\n\n<pre><code>RewriteRule ^/(.*)$ balancer://cluster%{REQUEST_URI} [P,QSA,L]\n</code></pre>\n\n<p>Opinion:\nUsing <code>RewriteRule</code>s and <code>RewriteCond</code>s to route requests to different applications or load balancers based on virtually any conceivable aspect of the request is just immensely powerful. Controlling requests on their way to the backend, and being able to modify the responses on their way back out, makes mod_rewrite the ideal place to centralize all routing-related config. </p>\n\n<p>Take the time to learn it, it's well worth it! :)</p>\n" }, { "answer_id": 26929985, "author": "JaredC", "author_id": 339532, "author_profile": "https://Stackoverflow.com/users/339532", "pm_score": 2, "selected": false, "text": "<p>A better understanding of the [L] flag is in order. The [L] flag <strong>is</strong> last, you just have to understand what will cause your request to be routed through the URL parsing engine again. From the docs (<a href=\"http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_l\" rel=\"nofollow\">http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_l</a>) (emphasis mine):</p>\n\n<blockquote>\n <p>The [L] flag causes mod_rewrite to stop processing the rule set. In\n most contexts, this means that if the rule matches, no further rules\n will be processed. This corresponds to the last command in Perl, or\n the break command in C. Use this flag to indicate that the current\n rule should be applied immediately without considering further rules.</p>\n \n <p><strong><em>If you are using RewriteRule in either .htaccess files or in <code>&lt;Directory&gt;</code> sections</em></strong>, it is important to have some understanding of\n how the rules are processed. The simplified form of this is that once\n the rules have been processed, <strong><em>the rewritten request is handed back</em></strong> to\n the URL parsing engine to do what it may with it. It is possible that\n as the rewritten request is handled, the .htaccess file or <code>&lt;Directory&gt;</code>\n section may be encountered again, and thus the ruleset may be run\n again from the start. Most commonly this will happen if one of the\n rules causes a redirect - either internal or external - causing the\n request process to start over.</p>\n</blockquote>\n\n<p>So the [L] flag <strong><em>does</em></strong> stop processing any further rewrite rules for <strong><em>that pass</em></strong> through the rule set. However, if your rule marked with [L] modified the request, and you're in the .htaccess context or the <code>&lt;Directory&gt;</code> section, then your modifed request is going to be passed back through the URL parsing engine again. And on the next pass, it may match a different rule this time. If you don't understand what happened, it looks like your first rewrite rule with the [L] flag had no effect.</p>\n\n<p>The best way around this is to use the [END] flag (<a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_end\" rel=\"nofollow\">http://httpd.apache.org/docs/current/rewrite/flags.html#flag_end</a>) instead of the [L] flag, if you truly want to stop all further processing of rules (and subsequent reparsing). However, the [END] flag is only available for Apache v2.3.9+, so if you have v2.2 or lower, you're stuck with just the [L] flag. In this case, you must rely on RewriteCond statements to prevent matching of rules on subsequent passes of the URL parsing engine. Or you must ensure that your RewriteRule's are in a context (i.e. httpd.conf) that will not cause your request to be re-parsed.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4853/" ]
There seem to be a decent number of `mod_rewrite` threads floating around lately with a bit of confusion over how certain aspects of it work. As a result I've compiled a few notes on common functionality, and perhaps a few annoying nuances. What other features / common issues have you run across using `mod_rewrite`?
Where to place mod\_rewrite rules --------------------------------- `mod_rewrite` rules may be placed within the `httpd.conf` file, or within the `.htaccess` file. if you have access to `httpd.conf`, placing rules here will offer a performance benefit (as the rules are processed once, as opposed to each time the `.htaccess` file is called). Logging mod\_rewrite requests ----------------------------- Logging may be enabled from within the `httpd.conf` file (including `<Virtual Host>`): ``` # logs can't be enabled from .htaccess # loglevel > 2 is really spammy! RewriteLog /path/to/rewrite.log RewriteLogLevel 2 ``` Common use cases ---------------- 1. To funnel all requests to a single point: ``` RewriteEngine on # ignore existing files RewriteCond %{REQUEST_FILENAME} !-f # ignore existing directories RewriteCond %{REQUEST_FILENAME} !-d # map requests to index.php and append as a query string RewriteRule ^(.*)$ index.php?query=$1 ``` Since Apache 2.2.16 you can also use [`FallbackResource`](http://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource). 2. Handling 301/302 redirects: ``` RewriteEngine on # 302 Temporary Redirect (302 is the default, but can be specified for clarity) RewriteRule ^oldpage\.html$ /newpage.html [R=302] # 301 Permanent Redirect RewriteRule ^oldpage2\.html$ /newpage.html [R=301] ``` *Note*: external redirects are implicitly 302 redirects: ``` # this rule: RewriteRule ^somepage\.html$ http://google.com # is equivalent to: RewriteRule ^somepage\.html$ http://google.com [R] # and: RewriteRule ^somepage\.html$ http://google.com [R=302] ``` 3. Forcing SSL ``` RewriteEngine on RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://example.com/$1 [R,L] ``` 4. Common flags: * `[R]` or `[redirect]` - force a redirect (defaults to a 302 temporary redirect) * `[R=301]` or `[redirect=301]` - force a 301 permanent redirect * `[L]` or `[last]` - stop rewriting process (see note below in common pitfalls) * `[NC]` or `[nocase]` - specify that matching should be case insensitive Using the long-form of flags is often more readable and will help others who come to read your code later. You can separate multiple flags with a comma: ``` RewriteRule ^olddir(.*)$ /newdir$1 [L,NC] ``` Common pitfalls --------------- 1. Mixing `mod_alias` style redirects with `mod_rewrite` ``` # Bad Redirect 302 /somepage.html http://example.com/otherpage.html RewriteEngine on RewriteRule ^(.*)$ index.php?query=$1 # Good (use mod_rewrite for both) RewriteEngine on # 302 redirect and stop processing RewriteRule ^somepage.html$ /otherpage.html [R=302,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # handle other redirects RewriteRule ^(.*)$ index.php?query=$1 ``` *Note*: you can mix `mod_alias` with `mod_rewrite`, but it involves more work than just handling basic redirects as above. 2. Context affects syntax Within `.htaccess` files, a leading slash is not used in the RewriteRule pattern: ``` # given: GET /directory/file.html # .htaccess # result: /newdirectory/file.html RewriteRule ^directory(.*)$ /newdirectory$1 # .htaccess # result: no match! RewriteRule ^/directory(.*)$ /newdirectory$1 # httpd.conf # result: /newdirectory/file.html RewriteRule ^/directory(.*)$ /newdirectory$1 # Putting a "?" after the slash will allow it to work in both contexts: RewriteRule ^/?directory(.*)$ /newdirectory$1 ``` 3. [L] is not last! (sometimes) The `[L]` flag stops processing any further rewrite rules *for that pass through the rule set*. However, if the URL was modified in that pass and you're in the `.htaccess` context or the `<Directory>` section, then your modified request is going to be passed back through the URL parsing engine again. And on the next pass, it may match a different rule this time. If you don't understand this, it often looks like your `[L]` flag had no effect. ``` # processing does not stop here RewriteRule ^dirA$ /dirB [L] # /dirC will be the final result RewriteRule ^dirB$ /dirC ``` Our rewrite log shows that the rules are run twice and the URL is updated twice: ``` rewrite 'dirA' -> '/dirB' internal redirect with /dirB [INTERNAL REDIRECT] rewrite 'dirB' -> '/dirC' ``` The best way around this is to use the `[END]` flag ([see Apache docs](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_end)) instead of the `[L]` flag, if you truly want to stop all further processing of rules (and subsequent passes). However, the `[END]` flag is only available for **Apache v2.3.9+**, so if you have v2.2 or lower, you're stuck with just the `[L]` flag. For earlier versions, you must rely on `RewriteCond` statements to prevent matching of rules on subsequent passes of the URL parsing engine. ``` # Only process the following RewriteRule if on the first pass RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ... ``` Or you must ensure that your RewriteRule's are in a context (i.e. `httpd.conf`) that will not cause your request to be re-parsed.
286,007
<p>I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't.</p> <p>As per the comment below, CATALINA_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.</p>
[ { "answer_id": 286011, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<p>Use the <code>CATALINA_OPTS</code> environment variable.</p>\n" }, { "answer_id": 286389, "author": "FoxyBOA", "author_id": 19347, "author_profile": "https://Stackoverflow.com/users/19347", "pm_score": 1, "selected": false, "text": "<p>Not sure that it will be applicable solution for you. But the only way for monitoring tomcat memory settings as well as number of connections etc. that actually works for us is <a href=\"http://www.lambdaprobe.org\" rel=\"nofollow noreferrer\">Lambda Probe</a>.</p>\n\n<p>It shows most of informations that we need for Tomcat tunning. We tested it with Tomcat 5.5 and 6.0 and it works fine despite beta status and date of last update in end of 2006.</p>\n" }, { "answer_id": 286415, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 1, "selected": false, "text": "<p>If you'd start Tomcat manually (not as service), then the CATALINA_OPTS environment variable is the way to go. If you'd start it as a service, then the settings are probably stored somewhere in the registry. I have Tomcat 6 installed in my machine and I found the settings at the <code>HKLM\\SOFTWARE\\Apache Software Foundation\\Procrun 2.0\\Tomcat6\\Parameters\\Java</code> key.</p>\n" }, { "answer_id": 299590, "author": "Cozzman", "author_id": 18191, "author_profile": "https://Stackoverflow.com/users/18191", "pm_score": 2, "selected": false, "text": "<p>Just to add to the previous comment, the documentation for the command line tool for updating the Tomcat service settings (if Tomcat is running as a service on Windows) is <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/windows-service-howto.html\" rel=\"nofollow noreferrer\">here</a>. This tool updates the registry with the proper settings.\nSo if you wanted to update the max memory setting for the Tomcat service you could run this (from the tomcat/bin directory), assuming the default service name of Tomcat5:</p>\n\n<pre><code>tomcat5 //US//Tomcat5 --JvmMx=512\n</code></pre>\n" }, { "answer_id": 325333, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 5, "selected": false, "text": "<p>Create a setenv.(sh|bat) file in the tomcat/bin directory with the environment variables that you want modified.</p>\n\n<p>The catalina script checks if the setenv script exists and runs it to set the environment variables. This way you can change the parameters to only one instance of tomcat and is easier to copy it to another instance.</p>\n\n<p>Probably your configuration app has created the setenv script and thats why tomcat is ignoring the environment variables.</p>\n" }, { "answer_id": 338019, "author": "Glenn", "author_id": 29771, "author_profile": "https://Stackoverflow.com/users/29771", "pm_score": 7, "selected": true, "text": "<p>Serhii's suggestion works and here is some more detail.</p>\n\n<p>If you look in your installation's bin directory you will see catalina.sh\nor .bat scripts. If you look in these you will see that they run a \nsetenv.sh or setenv.bat script respectively, if it exists, to set environment variables.\nThe relevant environment variables are described in the comments at the\ntop of catalina.sh/bat. To use them create, for example, a file\n$CATALINA_HOME/bin/setenv.sh with contents</p>\n\n<pre><code>export JAVA_OPTS=\"-server -Xmx512m\"\n</code></pre>\n\n<p>For Windows you will need, in setenv.bat, something like</p>\n\n<pre><code>set JAVA_OPTS=-server -Xmx768m\n</code></pre>\n\n<p>Hope this helps,\nGlenn</p>\n" }, { "answer_id": 3652561, "author": "Dmitriy Kochergin", "author_id": 431501, "author_profile": "https://Stackoverflow.com/users/431501", "pm_score": 2, "selected": false, "text": "<p>I use following <code>setenv.bat</code> contents:</p>\n\n<pre><code>==============setenv.bat============\n\n set JAVA_OPTS=-XX:MaxPermSize=256m -Xms256M -Xmx768M -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=7777,server=y,suspend=n %JAVA_OPTS%\n\n====================================\n</code></pre>\n\n<p>It also enables debugging and sets debug port to 7777, and appends previous content of <code>JAVA_OPTS</code>.</p>\n" }, { "answer_id": 3964598, "author": "DrTune", "author_id": 479935, "author_profile": "https://Stackoverflow.com/users/479935", "pm_score": 2, "selected": false, "text": "<p>Handy for linux virtual machines; Use 75% of your total system memory for Tomcat. Yay AWK.</p>\n\n<p>Put at start of \"{tomcat}/bin/startup.sh\"</p>\n\n<pre><code>export CATALINA_OPTS=\"-Xmx`cat /proc/meminfo | grep MemTotal | awk '{ print $2*0.75 } '`k\"\n</code></pre>\n" }, { "answer_id": 8111885, "author": "Ondrej Kvasnovsky", "author_id": 931428, "author_profile": "https://Stackoverflow.com/users/931428", "pm_score": 2, "selected": false, "text": "<p>I like the idea of seting tomcat6 memory based on available server memory (it is cool because I don't have to change the setup after hardware upgrade). Here is my (a bit extended memory setup):</p>\n\n<blockquote>\n <p>export CATALINA_OPTS=\"-Xmx<code>`cat /proc/meminfo | grep MemTotal | awk '{\n print $2*0.75 } '`</code>k -Xms<code>`cat /proc/meminfo | grep MemTotal | awk '{\n print $2*0.75 } '`</code>k -XX:NewSize=<code>`cat /proc/meminfo | grep MemTotal |\n awk '{ print $2*0.15 } '`</code>k -XX:MaxNewSize=<code>`cat /proc/meminfo | grep\n MemTotal | awk '{ print $2*0.15 } '`</code>k -XX:PermSize=<code>`cat /proc/meminfo\n | grep MemTotal | awk '{ print $2*0.15 } '`</code>k -XX:MaxPermSize=<code>`cat\n /proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`</code>k\"</p>\n</blockquote>\n\n<p>Put it to: \"{tomcat}/bin/startup.sh\" (e.g. \"/usr/share/tomcat6/bin\" for Ubuntu 10.10)</p>\n" }, { "answer_id": 8207031, "author": "martinusadyh", "author_id": 563694, "author_profile": "https://Stackoverflow.com/users/563694", "pm_score": 3, "selected": false, "text": "<p>If you using Ubuntu 11.10 and apache-tomcat6 (installing from apt-get), you can put this configuration at <strong>/usr/share/tomcat6/bin/catalina.sh</strong></p>\n\n<pre><code># -----------------------------------------------------------------------------\n\nJAVA_OPTS=\"-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m \\\n-Xmx1024m -XX:NewSize=512m -XX:MaxNewSize=512m -XX:PermSize=512m \\\n-XX:MaxPermSize=512m -XX:+DisableExplicitGC\"\n</code></pre>\n\n<p>After that, you can check your configuration via ps -ef | grep tomcat :)</p>\n" }, { "answer_id": 10391630, "author": "Sailab Rahi", "author_id": 470848, "author_profile": "https://Stackoverflow.com/users/470848", "pm_score": 0, "selected": false, "text": "<p>Just edit your your catalina/bin/startup.sh script. Add the following commands in it: </p>\n\n<pre><code>#Adjust it to the size you want. Ignore the from bit.\nexport CATALINA_OPTS=\"-Xmx1024m\"\n#This should point to your catalina base directory \nexport CATALINA_BASE=/usr/local/tomcat\n#This is only used if you editing the instance of your tomcat\n/usr/share/tomcat6/bin/startup.sh\n</code></pre>\n\n<p>Sailab: <a href=\"http://www.facejar.com/member/page-id-477.html\" rel=\"nofollow\">http://www.facejar.com/member/page-id-477.html</a></p>\n" }, { "answer_id": 11121061, "author": "Erel Segal-Halevi", "author_id": 827927, "author_profile": "https://Stackoverflow.com/users/827927", "pm_score": 1, "selected": false, "text": "<p>If you run Tomcat on Windows, you can use the neat \"Tomcat Monitor\" application that ships with Tomcat.</p>\n\n<p>Go to the Java tab. At the bottom, below the \"Java Options\" textarea, you will find 3 input fields:</p>\n\n<ul>\n<li>Initial memory pool <strong><em>_</em>__</strong> MB</li>\n<li>Maximum memory pool <strong><em>_</em>__</strong> MB</li>\n<li>Thread stack size <strong><em>_</em>____</strong> KB</li>\n</ul>\n" }, { "answer_id": 36162707, "author": "Torge", "author_id": 2075537, "author_profile": "https://Stackoverflow.com/users/2075537", "pm_score": 0, "selected": false, "text": "<p>In my case there was a /etc/sysconfig/tomcat5.conf file overwriting all settings in /etc/tomcat5/tomcat5.conf</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1282409/" ]
I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA\_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't. As per the comment below, CATALINA\_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.
Serhii's suggestion works and here is some more detail. If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA\_HOME/bin/setenv.sh with contents ``` export JAVA_OPTS="-server -Xmx512m" ``` For Windows you will need, in setenv.bat, something like ``` set JAVA_OPTS=-server -Xmx768m ``` Hope this helps, Glenn
286,021
<p>We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise.</p> <p>We have two sites:</p> <p>1) Flex / Flash 2) HTML</p> <p>I think with Flex I can attempt to download <a href="http://youtube.com/crossdomain.xml" rel="noreferrer">http://youtube.com/crossdomain.xml</a> and if it is valid XML assume the site is available</p> <p>But with HTML I don't know how to do it. I can't even think of a 'nice hack'.</p>
[ { "answer_id": 286055, "author": "Tristan Havelick", "author_id": 30529, "author_profile": "https://Stackoverflow.com/users/30529", "pm_score": 3, "selected": false, "text": "<p>This should work. Basically, it loads a youtube.com javascript file, then checks if a function in that file exists. </p>\n\n<pre><code>&lt;html&gt;\n\n&lt;head&gt;\n &lt;script src=\"http://www.youtube.com/js/account.js\"&gt;&lt;/script&gt;\n &lt;script&gt;\n function has_you_tube()\n {\n if(typeof addVideosToQuicklist == 'function')\n {\n return true;\n }\n else\n {\n return false;\n }\n\n }\n &lt;/script&gt;\n\n&lt;/head&gt;\n&lt;body&gt;\n &lt;script&gt;alert( \"has_youtube: \" + has_you_tube() ); &lt;/script&gt;\n&lt;/body&gt;\n\n\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 286066, "author": "lacker", "author_id": 2652, "author_profile": "https://Stackoverflow.com/users/2652", "pm_score": 4, "selected": false, "text": "<p>You can load an image from youtube using javascript and check its properties. The favicon is tiny and has a consistent url -</p>\n\n<pre><code>var image = new Image();\nimage.src = \"http://youtube.com/favicon.ico\";\nif (image.height &gt; 0) {\n // The user can access youtube\n} else {\n // The user can't access youtube\n}\n</code></pre>\n\n<p>I think this is slightly better than loading javascript because this won't try to run any code, and while youtube might rename their javascript files, or functions from those files, they are unlikely to ever rename their favicon.</p>\n" }, { "answer_id": 1804634, "author": "tiangolo", "author_id": 219530, "author_profile": "https://Stackoverflow.com/users/219530", "pm_score": 5, "selected": true, "text": "<p>I like lacker's solution, but yes, it creates a <a href=\"http://en.wikipedia.org/wiki/Race_condition\" rel=\"noreferrer\" title=\"Race Condition on Wikipedia\">race condition</a>.\nThis will work and won't create a race contition:</p>\n\n<pre><code>var image = new Image();\nimage.onload = function(){\n// The user can access youtube\n};\nimage.onerror = function(){\n// The user can't access youtube\n};\nimage.src = \"http://youtube.com/favicon.ico\";\n</code></pre>\n" }, { "answer_id": 19913153, "author": "mdogggg", "author_id": 2094986, "author_profile": "https://Stackoverflow.com/users/2094986", "pm_score": 1, "selected": false, "text": "<p>I got stuck on this today and tried the favicon test but it wasnt working in IE. I was using the <a href=\"https://developers.google.com/youtube/iframe_api_reference#loadVideoById\" rel=\"nofollow\">YouTube Player API Reference for iframe Embeds</a> to embed youtube videos into my site so what I did is perform a check on the player var defined just before the onYouTubeIFrameReady with a delay on the javascript call.</p>\n\n<pre><code>&lt;script&gt; function YouTubeTester() { \n if (player == undefined) {\n alert(\"youtube blocked\");\n }\n }\n&lt;/script&gt;\n&lt;script&gt;window.setTimeout(\"YouTubeTester()\", 500);&lt;/script&gt;\n</code></pre>\n\n<p>Seems to work for me. I needed the delay to get it to work in IE. </p>\n" }, { "answer_id": 32099792, "author": "Muyiwa Familoni", "author_id": 5244102, "author_profile": "https://Stackoverflow.com/users/5244102", "pm_score": 0, "selected": false, "text": "<p>This worked for me... Its also my first post, hope it helps some one too.</p>\n\n<pre><code>&lt;?php\n\n$v = file_get_contents(\"https://www.youtube.com/iframe_api\");\n\n//Tie counts to a variable\n$test = substr_count($v, 'loading');\n\nif ($test &gt; 0)\n\n{ ?&gt;\n &lt;iframe&gt;YOUTUBE VIDEO GOES HERE&lt;/iframe&gt;\n\n &lt;?php\n}\n\nelse\n\n{\n\necho \"&lt;br/&gt; no connection\";\n\n}\n\n?&gt;\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise. We have two sites: 1) Flex / Flash 2) HTML I think with Flex I can attempt to download <http://youtube.com/crossdomain.xml> and if it is valid XML assume the site is available But with HTML I don't know how to do it. I can't even think of a 'nice hack'.
I like lacker's solution, but yes, it creates a [race condition](http://en.wikipedia.org/wiki/Race_condition "Race Condition on Wikipedia"). This will work and won't create a race contition: ``` var image = new Image(); image.onload = function(){ // The user can access youtube }; image.onerror = function(){ // The user can't access youtube }; image.src = "http://youtube.com/favicon.ico"; ```
286,031
<p>I am trying to share DTO's from my datalayer assembly between the client and WCF service. This works using svcutil, but doesn't work when using VS2008. VS2008 generates it's own DTO objects whereas svcutil uses the shared data type.</p> <p>The svcutil parameters I used are:</p> <pre><code>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcUtil" /serializer:DataContractSerializer /language:vb /out:ServiceClient.cs /namespace:*,CommonWCF /noconfig /reference:"D:\trunk\DataLayer\bin\Debug\DataLayer.dll" /collectionType:System.Collections.Generic.List`1 http://localhost:3371/Common.svc </code></pre> <p>I read that VS2008 just calls svcutil behind the scenes, so why doesn't it work? I really want to avoid adding a manual process to the build process.</p>
[ { "answer_id": 289308, "author": "Preet Sangha", "author_id": 30225, "author_profile": "https://Stackoverflow.com/users/30225", "pm_score": 0, "selected": false, "text": "<p>If you avoid using a service reference, and just include a reference to the the svcutil generated code then this should avoid this issue. Our DTO's are in shared assemblies.</p>\n" }, { "answer_id": 292371, "author": "ptutt", "author_id": 24681, "author_profile": "https://Stackoverflow.com/users/24681", "pm_score": 1, "selected": true, "text": "<p>I created a batch file which calls svcutil and added it as a pre-build task to avoid this being a manual operation. This has solved my problem, but I am still not sure why there is a different behaviour between svcutil and the vs2008 gui method.</p>\n" }, { "answer_id": 397970, "author": "oefe", "author_id": 49793, "author_profile": "https://Stackoverflow.com/users/49793", "pm_score": 2, "selected": false, "text": "<p>Just use <code>ClientFactory&lt;T&gt;</code>.</p>\n\n<p>You don't really need either svcutil nor a service reference. The code which they generate is only a bloated wrapper around ClientFactory that adds virtually no functionality.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24681/" ]
I am trying to share DTO's from my datalayer assembly between the client and WCF service. This works using svcutil, but doesn't work when using VS2008. VS2008 generates it's own DTO objects whereas svcutil uses the shared data type. The svcutil parameters I used are: ``` "C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcUtil" /serializer:DataContractSerializer /language:vb /out:ServiceClient.cs /namespace:*,CommonWCF /noconfig /reference:"D:\trunk\DataLayer\bin\Debug\DataLayer.dll" /collectionType:System.Collections.Generic.List`1 http://localhost:3371/Common.svc ``` I read that VS2008 just calls svcutil behind the scenes, so why doesn't it work? I really want to avoid adding a manual process to the build process.
I created a batch file which calls svcutil and added it as a pre-build task to avoid this being a manual operation. This has solved my problem, but I am still not sure why there is a different behaviour between svcutil and the vs2008 gui method.
286,039
<p>Is there a way to get the count of rows in all tables in a MySQL database without running a <code>SELECT count()</code> on each table?</p>
[ { "answer_id": 286047, "author": "gpojd", "author_id": 28071, "author_profile": "https://Stackoverflow.com/users/28071", "pm_score": 8, "selected": false, "text": "<p>You can probably put something together with <a href=\"http://dev.mysql.com/doc/refman/5.0/en/tables-table.html\" rel=\"noreferrer\">Tables table</a>. I've never done it, but it looks like it has a column for <em>TABLE_ROWS</em> and one for <em>TABLE NAME</em>. </p>\n\n<p>To get rows per table, you can use a query like this: </p>\n\n<pre><code>SELECT table_name, table_rows\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = '**YOUR SCHEMA**';\n</code></pre>\n" }, { "answer_id": 286048, "author": "Hates_", "author_id": 3410, "author_profile": "https://Stackoverflow.com/users/3410", "pm_score": 10, "selected": true, "text": "<pre><code>SELECT SUM(TABLE_ROWS) \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = '{your_db}';\n</code></pre>\n\n<p><a href=\"https://dev.mysql.com/doc/refman/5.7/en/tables-table.html\" rel=\"noreferrer\">Note from the docs though:</a> For InnoDB tables, <strong>the row count is only a rough estimate</strong> used in SQL optimization. You'll need to use COUNT(*) for exact counts (which is more expensive).</p>\n" }, { "answer_id": 5477237, "author": "Jake Drew", "author_id": 682656, "author_profile": "https://Stackoverflow.com/users/682656", "pm_score": 4, "selected": false, "text": "<p>This stored procedure lists tables, counts records, and produces a total number of records at the end.</p>\n\n<p>To run it after adding this procedure:</p>\n\n<pre><code>CALL `COUNT_ALL_RECORDS_BY_TABLE` ();\n</code></pre>\n\n<p>-</p>\n\n<p>The Procedure:</p>\n\n<pre><code>DELIMITER $$\n\nCREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `COUNT_ALL_RECORDS_BY_TABLE`()\nBEGIN\nDECLARE done INT DEFAULT 0;\nDECLARE TNAME CHAR(255);\n\nDECLARE table_names CURSOR for \n SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE();\n\nDECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n\nOPEN table_names; \n\nDROP TABLE IF EXISTS TCOUNTS;\nCREATE TEMPORARY TABLE TCOUNTS \n (\n TABLE_NAME CHAR(255),\n RECORD_COUNT INT\n ) ENGINE = MEMORY; \n\n\nWHILE done = 0 DO\n\n FETCH NEXT FROM table_names INTO TNAME;\n\n IF done = 0 THEN\n SET @SQL_TXT = CONCAT(\"INSERT INTO TCOUNTS(SELECT '\" , TNAME , \"' AS TABLE_NAME, COUNT(*) AS RECORD_COUNT FROM \", TNAME, \")\");\n\n PREPARE stmt_name FROM @SQL_TXT;\n EXECUTE stmt_name;\n DEALLOCATE PREPARE stmt_name; \n END IF;\n\nEND WHILE;\n\nCLOSE table_names;\n\nSELECT * FROM TCOUNTS;\n\nSELECT SUM(RECORD_COUNT) AS TOTAL_DATABASE_RECORD_CT FROM TCOUNTS;\n\nEND\n</code></pre>\n" }, { "answer_id": 8078817, "author": "Robin Manoli", "author_id": 942621, "author_profile": "https://Stackoverflow.com/users/942621", "pm_score": 2, "selected": false, "text": "<p>If you use the database information_schema, you can use this mysql code (the where part makes the query not show tables that have a null value for rows):</p>\n\n<pre><code>SELECT TABLE_NAME, TABLE_ROWS\nFROM `TABLES`\nWHERE `TABLE_ROWS` &gt;=0\n</code></pre>\n" }, { "answer_id": 8163665, "author": "Michael Voigt", "author_id": 716725, "author_profile": "https://Stackoverflow.com/users/716725", "pm_score": -1, "selected": false, "text": "<p>If you want the exact numbers, use the following ruby script. You need Ruby and RubyGems.</p>\n\n<p>Install following Gems:</p>\n\n<pre><code>$&gt; gem install dbi\n$&gt; gem install dbd-mysql\n</code></pre>\n\n<p>File: count_table_records.rb</p>\n\n<pre><code>require 'rubygems'\nrequire 'dbi'\n\ndb_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')\n\n# Collect all Tables\nsql_1 = db_handler.prepare('SHOW tables;')\nsql_1.execute\ntables = sql_1.map { |row| row[0]}\nsql_1.finish\n\ntables.each do |table_name|\n sql_2 = db_handler.prepare(\"SELECT count(*) FROM #{table_name};\")\n sql_2.execute\n sql_2.each do |row|\n puts \"Table #{table_name} has #{row[0]} rows.\"\n end\n sql_2.finish\nend\n\ndb_handler.disconnect\n</code></pre>\n\n<p>Go back to the command-line:</p>\n\n<pre><code>$&gt; ruby count_table_records.rb\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Table users has 7328974 rows.\n</code></pre>\n" }, { "answer_id": 8690288, "author": "Nathan", "author_id": 71650, "author_profile": "https://Stackoverflow.com/users/71650", "pm_score": 7, "selected": false, "text": "<p>Like @Venkatramanan and others I found INFORMATION_SCHEMA.TABLES unreliable (using InnoDB, MySQL 5.1.44), giving different row counts each time I run it even on quiesced tables. Here's a relatively hacky (but flexible/adaptable) way of generating a big SQL statement you can paste into a new query, without installing Ruby gems and stuff.</p>\n\n<pre><code>SELECT CONCAT(\n 'SELECT \"', \n table_name, \n '\" AS table_name, COUNT(*) AS exact_row_count FROM `', \n table_schema,\n '`.`',\n table_name, \n '` UNION '\n) \nFROM INFORMATION_SCHEMA.TABLES \nWHERE table_schema = '**my_schema**';\n</code></pre>\n\n<p>It produces output like this:</p>\n\n<pre><code>SELECT \"func\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.func UNION \nSELECT \"general_log\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.general_log UNION \nSELECT \"help_category\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_category UNION \nSELECT \"help_keyword\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_keyword UNION \nSELECT \"help_relation\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_relation UNION \nSELECT \"help_topic\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_topic UNION \nSELECT \"host\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.host UNION \nSELECT \"ndb_binlog_index\" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.ndb_binlog_index UNION \n</code></pre>\n\n<p>Copy and paste except for the last UNION to get nice output like,</p>\n\n<pre><code>+------------------+-----------------+\n| table_name | exact_row_count |\n+------------------+-----------------+\n| func | 0 |\n| general_log | 0 |\n| help_category | 37 |\n| help_keyword | 450 |\n| help_relation | 990 |\n| help_topic | 504 |\n| host | 0 |\n| ndb_binlog_index | 0 |\n+------------------+-----------------+\n8 rows in set (0.01 sec)\n</code></pre>\n" }, { "answer_id": 10009253, "author": "koswara1482", "author_id": 1312571, "author_profile": "https://Stackoverflow.com/users/1312571", "pm_score": 0, "selected": false, "text": "<p>This is how I count TABLES and ALL RECORDS using PHP:</p>\n\n<pre><code>$dtb = mysql_query(\"SHOW TABLES\") or die (mysql_error());\n$jmltbl = 0;\n$jml_record = 0;\n$jml_record = 0;\n\nwhile ($row = mysql_fetch_array($dtb)) { \n $sql1 = mysql_query(\"SELECT * FROM \" . $row[0]); \n $jml_record = mysql_num_rows($sql1); \n echo \"Table: \" . $row[0] . \": \" . $jml_record record . \"&lt;br&gt;\"; \n $jmltbl++;\n $jml_record += $jml_record;\n}\n\necho \"--------------------------------&lt;br&gt;$jmltbl Tables, $jml_record &gt; records.\";\n</code></pre>\n" }, { "answer_id": 11778602, "author": "Gustavo Castro", "author_id": 1571560, "author_profile": "https://Stackoverflow.com/users/1571560", "pm_score": 4, "selected": false, "text": "<pre><code> SELECT TABLE_NAME,SUM(TABLE_ROWS) \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = 'your_db' \n GROUP BY TABLE_NAME;\n</code></pre>\n\n<p>That's all you need.</p>\n" }, { "answer_id": 11803106, "author": "user1575139", "author_id": 1575139, "author_profile": "https://Stackoverflow.com/users/1575139", "pm_score": 1, "selected": false, "text": "<p>The following query produces a(nother) query that will get the value of count(*) for every table, from every schema, listed in information_schema.tables. The entire result of the query shown here - all rows taken together - comprise a valid SQL statement ending in a semicolon - no dangling 'union'. The dangling union is avoided by use of a union in the query below.</p>\n\n<pre><code>select concat('select \"', table_schema, '.', table_name, '\" as `schema.table`,\n count(*)\n from ', table_schema, '.', table_name, ' union ') as 'Query Row'\n from information_schema.tables\n union\n select '(select null, null limit 0);';\n</code></pre>\n" }, { "answer_id": 17820410, "author": "djburdick", "author_id": 181585, "author_profile": "https://Stackoverflow.com/users/181585", "pm_score": 6, "selected": false, "text": "<p>I just run:</p>\n\n<pre><code>show table status;\n</code></pre>\n\n<p>This will give you the row count for EVERY table plus a bunch of other info.\nI used to use the selected answer above, but this is much easier.</p>\n\n<p>I'm not sure if this works with all versions, but I'm using 5.5 with InnoDB engine.</p>\n" }, { "answer_id": 21794208, "author": "Nimesh07", "author_id": 2524176, "author_profile": "https://Stackoverflow.com/users/2524176", "pm_score": 2, "selected": false, "text": "<p>You can try this. It is working fine for me.</p>\n\n<pre><code>SELECT IFNULL(table_schema,'Total') \"Database\",TableCount \nFROM (SELECT COUNT(1) TableCount,table_schema \n FROM information_schema.tables \n WHERE table_schema NOT IN ('information_schema','mysql') \n GROUP BY table_schema WITH ROLLUP) A;\n</code></pre>\n" }, { "answer_id": 22483503, "author": "lsaffie", "author_id": 1161661, "author_profile": "https://Stackoverflow.com/users/1161661", "pm_score": 1, "selected": false, "text": "<p>This is what I do to get the actual count (no using the schema) </p>\n\n<p>It's slower but more accurate.</p>\n\n<p>It's a two step process at</p>\n\n<ol>\n<li><p>Get list of tables for your db. You can get it using </p>\n\n<pre><code>mysql -uroot -p mydb -e \"show tables\"\n</code></pre></li>\n<li><p>Create and assign the list of tables to the array variable in this bash script (separated by a single space just like in the code below)</p>\n\n<pre><code>array=( table1 table2 table3 )\n\nfor i in \"${array[@]}\"\ndo\n echo $i\n mysql -uroot mydb -e \"select count(*) from $i\"\ndone\n</code></pre></li>\n<li><p>Run it:</p>\n\n<pre><code>chmod +x script.sh; ./script.sh\n</code></pre></li>\n</ol>\n" }, { "answer_id": 25373966, "author": "apotek", "author_id": 1499866, "author_profile": "https://Stackoverflow.com/users/1499866", "pm_score": 0, "selected": false, "text": "<p>Poster wanted row counts without counting, but didn't specify which table engine. With InnoDB, I only know one way, which is to count.</p>\n\n<p>This is how I pick my potatoes:</p>\n\n<pre><code># Put this function in your bash and call with:\n# rowpicker DBUSER DBPASS DBNAME [TABLEPATTERN]\nfunction rowpicker() {\n UN=$1\n PW=$2\n DB=$3\n if [ ! -z \"$4\" ]; then\n PAT=\"LIKE '$4'\"\n tot=-2\n else\n PAT=\"\"\n tot=-1\n fi\n for t in `mysql -u \"$UN\" -p\"$PW\" \"$DB\" -e \"SHOW TABLES $PAT\"`;do\n if [ $tot -lt 0 ]; then\n echo \"Skipping $t\";\n let \"tot += 1\";\n else\n c=`mysql -u \"$UN\" -p\"$PW\" \"$DB\" -e \"SELECT count(*) FROM $t\"`;\n c=`echo $c | cut -d \" \" -f 2`;\n echo \"$t: $c\";\n let \"tot += c\";\n fi;\n done;\n echo \"total rows: $tot\"\n}\n</code></pre>\n\n<p>I am making no assertions about this other than that this is a really ugly but effective way to get how many rows exist in each table in the database regardless of table engine and without having to have permission to install stored procedures, and without needing to install ruby or php. Yes, its rusty. Yes it counts. count(*) is accurate.</p>\n" }, { "answer_id": 29371708, "author": "AdamMc331", "author_id": 3131147, "author_profile": "https://Stackoverflow.com/users/3131147", "pm_score": -1, "selected": false, "text": "<p>If you know the number of tables and their names, and assuming they each have primary keys, you can use a cross join in combination with <code>COUNT(distinct [column])</code> to get the rows that come from each table:</p>\n\n<pre><code>SELECT \n COUNT(distinct t1.id) + \n COUNT(distinct t2.id) + \n COUNT(distinct t3.id) AS totalRows\nFROM firstTable t1, secondTable t2, thirdTable t3;\n</code></pre>\n\n<p>Here is an <a href=\"http://sqlfiddle.com/#!9/772b4/1\" rel=\"nofollow\">SQL Fiddle</a> example.</p>\n" }, { "answer_id": 40461844, "author": "filimonov", "author_id": 1555175, "author_profile": "https://Stackoverflow.com/users/1555175", "pm_score": 2, "selected": false, "text": "<p>One more option: for non InnoDB it uses data from information_schema.TABLES (as it's faster), for InnoDB - select count(*) to get the accurate count. Also it ignores views.</p>\n\n<pre><code>SET @table_schema = DATABASE();\n-- or SET @table_schema = 'my_db_name';\n\nSET GROUP_CONCAT_MAX_LEN=131072;\nSET @selects = NULL;\n\nSELECT GROUP_CONCAT(\n 'SELECT \"', table_name,'\" as TABLE_NAME, COUNT(*) as TABLE_ROWS FROM `', table_name, '`'\n SEPARATOR '\\nUNION\\n') INTO @selects\n FROM information_schema.TABLES\n WHERE TABLE_SCHEMA = @table_schema\n AND ENGINE = 'InnoDB'\n AND TABLE_TYPE = \"BASE TABLE\";\n\nSELECT CONCAT_WS('\\nUNION\\n',\n CONCAT('SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND ENGINE &lt;&gt; \"InnoDB\" AND TABLE_TYPE = \"BASE TABLE\"'),\n @selects) INTO @selects;\n\nPREPARE stmt FROM @selects;\nEXECUTE stmt USING @table_schema;\nDEALLOCATE PREPARE stmt;\n</code></pre>\n\n<p>If your database has a lot of big InnoDB tables counting all rows can take more time.</p>\n" }, { "answer_id": 40805736, "author": "user3260912", "author_id": 3260912, "author_profile": "https://Stackoverflow.com/users/3260912", "pm_score": 3, "selected": false, "text": "<p>There's a bit of a hack/workaround to this estimate problem.</p>\n\n<p>Auto_Increment - for some reason this returns a much more accurate row count for your database if you have auto increment set up on tables.</p>\n\n<p>Found this when exploring why show table info did not match up with the actual data.</p>\n\n<pre><code>SELECT\ntable_schema 'Database',\nSUM(data_length + index_length) AS 'DBSize',\nSUM(TABLE_ROWS) AS DBRows,\nSUM(AUTO_INCREMENT) AS DBAutoIncCount\nFROM information_schema.tables\nGROUP BY table_schema;\n\n\n+--------------------+-----------+---------+----------------+\n| Database | DBSize | DBRows | DBAutoIncCount |\n+--------------------+-----------+---------+----------------+\n| Core | 35241984 | 76057 | 8341 |\n| information_schema | 163840 | NULL | NULL |\n| jspServ | 49152 | 11 | 856 |\n| mysql | 7069265 | 30023 | 1 |\n| net_snmp | 47415296 | 95123 | 324 |\n| performance_schema | 0 | 1395326 | NULL |\n| sys | 16384 | 6 | NULL |\n| WebCal | 655360 | 2809 | NULL |\n| WxObs | 494256128 | 530533 | 3066752 |\n+--------------------+-----------+---------+----------------+\n9 rows in set (0.40 sec)\n</code></pre>\n\n<p>You could then easily use PHP or whatever to return the max of the 2 data columns to give the \"best estimate\" for row count.</p>\n\n<p>i.e. </p>\n\n<pre><code>SELECT\ntable_schema 'Database',\nSUM(data_length + index_length) AS 'DBSize',\nGREATEST(SUM(TABLE_ROWS), SUM(AUTO_INCREMENT)) AS DBRows\nFROM information_schema.tables\nGROUP BY table_schema;\n</code></pre>\n\n<p>Auto Increment will always be +1 * (table count) rows off, but even with 4,000 tables and 3 million rows, that's 99.9% accurate. Much better than the estimated rows.</p>\n\n<p>The beauty of this is that the row counts returned in performance_schema are erased for you, as well, because greatest does not work on nulls. This may be an issue if you have no tables with auto increment, though.</p>\n" }, { "answer_id": 56710008, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 5, "selected": false, "text": "<p>Simple way:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT\n TABLE_NAME, SUM(TABLE_ROWS)\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = '{Your_DB}'\nGROUP BY TABLE_NAME;\n</code></pre>\n\n<p>Result example:</p>\n\n<pre><code>+----------------+-----------------+\n| TABLE_NAME | SUM(TABLE_ROWS) |\n+----------------+-----------------+\n| calls | 7533 |\n| courses | 179 |\n| course_modules | 298 |\n| departments | 58 |\n| faculties | 236 |\n| modules | 169 |\n| searches | 25423 |\n| sections | 532 |\n| universities | 57 |\n| users | 10293 |\n+----------------+-----------------+\n</code></pre>\n" }, { "answer_id": 57100657, "author": "Adam", "author_id": 209568, "author_profile": "https://Stackoverflow.com/users/209568", "pm_score": 0, "selected": false, "text": "<p>Based on @Nathan's answer above, but without needing to \"remove the final union\" and with the option to sort the output, I use the following SQL. It generates another SQL statement which then just run:</p>\n\n<pre><code>select CONCAT( 'select * from (\\n', group_concat( single_select SEPARATOR ' UNION\\n'), '\\n ) Q order by Q.exact_row_count desc') as sql_query\nfrom (\n SELECT CONCAT(\n 'SELECT \"', \n table_name, \n '\" AS table_name, COUNT(1) AS exact_row_count\n FROM `', \n table_schema,\n '`.`',\n table_name, \n '`'\n ) as single_select\n FROM INFORMATION_SCHEMA.TABLES \n WHERE table_schema = 'YOUR_SCHEMA_NAME'\n and table_type = 'BASE TABLE'\n) Q \n</code></pre>\n\n<p>You do need a sufficiently large value of <code>group_concat_max_len</code> server variable but from MariaDb 10.2.4 it should default to 1M.</p>\n" }, { "answer_id": 61436094, "author": "vast", "author_id": 1617079, "author_profile": "https://Stackoverflow.com/users/1617079", "pm_score": -1, "selected": false, "text": "<p>The code below generation the select query for all tales. Just delete last \"UNION ALL\" select all result and paste a new query window to run.</p>\n\n<pre><code>SELECT \nconcat('select ''', table_name ,''' as TableName, COUNT(*) as RowCount from ' , table_name , ' UNION ALL ') as TR FROM\ninformation_schema.tables where \ntable_schema = 'Database Name'\n</code></pre>\n" }, { "answer_id": 72717988, "author": "Jay", "author_id": 11109901, "author_profile": "https://Stackoverflow.com/users/11109901", "pm_score": 0, "selected": false, "text": "<p>I don't know why this has to be so hard but that's life.\nHere's my bash script that performs actual counts. Just save this as (e.g. count_rows.sh ), make it executable (e.g. chmod 755 count_rows.sh ), and run it (e.g. ./count_rows.sh )</p>\n<pre><code>#!/bin/bash\n\nreadarray -t TABLES &lt; &lt;(mysql --skip-column-names -u myuser -pmypassword mydbname -e &quot;show tables&quot;)\n\n# now we have an array like:\n# TABLES='([0]=&quot;customer&quot; [1]=&quot;order&quot; [2]=&quot;product&quot;)'\n# You can print out the array with:\n#declare -p TABLES\n\n\nfor i in &quot;${TABLES[@]}&quot;\ndo\n #echo $i\n COUNT=$(mysql --skip-column-names -u username -pmypassword mydbname -e &quot;select count(*) from $i&quot;)\n echo $i : $COUNT\ndone\n</code></pre>\n" }, { "answer_id": 73653042, "author": "HoldOffHunger", "author_id": 2430549, "author_profile": "https://Stackoverflow.com/users/2430549", "pm_score": 0, "selected": false, "text": "<p>Like many others, I have difficulty getting an accurate value on the <code>INFORMATION_SCHEMA</code> tables with InnoDB, and would infinitely benefit from being able to make a query that depends on <code>count()</code>, and, hopefully, <em>do it in one, single query.</em></p>\n<p>First, make sure to enable massive group_concats:</p>\n<pre><code>SET SESSION group_concat_max_len = 1000000;\n</code></pre>\n<p>Then run this query to get the resultant query you'll run for your database.</p>\n<pre><code>SELECT CONCAT('SELECT ', GROUP_CONCAT(table1.count SEPARATOR ',\\n')) FROM (\n SELECT concat('(SELECT count(id) AS \\'',table_name,' Count\\' ','FROM ',table_name,') AS ',table_name,'_Count') AS 'count'\n FROM information_schema.tables \n WHERE table_schema = '**YOUR_DATABASE_HERE**'\n) AS table1\n</code></pre>\n<p>This will generate output such as...</p>\n<pre><code>SELECT (SELECT count(id) AS 'table1 Count' FROM table1) AS table1_Count,\n (SELECT count(id) AS 'table2 Count' FROM table2) AS table2_Count,\n (SELECT count(id) AS 'table3 Count' FROM table3) AS table3_Count;\n</code></pre>\n<p>This in turn gave the following results:</p>\n<pre><code>*************************** 1. row ***************************\ntable1_Count: 1\ntable2_Count: 1\ntable3_Count: 0\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37204/" ]
Is there a way to get the count of rows in all tables in a MySQL database without running a `SELECT count()` on each table?
``` SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{your_db}'; ``` [Note from the docs though:](https://dev.mysql.com/doc/refman/5.7/en/tables-table.html) For InnoDB tables, **the row count is only a rough estimate** used in SQL optimization. You'll need to use COUNT(\*) for exact counts (which is more expensive).
286,058
<p>If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?</p>
[ { "answer_id": 286063, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>There's some discussion of these factors in the documentation for <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Hashtable.html\" rel=\"nofollow noreferrer\"><code>Hashtable</code></a></p>\n" }, { "answer_id": 286073, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "<p>You need to factor in the hash function as well.</p>\n\n<p>one rule of thumb suggests make the table size about double, so that there is room to expand, and hopefully keep the number of collisions small.</p>\n\n<p>Another rule of thumb is to assume that you are doing some sort of modulo related hashing, then round your table size up to the next largest prime number, and use that prime number as the modulo value.</p>\n\n<p>What kind of things are you hashing? More detail should generate better advice.</p>\n" }, { "answer_id": 286079, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": true, "text": "<p>It depends on the load factor (the \"percent full\" point where the table will increase its size and re-distribute its elements). If you know you have exactly 1000 entries, and that number will never change, you can just set the load factor to 1.0 and the initial size to 1000 for maximum efficiency. If you weren't sure of the exact size, you could leave the load factor at its default of 0.75 and set your initial size to 1334 (expected size/LF) for <em>really</em> good performance, at a cost of extra memory.</p>\n\n<p>You can use the following constructor to set the load factor:</p>\n\n<pre><code>Hashtable(int initialCapacity, float loadFactor) \n</code></pre>\n" }, { "answer_id": 286097, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 0, "selected": false, "text": "<p>Twice is good.</p>\n\n<p>You don't have a big keyset.\nDon't bother about difficult discussions about your HashTable implementation, and go for 2000.</p>\n" }, { "answer_id": 286233, "author": "ReneS", "author_id": 33229, "author_profile": "https://Stackoverflow.com/users/33229", "pm_score": 1, "selected": false, "text": "<p>Let it grow. With this size, the automatic handling is fine. Other than that, 2 x size + 1 is a simple formula. Prime numbers are also kind of good, but as soon as your data set reaches a certain size, the hash implementation might decide to rehash and grow the table.</p>\n\n<p>Your keys are driving the effectiveness and are hopefully distinct enough. </p>\n\n<p>Bottom line: Ask the size question when you have problems such as size or slow performance, other than that: Do not worry!</p>\n" }, { "answer_id": 286262, "author": "Terry Lacy", "author_id": 37224, "author_profile": "https://Stackoverflow.com/users/37224", "pm_score": 0, "selected": false, "text": "<p>I'd like to reiterate what <a href=\"https://stackoverflow.com/users/33229/wwwflickrcomphotosrene-germany\">https://stackoverflow.com/users/33229/wwwflickrcomphotosrene-germany</a> said above. 1000 doesn't seem like a very big hash to me. I've been using a lot of hashtables about that size in java without seeing much in the way of performance problems. And I hardly ever muck about with the size or load factor. </p>\n\n<p>If you've run a profiler on your code and determined that the hashtable is your problem, then by all means start tweaking. Otherwise, I wouldn't assume you've got a problem until you're sure.</p>\n\n<p>After all, in most code, the performance problem isn't where you think it is. I try not to anticipate.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36545/" ]
If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?
It depends on the load factor (the "percent full" point where the table will increase its size and re-distribute its elements). If you know you have exactly 1000 entries, and that number will never change, you can just set the load factor to 1.0 and the initial size to 1000 for maximum efficiency. If you weren't sure of the exact size, you could leave the load factor at its default of 0.75 and set your initial size to 1334 (expected size/LF) for *really* good performance, at a cost of extra memory. You can use the following constructor to set the load factor: ``` Hashtable(int initialCapacity, float loadFactor) ```
286,060
<p>ASP.Net 3.5 running under IIS 7 doesn't seem to allow this out of the box.</p> <pre><code> if (!EventLog.SourceExists("MyAppLog")) EventLog.CreateEventSource("MyAppLog", "Application"); EventLog myLog = new EventLog(); myLog.Source = "MyAppLog"; myLog.WriteEntry("Message"); </code></pre>
[ { "answer_id": 286082, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 6, "selected": true, "text": "<p>This is part of windows security since windows 2003.</p>\n\n<p>You need to create an entry in the registry under HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Eventlog\\Application Make sure that network service or the account you impersonate has permission to this registry key.</p>\n\n<p>@CheGueVerra's link: <a href=\"http://support.microsoft.com/?id=329291\" rel=\"noreferrer\">Requested Registry Access Is Not Allowed</a></p>\n" }, { "answer_id": 7848414, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 5, "selected": false, "text": "<p>I've copied this answer from <a href=\"https://stackoverflow.com/questions/2587453/log4net-eventlogappender-does-not-work-for-asp-net-2-0-website\">here</a> (the question was Log4Net but the answer still applies). The technet link misses a vital step.</p>\n<h3>Create a registry key</h3>\n<p><code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\eventlog\\Application\\MY-AWESOME-APP</code></p>\n<h3>Create a string value inside this</h3>\n<p>Name it <code>EventMessageFile</code>, set its value to</p>\n<blockquote>\n<p>C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll</p>\n</blockquote>\n<p>That path appears to work in both 64 bit and 32 bit environments.</p>\n<p>With this technique you don't need to set permissions in the registry, and once the key above is created it should just work.</p>\n<p><strong>Alternatively</strong><br />\nIf you don't have a large server farm but just a small &quot;web garden&quot; you could run a console application on each server that creates the event log source using <a href=\"http://msdn.microsoft.com/en-us/library/5zbwd3s3.aspx\" rel=\"noreferrer\"><code>EventLog.CreateEventSource</code></a>, make sure the console application is run by an administrator.</p>\n" }, { "answer_id": 34918123, "author": "MacGyver", "author_id": 640205, "author_profile": "https://Stackoverflow.com/users/640205", "pm_score": 3, "selected": false, "text": "<p>Right click the application and choose \"Run as Administrator\"</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25372/" ]
ASP.Net 3.5 running under IIS 7 doesn't seem to allow this out of the box. ``` if (!EventLog.SourceExists("MyAppLog")) EventLog.CreateEventSource("MyAppLog", "Application"); EventLog myLog = new EventLog(); myLog.Source = "MyAppLog"; myLog.WriteEntry("Message"); ```
This is part of windows security since windows 2003. You need to create an entry in the registry under HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application Make sure that network service or the account you impersonate has permission to this registry key. @CheGueVerra's link: [Requested Registry Access Is Not Allowed](http://support.microsoft.com/?id=329291)
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
[ { "answer_id": 286064, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 5, "selected": true, "text": "<p>I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably).</p>\n\n<p><code>EDIT:</code> What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine.</p>\n\n<pre><code>&gt;&gt;&gt; import decimal\n&gt;&gt;&gt; print(decimal.Decimal(\"1.2\") ** 2)\n1.44\n</code></pre>\n\n<p>The <a href=\"http://docs.python.org/library/decimal.html\" rel=\"noreferrer\">module documentation</a> explains the need for and usage of <code>decimal.Decimal</code> pretty clearly, you should check it out if you haven't yet.</p>\n" }, { "answer_id": 286068, "author": "Doug Currie", "author_id": 33252, "author_profile": "https://Stackoverflow.com/users/33252", "pm_score": 4, "selected": false, "text": "<p>IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal.</p>\n\n<p>Please read <a href=\"http://docs.sun.com/source/806-3568/ncg_goldberg.html\" rel=\"nofollow noreferrer\">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a></p>\n\n<p>Other options besides a Decimal class are </p>\n\n<ul>\n<li><p>using Common Lisp or <a href=\"http://docs.python.org/whatsnew/2.6.html#the-fractions-module\" rel=\"nofollow noreferrer\">Python 2.6</a> or another language with exact rationals</p></li>\n<li><p>converting the doubles to close rationals using, e.g., <a href=\"http://www.ics.uci.edu/~eppstein/numth/frap.c\" rel=\"nofollow noreferrer\">frap</a></p></li>\n</ul>\n" }, { "answer_id": 286119, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>First, your input can be simplified a lot. You don't need to read and parse a file. You can just declare your objects in Python notation. Eval the file.</p>\n\n<pre><code>b = [\n [4.0, -2.0, 1.0],\n [1.0, +5.0, -3.0],\n [2.0, +2.0, +5.0],\n]\ny = [ 11.0, -6.0, 7.0 ]\n</code></pre>\n\n<p>Second, y=-1.2-0.20000000000000001x+0.59999999999999998z isn't unusual. There's no exact representation in binary notation for 0.2 or 0.6. Consequently, the values displayed are the decimal approximations of the original not exact representations. Those are true for just about every kind of floating-point processor there is.</p>\n\n<p>You can try the Python 2.6 <a href=\"http://docs.python.org/library/fractions.html\" rel=\"nofollow noreferrer\">fractions</a> module. There's an older <a href=\"http://infohost.nmt.edu/tcc/help/lang/python/examples/rational/\" rel=\"nofollow noreferrer\">rational</a> package that might help.</p>\n\n<p>Yes, raising floating-point numbers to powers increases the errors. Consequently, you have to be sure to avoid using the right-most positions of the floating-point number, since those bits are mostly noise.</p>\n\n<p>When displaying floating-point numbers, you have to appropriately round them to avoid seeing the noise bits.</p>\n\n<pre><code>&gt;&gt;&gt; a\n0.20000000000000001\n&gt;&gt;&gt; \"%.4f\" % (a,)\n'0.2000'\n</code></pre>\n" }, { "answer_id": 286122, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "<p>Also see <a href=\"https://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-pointrounding-error\">What is a simple example of floating point error</a>, here on SO, which has some answers. The one I give actually uses python as the example language...</p>\n" }, { "answer_id": 287079, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>I'd caution against the decimal module for tasks like this. Its purpose is really more dealing with real-world decimal numbers (eg. matching human bookkeeping practices), with finite precision, not performing exact precision math. There are numbers not exactly representable in decimal just as there are in binary, and performing arithmetic in decimal is also much slower than alternatives.</p>\n\n<p>Instead, if you want exact results you should use rational arithmetic. These will represent numbers as a numerator/denomentator pair, so can exactly represent all rational numbers. If you're only using multiplication and division (rather than operations like square roots that can result in irrational numbers), you will never lose precision.</p>\n\n<p>As others have mentioned, python 2.6 will have a built-in rational type, though note that this isn't really a high-performing implementation - for speed you're better using libraries like <a href=\"http://gmpy.sourceforge.net/\" rel=\"nofollow noreferrer\">gmpy</a>. Just replace your calls to float() to gmpy.mpq() and your code should now give exact results (though you may want to format the results as floats for display purposes).</p>\n\n<p>Here's a slightly tidied version of your code to load a matrix that will use gmpy rationals instead:</p>\n\n<pre><code>def read_matrix(f):\n b,y = [], []\n for line in f:\n bits = line.split(\",\")\n b.append( map(gmpy.mpq, bits[:-1]) )\n y.append(gmpy.mpq(bits[-1]))\n return b,y\n</code></pre>\n" }, { "answer_id": 317171, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>It is not an answer to your question, but related:</p>\n\n<pre><code>#!/usr/bin/env python\nfrom numpy import abs, dot, loadtxt, max\nfrom numpy.linalg import solve\n\ndata = loadtxt('gauss.dat', delimiter=',')\na, b = data[:,:-1], data[:,-1:]\nx = solve(a, b) # here you may use any method you like instead of `solve`\nprint(x)\nprint(max(abs((dot(a, x) - b) / b))) # check solution\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ cat gauss.dat\n4.0, 2.0, 1.0, 11.0\n1.0, 5.0, 3.0, 6.0 \n2.0, 2.0, 5.0, 7.0\n\n$ python loadtxt_example.py\n[[ 2.4]\n [ 0.6]\n [ 0.2]]\n0.0\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338360/" ]
I seem to be losing a lot of precision with floats. For example I need to solve a matrix: ``` 4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 ``` This is the code I use to import the matrix from a text file: ``` f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) ``` I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z: ``` x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 ``` Here is the code I use to rearrange the equations. `b` is a matrix of coefficients and `y` is the answer vector: ``` def equations(b,y): i=0 eqn=[] row=[] while(i<len(b)): j=0 row=[] while(j<len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn ``` However the answers I get back aren't precise to the decimal place. For example, upon rearranging the second equation from above, I should get: ``` y=-1.2-.2x+.6z ``` What I get is: ``` y=-1.2-0.20000000000000001x+0.59999999999999998z ``` This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the `Decimal` class but it does not work well with powers (i.e, `Decimal(x)**2`). Any ideas?
I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably). `EDIT:` What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine. ``` >>> import decimal >>> print(decimal.Decimal("1.2") ** 2) 1.44 ``` The [module documentation](http://docs.python.org/library/decimal.html) explains the need for and usage of `decimal.Decimal` pretty clearly, you should check it out if you haven't yet.
286,062
<p>How would I go about creating a Google map that allows the user to zoom beyond the default zoom levels for the map? Would I have to create a new map type that has a greater maximum zoom? Are there any tutorials out there that show how to do this?</p>
[ { "answer_id": 286064, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 5, "selected": true, "text": "<p>I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably).</p>\n\n<p><code>EDIT:</code> What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine.</p>\n\n<pre><code>&gt;&gt;&gt; import decimal\n&gt;&gt;&gt; print(decimal.Decimal(\"1.2\") ** 2)\n1.44\n</code></pre>\n\n<p>The <a href=\"http://docs.python.org/library/decimal.html\" rel=\"noreferrer\">module documentation</a> explains the need for and usage of <code>decimal.Decimal</code> pretty clearly, you should check it out if you haven't yet.</p>\n" }, { "answer_id": 286068, "author": "Doug Currie", "author_id": 33252, "author_profile": "https://Stackoverflow.com/users/33252", "pm_score": 4, "selected": false, "text": "<p>IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal.</p>\n\n<p>Please read <a href=\"http://docs.sun.com/source/806-3568/ncg_goldberg.html\" rel=\"nofollow noreferrer\">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a></p>\n\n<p>Other options besides a Decimal class are </p>\n\n<ul>\n<li><p>using Common Lisp or <a href=\"http://docs.python.org/whatsnew/2.6.html#the-fractions-module\" rel=\"nofollow noreferrer\">Python 2.6</a> or another language with exact rationals</p></li>\n<li><p>converting the doubles to close rationals using, e.g., <a href=\"http://www.ics.uci.edu/~eppstein/numth/frap.c\" rel=\"nofollow noreferrer\">frap</a></p></li>\n</ul>\n" }, { "answer_id": 286119, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>First, your input can be simplified a lot. You don't need to read and parse a file. You can just declare your objects in Python notation. Eval the file.</p>\n\n<pre><code>b = [\n [4.0, -2.0, 1.0],\n [1.0, +5.0, -3.0],\n [2.0, +2.0, +5.0],\n]\ny = [ 11.0, -6.0, 7.0 ]\n</code></pre>\n\n<p>Second, y=-1.2-0.20000000000000001x+0.59999999999999998z isn't unusual. There's no exact representation in binary notation for 0.2 or 0.6. Consequently, the values displayed are the decimal approximations of the original not exact representations. Those are true for just about every kind of floating-point processor there is.</p>\n\n<p>You can try the Python 2.6 <a href=\"http://docs.python.org/library/fractions.html\" rel=\"nofollow noreferrer\">fractions</a> module. There's an older <a href=\"http://infohost.nmt.edu/tcc/help/lang/python/examples/rational/\" rel=\"nofollow noreferrer\">rational</a> package that might help.</p>\n\n<p>Yes, raising floating-point numbers to powers increases the errors. Consequently, you have to be sure to avoid using the right-most positions of the floating-point number, since those bits are mostly noise.</p>\n\n<p>When displaying floating-point numbers, you have to appropriately round them to avoid seeing the noise bits.</p>\n\n<pre><code>&gt;&gt;&gt; a\n0.20000000000000001\n&gt;&gt;&gt; \"%.4f\" % (a,)\n'0.2000'\n</code></pre>\n" }, { "answer_id": 286122, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "<p>Also see <a href=\"https://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-pointrounding-error\">What is a simple example of floating point error</a>, here on SO, which has some answers. The one I give actually uses python as the example language...</p>\n" }, { "answer_id": 287079, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>I'd caution against the decimal module for tasks like this. Its purpose is really more dealing with real-world decimal numbers (eg. matching human bookkeeping practices), with finite precision, not performing exact precision math. There are numbers not exactly representable in decimal just as there are in binary, and performing arithmetic in decimal is also much slower than alternatives.</p>\n\n<p>Instead, if you want exact results you should use rational arithmetic. These will represent numbers as a numerator/denomentator pair, so can exactly represent all rational numbers. If you're only using multiplication and division (rather than operations like square roots that can result in irrational numbers), you will never lose precision.</p>\n\n<p>As others have mentioned, python 2.6 will have a built-in rational type, though note that this isn't really a high-performing implementation - for speed you're better using libraries like <a href=\"http://gmpy.sourceforge.net/\" rel=\"nofollow noreferrer\">gmpy</a>. Just replace your calls to float() to gmpy.mpq() and your code should now give exact results (though you may want to format the results as floats for display purposes).</p>\n\n<p>Here's a slightly tidied version of your code to load a matrix that will use gmpy rationals instead:</p>\n\n<pre><code>def read_matrix(f):\n b,y = [], []\n for line in f:\n bits = line.split(\",\")\n b.append( map(gmpy.mpq, bits[:-1]) )\n y.append(gmpy.mpq(bits[-1]))\n return b,y\n</code></pre>\n" }, { "answer_id": 317171, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>It is not an answer to your question, but related:</p>\n\n<pre><code>#!/usr/bin/env python\nfrom numpy import abs, dot, loadtxt, max\nfrom numpy.linalg import solve\n\ndata = loadtxt('gauss.dat', delimiter=',')\na, b = data[:,:-1], data[:,-1:]\nx = solve(a, b) # here you may use any method you like instead of `solve`\nprint(x)\nprint(max(abs((dot(a, x) - b) / b))) # check solution\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ cat gauss.dat\n4.0, 2.0, 1.0, 11.0\n1.0, 5.0, 3.0, 6.0 \n2.0, 2.0, 5.0, 7.0\n\n$ python loadtxt_example.py\n[[ 2.4]\n [ 0.6]\n [ 0.2]]\n0.0\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How would I go about creating a Google map that allows the user to zoom beyond the default zoom levels for the map? Would I have to create a new map type that has a greater maximum zoom? Are there any tutorials out there that show how to do this?
I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably). `EDIT:` What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine. ``` >>> import decimal >>> print(decimal.Decimal("1.2") ** 2) 1.44 ``` The [module documentation](http://docs.python.org/library/decimal.html) explains the need for and usage of `decimal.Decimal` pretty clearly, you should check it out if you haven't yet.
286,085
<p>I've installed Subversion on Ubuntu following the guide <em><a href="http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth" rel="nofollow noreferrer">Installation of Subversion on Ubuntu, with Apache, SSL, and BasicAuth.</a></em>.</p> <p>It works, and I was able commit and create different repositories, but somehow, from time to time (sometimes minutes), when trying to do a commit, I'm forced to reset or recreate my user and password with the following command.</p> <pre><code>htpasswd2 -c -m /etc/apache2/dav_svn.passwd $AUTH_USER </code></pre> <p>Because SVN does not recognize my user/password anymore. </p> <p>I'm using TortoiseSVN as SVN Client. I would like to know why this is happening. Maybe it's a configuration issue, or maybe TortoiseSVN is sending invalid credentials, causing a locked account. Since I'm far from being an SVN expert/administrator. Are there some pointers in order to attack the problem.</p>
[ { "answer_id": 286127, "author": "ala", "author_id": 37198, "author_profile": "https://Stackoverflow.com/users/37198", "pm_score": -1, "selected": false, "text": "<p>I'm using TortoiseSVN as well, but on Windows users' passwords are managed by <a href=\"http://en.wikipedia.org/wiki/Active_Directory\" rel=\"nofollow noreferrer\">Active Directory</a> on the network domain. So usernames are in the format <code>&lt;domain&gt;\\&lt;user&gt;</code>. And from time to time (weeks), I need to reset the password; it seems like the password is changed. I just do not know why. </p>\n" }, { "answer_id": 293726, "author": "tommym", "author_id": 37607, "author_profile": "https://Stackoverflow.com/users/37607", "pm_score": 2, "selected": true, "text": "<p>Check if your password-file actually has changed. Do a</p>\n\n<p><code>md5 /etc/apache2/dav_svn.passwd</code> or <code>cat /etc/apache2/dav_svn.passwd</code></p>\n\n<p>when it works, and after it stops working. If it changes, you've gotta figure out why (automatic update from a cronjob? some website/admin tool changing it for you?)</p>\n\n<p>Note that subversion + apache does <em>not</em> change this file in any way if you're using any form of default setup.</p>\n\n<p>I also hope that you replace $AUTH_USER with your proper username ;-) (or at least have exported the variable).</p>\n\n<p>If the file hasn't changed, then it's something else. See if there's anything in the apache error log.</p>\n\n<p>A few other possibilities:</p>\n\n<ul>\n<li>Try disabling https (for testing - since you probably don't have a valid certificate).</li>\n<li>Check your .subversion/auth folder; I'm not sure about tortoisesvn, but I believe it stores credential information there (just like vanilla svn).</li>\n<li>Not likely, but instead of recreating your user see if <code>touch /etc/apache2/dav_svn.passwd</code> will do the trick.</li>\n<li>Is the file writable by anyone but root? If so, <code>chmod 644 /etc/apache2/dav_svn.passwd</code></li>\n</ul>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32424/" ]
I've installed Subversion on Ubuntu following the guide *[Installation of Subversion on Ubuntu, with Apache, SSL, and BasicAuth.](http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth)*. It works, and I was able commit and create different repositories, but somehow, from time to time (sometimes minutes), when trying to do a commit, I'm forced to reset or recreate my user and password with the following command. ``` htpasswd2 -c -m /etc/apache2/dav_svn.passwd $AUTH_USER ``` Because SVN does not recognize my user/password anymore. I'm using TortoiseSVN as SVN Client. I would like to know why this is happening. Maybe it's a configuration issue, or maybe TortoiseSVN is sending invalid credentials, causing a locked account. Since I'm far from being an SVN expert/administrator. Are there some pointers in order to attack the problem.
Check if your password-file actually has changed. Do a `md5 /etc/apache2/dav_svn.passwd` or `cat /etc/apache2/dav_svn.passwd` when it works, and after it stops working. If it changes, you've gotta figure out why (automatic update from a cronjob? some website/admin tool changing it for you?) Note that subversion + apache does *not* change this file in any way if you're using any form of default setup. I also hope that you replace $AUTH\_USER with your proper username ;-) (or at least have exported the variable). If the file hasn't changed, then it's something else. See if there's anything in the apache error log. A few other possibilities: * Try disabling https (for testing - since you probably don't have a valid certificate). * Check your .subversion/auth folder; I'm not sure about tortoisesvn, but I believe it stores credential information there (just like vanilla svn). * Not likely, but instead of recreating your user see if `touch /etc/apache2/dav_svn.passwd` will do the trick. * Is the file writable by anyone but root? If so, `chmod 644 /etc/apache2/dav_svn.passwd`
286,090
<p>The question is actually about stack overflows in C. I have an assigment that I can not get done for the life of me, I've looked at everything in the gdb and I just cant figure it.</p> <p>The question is the following:</p> <pre><code>int i,n; void confused() { printf("who called me"); exit(0); } void shell_call(char *c) { printf(" ***Now calling \"%s\" shell command *** \n",c); system(c); exit(0); } void victim_func() { int a[4]; printf("[8]:%x\n", &amp;a[8]); printf("Enter n: "); scanf("%d",&amp;n); printf("Enter %d HEX Values \n",n); for(i=0;i&lt;n;i++) scanf("%x",&amp;a[i]); printf("Done reading junk numbers\n"); } int main() { printf("ls=736c --- ps = 7370 --- cal = 6c6163\n"); printf("location of confused %x \n", confused); printf("location of shell_call %x \n", shell_call); victim_func(); printf("Done, thank you\n"); } </code></pre> <p>Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications. I did this by running the program, setting <code>N</code> to <code>7</code>, which gets me to the Function Pointer of the <code>victim_func</code> frame, I write <code>a[7]</code> with the memory address of confused or <code>shell_call</code>, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1)</p> <p>My question is the following, how could I control which argument gets passed to the <code>shell_code</code> funcion? ie. how do I write a <code>string</code> to <code>char* c</code>. The whole point is executing unix commands like <strong>ps</strong> etc, by running only the program.</p> <p>I figured writing the EBI pointer with the hex representation of <strong>ps</strong> and setting the arg list of <code>shell_call</code> to that, but that didn't work. I also tried inputing <code>argsv</code> arguments and setting the arg list of <code>shell_call</code> to the <code>arg_list</code> of main, but didn't work either. </p> <p>I think the second version should work, but I believe I'm not setting the arg list of the new stack frame correctly ( I did it by writing <code>a[8]</code> to <code>0</code>, since its the first part of the function pointer, and writing <code>a[9]=736c</code> and <code>a[10]=0000</code>, but its probably not right since those are the parameters of <code>victim_func</code>. So how do I access the parameters of <code>shell_call</code>? </p>
[ { "answer_id": 286221, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 3, "selected": false, "text": "<p>I probably shouldn't do your homework for you. But the basically:</p>\n\n<p>You need to get a character buffer somewhere in memory to store the string you want to execute. Obviously, you can do this the same way you are getting the other functions called (i.e. you put the text on the stack as well). After you have that written, you need to write a pointer to it on to the stack in the location that the shell_code function expects to find its arguments.</p>\n\n<p>The best way to figure this out without me doing <em>all</em> of the work for you is to write down your stack/memory contents on a piece of paper/whiteboard. Write down how it would look if you called shell_code normally from inside the program. Then write down what the stack looks like inside victum_func and figure out which things to change to get it to look like it would look \"naturally\" (of course keeping in mind some things are \"don't cares\" like the return address).</p>\n\n<p>That's all the charity you're gonna get from me today! :-P</p>\n" }, { "answer_id": 292514, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 1, "selected": false, "text": "<p>You need to manipulate the stack-frame of the caller (<code>main()</code>), and arrange it in such a way that returning to <code>shell_call()</code> from the epilog of the overflowed <code>victim_func()</code> the latter could find a settled stack as it was been called by the main. </p>\n\n<p>In doing so you probably have to mangle the frame-pointer in the stackframe of the victim, that will be restored in %ebp by means of <code>leave</code>.</p>\n" }, { "answer_id": 292534, "author": "bdd", "author_id": 67445, "author_profile": "https://Stackoverflow.com/users/67445", "pm_score": 2, "selected": false, "text": "<p>SoapBox already did a great job of leading you in the right direction.</p>\n\n<p>For more information;\n<a href=\"http://www.skullsecurity.org/wiki/index.php/Example_4\" rel=\"nofollow noreferrer\">http://www.skullsecurity.org/wiki/index.php/Example_4</a></p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The question is actually about stack overflows in C. I have an assigment that I can not get done for the life of me, I've looked at everything in the gdb and I just cant figure it. The question is the following: ``` int i,n; void confused() { printf("who called me"); exit(0); } void shell_call(char *c) { printf(" ***Now calling \"%s\" shell command *** \n",c); system(c); exit(0); } void victim_func() { int a[4]; printf("[8]:%x\n", &a[8]); printf("Enter n: "); scanf("%d",&n); printf("Enter %d HEX Values \n",n); for(i=0;i<n;i++) scanf("%x",&a[i]); printf("Done reading junk numbers\n"); } int main() { printf("ls=736c --- ps = 7370 --- cal = 6c6163\n"); printf("location of confused %x \n", confused); printf("location of shell_call %x \n", shell_call); victim_func(); printf("Done, thank you\n"); } ``` Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications. I did this by running the program, setting `N` to `7`, which gets me to the Function Pointer of the `victim_func` frame, I write `a[7]` with the memory address of confused or `shell_call`, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1) My question is the following, how could I control which argument gets passed to the `shell_code` funcion? ie. how do I write a `string` to `char* c`. The whole point is executing unix commands like **ps** etc, by running only the program. I figured writing the EBI pointer with the hex representation of **ps** and setting the arg list of `shell_call` to that, but that didn't work. I also tried inputing `argsv` arguments and setting the arg list of `shell_call` to the `arg_list` of main, but didn't work either. I think the second version should work, but I believe I'm not setting the arg list of the new stack frame correctly ( I did it by writing `a[8]` to `0`, since its the first part of the function pointer, and writing `a[9]=736c` and `a[10]=0000`, but its probably not right since those are the parameters of `victim_func`. So how do I access the parameters of `shell_call`?
I probably shouldn't do your homework for you. But the basically: You need to get a character buffer somewhere in memory to store the string you want to execute. Obviously, you can do this the same way you are getting the other functions called (i.e. you put the text on the stack as well). After you have that written, you need to write a pointer to it on to the stack in the location that the shell\_code function expects to find its arguments. The best way to figure this out without me doing *all* of the work for you is to write down your stack/memory contents on a piece of paper/whiteboard. Write down how it would look if you called shell\_code normally from inside the program. Then write down what the stack looks like inside victum\_func and figure out which things to change to get it to look like it would look "naturally" (of course keeping in mind some things are "don't cares" like the return address). That's all the charity you're gonna get from me today! :-P
286,093
<p>I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.</p> <p>Here's what I thought would work:</p> <pre class="lang-cs prettyprint-override"><code>[Test] public void just_once() { var key = "id_of_something"; var source = MockRepository.GenerateStub&lt;ISomeDataSource&gt;(); source.Expect(x =&gt; x.GetSomethingThatTakesALotOfResources(key)) .Return(new Something()) .Repeat.Once(); var client = new Client(soure); // the first call I expect the client to use the source client.GetMeMyThing(key); // the second call the result should be cached // and source is not used client.GetMeMyThing(key); } </code></pre> <p>I want this test to fail if the second invocation of <code>GetMeMyThing()</code> calls <code>source.GetSomethingThatTakesALotOfResources()</code>.</p>
[ { "answer_id": 286125, "author": "Christopher Bennage", "author_id": 6855, "author_profile": "https://Stackoverflow.com/users/6855", "pm_score": 2, "selected": false, "text": "<p>Here is what I just did (as recommended by <a href=\"http://twitter.com/rayhouston/statuses/1003171744\" rel=\"nofollow noreferrer\">Ray Houston</a>). I would still appreciate a more elegant solution...</p>\n\n<pre><code>[Test]\npublic void just_once()\n{\n var key = \"id_of_something\";\n\n var source = MockRepository.GenerateStub&lt;ISomeDataSource&gt;();\n\n // set a positive expectation\n source.Expect(x =&gt; x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .Repeat.Once();\n\n var client = new Client(soure);\n\n client.GetMeMyThing(key);\n\n // set a negative expectation\n source.Expect(x =&gt; x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .Repeat.Never();\n\n client.GetMeMyThing(key);\n}\n</code></pre>\n" }, { "answer_id": 286176, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>You may be interested in <a href=\"http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx#Thedifferencebetweenstubsandmocks\" rel=\"noreferrer\">this bit</a> from the Rhino Mocks 3.5 Documentation (quoted below). Looks like you need to mock the class, not stub it, for it to work the way you expect.</p>\n\n<blockquote>\n <p>The difference between stubs and mocks</p>\n \n <p>...</p>\n \n <p>A mock is an object that we can set\n expectations on, and which will verify\n that the expected actions have indeed\n occurred. A stub is an object that you\n use in order to pass to the code under\n test. You can setup expectations on\n it, so it would act in certain ways,\n but those expectations will never be\n verified. A stub's properties will\n automatically behave like normal\n properties, and you can't set\n expectations on them.</p>\n \n <p>If you want to verify the behavior of\n the code under test, you will use a\n mock with the appropriate expectation,\n and verify that. If you want just to\n pass a value that may need to act in a\n certain way, but isn't the focus of\n this test, you will use a stub.</p>\n \n <p>IMPORTANT: A stub will never cause a\n test to fail.</p>\n</blockquote>\n" }, { "answer_id": 568446, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 6, "selected": true, "text": "<p>Here's how I'd verify a method is called once.</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>[Test]\npublic void just_once()\n{\n // Arrange (Important to GenerateMock not GenerateStub)\n var a = MockRepository.GenerateMock&lt;ISomeDataSource&gt;();\n a.Expect(x =&gt; x.GetSomethingThatTakesALotOfResources()).Return(new Something()).Repeat.Once();\n\n // Act\n // First invocation should call GetSomethingThatTakesALotOfResources\n a.GetMeMyThing();\n\n // Second invocation should return cached result\n a.GetMeMyThing();\n\n // Assert\n a.VerifyAllExpectations();\n}\n</code></pre>\n" }, { "answer_id": 773040, "author": "Tim Ottinger", "author_id": 15929, "author_profile": "https://Stackoverflow.com/users/15929", "pm_score": -1, "selected": false, "text": "<p>Having a feature called \"Exactly\" would be handy to write tests on code that might otherwise get into an infinite loop. I would love to write a test such that the second call to a method would raise an exception.</p>\n\n<p>Some libraries for python allow you to sequence expectations, so the first returns false and the second raises an exception.</p>\n\n<p>Rhino won't do that. A partial mock with .Once will intercept the first call, and the rest will be passed on to the original method. So that sucks, but it's true.</p>\n\n<p>You'll have to create a hand-mock. Derive a \"testable\" class, and give it the ability to raise after the first call. </p>\n" }, { "answer_id": 886264, "author": "Jon Cahill", "author_id": 10830, "author_profile": "https://Stackoverflow.com/users/10830", "pm_score": 4, "selected": false, "text": "<p>I have been using the AssertWasCalled extension to get around this problem. This is the best I could find/come up with but it would be better if I didn't have to specify the call twice.</p>\n\n<pre><code> [Test]\n public void just_once()\n {\n var key = \"id_of_something\";\n\n var source = MockRepository.GenerateStub&lt;ISomeDataSource&gt;();\n\n // set a positive expectation\n source.Expect(x =&gt; x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .Repeat.Once();\n\n var client = new Client(soure);\n client.GetMeMyThing(key);\n client.GetMeMyThing(key);\n\n source.AssertWasCalled(x =&gt; x.GetSomethingThatTakesALotOfResources(key),\n x =&gt; x.Repeat.Once());\n source.VerifyAllExpectations();\n }\n</code></pre>\n" }, { "answer_id": 5188515, "author": "Ergwun", "author_id": 177018, "author_profile": "https://Stackoverflow.com/users/177018", "pm_score": 2, "selected": false, "text": "<p>You can pass a delegate to WhenCalled to count calls:</p>\n\n<pre><code>...\nuint callCount = 0;\nsource.Expect(x =&gt; x.GetSomethingThatTakesALotOfResources(key))\n .Return(new Something())\n .WhenCalled((y) =&gt; { callCount++; });\n...\nAssert.AreEqual(1, callCount);\n</code></pre>\n\n<p>Also, you should use a mock not a stub, and verify expectations on the mock too.</p>\n" }, { "answer_id": 47057979, "author": "Balpreet Patil", "author_id": 1351171, "author_profile": "https://Stackoverflow.com/users/1351171", "pm_score": 0, "selected": false, "text": "<p>You can create strict mock, if you want to ensure that a method is called only once.</p>\n\n<pre><code>var mock = MockRepository.GenerateStrictMock&lt;IMustOnlyBeCalledOnce&gt;();\nmock.Expect(a =&gt; a.Process()).Repeat.Once();\nvar helloWorld= new HelloWorld(mock);\n\nhelloworld.Process()\n\nmock.VerifyAllExpectations();\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6855/" ]
I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5. Here's what I thought would work: ```cs [Test] public void just_once() { var key = "id_of_something"; var source = MockRepository.GenerateStub<ISomeDataSource>(); source.Expect(x => x.GetSomethingThatTakesALotOfResources(key)) .Return(new Something()) .Repeat.Once(); var client = new Client(soure); // the first call I expect the client to use the source client.GetMeMyThing(key); // the second call the result should be cached // and source is not used client.GetMeMyThing(key); } ``` I want this test to fail if the second invocation of `GetMeMyThing()` calls `source.GetSomethingThatTakesALotOfResources()`.
Here's how I'd verify a method is called once. ```cs [Test] public void just_once() { // Arrange (Important to GenerateMock not GenerateStub) var a = MockRepository.GenerateMock<ISomeDataSource>(); a.Expect(x => x.GetSomethingThatTakesALotOfResources()).Return(new Something()).Repeat.Once(); // Act // First invocation should call GetSomethingThatTakesALotOfResources a.GetMeMyThing(); // Second invocation should return cached result a.GetMeMyThing(); // Assert a.VerifyAllExpectations(); } ```
286,096
<pre><code>typedef struct { nat id; char *data; } element_struct; typedef element_struct * element; void push(element e, queue s) { nat lt = s-&gt;length; if (lt == max_length - 1) { printf("Error in push: Queue is full.\n"); return; } else { s-&gt;contents[lt] = e; s-&gt;length = lt + 1; } } int main () { push(something_of_type_element, s); } </code></pre> <p>How would i go about formatting "<code>something_of_type_element</code>"?</p> <p>Thanks</p> <p>Notes: nat is the same as int</p>
[ { "answer_id": 286108, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 2, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>element elem = malloc(sizeof(element_struct));\nif (elem == NULL) {\n /* Handle error. */\n}\n\nelem-&gt;id = something;\nelem-&gt;data = something_else;\n\npush(elem, s);\n</code></pre>\n\n<p>Note that there's lots of memory management missing here...</p>\n" }, { "answer_id": 286111, "author": "Judge Maygarden", "author_id": 1491, "author_profile": "https://Stackoverflow.com/users/1491", "pm_score": 2, "selected": true, "text": "<p>Like this:</p>\n\n<pre><code>element_struct foo = { 1, \"bar\" };\npush(&amp;foo, s);\n</code></pre>\n\n<p>If you have a C99 compiler you can do this:</p>\n\n<pre><code>element_struct foo = {\n .id = 1,\n .data = \"bar\"\n};\npush(&amp;foo, s);\n</code></pre>\n\n<p>Note that the data in the structure must be copied if it needs to live longer than the scope in which it was defined. Otherwise, memory can be allocated on the heap with malloc (see below), or a global or static variable could be used.</p>\n\n<pre><code>element_struct foo = malloc(sizeof (element_struct));\n\nfoo.id = 1;\nfoo.data = \"bar\";\npush(foo, s);\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31549/" ]
``` typedef struct { nat id; char *data; } element_struct; typedef element_struct * element; void push(element e, queue s) { nat lt = s->length; if (lt == max_length - 1) { printf("Error in push: Queue is full.\n"); return; } else { s->contents[lt] = e; s->length = lt + 1; } } int main () { push(something_of_type_element, s); } ``` How would i go about formatting "`something_of_type_element`"? Thanks Notes: nat is the same as int
Like this: ``` element_struct foo = { 1, "bar" }; push(&foo, s); ``` If you have a C99 compiler you can do this: ``` element_struct foo = { .id = 1, .data = "bar" }; push(&foo, s); ``` Note that the data in the structure must be copied if it needs to live longer than the scope in which it was defined. Otherwise, memory can be allocated on the heap with malloc (see below), or a global or static variable could be used. ``` element_struct foo = malloc(sizeof (element_struct)); foo.id = 1; foo.data = "bar"; push(foo, s); ```
286,103
<p>Our Windows Forms application by default saves data files in a user's 'My Documents' folder (on XP) or 'Documents' folder (on Vista). We look up this location by calling:</p> <pre><code>Environment.GetFolderPath( Environment.SpecialFolder.Personal ) </code></pre> <p>We know for sure this works great for users whose personal folder is on a local disk. What we're not sure about is domain users who have Folder Redirection in effect for their profile/personal data folders.</p> <p>My question is: <strong>Does the above call properly resolve regardless of whether Folder Redirection is active?</strong></p> <p>I don't have the environment to test this out, and I haven't been able to find any definite confirmation one way or the other.</p>
[ { "answer_id": 286131, "author": "Jon Norton", "author_id": 4797, "author_profile": "https://Stackoverflow.com/users/4797", "pm_score": 1, "selected": false, "text": "<p>I would expect that it does. The documentation for both <code>Environment.GetFolderPath</code> and the underlying <a href=\"http://msdn.microsoft.com/en-us/library/bb762204(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>SHGetSpecialFolderPath</code></a> don't give any indication that it would not resolve correctly nor can I find anything that you would use its place.</p>\n" }, { "answer_id": 286147, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": true, "text": "<p>Yes it does. You can test this out yourself by updating the corresponding registry entry for the folder. Look under ...</p>\n\n<pre><code>\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\\n</code></pre>\n" }, { "answer_id": 11563415, "author": "rachel", "author_id": 423306, "author_profile": "https://Stackoverflow.com/users/423306", "pm_score": 2, "selected": false, "text": "<p>I've had a user reporting the following error on an <code>Environment.GetFolderPath(Environment.SpecialFolder.Personal)</code> call on an XP machine whose My Documents is redirected to the network (it goes to drive O):</p>\n\n<pre><code>System.ArgumentException: Absolute path information is required.\n at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)\n at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)\n at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)\n at System.Environment.GetFolderPath(SpecialFolder folder, SpecialFolderOption option)\n at System.Environment.GetFolderPath(SpecialFolder folder)\n</code></pre>\n\n<p>I haven't had direct access to this machine configuration yet, but from google searches and the user's help, I believe the redirect is lacking a trailing \\ (eg. O: instead of O:\\).</p>\n\n<p>So I believe the answer would be <strong>no, it doesn't correctly resolve everytime</strong>.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17966/" ]
Our Windows Forms application by default saves data files in a user's 'My Documents' folder (on XP) or 'Documents' folder (on Vista). We look up this location by calling: ``` Environment.GetFolderPath( Environment.SpecialFolder.Personal ) ``` We know for sure this works great for users whose personal folder is on a local disk. What we're not sure about is domain users who have Folder Redirection in effect for their profile/personal data folders. My question is: **Does the above call properly resolve regardless of whether Folder Redirection is active?** I don't have the environment to test this out, and I haven't been able to find any definite confirmation one way or the other.
Yes it does. You can test this out yourself by updating the corresponding registry entry for the folder. Look under ... ``` \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\ ```
286,104
<p>Before anybody asks, I am not doing any kind of screenscraping.</p> <p>I'm trying to parse an html string to find a div with a certain id. I cannot for the life of me get this to work. The following expression worked in one instance, but not in another. I'm not sure if it has to do with extra elements in the html or not.</p> <pre><code>&lt;div\s*?id=(\""|&amp;quot;|&amp;#34;)content(\""|&amp;quot;|&amp;#34;).*?&gt;\s*?(?&gt;(?! &lt;div\s*?&gt; | &lt;/div&gt; ) | &lt;div\s*?&gt;(?&lt;DEPTH&gt;) | &lt;/div&gt;(?&lt;-DEPTH&gt;) | .?)*(?(DEPTH)(?!))&lt;/div&gt; </code></pre> <p>It is finding the first div with the right id correctly, but it then closes at the first closing div, and not the related div.</p> <pre><code>&lt;div id="firstdiv"&gt;begining content&lt;div id="content"&gt;some other stuff &lt;div id="otherdiv"&gt;other stuff here&lt;/div&gt; more stuff &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This should bring back</p> <pre><code>&lt;div id="content"&gt;some other stuff &lt;div id="otherdiv"&gt;other stuff here&lt;/div&gt; more stuff &lt;/div&gt; </code></pre> <p>, but for some reason, it is not. It is bring back:</p> <pre><code> &lt;div id="content"&gt;some other stuff &lt;div id="otherdiv"&gt;other stuff here&lt;/div&gt; </code></pre> <p>Does anybody have an easier expression to handle this?</p> <p>To clarify, this is in .NET, and I'm using the DEPTH keyword. You can find more details <a href="http://www.m-8.dk/resources/RegEx-Balancing-Group.aspx" rel="noreferrer">here</a>.</p>
[ { "answer_id": 286113, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 3, "selected": false, "text": "<p>Are you asking for a regular expression that can keep track of the number of DIV tags nested inside a DIV tag? I'm afraid that isn't possible with regular expressions.</p>\n\n<p>You could use a regular expression to get the index of the first DIV tag, then loop over the characters in the string, starting at that index, and keeping a count of the number of open div tags. When you encounter a close div-tag, and the count is zero, then you have the starting and ending indices in the string that contains the substring you want.</p>\n" }, { "answer_id": 286129, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>What programming language? If it's .Net and you're sure the html is well-formed you can load it into an XmlDocument or XDocument object and do an xpath query on it.</p>\n" }, { "answer_id": 286130, "author": "Dan Fego", "author_id": 34426, "author_profile": "https://Stackoverflow.com/users/34426", "pm_score": 2, "selected": false, "text": "<p>Cybis speaks the truth. This sort of stuff falls into Context-Free Languages, which are more powerful than Regular Languages (the kind of things covered by regular expressions). There's a lot of computer science theory involved, but let it rest to say that any language worth its salt will have a library for this sort of stuff written that you should probably be using.</p>\n" }, { "answer_id": 287758, "author": "pro3carp3", "author_id": 7899, "author_profile": "https://Stackoverflow.com/users/7899", "pm_score": 4, "selected": true, "text": "<p>In .NET you can do this:</p>\n\n<pre><code>(?&lt;text&gt;\n(&lt;div\\s*?id=(\\\"|&amp;quot;|&amp;\\#34;)content(\\\"|&amp;quot;|&amp;\\#34;).*?&gt;)\n\n (?&gt;\n .*?&lt;/div&gt;\n |\n .*?&lt;div (?&gt;depth)\n |\n .*?&lt;/div&gt; (?&gt;-depth)\n )*)\n (?(depth)(?!))\n.*?&lt;/div&gt;\n</code></pre>\n\n<p>You must use the singleline option. Here is an example using the console:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\nnamespace Temp\n{\n class Program\n {\n static void Main()\n {\n string s = @\"\n&lt;div id=\"\"firstdiv\"\"&gt;begining content&lt;div id=\"\"content\"\"&gt;some other stuff\n &lt;div id=\"\"otherdiv\"\"&gt;other stuff here&lt;/div&gt;\n more stuff\n &lt;/div&gt;\n&lt;/div&gt;\";\n Regex r = new Regex(@\"(?&lt;text&gt;(&lt;div\\s*?id=(\\\"\"|&amp;quot;|&amp;\\#34;)\"\n + @\"content(\\\"\"|&amp;quot;|&amp;\\#34;).*?&gt;)(?&gt;.*?&lt;/div&gt;|.*?&lt;div \"\n + @\"(?&gt;depth)|.*?&lt;/div&gt; (?&gt;-depth))*)(?(depth)(?!)).*?&lt;/div&gt;\",\n RegexOptions.Singleline);\n Console.WriteLine(\"HTML:\\n\");\n Console.WriteLine(s);\n Match m = r.Match(s);\n if (m.Success)\n {\n Console.WriteLine(\"\\nCaptured text:\\n\");\n Console.WriteLine(m.Groups[4]);\n\n }\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534/" ]
Before anybody asks, I am not doing any kind of screenscraping. I'm trying to parse an html string to find a div with a certain id. I cannot for the life of me get this to work. The following expression worked in one instance, but not in another. I'm not sure if it has to do with extra elements in the html or not. ``` <div\s*?id=(\""|&quot;|&#34;)content(\""|&quot;|&#34;).*?>\s*?(?>(?! <div\s*?> | </div> ) | <div\s*?>(?<DEPTH>) | </div>(?<-DEPTH>) | .?)*(?(DEPTH)(?!))</div> ``` It is finding the first div with the right id correctly, but it then closes at the first closing div, and not the related div. ``` <div id="firstdiv">begining content<div id="content">some other stuff <div id="otherdiv">other stuff here</div> more stuff </div> </div> ``` This should bring back ``` <div id="content">some other stuff <div id="otherdiv">other stuff here</div> more stuff </div> ``` , but for some reason, it is not. It is bring back: ``` <div id="content">some other stuff <div id="otherdiv">other stuff here</div> ``` Does anybody have an easier expression to handle this? To clarify, this is in .NET, and I'm using the DEPTH keyword. You can find more details [here](http://www.m-8.dk/resources/RegEx-Balancing-Group.aspx).
In .NET you can do this: ``` (?<text> (<div\s*?id=(\"|&quot;|&\#34;)content(\"|&quot;|&\#34;).*?>) (?> .*?</div> | .*?<div (?>depth) | .*?</div> (?>-depth) )*) (?(depth)(?!)) .*?</div> ``` You must use the singleline option. Here is an example using the console: ``` using System; using System.Text.RegularExpressions; namespace Temp { class Program { static void Main() { string s = @" <div id=""firstdiv"">begining content<div id=""content"">some other stuff <div id=""otherdiv"">other stuff here</div> more stuff </div> </div>"; Regex r = new Regex(@"(?<text>(<div\s*?id=(\""|&quot;|&\#34;)" + @"content(\""|&quot;|&\#34;).*?>)(?>.*?</div>|.*?<div " + @"(?>depth)|.*?</div> (?>-depth))*)(?(depth)(?!)).*?</div>", RegexOptions.Singleline); Console.WriteLine("HTML:\n"); Console.WriteLine(s); Match m = r.Match(s); if (m.Success) { Console.WriteLine("\nCaptured text:\n"); Console.WriteLine(m.Groups[4]); } Console.ReadLine(); } } } ```
286,105
<p>I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math operations using the C API. The wrapper only consists of a header file and as much use on inlining is made as possible.</p> <p>Is there an appreciable penalty for wrapping the C code versus porting and inlining the implementation directly into the C++ class? This library is used in time critical applications. So, does the boost from eliminating indirection compensate for the maintenance headache of two ports?</p> <p>Example of C interface:</p> <pre><code>typedef float VECTOR3[3]; void v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs); </code></pre> <p>Example of C++ wrapper:</p> <pre><code>class Vector3 { private: VECTOR3 v_; public: // copy constructors, etc... Vector3&amp; operator+=(const Vector3&amp; rhs) { v3_add(&amp;this-&gt;v_, this-&gt;v_, const_cast&lt;VECTOR3&gt; (rhs.v_)); return *this; } Vector3 operator+(const Vector3&amp; rhs) const { Vector3 tmp(*this); tmp += rhs; return tmp; } // more methods... }; </code></pre>
[ { "answer_id": 286116, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 1, "selected": false, "text": "<p>I don't think you'll notice much perf difference. Assuming your target platform support all your data types, </p>\n\n<p>I'm coding for the DS and a few other ARM devices and floating points are evil...I had to typedef float to FixedPoint&lt;16,8></p>\n" }, { "answer_id": 286118, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>If you're just wrapping the C library calls in C++ class functions (in other words, the C++ functions do nothing but call C functions), then the compiler will optimize these calls so that it's not a performance penalty.</p>\n" }, { "answer_id": 286143, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>As usual with everything related to optimization, the answer is that you have to measure the performance itself before you know if the optimization is worthwhile.</p>\n\n<ul>\n<li>Benchmark two different functions, one calling the C-style functions directly and another calling through the wrapper. See which one runs faster, or if the difference is within the margin of error of your measurement (which would mean there is no difference you can measure).</li>\n<li>Look at the assembly code generated by the two functions in the previous step (on gcc, use <code>-S</code> or <code>-save-temps</code>). See if the compiler did something stupid, or if your wrappers have any performance bug.</li>\n</ul>\n\n<p>Unless the performance difference is too big in favor of not using the wrapper, reimplementing is not a good idea, since you risk introducing bugs (which could even cause results which look sane but are wrong). Even if the difference is big, it would be simpler and less risky to just remember C++ is very compatible with C and use your library in the C style even within C++ code.</p>\n" }, { "answer_id": 286341, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "<p>If you are worried that the overhead of calling functions is slowing you down, why not test inlining the C code or turning it into macros?</p>\n\n<p>Also, why not improve the const correctness of the C code while you are at it - const_cast should really be used sparingly, especially on interfaces you control.</p>\n" }, { "answer_id": 286384, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>As with any question about performance, you'll be told to measure to get your answer (and that's the strictly correct answer).</p>\n\n<p>But as a rule of thumb, for simple inline methods that can actually be inlined, you'll see no performance penalty. In general, an inline method that does nothing but pass the call onto another function is a great candidate for inlining.</p>\n\n<p>However, even if your wrapper methods were not inlined, I suspect you'd notice no performance penalty - not even a measurable one - unless the wrapper method was being called in some critical loop. Even then it would likely only be measurable if the wrapped function itself didn't do much work.</p>\n\n<p>This type of thing is about the last thing to be concerned about. First worry about making your code correct, maintainable, and that you're using appropriate algorithms.</p>\n" }, { "answer_id": 286617, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 3, "selected": true, "text": "<p>Your wrapper itself will be inlined, however, your method calls to the C library typically will not. (This would require link-time-optimizations which are technically possible, but to AFAIK rudimentary at best in todays tools)</p>\n\n<p>Generally, a function call as such is not very expensive. The cycle cost has decreased considerably over the last years, and it can be predicted easily, so the the call penalty as such is negligible.</p>\n\n<p>However, inlining opens the door to more optimizations: if you have v = a + b + c, your wrapper class forces the generation of stack variables, whereas for inlined calls, the majority of the data can be kept in the FPU stack. Also, inlined code allows simplifying instructions, considering constant values, and more.</p>\n\n<p>So while the <strong>measure before you invest</strong> rule holds true, I would expect some room for improvements here.</p>\n\n<hr>\n\n<p>A typical solution is to bring the C implementaiton into a format that it can be used either as inline functions or as \"C\" body:</p>\n\n<pre><code>// V3impl.inl\nvoid V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs)\n{\n // here you maintain the actual implementations\n // ...\n}\n\n// C header\n#define V3DECL \nvoid V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs);\n\n// C body\n#include \"V3impl.inl\"\n\n\n// CPP Header\n#define V3DECL inline\nnamespace v3core {\n #include \"V3impl.inl\"\n} // namespace\n\nclass Vector3D { ... }\n</code></pre>\n\n<p>This likely makes sense only for selected methods with comparedly simple bodies. I'd move the methods to a separate namespace for the C++ implementation, as you will usually not need them directly. </p>\n\n<p>(Note that the inline is just a compiler hint, it doesn't force the method to be inlined.\nBut that's good: if the code size of an inner loop exceeds the instruction cache, inlining easily hurts performance)</p>\n\n<p>Whether the pass/return-by-reference can be resolved depends on the strength of your compiler, I've seen many where \n foo(X * out)\nforces stack variables, whereas\n X foo()\ndoes keep values in registers.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491/" ]
I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math operations using the C API. The wrapper only consists of a header file and as much use on inlining is made as possible. Is there an appreciable penalty for wrapping the C code versus porting and inlining the implementation directly into the C++ class? This library is used in time critical applications. So, does the boost from eliminating indirection compensate for the maintenance headache of two ports? Example of C interface: ``` typedef float VECTOR3[3]; void v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs); ``` Example of C++ wrapper: ``` class Vector3 { private: VECTOR3 v_; public: // copy constructors, etc... Vector3& operator+=(const Vector3& rhs) { v3_add(&this->v_, this->v_, const_cast<VECTOR3> (rhs.v_)); return *this; } Vector3 operator+(const Vector3& rhs) const { Vector3 tmp(*this); tmp += rhs; return tmp; } // more methods... }; ```
Your wrapper itself will be inlined, however, your method calls to the C library typically will not. (This would require link-time-optimizations which are technically possible, but to AFAIK rudimentary at best in todays tools) Generally, a function call as such is not very expensive. The cycle cost has decreased considerably over the last years, and it can be predicted easily, so the the call penalty as such is negligible. However, inlining opens the door to more optimizations: if you have v = a + b + c, your wrapper class forces the generation of stack variables, whereas for inlined calls, the majority of the data can be kept in the FPU stack. Also, inlined code allows simplifying instructions, considering constant values, and more. So while the **measure before you invest** rule holds true, I would expect some room for improvements here. --- A typical solution is to bring the C implementaiton into a format that it can be used either as inline functions or as "C" body: ``` // V3impl.inl void V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs) { // here you maintain the actual implementations // ... } // C header #define V3DECL void V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs); // C body #include "V3impl.inl" // CPP Header #define V3DECL inline namespace v3core { #include "V3impl.inl" } // namespace class Vector3D { ... } ``` This likely makes sense only for selected methods with comparedly simple bodies. I'd move the methods to a separate namespace for the C++ implementation, as you will usually not need them directly. (Note that the inline is just a compiler hint, it doesn't force the method to be inlined. But that's good: if the code size of an inner loop exceeds the instruction cache, inlining easily hurts performance) Whether the pass/return-by-reference can be resolved depends on the strength of your compiler, I've seen many where foo(X \* out) forces stack variables, whereas X foo() does keep values in registers.
286,123
<p>I have to read a txt file with lines formated like this:</p> <pre> 1: (G, 2), (F, 3) 2: (G, 2), (F, 3) 3: (F, 4), (G, 5) 4: (F, 4), (G, 5) 5: (F, 6), (c, w) 6: (p, f), (G, 7) 7: (G, 7), (G, 7) w: (c, w), (c, w) </pre> <p>Each line will feed a struct with its data (the 5 numbers or letters in it).<br> What's the best way to read the line and get the strings I want?<br> I'm currently using a long sequence of conditions using <code>fgetc</code> but that seems ugly and not very smart.<br> I can't use arrays because the lines may vary in size if the numbers have two digits.</p>
[ { "answer_id": 286133, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>fgets() and sscanf() as I remember</p>\n" }, { "answer_id": 286138, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>Use <code>fgets()</code>:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n char line[256];\n while(fgets(line, sizeof(line), stdin) != NULL) // fgets returns NULL on EOF\n {\n // process line; line is guaranteed to be null-terminated, but it might not end in a\n // newline character '\\n' if the line was longer than the buffer size (in this case,\n // 256 characters)\n }\n\n return 0;\n}</code></pre>\n" }, { "answer_id": 286151, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>I think you could parse it along the lines of:</p>\n\n<pre><code>fscanf(file,\"%c: (%c, %c), (%c, %c)\", &amp;first,&amp;second,&amp;third,&amp;fourth,&amp;fifth);\n</code></pre>\n" }, { "answer_id": 286172, "author": "che", "author_id": 7806, "author_profile": "https://Stackoverflow.com/users/7806", "pm_score": 0, "selected": false, "text": "<p>fscanf works pretty nice, but you'll have to use string conversions, because chars wouldn't work for numbers with more than one digit.</p>\n\n<p>Isn't this some kind of homework?</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid main(int argc, char **argv) {\n FILE * f;\n f = fopen(argv[1], \"r\");\n\n while (1) {\n char char_or_num[32][5]; // five string arrays, up to 32 chars\n int i;\n int did_read;\n\n did_read = fscanf(f, \"%32[0-9a-zA-Z]: (%32[0-9a-zA-Z], %32[0-9a-zA-Z]), (%32[0-9a-zA-Z], %32[0-9a-zA-Z])\\n\", char_or_num[0], char_or_num[1], char_or_num[2], char_or_num[3], char_or_num[4]);\n if (did_read != 5) {\n break;\n }\n printf(\"%s, %s, %s, %s, %s\\n\", char_or_num[0], char_or_num[1], char_or_num[2], char_or_num[3], char_or_num[4]);\n }\n\n fclose(f);\n}\n</code></pre>\n" }, { "answer_id": 286178, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre>\n#include\nvoid\nf()\n{\n FILE* fp;\n\n if ( (fp = fopen(\"foo.txt\", \"r\")) == NULL)\n {\n perror(\"fopen\");\n return;\n }\n\n char ch[5];\n while (fscanf(fp, \"%c: (%c, %c), (%c, %c)\\n\", &ch[0], &ch[1], &ch[2], &ch[3], &ch[4]) == 5)\n {\n printf(\"--> %c %c %c %c %c\\n\", ch[0], ch[1], ch[2], ch[3], ch[4]);\n }\n\nfclose(fp);\n}\n</pre>\n" }, { "answer_id": 286234, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": 0, "selected": false, "text": "<p>Basically you'll have to save the position of the file ptr via fgetpos, walk to the end of the line (however you define it), save that size, fsetpos to the previous position, allocate a buffer big enough to hold the line, and then call fread with the new buffer.</p>\n" }, { "answer_id": 286318, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Assuming you have the correct variables, this should work:</p>\n\n<pre><code> fscanf(fp, \"%[^:]: (%[^,], %[^)]), (%[^,], %[^)])\", a, b, c, d, e);\n</code></pre>\n\n<p>fp is a file pointer\nand \"a\" to \"e\" are char pointers</p>\n" }, { "answer_id": 286320, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": true, "text": "<pre><code>#include &lt;stdio.h&gt;\n\nint main (void)\n{\n char buf[81]; /* Support lines up to 80 characters */\n char parts[5][11]; /* Support up to 10 characters in each part */\n\n while (fgets(buf, sizeof(buf), stdin) != NULL)\n {\n if (sscanf(buf, \"%10[^:]: (%10[^,], %10[^)]), (%10[^,], %10[^)])\",\n parts[0], parts[1], parts[2], parts[3], parts[4]) == 5)\n {\n printf(\"parts: %s, %s, %s, %s, %s\\n\",\n parts[0], parts[1], parts[2], parts[3], parts[4]);\n }\n else\n {\n printf(\"Invalid input: %s\", buf);\n }\n }\n return 0;\n}\n</code></pre>\n\n<p>Sample run:</p>\n\n<pre><code>$ ./test\n1: (G, 2), (F, 3)\n2: (G, 2), (F, 3)\n3: (F, 4), (G, 5)\n4: (F, 4), (G, 5)\n5: (F, 6), (c, w)\n6: (p, f), (G, 7)\n7: (G, 7), (G, 7)\nw: (c, w), (c, w)\nparts: 1, G, 2, F, 3\nparts: 2, G, 2, F, 3\nparts: 3, F, 4, G, 5\nparts: 4, F, 4, G, 5\nparts: 5, F, 6, c, w\nparts: 6, p, f, G, 7\nparts: 7, G, 7, G, 7\nparts: w, c, w, c, w\n</code></pre>\n\n<p>If the last value in the input is more than 10 characters it will be truncated with no indication of error, if this is not acceptable you can use the <code>%c</code> conversion specifier as a sixth argument to capture the next character after the last value and make sure it is a closing parenthesis.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9835/" ]
I have to read a txt file with lines formated like this: ``` 1: (G, 2), (F, 3) 2: (G, 2), (F, 3) 3: (F, 4), (G, 5) 4: (F, 4), (G, 5) 5: (F, 6), (c, w) 6: (p, f), (G, 7) 7: (G, 7), (G, 7) w: (c, w), (c, w) ``` Each line will feed a struct with its data (the 5 numbers or letters in it). What's the best way to read the line and get the strings I want? I'm currently using a long sequence of conditions using `fgetc` but that seems ugly and not very smart. I can't use arrays because the lines may vary in size if the numbers have two digits.
``` #include <stdio.h> int main (void) { char buf[81]; /* Support lines up to 80 characters */ char parts[5][11]; /* Support up to 10 characters in each part */ while (fgets(buf, sizeof(buf), stdin) != NULL) { if (sscanf(buf, "%10[^:]: (%10[^,], %10[^)]), (%10[^,], %10[^)])", parts[0], parts[1], parts[2], parts[3], parts[4]) == 5) { printf("parts: %s, %s, %s, %s, %s\n", parts[0], parts[1], parts[2], parts[3], parts[4]); } else { printf("Invalid input: %s", buf); } } return 0; } ``` Sample run: ``` $ ./test 1: (G, 2), (F, 3) 2: (G, 2), (F, 3) 3: (F, 4), (G, 5) 4: (F, 4), (G, 5) 5: (F, 6), (c, w) 6: (p, f), (G, 7) 7: (G, 7), (G, 7) w: (c, w), (c, w) parts: 1, G, 2, F, 3 parts: 2, G, 2, F, 3 parts: 3, F, 4, G, 5 parts: 4, F, 4, G, 5 parts: 5, F, 6, c, w parts: 6, p, f, G, 7 parts: 7, G, 7, G, 7 parts: w, c, w, c, w ``` If the last value in the input is more than 10 characters it will be truncated with no indication of error, if this is not acceptable you can use the `%c` conversion specifier as a sixth argument to capture the next character after the last value and make sure it is a closing parenthesis.
286,124
<p>How can I test <code>Controller.ViewData.ModelState</code>? I would prefer to do it without any mock framework. </p>
[ { "answer_id": 589350, "author": "Scott Hanselman", "author_id": 6380, "author_profile": "https://Stackoverflow.com/users/6380", "pm_score": 7, "selected": true, "text": "<p>You don't have to use a Mock if you're using the Repository Pattern for your data, of course.</p>\n\n<p>Some examples:\n<a href=\"http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx\" rel=\"noreferrer\">http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx</a></p>\n\n<pre><code>// Test for required \"FirstName\".\n controller.ViewData.ModelState.Clear();\n\n newCustomer = new Customer\n {\n FirstName = \"\",\n LastName = \"Smith\",\n Zip = \"34275\", \n };\n\n controller.Create(newCustomer);\n\n // Make sure that our validation found the error!\n Assert.IsTrue(controller.ViewData.ModelState.Count == 1, \n \"FirstName must be required.\");\n</code></pre>\n" }, { "answer_id": 5580363, "author": "VaSSaV", "author_id": 696691, "author_profile": "https://Stackoverflow.com/users/696691", "pm_score": 5, "selected": false, "text": "<pre><code>//[Required]\n//public string Name { get; set; }\n//[Required]\n//public string Description { get; set; }\n\nProductModelEdit model = new ProductModelEdit() ;\n//Init ModelState\nvar modelBinder = new ModelBindingContext()\n{\n ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(\n () =&gt; model, model.GetType()),\n ValueProvider=new NameValueCollectionValueProvider(\n new NameValueCollection(), CultureInfo.InvariantCulture)\n};\nvar binder=new DefaultModelBinder().BindModel(\n new ControllerContext(),modelBinder );\nProductController.ModelState.Clear();\nProductController.ModelState.Merge(modelBinder.ModelState);\n\nViewResult result = (ViewResult)ProductController.CreateProduct(null,model);\nAssert.IsTrue(result.ViewData.ModelState[\"Name\"].Errors.Count &gt; 0);\nAssert.True(result.ViewData.ModelState[\"Description\"].Errors.Count &gt; 0);\nAssert.True(!result.ViewData.ModelState.IsValid);\n</code></pre>\n" }, { "answer_id": 30601114, "author": "Alex Stephens", "author_id": 1955203, "author_profile": "https://Stackoverflow.com/users/1955203", "pm_score": 0, "selected": false, "text": "<p>Adding to the great answers above, check out this fantastic use of the protected TryValidateModel method within the Controller class.</p>\n\n<p>Simply create a test class inheriting from controller and pass your model to the TryValidateModel method. Here's the link:\n<a href=\"http://blog.icanmakethiswork.io/2013/03/unit-testing-modelstate.html\" rel=\"nofollow\">http://blog.icanmakethiswork.io/2013/03/unit-testing-modelstate.html</a></p>\n\n<p>Full credit goes to John Reilly and Marc Talary for this solution.</p>\n" }, { "answer_id": 38289159, "author": "Bart Verkoeijen", "author_id": 70182, "author_profile": "https://Stackoverflow.com/users/70182", "pm_score": 4, "selected": false, "text": "<p>For testing Web API, use the <a href=\"https://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.validate(v=vs.118).aspx\">Validate</a> method on the controller:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var controller = new MyController();\ncontroller.Configuration = new HttpConfiguration();\nvar model = new MyModel();\n\ncontroller.Validate(model);\nvar result = controller.MyMethod(model);\n</code></pre>\n" }, { "answer_id": 49393360, "author": "Paul - Soura Tech LLC", "author_id": 3071582, "author_profile": "https://Stackoverflow.com/users/3071582", "pm_score": 4, "selected": false, "text": "<p>Ran into this problem for .NetCore 2.1\nHere's my solution:</p>\n\n<p><strong>Extension Method</strong></p>\n\n<pre><code>using Microsoft.AspNetCore.Mvc;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\n\nnamespace MyExtension\n{\n public static void BindViewModel&lt;T&gt;(this Controller controller, T model)\n {\n if (model == null) return;\n\n var context = new ValidationContext(model, null, null);\n var results = new List&lt;ValidationResult&gt;();\n\n if (!Validator.TryValidateObject(model, context, results, true))\n {\n controller.ModelState.Clear();\n foreach (ValidationResult result in results)\n {\n var key = result.MemberNames.FirstOrDefault() ?? \"\";\n controller.ModelState.AddModelError(key, result.ErrorMessage);\n }\n }\n }\n}\n</code></pre>\n\n<p><strong>View Model</strong></p>\n\n<pre><code>public class MyViewModel\n{\n [Required]\n public string Name { get; set; }\n}\n</code></pre>\n\n<p><strong>Unit Test</strong></p>\n\n<pre><code>public async void MyUnitTest()\n{\n // helper method to create instance of the Controller\n var controller = this.CreateController();\n\n var model = new MyViewModel\n {\n Name = null\n };\n\n // here we call the extension method to validate the model\n // and set the errors to the Controller's ModelState\n controller.BindViewModel(model);\n\n var result = await controller.ActionName(model);\n\n Assert.NotNull(result);\n var viewResult = Assert.IsType&lt;BadRequestObjectResult&gt;(result);\n}\n</code></pre>\n" }, { "answer_id": 52611541, "author": "abovetempo", "author_id": 7231971, "author_profile": "https://Stackoverflow.com/users/7231971", "pm_score": 2, "selected": false, "text": "<p>This not only let's you check that the error exists but also checks that it has the exact same error message as expected. For example both of these parameters are Required so their error message shows as \"Required\".</p>\n\n<p>Model markup:</p>\n\n<pre><code>//[Required]\n//public string Name { get; set; }\n//[Required]\n//public string Description { get; set; }\n</code></pre>\n\n<p>Unit test code:</p>\n\n<pre><code>ProductModelEdit model = new ProductModelEdit() ;\n//Init ModelState\nvar modelBinder = new ModelBindingContext()\n{\n ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(\n () =&gt; model, model.GetType()),\n ValueProvider=new NameValueCollectionValueProvider(\n new NameValueCollection(), CultureInfo.InvariantCulture)\n};\nvar binder=new DefaultModelBinder().BindModel(\n new ControllerContext(),modelBinder );\nProductController.ModelState.Clear();\nProductController.ModelState.Merge(modelBinder.ModelState);\n\nViewResult result = (ViewResult)ProductController.CreateProduct(null,model);\nAssert.IsTrue(!result.ViewData.ModelState.IsValid);\n//Make sure Name has correct errors\nAssert.IsTrue(result.ViewData.ModelState[\"Name\"].Errors.Count &gt; 0);\nAssert.AreEqual(result.ViewData.ModelState[\"Name\"].Errors[0].ErrorMessage, \"Required\");\n//Make sure Description has correct errors\nAssert.IsTrue(result.ViewData.ModelState[\"Description\"].Errors.Count &gt; 0);\nAssert.AreEqual(result.ViewData.ModelState[\"Description\"].Errors[0].ErrorMessage, \"Required\");\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32173/" ]
How can I test `Controller.ViewData.ModelState`? I would prefer to do it without any mock framework.
You don't have to use a Mock if you're using the Repository Pattern for your data, of course. Some examples: <http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx> ``` // Test for required "FirstName". controller.ViewData.ModelState.Clear(); newCustomer = new Customer { FirstName = "", LastName = "Smith", Zip = "34275", }; controller.Create(newCustomer); // Make sure that our validation found the error! Assert.IsTrue(controller.ViewData.ModelState.Count == 1, "FirstName must be required."); ```
286,132
<p>I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.<br> My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.</p> <p>Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.</p>
[ { "answer_id": 286177, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>In rails this is called rendering a partial view, and you do it with <code>render :partial =&gt; 'yourfilename'</code>. I believe ASP.NET MVC has a similar <code>RenderPartial</code> method, but I can't find the official docs for MVC to confirm or deny such a thing.</p>\n" }, { "answer_id": 286312, "author": "Andrew Harry", "author_id": 30576, "author_profile": "https://Stackoverflow.com/users/30576", "pm_score": 2, "selected": false, "text": "<p>After much digging in google i have found the answer.\nYou can not get easy access to the html outputted by the view.</p>\n\n<p><a href=\"http://ayende.com/Blog/archive/2008/11/11/another-asp.net-mvc-bug-rendering-views-to-different-output-source.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2008/11/11/another-asp.net-mvc-bug-rendering-views-to-different-output-source.aspx</a></p>\n" }, { "answer_id": 286381, "author": "Christian Dalager", "author_id": 11239, "author_profile": "https://Stackoverflow.com/users/11239", "pm_score": 3, "selected": false, "text": "<p>You would create your action like this:</p>\n\n<pre><code> public PartialViewResult LoginForm()\n {\n var model = // get model data from somewhere\n return PartialView(model);\n }</code></pre>\n\n<p>And the action would return the rendered partial view to your jquery response.</p>\n\n<p>Your jquery could look something like this:</p>\n\n<pre><code>$('#targetdiv').load('/MyController/LoginForm',function(){alert('complete!');});</code></pre>\n" }, { "answer_id": 286634, "author": "Hrvoje Hudo", "author_id": 1407, "author_profile": "https://Stackoverflow.com/users/1407", "pm_score": 3, "selected": false, "text": "<p>You should use jquery to populate your divs (and create new html elements if needed), and Json serialization for ActionResult. </p>\n\n<p>Other way is to use jquery to call some controller/action, but instead json use regular View (aspx or ascx, webforms view engine) for rendering content, and with jquery just inject that html to some div. This is half way to UpdatePanels from asp.net ajax... </p>\n\n<p>I would probably go with first method, with json, where you have little more job to do, but it's much more \"optimized\", because you don't transfer whole html over the wire, there are just serialized objects. It's the way that \"big ones\" (gmail, g docs, hotmail,..) do it - lot of JS code that manipulates with UI.</p>\n\n<p>If you don't need ajax, then you basically have two ways of calling partial views:</p>\n\n<ul>\n<li>html.renderpartial(\"name of ascx\")</li>\n<li>html.RenderAction(x=>x.ActionName) from Microsoft.web.mvc (mvc futures)</li>\n</ul>\n" }, { "answer_id": 294559, "author": "Kevin Zink", "author_id": 38102, "author_profile": "https://Stackoverflow.com/users/38102", "pm_score": 3, "selected": false, "text": "<p>I put together a rough framework which allows you to render views to a string from a controller method in MVC Beta. This should help solve this limitation for now.</p>\n\n<p>Additionally, I also put together a Rails-like RJS javascript generating framework for MVC Beta.</p>\n\n<p>Check it out at <a href=\"http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc\" rel=\"nofollow noreferrer\">http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc</a> and let me know what you think.</p>\n" }, { "answer_id": 294676, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 3, "selected": true, "text": "<p>You have several options.</p>\n\n<p>Create a MVC View User Control and action handler in your controller for the view. To render the view use </p>\n\n<pre><code>&lt;% Html.RenderPartial(\"MyControl\") %&gt;\n</code></pre>\n\n<p>In this case your action handler will need to pass the model data to the view</p>\n\n<pre><code>public ActionResult MyControl ()\n{\n // get modelData\n\n render View (modelData);\n}\n</code></pre>\n\n<p>Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent:</p>\n\n<pre><code>&lt;% Html.RenderPartial(\"MyControl\", ViewData.Model) %&gt;\n</code></pre>\n\n<p>If your user control has it's own data type you can also construct it within the page</p>\n\n<p>In MyControl.ascx.cs:</p>\n\n<pre><code>public class MyControlViewData\n{\n public string Name { get; set; }\n public string Email { get; set; }\n}\n\npublic partial class MyControl : System.Web.Mvc.ViewUserControl &lt;MyControlViewData&gt;\n{\n}\n</code></pre>\n\n<p>And in your page you can initialize your control's data model:</p>\n\n<pre><code>&lt;% Html.RenderPartial(\"MyControl\", new MyControlViewData ()\n {\n Name= ViewData.Model.FirstName,\n Email = ViewData.Model.Email,\n });\n %&gt;\n</code></pre>\n" }, { "answer_id": 1052781, "author": "pupeno", "author_id": 6068, "author_profile": "https://Stackoverflow.com/users/6068", "pm_score": 5, "selected": false, "text": "<p>This is a solution that is working with ASP.Net MVC 1.0 (many that claim to work with beta 3 don't work with 1.0), doesn't suffer of the 'Server cannot set content type after HTTP headers have been sent' problem and can be called from within a controller (not only a view):</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Render a view into a string. It's a hack, it may fail badly.\n/// &lt;/summary&gt;\n/// &lt;param name=\"name\"&gt;Name of the view, that is, its path.&lt;/param&gt;\n/// &lt;param name=\"data\"&gt;Data to pass to the view, a model or something like that.&lt;/param&gt;\n/// &lt;returns&gt;A string with the (HTML of) view.&lt;/returns&gt;\npublic static string RenderPartialToString(string controlName, object viewData) {\n ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };\n viewPage.Url = GetBogusUrlHelper();\n\n viewPage.ViewData = new ViewDataDictionary(viewData);\n viewPage.Controls.Add(viewPage.LoadControl(controlName));\n\n StringBuilder sb = new StringBuilder();\n using (StringWriter sw = new StringWriter(sb)) {\n using (HtmlTextWriter tw = new HtmlTextWriter(sw)) {\n viewPage.RenderControl(tw);\n }\n }\n\n return sb.ToString();\n}\n\npublic static UrlHelper GetBogusUrlHelper() {\n var httpContext = HttpContext.Current;\n\n if (httpContext == null) {\n var request = new HttpRequest(\"/\", Config.Url.ToString(), \"\");\n var response = new HttpResponse(new StringWriter());\n httpContext = new HttpContext(request, response);\n }\n\n var httpContextBase = new HttpContextWrapper(httpContext);\n var routeData = new RouteData();\n var requestContext = new RequestContext(httpContextBase, routeData);\n\n return new UrlHelper(requestContext);\n}\n</code></pre>\n\n<p>It's a static method you can drop somewhere you find it convenient. You can call it this way:</p>\n\n<pre><code>string view = RenderPartialToString(\"~/Views/Controller/AView.ascx\", someModelObject); \n</code></pre>\n" }, { "answer_id": 3296424, "author": "Rob King", "author_id": 393307, "author_profile": "https://Stackoverflow.com/users/393307", "pm_score": 2, "selected": false, "text": "<p>I've done something similar for an app I'm working on. I have partial views returning rendered content can be called using their REST path or using:</p>\n\n<pre><code>&lt;% Html.RenderAction(\"Action\", \"Controller\"); %&gt;\n</code></pre>\n\n<p>Then in my actual display HTML I have a DIV which is filled from jQuery:</p>\n\n<pre><code>&lt;div class=\"onload\"&gt;/controller/action&lt;/div&gt;\n</code></pre>\n\n<p>The jQuery looks like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $.ajaxSetup({ cache: false });\n\n $(document).ready(function () {\n $('div.onload').each(function () {\n var source = $(this).html();\n if (source != \"\") {\n $(this).load(source);\n }\n });\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>This scans for all DIV that match the \"onload\" class and reads the REST path from their content. It then does a jQuery.load on that REST path and populates the DIV with the result.</p>\n\n<p>Sorry gotta go catch my ride home. Let me know if you want me to elaborate more.</p>\n" }, { "answer_id": 14284339, "author": "Paco Lf", "author_id": 1476071, "author_profile": "https://Stackoverflow.com/users/1476071", "pm_score": 0, "selected": false, "text": "<p>it is very simple you just have to create a strongly typed partial view(or user control) then in your cotroller something like this:</p>\n\n<pre><code>public PartialViewResult yourpartialviewresult()\n{\n var yourModel\n return PartialView(\"yourPartialView\", yourModel);\n}\n</code></pre>\n\n<p>then you can use JQuery to perform the request whener you want:</p>\n\n<pre><code>$.ajax({\n type: 'GET',\n url: '/home/yourpartialviewresult',\n dataType: 'html', //be sure to use html dataType\n contentType: 'application/json; charset=utf-8',\n success: function(data){\n $(container).html(data);\n },\n complete: function(){ }\n }); \n</code></pre>\n" }, { "answer_id": 45574937, "author": "Himanshu Patel", "author_id": 1376658, "author_profile": "https://Stackoverflow.com/users/1376658", "pm_score": 0, "selected": false, "text": "<p>I found this one line code to work perfectly. orderModel being my model object. In my case I had a helper method in which I had to merge a partial view's html.</p>\n\n<pre><code>System.Web.Mvc.Html.PartialExtensions.Partial(html, \"~/Views/Orders/OrdersPartialView.cshtml\", orderModel).ToString();\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30576/" ]
I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool. My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns. Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.
You have several options. Create a MVC View User Control and action handler in your controller for the view. To render the view use ``` <% Html.RenderPartial("MyControl") %> ``` In this case your action handler will need to pass the model data to the view ``` public ActionResult MyControl () { // get modelData render View (modelData); } ``` Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent: ``` <% Html.RenderPartial("MyControl", ViewData.Model) %> ``` If your user control has it's own data type you can also construct it within the page In MyControl.ascx.cs: ``` public class MyControlViewData { public string Name { get; set; } public string Email { get; set; } } public partial class MyControl : System.Web.Mvc.ViewUserControl <MyControlViewData> { } ``` And in your page you can initialize your control's data model: ``` <% Html.RenderPartial("MyControl", new MyControlViewData () { Name= ViewData.Model.FirstName, Email = ViewData.Model.Email, }); %> ```
286,141
<p>How do I remove all attributes which are <code>undefined</code> or <code>null</code> in a JavaScript object?</p> <p>(Question is similar to <a href="https://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object">this one</a> for Arrays)</p>
[ { "answer_id": 286145, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 4, "selected": false, "text": "<p>You are probably looking for the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator\" rel=\"noreferrer\"><code>delete</code></a> keyword.</p>\n\n<pre><code>var obj = { };\nobj.theProperty = 1;\ndelete obj.theProperty;\n</code></pre>\n" }, { "answer_id": 286162, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 9, "selected": true, "text": "<p>You can loop through the object:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var test = {\n test1: null,\n test2: 'somestring',\n test3: 3,\n}\n\nfunction clean(obj) {\n for (var propName in obj) {\n if (obj[propName] === null || obj[propName] === undefined) {\n delete obj[propName];\n }\n }\n return obj\n}\n\nconsole.log(test);\nconsole.log(clean(test));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you're concerned about this property removal not running up object's proptype chain, you can also:</p>\n<pre><code>function clean(obj) {\n var propNames = Object.getOwnPropertyNames(obj);\n for (var i = 0; i &lt; propNames.length; i++) {\n var propName = propNames[i];\n if (obj[propName] === null || obj[propName] === undefined) {\n delete obj[propName];\n }\n }\n}\n</code></pre>\n<p>A few notes on null vs undefined:</p>\n<pre><code>test.test1 === null; // true\ntest.test1 == null; // true\n\ntest.notaprop === null; // false\ntest.notaprop == null; // true\n\ntest.notaprop === undefined; // true\ntest.notaprop == undefined; // true\n</code></pre>\n" }, { "answer_id": 12777816, "author": "nguyên", "author_id": 572180, "author_profile": "https://Stackoverflow.com/users/572180", "pm_score": 3, "selected": false, "text": "<p>you can do shorter with <code>!</code> condition</p>\n\n<pre><code>var r = {a: null, b: undefined, c:1};\nfor(var k in r)\n if(!r[k]) delete r[k];\n</code></pre>\n\n<p>Remember in usage : as @semicolor announce in comments: <em>This would also delete properties if the value is an empty string, false or zero</em> </p>\n" }, { "answer_id": 24190282, "author": "Wumms", "author_id": 1097958, "author_profile": "https://Stackoverflow.com/users/1097958", "pm_score": 5, "selected": false, "text": "<p>If somebody needs a recursive version of Owen's (and Eric's) answer, here it is:</p>\n\n<pre><code>/**\n * Delete all null (or undefined) properties from an object.\n * Set 'recurse' to true if you also want to delete properties in nested objects.\n */\nfunction delete_null_properties(test, recurse) {\n for (var i in test) {\n if (test[i] === null) {\n delete test[i];\n } else if (recurse &amp;&amp; typeof test[i] === 'object') {\n delete_null_properties(test[i], recurse);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 30386744, "author": "Alexandre Farber", "author_id": 4927045, "author_profile": "https://Stackoverflow.com/users/4927045", "pm_score": 5, "selected": false, "text": "<p>JSON.stringify removes the undefined keys.</p>\n\n<pre><code>removeUndefined = function(json){\n return JSON.parse(JSON.stringify(json))\n}\n</code></pre>\n" }, { "answer_id": 34949831, "author": "sam", "author_id": 1660475, "author_profile": "https://Stackoverflow.com/users/1660475", "pm_score": 3, "selected": false, "text": "<p>For a deep search I used the following code, maybe it will be useful for anyone looking at this question (it is not usable for cyclic dependencies ) : </p>\n\n<pre><code>function removeEmptyValues(obj) {\n for (var propName in obj) {\n if (!obj[propName] || obj[propName].length === 0) {\n delete obj[propName];\n } else if (typeof obj[propName] === 'object') {\n removeEmptyValues(obj[propName]);\n }\n }\n return obj;\n }\n</code></pre>\n" }, { "answer_id": 35871405, "author": "Ben", "author_id": 3150636, "author_profile": "https://Stackoverflow.com/users/3150636", "pm_score": 7, "selected": false, "text": "<p>If you are using lodash or underscore.js, here is a simple solution: </p>\n\n<pre><code>var obj = {name: 'John', age: null};\n\nvar compacted = _.pickBy(obj);\n</code></pre>\n\n<p>This will only work with lodash 4, pre lodash 4 or underscore.js, use <code>_.pick(obj, _.identity)</code>;</p>\n" }, { "answer_id": 36579096, "author": "Alex Johnson", "author_id": 1508105, "author_profile": "https://Stackoverflow.com/users/1508105", "pm_score": 2, "selected": false, "text": "<p>To piggypack on <a href=\"https://stackoverflow.com/a/35871405/1508105\">Ben's answer</a> on how to solve this problem using lodash's <code>_.pickBy</code>, you can also solve this problem in the sister library: <a href=\"http://underscorejs.org\" rel=\"nofollow noreferrer\">Underscore.js</a>'s <code>_.pick</code>.</p>\n\n<pre><code>var obj = {name: 'John', age: null};\n\nvar compacted = _.pick(obj, function(value) {\n return value !== null &amp;&amp; value !== undefined;\n});\n</code></pre>\n\n<p>See: <a href=\"https://jsfiddle.net/96p3g9d0/6/\" rel=\"nofollow noreferrer\">JSFiddle Example</a></p>\n" }, { "answer_id": 36955172, "author": "Łukasz Jagodziński", "author_id": 1584746, "author_profile": "https://Stackoverflow.com/users/1584746", "pm_score": 2, "selected": false, "text": "<p>If someone needs to remove <code>undefined</code> values from an object with deep search using <code>lodash</code> then here is the code that I'm using. It's quite simple to modify it to remove all empty values (<code>null</code>/<code>undefined</code>).</p>\n\n<pre><code>function omitUndefinedDeep(obj) {\n return _.reduce(obj, function(result, value, key) {\n if (_.isObject(value)) {\n result[key] = omitUndefinedDeep(value);\n }\n else if (!_.isUndefined(value)) {\n result[key] = value;\n }\n return result;\n }, {});\n}\n</code></pre>\n" }, { "answer_id": 38340730, "author": "Rotareti", "author_id": 1612318, "author_profile": "https://Stackoverflow.com/users/1612318", "pm_score": 10, "selected": false, "text": "<h3>ES10/ES2019 examples</h3>\n<p>A simple one-liner (returning a new object).</p>\n<pre class=\"lang-js prettyprint-override\"><code>let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) =&gt; v != null));\n</code></pre>\n<p>Same as above but written as a function.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n return Object.fromEntries(Object.entries(obj).filter(([_, v]) =&gt; v != null));\n}\n</code></pre>\n<p>This function uses <em>recursion</em> to remove items from nested objects.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n return Object.fromEntries(\n Object.entries(obj)\n .filter(([_, v]) =&gt; v != null)\n .map(([k, v]) =&gt; [k, v === Object(v) ? removeEmpty(v) : v])\n );\n}\n</code></pre>\n<h3>ES6/ES2015 examples</h3>\n<p>A simple one-liner. Warning: This mutates the given object instead of returning a new one.</p>\n<pre class=\"lang-js prettyprint-override\"><code>Object.keys(obj).forEach((k) =&gt; obj[k] == null &amp;&amp; delete obj[k]);\n</code></pre>\n<p>A single declaration (not mutating the given object).</p>\n<pre class=\"lang-js prettyprint-override\"><code>let o = Object.keys(obj)\n .filter((k) =&gt; obj[k] != null)\n .reduce((a, k) =&gt; ({ ...a, [k]: obj[k] }), {});\n</code></pre>\n<p>Same as above but written as a function.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n return Object.entries(obj)\n .filter(([_, v]) =&gt; v != null)\n .reduce((acc, [k, v]) =&gt; ({ ...acc, [k]: v }), {});\n}\n</code></pre>\n<p>This function uses recursion to remove items from nested objects.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n return Object.entries(obj)\n .filter(([_, v]) =&gt; v != null)\n .reduce(\n (acc, [k, v]) =&gt; ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }),\n {}\n );\n}\n</code></pre>\n<p>Same as the function above, but written in an imperative (non-functional) style.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n const newObj = {};\n Object.entries(obj).forEach(([k, v]) =&gt; {\n if (v === Object(v)) {\n newObj[k] = removeEmpty(v);\n } else if (v != null) {\n newObj[k] = obj[k];\n }\n });\n return newObj;\n}\n</code></pre>\n<h3>ES5/ES2009 examples</h3>\n<p>In the old days things were a lot more verbose.</p>\n<p>This is a non recursive version written in a functional style.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n return Object.keys(obj)\n .filter(function (k) {\n return obj[k] != null;\n })\n .reduce(function (acc, k) {\n acc[k] = obj[k];\n return acc;\n }, {});\n}\n</code></pre>\n<p>This is a non recursive version written in an imperative style.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n const newObj = {};\n Object.keys(obj).forEach(function (k) {\n if (obj[k] &amp;&amp; typeof obj[k] === &quot;object&quot;) {\n newObj[k] = removeEmpty(obj[k]);\n } else if (obj[k] != null) {\n newObj[k] = obj[k];\n }\n });\n return newObj;\n}\n</code></pre>\n<p>And a recursive version written in a functional style.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeEmpty(obj) {\n return Object.keys(obj)\n .filter(function (k) {\n return obj[k] != null;\n })\n .reduce(function (acc, k) {\n acc[k] = typeof obj[k] === &quot;object&quot; ? removeEmpty(obj[k]) : obj[k];\n return acc;\n }, {});\n}\n</code></pre>\n" }, { "answer_id": 40517249, "author": "Alex Mueller", "author_id": 1489958, "author_profile": "https://Stackoverflow.com/users/1489958", "pm_score": 4, "selected": false, "text": "<p>You can use a combination of <code>JSON.stringify</code>, its replacer parameter, and <code>JSON.parse</code> to turn it back into an object. Using this method also means the replacement is done to all nested keys within nested objects.</p>\n\n<p><strong>Example Object</strong></p>\n\n<pre><code>var exampleObject = {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3],\n object: {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3]\n },\n arrayOfObjects: [\n {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3]\n },\n {\n string: 'value',\n emptyString: '',\n integer: 0,\n nullValue: null,\n array: [1, 2, 3]\n }\n ]\n};\n</code></pre>\n\n<p><strong>Replacer Function</strong></p>\n\n<pre><code>function replaceUndefinedOrNull(key, value) {\n if (value === null || value === undefined) {\n return undefined;\n }\n\n return value;\n}\n</code></pre>\n\n<p><strong>Clean the Object</strong></p>\n\n<pre><code>exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull);\nexampleObject = JSON.parse(exampleObject);\n</code></pre>\n\n<p><a href=\"http://codepen.io/ajmueller/pen/gLaBLX\" rel=\"noreferrer\" title=\"CodePen\">CodePen example</a></p>\n" }, { "answer_id": 40844595, "author": "Amio.io", "author_id": 1075289, "author_profile": "https://Stackoverflow.com/users/1075289", "pm_score": 3, "selected": false, "text": "<p>Using <a href=\"http://ramdajs.com/docs/#pickBy\" rel=\"noreferrer\">ramda#pickBy</a> you will remove all <code>null</code>, <code>undefined</code> and <code>false</code> values:</p>\n\n<pre><code>const obj = {a:1, b: undefined, c: null, d: 1}\nR.pickBy(R.identity, obj)\n</code></pre>\n\n<p>As @manroe pointed out, to keep <code>false</code> values use <code>isNil()</code>:</p>\n\n<pre><code>const obj = {a:1, b: undefined, c: null, d: 1, e: false}\nR.pickBy(v =&gt; !R.isNil(v), obj)\n</code></pre>\n" }, { "answer_id": 42658601, "author": "Dana Woodman", "author_id": 529829, "author_profile": "https://Stackoverflow.com/users/529829", "pm_score": 2, "selected": false, "text": "<p>With Lodash:</p>\n\n<pre><code>_.omitBy({a: 1, b: null}, (v) =&gt; !v)\n</code></pre>\n" }, { "answer_id": 42755601, "author": "bsyk", "author_id": 2242975, "author_profile": "https://Stackoverflow.com/users/2242975", "pm_score": 2, "selected": false, "text": "<p>If you don't want to mutate in place, but return a clone with the null/undefined removed, you could use the ES6 reduce function.</p>\n\n<pre><code>// Helper to remove undefined or null properties from an object\nfunction removeEmpty(obj) {\n // Protect against null/undefined object passed in\n return Object.keys(obj || {}).reduce((x, k) =&gt; {\n // Check for null or undefined\n if (obj[k] != null) {\n x[k] = obj[k];\n }\n return x;\n }, {});\n}\n</code></pre>\n" }, { "answer_id": 42848007, "author": "Jin Zhao", "author_id": 2718861, "author_profile": "https://Stackoverflow.com/users/2718861", "pm_score": 3, "selected": false, "text": "<p>Instead of delete the property, you can also create a new object with the keys that are not null.</p>\n\n<pre><code>const removeEmpty = (obj) =&gt; {\n return Object.keys(obj).filter(key =&gt; obj[key]).reduce(\n (newObj, key) =&gt; {\n newObj[key] = obj[key]\n return newObj\n }, {}\n )\n}\n</code></pre>\n" }, { "answer_id": 43629975, "author": "Michael J. Zoidl", "author_id": 1624739, "author_profile": "https://Stackoverflow.com/users/1624739", "pm_score": 3, "selected": false, "text": "<p>Shorter ES6 pure solution, convert it to an array, use the filter function and convert it back to an object.\nWould also be easy to make a function... </p>\n\n<p>Btw. with this <code>.length &gt; 0</code> i check if there is an empty string / array, so it will remove empty keys.</p>\n\n<pre><code>const MY_OBJECT = { f: 'te', a: [] }\n\nObject.keys(MY_OBJECT)\n .filter(f =&gt; !!MY_OBJECT[f] &amp;&amp; MY_OBJECT[f].length &gt; 0)\n .reduce((r, i) =&gt; { r[i] = MY_OBJECT[i]; return r; }, {});\n</code></pre>\n\n<p><strong>JS BIN</strong> <a href=\"https://jsbin.com/kugoyinora/edit?js,console\" rel=\"noreferrer\">https://jsbin.com/kugoyinora/edit?js,console</a></p>\n" }, { "answer_id": 44032137, "author": "JeffD23", "author_id": 3808414, "author_profile": "https://Stackoverflow.com/users/3808414", "pm_score": 4, "selected": false, "text": "<p>Simplest possible Lodash solution to return an object with the <code>null</code> and <code>undefined</code> values filtered out.</p>\n\n<p><code>_.omitBy(obj, _.isNil)</code></p>\n" }, { "answer_id": 44939678, "author": "dpmott", "author_id": 2773846, "author_profile": "https://Stackoverflow.com/users/2773846", "pm_score": 2, "selected": false, "text": "<p>If you use eslint and want to avoid tripping the the no-param-reassign rule, you can use Object.assign in conjunction with .reduce and a computed property name for a fairly elegant ES6 solution:</p>\n\n<pre><code>const queryParams = { a: 'a', b: 'b', c: 'c', d: undefined, e: null, f: '', g: 0 };\nconst cleanParams = Object.keys(queryParams) \n .filter(key =&gt; queryParams[key] != null)\n .reduce((acc, key) =&gt; Object.assign(acc, { [key]: queryParams[key] }), {});\n// { a: 'a', b: 'b', c: 'c', f: '', g: 0 }\n</code></pre>\n" }, { "answer_id": 46451724, "author": "DaniOcean", "author_id": 1353721, "author_profile": "https://Stackoverflow.com/users/1353721", "pm_score": 2, "selected": false, "text": "<p>If you want 4 lines of a pure ES7 solution:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const clean = e =&gt; e instanceof Object ? Object.entries(e).reduce((o, [k, v]) =&gt; {\n if (typeof v === 'boolean' || v) o[k] = clean(v);\n return o;\n}, e instanceof Array ? [] : {}) : e;\n</code></pre>\n\n<p>Or if you prefer more readable version:\n</p>\n\n<pre><code>function filterEmpty(obj, [key, val]) {\n if (typeof val === 'boolean' || val) {\n obj[key] = clean(val)\n };\n\n return obj;\n}\n\nfunction clean(entry) {\n if (entry instanceof Object) {\n const type = entry instanceof Array ? [] : {};\n const entries = Object.entries(entry);\n\n return entries.reduce(filterEmpty, type);\n }\n\n return entry;\n}\n</code></pre>\n\n<p>This will preserve boolean values and it will clean arrays too. It also preserves the original object by returning a cleaned copy.</p>\n" }, { "answer_id": 47205128, "author": "bharath muppa", "author_id": 4029794, "author_profile": "https://Stackoverflow.com/users/4029794", "pm_score": 3, "selected": false, "text": "<p>I have same scenario in my project and achieved using following method.</p>\n\n<p>It works with all data types, few mentioned above doesn't work with date and empty arrays . </p>\n\n<p><strong>removeEmptyKeysFromObject.js</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>removeEmptyKeysFromObject(obj) {\r\n Object.keys(obj).forEach(key =&gt; {\r\n if (Object.prototype.toString.call(obj[key]) === '[object Date]' &amp;&amp; (obj[key].toString().length === 0 || obj[key].toString() === 'Invalid Date')) {\r\n delete obj[key];\r\n } else if (obj[key] &amp;&amp; typeof obj[key] === 'object') {\r\n this.removeEmptyKeysFromObject(obj[key]);\r\n } else if (obj[key] == null || obj[key] === '') {\r\n delete obj[key];\r\n }\r\n\r\n if (obj[key]\r\n &amp;&amp; typeof obj[key] === 'object'\r\n &amp;&amp; Object.keys(obj[key]).length === 0\r\n &amp;&amp; Object.prototype.toString.call(obj[key]) !== '[object Date]') {\r\n delete obj[key];\r\n }\r\n});\r\n return obj;\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>pass any object to this function removeEmptyKeysFromObject()</p>\n" }, { "answer_id": 51600150, "author": "Felippe Nardi", "author_id": 1762125, "author_profile": "https://Stackoverflow.com/users/1762125", "pm_score": 2, "selected": false, "text": "<p>Here is a functional way to remove <code>nulls</code> from an Object using ES6 without mutating the object using only <code>reduce</code>:</p>\n\n<pre><code>const stripNulls = (obj) =&gt; {\n return Object.keys(obj).reduce((acc, current) =&gt; {\n if (obj[current] !== null) {\n return { ...acc, [current]: obj[current] }\n }\n return acc\n }, {})\n}\n</code></pre>\n" }, { "answer_id": 51686226, "author": "Ben Carp", "author_id": 7224430, "author_profile": "https://Stackoverflow.com/users/7224430", "pm_score": 1, "selected": false, "text": "<h3>Clean object in place</h3>\n\n<pre class=\"lang-js prettyprint-override\"><code>// General cleanObj function\nconst cleanObj = (valsToRemoveArr, obj) =&gt; {\n Object.keys(obj).forEach( (key) =&gt;\n if (valsToRemoveArr.includes(obj[key])){\n delete obj[key]\n }\n })\n}\n\ncleanObj([undefined, null], obj)\n</code></pre>\n\n<h3>Pure function</h3>\n\n<pre class=\"lang-js prettyprint-override\"><code>const getObjWithoutVals = (dontReturnValsArr, obj) =&gt; {\n const cleanObj = {}\n Object.entries(obj).forEach( ([key, val]) =&gt; {\n if(!dontReturnValsArr.includes(val)){\n cleanObj[key]= val\n } \n })\n return cleanObj\n}\n\n//To get a new object without `null` or `undefined` run: \nconst nonEmptyObj = getObjWithoutVals([undefined, null], obj)\n</code></pre>\n" }, { "answer_id": 52518442, "author": "Yinon", "author_id": 3027703, "author_profile": "https://Stackoverflow.com/users/3027703", "pm_score": 2, "selected": false, "text": "<p>a reduce helper can do the trick (without type checking) -</p>\n\n<pre><code>const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) =&gt; {\n if (value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n</code></pre>\n" }, { "answer_id": 52831153, "author": "Hardik Pithva", "author_id": 4790490, "author_profile": "https://Stackoverflow.com/users/4790490", "pm_score": 2, "selected": false, "text": "<p>You can also use <code>...</code> spread syntax using <code>forEach</code> something like this:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let obj = { a: 1, b: \"b\", c: undefined, d: null };\nlet cleanObj = {};\n\nObject.keys(obj).forEach(val =&gt; {\n const newVal = obj[val];\n cleanObj = newVal ? { ...cleanObj, [val]: newVal } : cleanObj;\n});\n\nconsole.info(cleanObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 53824356, "author": "Peter Aron Zentai", "author_id": 1269946, "author_profile": "https://Stackoverflow.com/users/1269946", "pm_score": 0, "selected": false, "text": "<p>If you prefer the pure/functional approach</p>\n\n<pre><code>const stripUndef = obj =&gt; \n Object.keys(obj)\n .reduce((p, c) =&gt; ({ ...p, ...(x[c] === undefined ? { } : { [c]: x[c] })}), {});\n</code></pre>\n" }, { "answer_id": 54455779, "author": "lewtur", "author_id": 7012762, "author_profile": "https://Stackoverflow.com/users/7012762", "pm_score": 0, "selected": false, "text": "<p>If you don't want to modify the original object (using some ES6 operators):</p>\n\n<pre><code>const keys = Object.keys(objectWithNulls).filter(key =&gt; objectWithNulls[key]);\nconst pairs = keys.map(key =&gt; ({ [key]: objectWithNulls[key] }));\n\nconst objectWithoutNulls = pairs.reduce((val, acc) =&gt; ({ ...val, ...acc }));\n</code></pre>\n\n<p>The <code>filter(key =&gt; objectWithNulls[key])</code>returns <em>anything that is truthy</em>, so will reject any values such as<code>0</code> or <code>false</code>, as well as <code>undefined</code> or <code>null</code>. Can be easily changed to <code>filter(key =&gt; objectWithNulls[key] !== undefined)</code>or something similar if this is unwanted behaviour.</p>\n" }, { "answer_id": 54707141, "author": "Scotty Jamison", "author_id": 7696223, "author_profile": "https://Stackoverflow.com/users/7696223", "pm_score": 4, "selected": false, "text": "<p>You can do a recursive removal in one line using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter\" rel=\"noreferrer\">json.stringify's replacer argument</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>const removeEmptyValues = obj =&gt; (\n JSON.parse(JSON.stringify(obj, (k,v) =&gt; v ?? undefined))\n)\n</code></pre>\n<p>Usage:</p>\n<pre><code>removeEmptyValues({a:{x:1,y:null,z:undefined}}) // Returns {a:{x:1}}\n</code></pre>\n<p>As mentioned in Emmanuel's comment, this technique only worked if your data structure contains only data types that can be put into JSON format (strings, numbers, lists, etc).</p>\n<p>(This answer has been updated to use the new <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"noreferrer\">Nullish Coalescing operator</a>. depending on browser support needs you may want to use this function instead: <code>(k,v) =&gt; v!=null ? v : undefined</code>)</p>\n" }, { "answer_id": 56093495, "author": "L. Zampetti", "author_id": 5872513, "author_profile": "https://Stackoverflow.com/users/5872513", "pm_score": 2, "selected": false, "text": "<p>Recursively remove null, undefined, empty objects and empty arrays, returning a copy (ES6 version)</p>\n\n<pre><code>export function skipEmpties(dirty) {\n let item;\n if (Array.isArray(dirty)) {\n item = dirty.map(x =&gt; skipEmpties(x)).filter(value =&gt; value !== undefined);\n return item.length ? item : undefined;\n } else if (dirty &amp;&amp; typeof dirty === 'object') {\n item = {};\n Object.keys(dirty).forEach(key =&gt; {\n const value = skipEmpties(dirty[key]);\n if (value !== undefined) {\n item[key] = value;\n }\n });\n return Object.keys(item).length ? item : undefined;\n } else {\n return dirty === null ? undefined : dirty;\n }\n}\n</code></pre>\n" }, { "answer_id": 56325271, "author": "peralmq", "author_id": 350195, "author_profile": "https://Stackoverflow.com/users/350195", "pm_score": 3, "selected": false, "text": "<p>Functional and immutable approach, without <code>.filter</code> and without creating more objects than needed</p>\n\n<pre><code>Object.keys(obj).reduce((acc, key) =&gt; (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})\n</code></pre>\n" }, { "answer_id": 57195634, "author": "Vardaman PK", "author_id": 11521196, "author_profile": "https://Stackoverflow.com/users/11521196", "pm_score": 1, "selected": false, "text": "<p>We can use JSON.stringify and JSON.parse to remove blank attributes from an object.</p>\n\n<pre><code>jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) =&gt; {\n if (value == null || value == '' || value == [] || value == {})\n return undefined;\n return value;\n });\n</code></pre>\n" }, { "answer_id": 57625661, "author": "chickens", "author_id": 1602301, "author_profile": "https://Stackoverflow.com/users/1602301", "pm_score": 8, "selected": false, "text": "<p><strong>Shortest one liners for ES6+</strong></p>\n\n<p>Filter all falsy values ( <code>\"\"</code>, <code>0</code>, <code>false</code>, <code>null</code>, <code>undefined</code> )</p>\n\n<pre><code>Object.entries(obj).reduce((a,[k,v]) =&gt; (v ? (a[k]=v, a) : a), {})\n</code></pre>\n\n<p>Filter <code>null</code> and <code>undefined</code> values:</p>\n\n<pre><code>Object.entries(obj).reduce((a,[k,v]) =&gt; (v == null ? a : (a[k]=v, a)), {})\n</code></pre>\n\n<p>Filter ONLY <code>null</code></p>\n\n<pre><code>Object.entries(obj).reduce((a,[k,v]) =&gt; (v === null ? a : (a[k]=v, a)), {})\n</code></pre>\n\n<p>Filter ONLY <code>undefined</code></p>\n\n<pre><code>Object.entries(obj).reduce((a,[k,v]) =&gt; (v === undefined ? a : (a[k]=v, a)), {})\n</code></pre>\n\n<p><strong>Recursive Solutions:</strong> Filters <code>null</code> and <code>undefined</code></p>\n\n<p>For Objects:</p>\n\n<pre><code>const cleanEmpty = obj =&gt; Object.entries(obj)\n .map(([k,v])=&gt;[k,v &amp;&amp; typeof v === \"object\" ? cleanEmpty(v) : v])\n .reduce((a,[k,v]) =&gt; (v == null ? a : (a[k]=v, a)), {});\n</code></pre>\n\n<p>For Objects and Arrays:</p>\n\n<pre><code>const cleanEmpty = obj =&gt; {\n if (Array.isArray(obj)) { \n return obj\n .map(v =&gt; (v &amp;&amp; typeof v === 'object') ? cleanEmpty(v) : v)\n .filter(v =&gt; !(v == null)); \n } else { \n return Object.entries(obj)\n .map(([k, v]) =&gt; [k, v &amp;&amp; typeof v === 'object' ? cleanEmpty(v) : v])\n .reduce((a, [k, v]) =&gt; (v == null ? a : (a[k]=v, a)), {});\n } \n}\n</code></pre>\n" }, { "answer_id": 60485904, "author": "JHH", "author_id": 1226020, "author_profile": "https://Stackoverflow.com/users/1226020", "pm_score": -1, "selected": false, "text": "<p>30+ answers but I didn't see this short ES6 one-liner, utilizing the spread operator thanks to <code>Object.assign()</code> being a vararg function that silently ignores any non-objects (like <code>false</code>).</p>\n\n<pre><code>Object.assign({}, ...Object.entries(obj).map(([k,v]) =&gt; v != null &amp;&amp; {[k]: v]))\n</code></pre>\n" }, { "answer_id": 60887364, "author": "Benny Neugebauer", "author_id": 451634, "author_profile": "https://Stackoverflow.com/users/451634", "pm_score": 0, "selected": false, "text": "<p>If you just want to remove undefined top-level properties from an object, I find this to be the easiest:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const someObject = {\r\n a: null,\r\n b: 'someString',\r\n c: 3,\r\n d: undefined\r\n};\r\n\r\nfor (let [key, value] of Object.entries(someObject)) {\r\n if (value === null || value === undefined) delete someObject[key];\r\n}\r\n\r\nconsole.log('Sanitized', someObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 61764079, "author": "Arturo Montoya", "author_id": 6526093, "author_profile": "https://Stackoverflow.com/users/6526093", "pm_score": 0, "selected": false, "text": "<pre><code>ES6 arrow function and ternary operator:\nObject.entries(obj).reduce((acc, entry) =&gt; {\n const [key, value] = entry\n if (value !== undefined) acc[key] = value;\n return acc;\n}, {})\n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> const obj = {test:undefined, test1:1 ,test12:0, test123:false};\r\n const newObj = Object.entries(obj).reduce((acc, entry) =&gt; {\r\n const [key, value] = entry\r\n if (value !== undefined) acc[key] = value;\r\n return acc;\r\n }, {})\r\n console.log(newObj)</code></pre>\r\n</div>\r\n</div>\r\n\n</code></pre>\n" }, { "answer_id": 61768333, "author": "Emmanuel N K", "author_id": 2969074, "author_profile": "https://Stackoverflow.com/users/2969074", "pm_score": 2, "selected": false, "text": "<p>Here is a comprehensive recursive function (originally based on the one by @chickens) that will:</p>\n\n<ul>\n<li>recursively remove what you tell it to <code>defaults=[undefined, null, '', NaN]</code></li>\n<li>Correctly handle regular objects, arrays and Date objects</li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {\n if (!defaults.length) return obj\n if (defaults.includes(obj)) return\n\n if (Array.isArray(obj))\n return obj\n .map(v =&gt; v &amp;&amp; typeof v === 'object' ? cleanEmpty(v, defaults) : v)\n .filter(v =&gt; !defaults.includes(v))\n\n return Object.entries(obj).length \n ? Object.entries(obj)\n .map(([k, v]) =&gt; ([k, v &amp;&amp; typeof v === 'object' ? cleanEmpty(v, defaults) : v]))\n .reduce((a, [k, v]) =&gt; (defaults.includes(v) ? a : { ...a, [k]: v}), {}) \n : obj\n}\n</code></pre>\n\n<p>USAGE:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// based off the recursive cleanEmpty function by @chickens. \r\n// This one can also handle Date objects correctly \r\n// and has a defaults list for values you want stripped.\r\n\r\nconst cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {\r\n if (!defaults.length) return obj\r\n if (defaults.includes(obj)) return\r\n\r\n if (Array.isArray(obj))\r\n return obj\r\n .map(v =&gt; v &amp;&amp; typeof v === 'object' ? cleanEmpty(v, defaults) : v)\r\n .filter(v =&gt; !defaults.includes(v))\r\n\r\n return Object.entries(obj).length \r\n ? Object.entries(obj)\r\n .map(([k, v]) =&gt; ([k, v &amp;&amp; typeof v === 'object' ? cleanEmpty(v, defaults) : v]))\r\n .reduce((a, [k, v]) =&gt; (defaults.includes(v) ? a : { ...a, [k]: v}), {}) \r\n : obj\r\n}\r\n\r\n\r\n// testing\r\n\r\nconsole.log('testing: undefined \\n', cleanEmpty(undefined))\r\nconsole.log('testing: null \\n',cleanEmpty(null))\r\nconsole.log('testing: NaN \\n',cleanEmpty(NaN))\r\nconsole.log('testing: empty string \\n',cleanEmpty(''))\r\nconsole.log('testing: empty array \\n',cleanEmpty([]))\r\nconsole.log('testing: date object \\n',cleanEmpty(new Date(1589339052 * 1000)))\r\nconsole.log('testing: nested empty arr \\n',cleanEmpty({ 1: { 2 :null, 3: [] }}))\r\nconsole.log('testing: comprehensive obj \\n', cleanEmpty({\r\n a: 5,\r\n b: 0,\r\n c: undefined,\r\n d: {\r\n e: null,\r\n f: [{\r\n a: undefined,\r\n b: new Date(),\r\n c: ''\r\n }]\r\n },\r\n g: NaN,\r\n h: null\r\n}))\r\nconsole.log('testing: different defaults \\n', cleanEmpty({\r\n a: 5,\r\n b: 0,\r\n c: undefined,\r\n d: {\r\n e: null,\r\n f: [{\r\n a: undefined,\r\n b: '',\r\n c: new Date()\r\n }]\r\n },\r\n g: [0, 1, 2, 3, 4],\r\n h: '',\r\n}, [undefined, null]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 62406569, "author": "Agus Suhardi", "author_id": 6251396, "author_profile": "https://Stackoverflow.com/users/6251396", "pm_score": 0, "selected": false, "text": "<p>remove empty field object</p>\n\n<pre><code>for (const objectKey of Object.keys(data)) {\n if (data[objectKey] === null || data[objectKey] === '' || data[objectKey] === 'null' || data[objectKey] === undefined) {\n delete data[objectKey];\n }\n }\n</code></pre>\n" }, { "answer_id": 62770539, "author": "Shikyo", "author_id": 1557162, "author_profile": "https://Stackoverflow.com/users/1557162", "pm_score": 1, "selected": false, "text": "<p>This question has been thoroughly answered already, i'd just like to contribute my version based on other examples given:</p>\n<pre><code>function filterObject(obj, filter) {\n return Object.entries(obj)\n .map(([key, value]) =&gt; {\n return [key, value &amp;&amp; typeof value === 'object'\n ? filterObject(value, filter)\n : value];\n })\n .reduce((acc, [key, value]) =&gt; {\n if (!filter.includes(value)) {\n acc[key] = value;\n }\n\n return acc;\n }, {});\n}\n</code></pre>\n<p>What makes this solution different is the ability to specify which values you'd like to filter in the second parameter like this:</p>\n<pre><code>const filtered = filterObject(originalObject, [null, '']);\n</code></pre>\n<p>Which will return a new object (does not mutate the original object) not including the properties with a value of <code>null</code> or <code>''</code>.</p>\n" }, { "answer_id": 64447384, "author": "ThomasReggi", "author_id": 340688, "author_profile": "https://Stackoverflow.com/users/340688", "pm_score": 2, "selected": false, "text": "<p>Here's an alternative</p>\n<p>Typescript:</p>\n<pre><code>function objectDefined &lt;T&gt;(obj: T): T {\n const acc: Partial&lt;T&gt; = {};\n for (const key in obj) {\n if (obj[key] !== undefined) acc[key] = obj[key];\n }\n return acc as T;\n}\n</code></pre>\n<p>Javascript:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function objectDefined(obj) {\n const acc = {};\n for (const key in obj) {\n if (obj[key] !== undefined) acc[key] = obj[key];\n }\n return acc;\n}\n</code></pre>\n" }, { "answer_id": 65263323, "author": "aalaap", "author_id": 44257, "author_profile": "https://Stackoverflow.com/users/44257", "pm_score": 2, "selected": false, "text": "<p>If you're okay with using <a href=\"https://lodash.com/\" rel=\"nofollow noreferrer\">Lodash</a>, you can add the <a href=\"http://deepdash.io/\" rel=\"nofollow noreferrer\">DeepDash</a> recursive library and achieve what you want with some pretty concise code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const prune = obj =&gt; _.filterDeep(obj, (v) =&gt; !(_.isUndefined(v) || _.isNull(v)));\n</code></pre>\n<p>Calling <code>prune(anObjectWithNulls)</code> will return the object without <code>undefined</code> or <code>null</code> values.</p>\n" }, { "answer_id": 66092400, "author": "Zahirul Haque", "author_id": 3863697, "author_profile": "https://Stackoverflow.com/users/3863697", "pm_score": 3, "selected": false, "text": "<p>Remove all the properties with null and undefined</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let obj = {\n\"id\": 1,\n\"firstName\": null,\n\"lastName\": null,\n\"address\": undefined,\n\"role\": \"customer\",\n\"photo\": \"fb79fd5d-06c9-4097-8fdc-6cebf73fab26/fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg\",\n\"location\": null,\n\"idNumber\": null,\n};\n\n let result = Object.entries(obj).reduce((a,[k,v]) =&gt; (v == null ? a : (a[k]=v, a)), {});\nconsole.log(result)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68863356, "author": "Harsh Soni", "author_id": 14058987, "author_profile": "https://Stackoverflow.com/users/14058987", "pm_score": 0, "selected": false, "text": "<pre><code>function filterObject(obj) {\n for (var propName in obj) {\n if (!(obj[propName] || obj[propName] === false)) {\n delete obj[propName];\n }\n }\n\n return obj;\n}\n</code></pre>\n<p><strong>This function also removes NaN value from an object and easy to understand</strong></p>\n" }, { "answer_id": 69497853, "author": "Lysandro Carioca", "author_id": 5914415, "author_profile": "https://Stackoverflow.com/users/5914415", "pm_score": 1, "selected": false, "text": "<p>Using Nullish coalescing available ES2020</p>\n<pre><code>const filterNullishPropertiesFromObject = (obj) =&gt; {\n const newEntries = Object.entries(obj).filter(([_, value]) =&gt; {\n const nullish = value ?? null;\n return nullish !== null;\n });\n\n return Object.fromEntries(newEntries);\n};\n</code></pre>\n" }, { "answer_id": 69726359, "author": "Guilherme Nimer", "author_id": 11237109, "author_profile": "https://Stackoverflow.com/users/11237109", "pm_score": -1, "selected": false, "text": "<p>Here's my version of chiken's function</p>\n<p>This will remove empty strings, undefined, null from object or object arrays and don't affect Date objects</p>\n<pre><code>const removeEmpty = obj =&gt; {\n if (Array.isArray(obj)) {\n return obj.map(v =&gt; (v &amp;&amp; !(v instanceof Date) &amp;&amp; typeof v === 'object' ? removeEmpty(v) : v)).filter(v =&gt; v)\n } else {\n return Object.entries(obj)\n .map(([k, v]) =&gt; [k, v &amp;&amp; !(v instanceof Date) &amp;&amp; typeof v === 'object' ? removeEmpty(v) : v])\n .reduce((a, [k, v]) =&gt; (typeof v !== 'boolean' &amp;&amp; !v ? a : ((a[k] = v), a)), {})\n }\n }\n</code></pre>\n" }, { "answer_id": 70580481, "author": "Koen Peters", "author_id": 1236396, "author_profile": "https://Stackoverflow.com/users/1236396", "pm_score": 0, "selected": false, "text": "<p>You can do this using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">nullish coalescing operator: ??</a> since that checks only for null and undefined values. Note that the example below changes obj itself. It also deletes null and undefined values of nested objects.</p>\n<pre><code>const removeEmptyKeys = (obj) =&gt; {\n Object.entries(obj).forEach(([k, v]) =&gt; {\n (v ?? delete obj[k])\n if (v &amp;&amp; typeof v === 'object') {\n removeEmptyKeys(v)\n }\n })\n}\n</code></pre>\n" }, { "answer_id": 70630093, "author": "Baptiste Arnaud", "author_id": 5654715, "author_profile": "https://Stackoverflow.com/users/5654715", "pm_score": 0, "selected": false, "text": "<p>Here is a super clean Typescript solution using <code>reduce</code>:</p>\n<pre><code>const removeUndefinedFields = &lt;T&gt;(obj: T): T =&gt;\n Object.keys(obj).reduce(\n (acc, key) =&gt;\n obj[key as keyof T] === undefined\n ? { ...acc }\n : { ...acc, [key]: obj[key as keyof T] },\n {} as T\n )\n</code></pre>\n" }, { "answer_id": 70771061, "author": "U. Bulle", "author_id": 5433463, "author_profile": "https://Stackoverflow.com/users/5433463", "pm_score": 0, "selected": false, "text": "<p>Here's recursive ES6 implementation that cleans up properties of the properties as well. It's a side-effect free function meaning that it does not modify the object so the return object must be used.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeUndefinedProperties(obj) {\n return Object.keys(obj || {})\n .reduce((acc, key) =&gt; {\n const value = obj[key];\n switch (typeof value) {\n case 'object': {\n const cleanValue = removeUndefinedProperties(value); // recurse\n if (!Object.keys(cleanValue).length) {\n return { ...acc };\n }\n return { ...acc, [key]: cleanValue };\n }\n case 'undefined':\n return { ...acc };\n default:\n return { ...acc, [key]: value };\n }\n }, {});\n}\n</code></pre>\n<p>In TypeScript, type it using <code>unknown</code> such as:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeUndefinedProperties(obj: unknown): unknown {\n return Object.keys(obj ?? {})\n .reduce((acc, key) =&gt; {\n const value = obj[key];\n switch (typeof value) {\n case 'object': {\n const cleanValue = removeUndefinedProperties(value); // recurse\n if (!Object.keys(cleanValue).length) {\n return { ...acc };\n }\n return { ...acc, [key]: cleanValue };\n }\n case 'undefined':\n return { ...acc };\n default:\n return { ...acc, [key]: value };\n }\n }, {});\n}\n</code></pre>\n" }, { "answer_id": 71184412, "author": "prakhar tomar", "author_id": 13860071, "author_profile": "https://Stackoverflow.com/users/13860071", "pm_score": 0, "selected": false, "text": "<p>Cleans empty array, empty object, empty string, undefined, NaN and null values.</p>\n<pre><code>function objCleanUp(obj:any) {\n for (var attrKey in obj) {\n var attrValue = obj[attrKey];\n if (attrValue === null || attrValue === undefined || attrValue === &quot;&quot; || attrValue !== attrValue) {\n delete obj[attrKey];\n } else if (Object.prototype.toString.call(attrValue) === &quot;[object Object]&quot;) {\n objCleanUp(attrValue);\n if(Object.keys(attrValue).length===0)delete obj[attrKey];\n } else if (Array.isArray(attrValue)) {\n attrValue.forEach(function (v,index) {\n objCleanUp(v);\n if(Object.keys(v).length===0)attrValue.splice(index,1);\n });\n if(attrValue.length===0)delete obj[attrKey];\n }\n }\n}\n\nobjCleanUp(myObject)\n</code></pre>\n<p>(attrValue !== attrValue) checks for NaN. Learned it <a href=\"https://stackoverflow.com/a/16988441/13860071\">here</a></p>\n" }, { "answer_id": 71815600, "author": "ahmelq", "author_id": 2722247, "author_profile": "https://Stackoverflow.com/users/2722247", "pm_score": 0, "selected": false, "text": "<p>Oneliner:</p>\n<pre><code>let obj = { a: 0, b: &quot;string&quot;, c: undefined, d: null };\n\nObject.keys(obj).map(k =&gt; obj[k] == undefined ? delete obj[k] : obj[k] );\n</code></pre>\n<p>console.log(obj);</p>\n<p><code>obj</code> will be <code>{ a: 0, b: &quot;string&quot; }</code></p>\n" }, { "answer_id": 71816805, "author": "Mohammed Rashad", "author_id": 8133129, "author_profile": "https://Stackoverflow.com/users/8133129", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var testObject = {\n test1: \"null\",\n test2: null,\n test3: 'somestring',\n test4: 3,\n test5: \"undefined\",\n test6: undefined,\n}\n\nfunction removeObjectItem(obj){\n for (var key in obj) {\n if (String(obj[key]) === \"null\" || String(obj[key]) === \"undefined\") {\n delete obj[key];\n }\n }\n return obj\n}\nconsole.log(removeObjectItem(testObject))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 71968391, "author": "ABHIJEET KHIRE", "author_id": 8621764, "author_profile": "https://Stackoverflow.com/users/8621764", "pm_score": 2, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// basic object you have to clean \n// ️ input _object\nconst _object = {\n a: null,\n b: undefined,\n email: '[email protected]',\n mob:88888888888,\n add:\"\"\n };\n \n// kays you have to remove having values included in array \n const CLEANER_VALUES = [null, undefined, '']\n \n// function to clean object pass the raw object and value format you have to clean\n const objectCleaner = (_object, _CLEANER_VALUES = CLEANER_VALUES) =&gt;{\n const cleanedObj = {..._object};\n Object.keys(cleanedObj).forEach(key =&gt; {\n if (_CLEANER_VALUES.includes(cleanedObj[key])) {\n delete cleanedObj[key];\n }});\n \n return cleanedObj;\n \n }\n \n // calling function \n const __cleandedObject = objectCleaner(_object, CLEANER_VALUES);\n console.log('yup you have cleaned object', __cleandedObject); \n // ️ output { email: \"[email protected]\",mob: 88888888888 }\n\n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 73068210, "author": "Nivethan", "author_id": 12719767, "author_profile": "https://Stackoverflow.com/users/12719767", "pm_score": 0, "selected": false, "text": "<h2>A generic function with TypeScript</h2>\n<pre><code>function cleanProps(object:Record&lt;string, string&gt;):Record&lt;string, string&gt; {\n let cleanObj = {};\n\n Object.keys(object).forEach((key) =&gt; {\n const property = object[key];\n cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;\n });\n\n return cleanObj;\n}\n\nexport default cleanProps;\n\n</code></pre>\n<p>now lets say you have a object like the following</p>\n<pre><code>interface Filters{\n searchString: string;\n location: string;\n sector: string\n}\n\nconst filters:Filters = {\n searchString: 'cute cats',\n location: '',\n sector: 'education',\n};\n</code></pre>\n<p>You can use the function as following</p>\n<pre><code>const result = cleanProps(filters as Record&lt;keyof Filters, string&gt;);\nconsole.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }\n\n</code></pre>\n" }, { "answer_id": 74164878, "author": "Yash Mehta", "author_id": 14368064, "author_profile": "https://Stackoverflow.com/users/14368064", "pm_score": 0, "selected": false, "text": "<p>This could be solved using Recursion. JavaScript objects could be an array and could have array with null values as a value.</p>\n<pre><code>function removeNullValues(obj) {\n // Check weather obj is an array\n if (Array.isArray(obj)) {\n // Creating copy of obj so that index is maintained after splice\n obj.slice(0).forEach((val) =&gt; {\n if (val === null) {\n obj.splice(obj.indexOf(val), 1);\n } else if (typeof val === 'object') {\n // Check if array has an object\n removeNullValues(val);\n }\n });\n } else if (typeof obj === 'object') {\n // Check for object\n Object.keys(obj).forEach((key) =&gt; {\n if (obj[key] === null) {\n delete obj[key];\n } else if (typeof obj[key] === 'object') {\n removeNullValues(obj[key]);\n }\n });\n }\n return obj;\n}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33581/" ]
How do I remove all attributes which are `undefined` or `null` in a JavaScript object? (Question is similar to [this one](https://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object) for Arrays)
You can loop through the object: ```js var test = { test1: null, test2: 'somestring', test3: 3, } function clean(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } return obj } console.log(test); console.log(clean(test)); ``` If you're concerned about this property removal not running up object's proptype chain, you can also: ``` function clean(obj) { var propNames = Object.getOwnPropertyNames(obj); for (var i = 0; i < propNames.length; i++) { var propName = propNames[i]; if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } } ``` A few notes on null vs undefined: ``` test.test1 === null; // true test.test1 == null; // true test.notaprop === null; // false test.notaprop == null; // true test.notaprop === undefined; // true test.notaprop == undefined; // true ```
286,149
<p>I'm trying to disable a button when a user submits a payment form and the code to post the form is causing a double post in firefox. This problem does not occur when the code is removed, and does not occur in any browser other than firefox.</p> <p>Any idea how to prevent the double post here?</p> <pre><code>System.Text.StringBuilder sb = new StringBuilder(); sb.Append("if (typeof(Page_ClientValidate) == 'function') { "); sb.Append("if (Page_ClientValidate() == false) { return false; }} "); sb.Append("this.value = 'Please wait...';"); sb.Append("this.disabled = true;"); sb.Append(Page.GetPostBackEventReference(btnSubmit )); sb.Append(";"); btnSubmit.Attributes.Add("onclick", sb.ToString()); </code></pre> <p>it's the sb.Append(Page.GetPostBackEventReference(btnSubmit )) line that's causing the issue</p> <p>Thanks</p> <p>EDIT: Here's the c# of the button:</p> <pre><code>&lt;asp:Button ID="cmdSubmit" runat="server" Text="Submit" /&gt; </code></pre> <p>here's the html<br><br> This code posts twice (and disables the submit button and verifies input):</p> <pre><code>&lt;input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; }} this.value = 'Please wait...';this.disabled = true;document.getElementById('ctl00_MainContent_cmdBack').disabled = true;__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" /&gt; </code></pre> <p><br>This code posts twice (but doesn’t disable the submit button):</p> <pre><code>&lt;input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" /&gt; </code></pre> <p><br>This code posts once (but doesn’t verify the user input and doesn’t disable the submit button):</p> <pre><code>&lt;input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="ctl00_MainContent_cmdSubmit" /&gt; </code></pre> <p><br>This code posts once (but doesn’t disable submit button):</p> <pre><code>&lt;input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&amp;quot;ctl00$MainContent$cmdSubmit&amp;quot;, &amp;quot;&amp;quot;, true, &amp;quot;&amp;quot;, &amp;quot;&amp;quot;, false, false))" id="ctl00_MainContent_cmdSubmit" /&gt; </code></pre> <p>This code doesn’t post at all: <br><br></p> <pre><code>&lt;input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="this.disabled = true;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&amp;quot;ctl00$MainContent$cmdSubmit&amp;quot;, &amp;quot;&amp;quot;, true, &amp;quot;&amp;quot;, &amp;quot;&amp;quot;, false, false))" id="ctl00_MainContent_cmdSubmit" /&gt; </code></pre> <p>Obviously it’s the disabling of the submit button that’s posing the problem. Do you have any ideas how we can disable the submit to avoid multiple clicking? </p>
[ { "answer_id": 286154, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 2, "selected": false, "text": "<p>Presumably, <code>btnSubmit</code> already has a server-side event hooked up. If so, the call to <code>Page.GetPostBackEventReference</code> should not be necessary. You should get your desired behavior simply by removing that line.</p>\n\n<p>Update: You mentioned attaching the event handler in C# code, but you don't mention where you do that. I'm guessing it's in the <code>Page_Load</code> handler. If that is the case, it wouldn't work properly, as it's too late to hook up a button click event handler at that point. Let's try this instead.</p>\n\n<p>First, it would be cleaner to put the JS into it's own function rather than building it in the C# code-behind. I suggest that you put it into a script block (or better yet, it's own .js file.)</p>\n\n<pre><code>function disableOnSubmit(target)\n{\n if (typeof(Page_ClientValidate) == 'function') {\n if (Page_ClientValidate() == false) { return false; }\n }\n target.value = 'Please wait...';\n target.disabled = true;\n return true;\n}\n</code></pre>\n\n<p>And for your ASPX button, try this:</p>\n\n<pre><code>&lt;asp:Button ID=\"cmdSubmit\" runat=\"server\" Text=\"Submit\" onclick=\"btnSumbit_Click\" OnClientClick=\"return disableOnSubmit(this);\" /&gt;\n</code></pre>\n" }, { "answer_id": 286159, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>Take that line out, the form will already submit because it is a submit button, not a regular button type, take a look at how ASP.NET renders the element out.</p>\n\n<p>Page validators are called in the form.onsubmit callback, so if your page is not valid, it will be validated there.</p>\n\n<p>So, just remove that line and you'll be set.</p>\n" }, { "answer_id": 1910457, "author": "ta4ka", "author_id": 232449, "author_profile": "https://Stackoverflow.com/users/232449", "pm_score": 0, "selected": false, "text": "<pre><code>private void checkButtonDoubleClick(Button button)\n {\n System.Text.StringBuilder sbValid = new System.Text.StringBuilder();\n sbValid.Append(\"if (typeof(Page_ClientValidate) == 'function') { \");\n sbValid.Append(\"if (Page_ClientValidate() == false) { return false; }} \");\n sbValid.Append(\"this.value = 'Please wait...';\");\n sbValid.Append(\"this.disabled = true;\");\n sbValid.Append(this.Page.ClientScript.GetPostBackEventReference(button, \"\"));\n sbValid.Append(\";return false;\");\n button.Attributes.Add(\"onclick\", sbValid.ToString());\n }\n</code></pre>\n" }, { "answer_id": 2544644, "author": "Clyde", "author_id": 305029, "author_profile": "https://Stackoverflow.com/users/305029", "pm_score": 1, "selected": false, "text": "<p>The answer is the add a return false; after your last line ;</p>\n\n<p>for example</p>\n\n<pre><code>sbValid.Append(this.Page.ClientScript.GetPostBackEventReference(button, \"\")); \nsbValid.Append(\";\");\n</code></pre>\n\n<p>must be</p>\n\n<pre><code> sbValid.Append(this.Page.ClientScript.GetPostBackEventReference(button, \"\")); \n sbValid.Append(\";return false;\");\n</code></pre>\n\n<p>this definitely worked for me.</p>\n" }, { "answer_id": 24120988, "author": "fgohil", "author_id": 1900285, "author_profile": "https://Stackoverflow.com/users/1900285", "pm_score": 0, "selected": false, "text": "<p>Try below code</p>\n<pre><code>&lt;asp:Button ID=&quot;cmdSubmit&quot; runat=&quot;server&quot; Text=&quot;Submit&quot; onclick=&quot;btnSumbit_Click&quot; OnClientClick=&quot;this.style.display = 'none';&quot;/&gt;\n</code></pre>\n<p>Update on 09 Oct 2021:--\nAnother better solution</p>\n<pre><code>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary btn-lg &quot; id=&quot;load1&quot; data-loading-text=&quot;&lt;i class='fa fa-circle-o-notch fa-spin'&gt;&lt;/i&gt; Processing Order&quot;&gt;Submit Order&lt;/button&gt;\n\n$('.btn').on('click', function() {\n var $this = $(this);\n $this.button('loading');\n setTimeout(function() {\n $this.button('reset');\n }, 8000);\n});\n</code></pre>\n" }, { "answer_id": 31873749, "author": "joy", "author_id": 5201325, "author_profile": "https://Stackoverflow.com/users/5201325", "pm_score": -1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;asp:Button ID=\"btn\" runat=\"server\" Text=\"something\" onclick=\"btn_Click\" \nValidationGroup=\"V1\" onClientClick=\"if(Page_ClientValidate('V1'))\n{this.disabled=true;this.value='Please Wait....';__doPostBack(this.id);}\n\"UseSubmitBehavior=\"false\" /&gt;\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36798/" ]
I'm trying to disable a button when a user submits a payment form and the code to post the form is causing a double post in firefox. This problem does not occur when the code is removed, and does not occur in any browser other than firefox. Any idea how to prevent the double post here? ``` System.Text.StringBuilder sb = new StringBuilder(); sb.Append("if (typeof(Page_ClientValidate) == 'function') { "); sb.Append("if (Page_ClientValidate() == false) { return false; }} "); sb.Append("this.value = 'Please wait...';"); sb.Append("this.disabled = true;"); sb.Append(Page.GetPostBackEventReference(btnSubmit )); sb.Append(";"); btnSubmit.Attributes.Add("onclick", sb.ToString()); ``` it's the sb.Append(Page.GetPostBackEventReference(btnSubmit )) line that's causing the issue Thanks EDIT: Here's the c# of the button: ``` <asp:Button ID="cmdSubmit" runat="server" Text="Submit" /> ``` here's the html This code posts twice (and disables the submit button and verifies input): ``` <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; }} this.value = 'Please wait...';this.disabled = true;document.getElementById('ctl00_MainContent_cmdBack').disabled = true;__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" /> ``` This code posts twice (but doesn’t disable the submit button): ``` <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="__doPostBack('ctl00$MainContent$cmdSubmit','');" id="ctl00_MainContent_cmdSubmit" /> ``` This code posts once (but doesn’t verify the user input and doesn’t disable the submit button): ``` <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="ctl00_MainContent_cmdSubmit" /> ``` This code posts once (but doesn’t disable submit button): ``` <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$cmdSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_MainContent_cmdSubmit" /> ``` This code doesn’t post at all: ``` <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" onclick="this.disabled = true;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$cmdSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_MainContent_cmdSubmit" /> ``` Obviously it’s the disabling of the submit button that’s posing the problem. Do you have any ideas how we can disable the submit to avoid multiple clicking?
Presumably, `btnSubmit` already has a server-side event hooked up. If so, the call to `Page.GetPostBackEventReference` should not be necessary. You should get your desired behavior simply by removing that line. Update: You mentioned attaching the event handler in C# code, but you don't mention where you do that. I'm guessing it's in the `Page_Load` handler. If that is the case, it wouldn't work properly, as it's too late to hook up a button click event handler at that point. Let's try this instead. First, it would be cleaner to put the JS into it's own function rather than building it in the C# code-behind. I suggest that you put it into a script block (or better yet, it's own .js file.) ``` function disableOnSubmit(target) { if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false) { return false; } } target.value = 'Please wait...'; target.disabled = true; return true; } ``` And for your ASPX button, try this: ``` <asp:Button ID="cmdSubmit" runat="server" Text="Submit" onclick="btnSumbit_Click" OnClientClick="return disableOnSubmit(this);" /> ```
286,150
<p>So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address <a href="http://www.stackoverflow.com/questions/ask">http://www.stackoverflow.com/questions/ask</a>. I would need the protocol and domain (e.g. <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?</p>
[ { "answer_id": 286155, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": -1, "selected": false, "text": "<pre><code>import re\nurl = \"http://stackoverflow.com/questions/ask\"\nprotocol, domain = re.match(r\"(http://[^/]*)(.*)\", url).groups()\n</code></pre>\n" }, { "answer_id": 286157, "author": "Dan Fego", "author_id": 34426, "author_profile": "https://Stackoverflow.com/users/34426", "pm_score": 3, "selected": false, "text": "<p>Use the Python urlparse module:</p>\n\n<p><a href=\"https://docs.python.org/library/urlparse.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/urlparse.html</a></p>\n\n<p>For a well-defined and well-traveled problem like this, don't bother with writing your own code, let alone your own regular expressions. They cause too much trouble ;-).</p>\n" }, { "answer_id": 286194, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 4, "selected": false, "text": "<p>Dan is right: urlparse is your friend:</p>\n\n<pre><code>&gt;&gt;&gt; from urlparse import urlparse\n&gt;&gt;&gt;\n&gt;&gt;&gt; parts = urlparse(\"http://www.stackoverflow.com/questions/ask\")\n&gt;&gt;&gt; parts.scheme + \"://\" + parts.netloc\n'http://www.stackoverflow.com'\n&gt;&gt;&gt; parts.path\n'/questions/ask'\n</code></pre>\n\n<p><strong>Note</strong>: In Python 3 it's <code>from urllib.parse import urlparse</code></p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address <http://www.stackoverflow.com/questions/ask>. I would need the protocol and domain (e.g. <http://www.stackoverflow.com>) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?
Dan is right: urlparse is your friend: ``` >>> from urlparse import urlparse >>> >>> parts = urlparse("http://www.stackoverflow.com/questions/ask") >>> parts.scheme + "://" + parts.netloc 'http://www.stackoverflow.com' >>> parts.path '/questions/ask' ``` **Note**: In Python 3 it's `from urllib.parse import urlparse`
286,161
<p>example:</p> <p>I want to see if <code>array[5]</code> holds a value or is empty.</p>
[ { "answer_id": 286163, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": false, "text": "<p>There is no such thing as an \"empty\" element in a Java array. If the array's length is at least six, then element 5 exists and it has a value. If you have not assigned anything else to that location, then it will have the value zero, just like an object's uninitialized field would have.</p>\n\n<p>If it is an array of <code>Object</code> descendants, then you can check whether the element is equal to <code>null</code>.</p>\n" }, { "answer_id": 286167, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 6, "selected": true, "text": "<p>Elements in primitive arrays can't be empty. They'll always get initialized to something (usually <code>0</code> for <code>int</code> arrays, but depends on how you declare the array).</p>\n\n<p>If you declare the array like so (for example):</p>\n\n<pre><code>int [] myArray ;\nmyArray = new int[7] ;\n</code></pre>\n\n<p>then all of the elements will default to <code>0</code>.</p>\n\n<p>An alternative syntax for declaring arrays is</p>\n\n<pre><code>int[] myArray = { 12, 7, 32, 15, 113, 0, 7 };\n</code></pre>\n\n<p>where the initial values for an array (of size seven in this case) are given in the curly braces <code>{}</code>.</p>\n" }, { "answer_id": 286171, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 2, "selected": false, "text": "<p>You have to define what you mean by empty. Depending on the datatype of the array you can decide on the semantics of empty. For example, if you have an array of ints you can decide that 0 is empty. Or if the array is of reference types then you can decide that null is empty. Then you simply check by comparing array[5] == null or array[5] == 0 etc.</p>\n" }, { "answer_id": 286252, "author": "Terry Lacy", "author_id": 37224, "author_profile": "https://Stackoverflow.com/users/37224", "pm_score": 2, "selected": false, "text": "<p>Primitive arrays (int, float, char, etc) are never \"empty\" (by which I assume you mean \"null\"), because primitive array elements can never be null.</p>\n\n<p>By default, an int array usually contains 0 when allocated. However, I never rely on this (spent too much time writing C code, I guess).</p>\n\n<p>One way is to pick a value that you want to treat as \"uninitialized\". It could be 0, or -1, or some other value that you're not going to use as a valid value. Initialize your array to that value after allocating it.</p>\n\n<p>Object arrays (String[] and any array of objects that extend Object), <em>can</em> have null elements, so you could create an Integer[] array and initialize it to nulls. I think I like that idea better than using a magic value as described above.</p>\n" }, { "answer_id": 286746, "author": "Leigh", "author_id": 26061, "author_profile": "https://Stackoverflow.com/users/26061", "pm_score": -1, "selected": false, "text": "<p>Create a constant to define the empty value, eg:</p>\n\n<pre><code>private static final int EMPTY = -1;\n</code></pre>\n\n<p>then create the array like this:</p>\n\n<pre><code>int[] myArray = new int[size];\nArrays.fill(myArray, EMPTY);\n</code></pre>\n\n<p>then to check if an element is 'empty', do this:</p>\n\n<pre><code>if (myArray[i] == EMPTY)\n{\n //element i is empty\n}\n</code></pre>\n" }, { "answer_id": 74200153, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "<h1>tl;dr</h1>\n<p>Use objects rather than primitives.</p>\n<pre><code>Integer[] myArray …\n… Objects.isNull( myArray[ 5 ] ) …\n… Objects.nonNull( myArray[ 5 ] ) …\n</code></pre>\n<h1>Use objects, not primitives ➠ <s><code>int[]</code></s> <code>Integer[]</code></h1>\n<p>The <a href=\"https://stackoverflow.com/a/286167/642706\">Answer by Bill the Lizard</a> is correct. An <strong>array of primitive values has no empty</strong> slots. All slots hold an element with a default value for that data type. For <code>int</code>, the default is <code>0</code>, zero.</p>\n<p>If you want to track empty slots, or “holes”, in your array, define the array as <strong>holding object references rather than primitive</strong> values. So you would want a <code>Integer[]</code> rather than <s><code>int[]</code></s>.</p>\n<pre><code>Integer[] integers = new Integer[ 12 ] ;\nSystem.out.println( Arrays.toString( integers ) ) ;\n</code></pre>\n<h2><code>null</code></h2>\n<p>When run we see that all the elements are <code>null</code>. This means no object references has yet been placed in that slot.</p>\n<blockquote>\n<p>[null, null, null, null, null, null, null, null, null, null, null, null]</p>\n</blockquote>\n<p>Let's assign some values. Java provides <a href=\"https://en.wikipedia.org/wiki/Boxing_(computer_science)#Autoboxing\" rel=\"nofollow noreferrer\">auto-boxing</a> for automatically converting <code>int</code> values into <code>Integer</code> objects.</p>\n<pre><code> integers[ 2 ] = 42 ; // Auto-boxing.\n integers[ 5 ] = Integer.valueOf( 99 ) ; // Unnecessary, because of auto-boxing.\n System.out.println( Arrays.toString( integers ) ) ;\n</code></pre>\n<p>When run, we see two slots are used while ten remain unused (<code>null</code>).</p>\n<blockquote>\n<p>[null, null, 42, null, null, 99, null, null, null, null, null, null]</p>\n</blockquote>\n<p>See this <a href=\"https://ideone.com/QccXf7\" rel=\"nofollow noreferrer\">code run at Ideone.com</a>.</p>\n<p>You said:</p>\n<blockquote>\n<p>I want to see if <code>array[5]</code> holds a value or is empty.</p>\n</blockquote>\n<p>Test for <code>null</code>.</p>\n<pre><code>boolean slotAtIndex5HoldsObjectRef = ( null != integers[ 5 ] ) ; // Parens are not necessary, but improve readability.\n</code></pre>\n<blockquote>\n<p>true</p>\n</blockquote>\n<p>More elegant to use the <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html\" rel=\"nofollow noreferrer\"><code>Objects</code></a> utility class.</p>\n<pre><code>boolean slot5Filled = Objects.nonNull( integers[ 5 ] ) ;\n</code></pre>\n<blockquote>\n<p>true</p>\n</blockquote>\n<p>Specify <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNullElse(T,T)\" rel=\"nofollow noreferrer\">a default value</a> if none assigned.</p>\n<pre><code> Integer x = Objects.requireNonNullElse( integers[ 5 ] , Integer.valueOf( 101 ) ) ;\n Integer y = Objects.requireNonNullElse( integers[ 7 ] , Integer.valueOf( 101 ) ) ;\n</code></pre>\n<blockquote>\n<p>x: 99</p>\n<p>y: 101</p>\n</blockquote>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36545/" ]
example: I want to see if `array[5]` holds a value or is empty.
Elements in primitive arrays can't be empty. They'll always get initialized to something (usually `0` for `int` arrays, but depends on how you declare the array). If you declare the array like so (for example): ``` int [] myArray ; myArray = new int[7] ; ``` then all of the elements will default to `0`. An alternative syntax for declaring arrays is ``` int[] myArray = { 12, 7, 32, 15, 113, 0, 7 }; ``` where the initial values for an array (of size seven in this case) are given in the curly braces `{}`.
286,184
<p>I have a c# winforms program and it opens up a serial port. The problem happens when the end user unplugs the usb cable and then the device disappears. After this the program will crash and want to report the error to microsoft. </p> <p>Is there a way to capture this event and shut down gracefully? </p>
[ { "answer_id": 286209, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "<p>If your try statement isn't catching the exception then let's hope Microsoft will inspect the dumps.</p>\n\n<p>There are some SetupDi APIs (I think ... it's been a while) that permit you to be advised of device arrivals and removals, but it won't help if you already crashed because the removed device was in the middle of your read or write operation.</p>\n" }, { "answer_id": 286263, "author": "jdigital", "author_id": 37231, "author_profile": "https://Stackoverflow.com/users/37231", "pm_score": 3, "selected": false, "text": "<p>Yes, there is a way to capture the event. Unfortunately, there can be a long delay between the time the device is removed and the time the program receives any notification.</p>\n\n<p>The approach is to trap com port events such as ErrorReceived and to catch the WM_DEVICECHANGE message.</p>\n\n<p>Not sure why your program is crashing; you should take a look at the stack to see where this is happening.</p>\n" }, { "answer_id": 1327400, "author": "MrHIDEn", "author_id": 160581, "author_profile": "https://Stackoverflow.com/users/160581", "pm_score": 2, "selected": false, "text": "<p>In registry at:<br/>\nHKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM<br/>\nis actual list of ports. If your port disappeared it means it was unplugged.<br/></p>\n\n<p><b>Real example:</b> (Try to remove your USB and press F5 in registry editor)<br/></p>\n\n<pre><code>Windows Registry Editor Version 5.00\nHKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM]\n\"Winachsf0\"=\"COM10\"\n\"\\\\Device\\\\mxuport0\"=\"COM1\"\n\"\\\\Device\\\\Serial2\"=\"COM13\"\n</code></pre>\n\n<p>COM10 - My fax modem<br/>\nCOM1 - <b>USB - moxa usb serial converter</b><br/>\nCOM13 - <b>USB - Profilic serial converter</b><br/></p>\n\n<p>Regards</p>\n" }, { "answer_id": 5270224, "author": "Fun Mun Pieng", "author_id": 2191695, "author_profile": "https://Stackoverflow.com/users/2191695", "pm_score": 1, "selected": false, "text": "<p>You could try to handle <code>ErrorReceived</code>.</p>\n\n<pre><code>private void buttonStart_Click(object sender, EventArgs e)\n{\n port.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(port_ErrorReceived);\n}\n\nvoid port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)\n{\n // TODO: handle the problem here\n}\n</code></pre>\n\n<p>Additionally, you could check whether the port exists before proceeding. You may want to check it once in a while, maybe just before reading/writing.</p>\n\n<pre><code>string[] ports = System.IO.Ports.SerialPort.GetPortNames();\nif (ports.Contains(\"COM7:\"))\n{\n // TODO: Can continue\n}\nelse\n{\n // TODO: Cannot, terminate properly\n}\n</code></pre>\n\n<p>You should also place <code>try-catch</code> blocks for all your serial port operations. It should help to prevent unexpected terminations.</p>\n\n<p>You may want to try to run the app in debug mode under your IDE and simulate the error. If an exception is throw, you would be able to identify where the problem becomes most evident. From there, you could probably try to find more specific solutions.</p>\n" }, { "answer_id": 5281396, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 4, "selected": true, "text": "<p>You can use WMI (Windows Management Instrumentation) to receive notification on USB events.\nI did exactly that two years ago, monitoring for plugging and unplugging of a specific usb device.<br>\nUnfortunately, the code stays with my former employer, but I found one example at <a href=\"http://bytes.com/topic/net/answers/102489-how-detect-usb-device-being-plugged-unplugged\" rel=\"nofollow\">bytes.com</a>:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Management;\nclass UsbWatcher \n{\n public static void Main() \n {\n WMIEvent wEvent = new WMIEvent();\n ManagementEventWatcher watcher = null;\n WqlEventQuery query;\n ManagementOperationObserver observer = new ManagementOperationObserver();\n\n ManagementScope scope = new ManagementScope(\"root\\\\CIMV2\");\n scope.Options.EnablePrivileges = true; \n try \n {\n query = new WqlEventQuery();\n query.EventClassName = \"__InstanceCreationEvent\";\n query.WithinInterval = new TimeSpan(0,0,10);\n\n query.Condition = @\"TargetInstance ISA 'Win32_USBControllerDevice' \";\n watcher = new ManagementEventWatcher(scope, query);\n\n watcher.EventArrived \n += new EventArrivedEventHandler(wEvent.UsbEventArrived);\n watcher.Start();\n }\n catch (Exception e)\n {\n //handle exception\n }\n}\n</code></pre>\n\n<p>I don't remember if I modified the query to receive events only for e specific device, or if I filtered out events from other devices in my event handler. For further information you may want to have a look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms257338.aspx\" rel=\"nofollow\">MSDN WMI .NET Code Directory</a>.</p>\n\n<p><strong>EDIT</strong>\nI found some more info on the event handler, it looks roughly like this:</p>\n\n<pre><code>protected virtual void OnUsbConnected(object Sender, EventArrivedEventArgs Arguments)\n{\n PropertyData TargetInstanceData = Arguments.NewEvent.Properties[\"TargetInstance\"];\n\n if (TargetInstanceData != null)\n {\n ManagementBaseObject TargetInstanceObject = (ManagementBaseObject)TargetInstanceData.Value;\n if (TargetInstanceObject != null)\n {\n string dependent = TargetInstanceObject.Properties[\"Dependent\"].Value.ToString();\n string deviceId = dependent.Substring(dependent.IndexOf(\"DeviceID=\") + 10);\n\n // device id string taken from windows device manager\n if (deviceId = \"USB\\\\\\\\VID_0403&amp;PID_6001\\\\\\\\12345678\\\"\")\n {\n // Device is connected\n }\n }\n }\n}\n</code></pre>\n\n<p>You may want to add some exception handling, though.</p>\n" }, { "answer_id": 21564661, "author": "jegan", "author_id": 1857677, "author_profile": "https://Stackoverflow.com/users/1857677", "pm_score": 2, "selected": false, "text": "<p>Although the answers already given provide a good starting point, I would like to add some working examples for .net 4.5 and also an example of capturing a <em>type</em> of usb device. </p>\n\n<p>In Treb's answer, he used the <code>'Win32_USBControllerDevice'</code>. This may or may not be the best condition for your query, depending on what you want to accomplish. The device id from the Win32_USBControllerDevice is unique to each device. So if you're looking for a unique id that identifies a single device, then that's exactly what you want. But if you're looking for a certain <em>type</em> of device, you could use <code>'Win32_PnPEntity'</code> and access the <code>Description</code> property. Here is an example of getting a certain <em>type</em> of device by its description:</p>\n\n<pre><code>using System;\nusing System.ComponentModel.Composition;\nusing System.Management;\n\npublic class UsbDeviceMonitor\n{\n private ManagementEventWatcher plugInWatcher;\n private ManagementEventWatcher unPlugWatcher;\n private const string MyDeviceDescription = @\"My Device Description\";\n\n ~UsbDeviceMonitor()\n {\n Dispose();\n }\n\n public void Dispose()\n {\n if (plugInWatcher != null)\n try\n {\n plugInWatcher.Dispose();\n plugInWatcher = null;\n }\n catch (Exception) { }\n\n if (unPlugWatcher == null) return;\n try\n {\n unPlugWatcher.Dispose();\n unPlugWatcher = null;\n }\n catch (Exception) { }\n }\n\n public void Start()\n {\n const string plugInSql = \"SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'\";\n const string unpluggedSql = \"SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'\";\n\n var scope = new ManagementScope(\"root\\\\CIMV2\") {Options = {EnablePrivileges = true}};\n\n var pluggedInQuery = new WqlEventQuery(plugInSql);\n plugInWatcher = new ManagementEventWatcher(scope, pluggedInQuery);\n plugInWatcher.EventArrived += HandlePluggedInEvent;\n plugInWatcher.Start();\n\n var unPluggedQuery = new WqlEventQuery(unpluggedSql);\n unPlugWatcher = new ManagementEventWatcher(scope, unPluggedQuery);\n unPlugWatcher.EventArrived += HandleUnPluggedEvent;\n unPlugWatcher.Start();\n }\n\n private void HandleUnPluggedEvent(object sender, EventArrivedEventArgs e)\n {\n var description = GetDeviceDescription(e.NewEvent);\n if (description.Equals(MyDeviceDescription))\n // Take actions here when the device is unplugged\n }\n\n private void HandlePluggedInEvent(object sender, EventArrivedEventArgs e)\n {\n var description = GetDeviceDescription(e.NewEvent);\n if (description.Equals(MyDeviceDescription))\n // Take actions here when the device is plugged in\n }\n\n private static string GetDeviceDescription(ManagementBaseObject newEvent)\n {\n var targetInstanceData = newEvent.Properties[\"TargetInstance\"];\n var targetInstanceObject = (ManagementBaseObject) targetInstanceData.Value;\n if (targetInstanceObject == null) return \"\";\n\n var description = targetInstanceObject.Properties[\"Description\"].Value.ToString();\n return description;\n }\n}\n</code></pre>\n\n<p>Some links that might be useful for researching which classes to use in your sql statements:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394084%28v=vs.85%29.aspx\" rel=\"nofollow\">Win32 Classes</a> - In the example above, the <code>'Win32_PnPEntity'</code> class was used.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394583%28v=vs.85%29.aspx\" rel=\"nofollow\">WMI System Classes</a> - In the example above, the <code>__InstanceCreationEvent</code> and <code>__InstanceDeletionEvent</code> classes were used.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32958/" ]
I have a c# winforms program and it opens up a serial port. The problem happens when the end user unplugs the usb cable and then the device disappears. After this the program will crash and want to report the error to microsoft. Is there a way to capture this event and shut down gracefully?
You can use WMI (Windows Management Instrumentation) to receive notification on USB events. I did exactly that two years ago, monitoring for plugging and unplugging of a specific usb device. Unfortunately, the code stays with my former employer, but I found one example at [bytes.com](http://bytes.com/topic/net/answers/102489-how-detect-usb-device-being-plugged-unplugged): ``` using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Management; class UsbWatcher { public static void Main() { WMIEvent wEvent = new WMIEvent(); ManagementEventWatcher watcher = null; WqlEventQuery query; ManagementOperationObserver observer = new ManagementOperationObserver(); ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { query = new WqlEventQuery(); query.EventClassName = "__InstanceCreationEvent"; query.WithinInterval = new TimeSpan(0,0,10); query.Condition = @"TargetInstance ISA 'Win32_USBControllerDevice' "; watcher = new ManagementEventWatcher(scope, query); watcher.EventArrived += new EventArrivedEventHandler(wEvent.UsbEventArrived); watcher.Start(); } catch (Exception e) { //handle exception } } ``` I don't remember if I modified the query to receive events only for e specific device, or if I filtered out events from other devices in my event handler. For further information you may want to have a look at the [MSDN WMI .NET Code Directory](http://msdn.microsoft.com/en-us/library/ms257338.aspx). **EDIT** I found some more info on the event handler, it looks roughly like this: ``` protected virtual void OnUsbConnected(object Sender, EventArrivedEventArgs Arguments) { PropertyData TargetInstanceData = Arguments.NewEvent.Properties["TargetInstance"]; if (TargetInstanceData != null) { ManagementBaseObject TargetInstanceObject = (ManagementBaseObject)TargetInstanceData.Value; if (TargetInstanceObject != null) { string dependent = TargetInstanceObject.Properties["Dependent"].Value.ToString(); string deviceId = dependent.Substring(dependent.IndexOf("DeviceID=") + 10); // device id string taken from windows device manager if (deviceId = "USB\\\\VID_0403&PID_6001\\\\12345678\"") { // Device is connected } } } } ``` You may want to add some exception handling, though.
286,187
<p>I'm developing an object-oriented PHP website right now and am trying to determine the best way to abstract database functionality from the rest of the system. Right now, I've got a DB class that manages all the connections and queries that the system uses (it's pretty much an interface to MDB2). However, when using this system, I've realized that I've got a lot of SQL query strings showing up everywhere in my code. For instance, in my User class, I've got something like this:</p> <pre><code>function checkLogin($email,$password,$remember=false){ $password = $this-&gt;__encrypt($password); $query = "SELECT uid FROM Users WHERE email=? AND pw=?"; $result = $this-&gt;db-&gt;q($query,array($email,$password)); if(sizeof($result) == 1){ $row = $result-&gt;fetchRow(MDB2_FETCHMODE_ASSOC); $uid = $row['uid']; }else{ return false; } /* Rest of the login script */ } </code></pre> <p>What I would like to do is find out the best technique for reducing the amount of inline SQL. I understand that one way to do this would be to write functions within User for each of the queries that User makes use of (something like the following), but that could lead to quite a few functions.</p> <pre><code>function checkLogin($email,$password,$remember=false){ $password = $this-&gt;__encrypt($password); $uid = $this-&gt;do_verify_login_query($email,$password); /* Rest of the login script */ } function do_verify_login_query($email,$encpw){ $query = "SELECT uid FROM Users WHERE email=? AND pw=?"; $result = $this-&gt;$db-&gt;q($query,array($email,$encpw)); if(sizeof($result) == 1){ $row = $result-&gt;fetchRow(MDB2_FETCHMODE_ASSOC); return $row['uid']; }else{ return false; } } </code></pre> <p>So...my question. What is the best technique for managing the large amount of queries that a typical database application would use? Would the way I described be the proper way of handling this situation? Or what about registering a list of queries within the DB class and associating with each a unique ID (such as USER_CHECKLOGIN) that is passed into the DB's query function? This method could also help with security, as it would limit the queries that could be run to only those that are registered in this list, but it's one more thing to remember when writing all the class functions. Thoughts?</p>
[ { "answer_id": 286208, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": true, "text": "<p>Having the SQL pulled out into separate functions is a decent start. Some other things you can do:</p>\n\n<ul>\n<li>Create separate classes for database access code. This will help make sure you don't have SQL functions scattered around in all of your PHP files.</li>\n<li>Load the SQL from external files. This completely separates your SQL code and your PHP code, making both more maintainable.</li>\n<li>Use stored procedures when you can. This removes the SQL from your PHP code altogether, and helps improve your database security by reducing the risk that external SQL will get executed.</li>\n</ul>\n" }, { "answer_id": 286214, "author": "D-Rock", "author_id": 36780, "author_profile": "https://Stackoverflow.com/users/36780", "pm_score": 2, "selected": false, "text": "<p>You might want to look into implementing the <a href=\"http://en.wikipedia.org/wiki/Active_record_pattern\" rel=\"nofollow noreferrer\">ActiveRecord Pattern</a>. Using a design pattern such as this provides some consistency in how you work with data from your tables. There can be some downsides to these sorts of approaches, mainly performance for certain types of queries but it can be worked around.</p>\n" }, { "answer_id": 286236, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<p>Another option can be the use of an ORM, for PHP the most powerful are:</p>\n\n<ul>\n<li><a href=\"http://propel.phpdb.org/trac/\" rel=\"nofollow noreferrer\">Propel</a></li>\n<li><a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine</a></li>\n</ul>\n\n<p>Both allow you to access your database using a set of objects, providing a simple API for storing and querying data, both have their own query language, that is converted internally to the targeted DBMS native SQL, this will ease migrating applications from one RDBMS to another with simple configuration changes. I also like the fact that you can encapsulate datamodel logic to add validation for example, only by extending your model classes.</p>\n" }, { "answer_id": 287478, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>Since you say you're doing this as OO PHP, then why do you have SQL scattered through all the methods in the first place? More common models would be:</p>\n\n<ol>\n<li>Use an ORM and let that handle the database.</li>\n<li>Give your classes one or more 'load' methods which use a single query to pull all of an object's data into memory and a 'save' method which uses a single query to update everything in the database. All the other methods only need to do in-memory manipulation and the database interactions are confined to the load/save methods.</li>\n</ol>\n\n<p>The first option will generally be more robust, but the second may run faster and will probably feel more familiar compared to the way you're used to doing things, if either of those are concerns.</p>\n\n<p>For your login example, the way I would do it, then, would be to simply load the user by email address, call <code>$user-&gt;check_password($entered_password)</code>, and throw an exception/return false/whatever if <code>check_password</code> fails. Neither <code>check_password</code> nor any of the login handling code need to concern themselves with the database, or even with knowing that a database is where the user gets loaded from.</p>\n" }, { "answer_id": 287701, "author": "Unlabeled Meat", "author_id": 20291, "author_profile": "https://Stackoverflow.com/users/20291", "pm_score": 0, "selected": false, "text": "<p>Another option is to think of the queries as data and store them in the database. For instance, you can create one table that stores the query with a name and another table that stores the parameters for that query. Then create a function in PHP that takes the name of the query and an array of params and executes the query, returning any results. You could also attach other metadata to the queries to restrict access to certain users, apply post-functions to the results, etc. </p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33212/" ]
I'm developing an object-oriented PHP website right now and am trying to determine the best way to abstract database functionality from the rest of the system. Right now, I've got a DB class that manages all the connections and queries that the system uses (it's pretty much an interface to MDB2). However, when using this system, I've realized that I've got a lot of SQL query strings showing up everywhere in my code. For instance, in my User class, I've got something like this: ``` function checkLogin($email,$password,$remember=false){ $password = $this->__encrypt($password); $query = "SELECT uid FROM Users WHERE email=? AND pw=?"; $result = $this->db->q($query,array($email,$password)); if(sizeof($result) == 1){ $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC); $uid = $row['uid']; }else{ return false; } /* Rest of the login script */ } ``` What I would like to do is find out the best technique for reducing the amount of inline SQL. I understand that one way to do this would be to write functions within User for each of the queries that User makes use of (something like the following), but that could lead to quite a few functions. ``` function checkLogin($email,$password,$remember=false){ $password = $this->__encrypt($password); $uid = $this->do_verify_login_query($email,$password); /* Rest of the login script */ } function do_verify_login_query($email,$encpw){ $query = "SELECT uid FROM Users WHERE email=? AND pw=?"; $result = $this->$db->q($query,array($email,$encpw)); if(sizeof($result) == 1){ $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC); return $row['uid']; }else{ return false; } } ``` So...my question. What is the best technique for managing the large amount of queries that a typical database application would use? Would the way I described be the proper way of handling this situation? Or what about registering a list of queries within the DB class and associating with each a unique ID (such as USER\_CHECKLOGIN) that is passed into the DB's query function? This method could also help with security, as it would limit the queries that could be run to only those that are registered in this list, but it's one more thing to remember when writing all the class functions. Thoughts?
Having the SQL pulled out into separate functions is a decent start. Some other things you can do: * Create separate classes for database access code. This will help make sure you don't have SQL functions scattered around in all of your PHP files. * Load the SQL from external files. This completely separates your SQL code and your PHP code, making both more maintainable. * Use stored procedures when you can. This removes the SQL from your PHP code altogether, and helps improve your database security by reducing the risk that external SQL will get executed.
286,190
<p>My present contract engagement is at a large E-Commerce company. Their code base which has origins going back to .Net 1.0 has caught me by surprise to contain many issues that raise the level of smell beyond the last crap I took. </p> <p>That notwithstanding and trying to diffuse my level of distraction from it, I go along merrily trying to add in features to either fix other problems or extend more crap. Where I touch the DAL/BLL the time it will take to fix the aforementioned will be done. However I wanted to get a vote of confidence from the experts to get some assurance of not wasting the clients time or worse having my credibility voted down by touching "stuff that works". Of course unit testing would solve or at least soften this worry. Perhaps this should also be added to the wtf.com?</p> <pre><code>Public Function GetSizeInfoBySite(ByVal siteID As String) As IList Dim strSQL As String = "YES INLINE SQL!! :)" Dim ci As CrapInfo Dim alAnArrayList As ArrayList Dim cn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim cmd As New SqlCommand(strSQL, cn) cmd.Parameters.Add(New SqlParameter("@MySiteID", SqlDbType.NVarChar, 2)).Value = siteID cn.Open() Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While rs.Read() ci = New CategoryInfo(rs("someID"), rs("someName")) If IsNothing(alAnArrayList) Then alAnArrayList = New ArrayList End If alAnArrayList.Add(ci) End While rs.Close() Return CType(alAnArrayList, IList) End Function </code></pre> <p>Does anyone see problems with this aside from the inline SQL which makes my gut churn? At the least wouldn't you ordinarily wrap the above in a try/catch/finally which most of us knows has been around since .Net v1.0? Even better would'nt it be wise to fix with Using statements? Does the SQLDataReader close really encapsulate the connection close automagically? </p>
[ { "answer_id": 286210, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "<p>Definitely get some using statements around the Connection and Reader objects. If there is an exception, they won't be closed until the Garbage Collector gets around to them. </p>\n\n<p>I tend not to call .Close() when there are using statements. Even if the SqlDataReader closes the connection on dispose (check the doco), putting a using around the Connection can't hurt and sticks to the pattern .</p>\n\n<p>If you do that the try/finally is only needed if you need to do exception handling right there. I tend to leave exception handling at the higher levels (wrap each UI entry point, Library entry points, extra info in exception) as the stacktrace is usually enough to debug the errors.</p>\n\n<p>Not that it matters much, but if you are re-factoring, move the collection initialization outside the loop. On second thoughts the code returns null if there are no records.</p>\n\n<p>At least SqlParameters are used! Get rid of anything that concatenates user input with SQL if you find it (SQL Injection attack) no matter how well \"Cleaned\" it is.</p>\n" }, { "answer_id": 286211, "author": "horatio", "author_id": 10102, "author_profile": "https://Stackoverflow.com/users/10102", "pm_score": 0, "selected": false, "text": "<p>If you were using c# I would wrap the datareader creation in a using statement but I don't think vb has those?</p>\n" }, { "answer_id": 286217, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<p>Nothing wrong with inline sql if the user input is properly parameterized, and this looks like it is. </p>\n\n<p>Other than that, yes you do need to close the connections. On a busy web site you could hit your limit and that would cause all kinds of weirdness.</p>\n\n<p>I also noticed it's still using an arraylist. Since they've moved on from .Net 1.0 it's time to update those to generic <code>List&lt;T&gt;</code>'s (and avoid the call to CType- you should be able to DirectCast() that instead).</p>\n" }, { "answer_id": 286244, "author": "hwiechers", "author_id": 5883, "author_profile": "https://Stackoverflow.com/users/5883", "pm_score": 2, "selected": false, "text": "<p>The connection will be closed when the reader is closed because it's using the CloseConnection command behavior.</p>\n\n<pre><code>Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)\n</code></pre>\n\n<p>According to MSDN (<a href=\"http://msdn.microsoft.com/en-us/library/aa326246(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa326246(VS.71).aspx</a>)</p>\n\n<blockquote>\n <p>If the SqlDataReader is created with CommandBehavior set to CloseConnection, closing the SqlDataReader closes the connection automatically.</p>\n</blockquote>\n" }, { "answer_id": 287202, "author": "JohnL", "author_id": 4814, "author_profile": "https://Stackoverflow.com/users/4814", "pm_score": 1, "selected": false, "text": "<p>In reply to some of the great points indicated by Joel and Robert I refactored the method as follows which ran flawless.</p>\n\n<pre><code>Public Function GetSomeInfoByBusObject(ByVal SomeID As String) As IList\nDim strSQL As String = \"InLine SQL\"\nDim ci As BusObject\nDim list As New GenList(Of BusObject)\nDim cn As New SqlConnection(\n ConfigurationSettings.AppSettings(\"ConnectionString\"))\nUsing cn\n Dim cmd As New SqlCommand(strSQL, cn)\n Using cmd\n cmd.Parameters.Add(New SqlParameter\n (\"@SomeID\", SqlDbType.NVarChar, 2)).Value = strSiteID\n cn.Open()\n Dim result As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)\n While result.Read()\n ci = New BusObject(rs(\"id), result(\"description\"))\n list.Add(DirectCast(ci, BusObject))\n End While\n result.Close()\n End Using\n Return list\nEnd Using\n</code></pre>\n\n<p>End Function</p>\n\n<p>Created a nice little helper class to wrap the generic details up</p>\n\n<pre><code>Public Class GenList(Of T)\n Inherits CollectionBase\n Public Function Add(ByVal value As T) As Integer\n Return List.Add(value)\n End Function\n Public Sub Remove(ByVal value As T)\n List.Remove(value)\n End Sub\n Public ReadOnly Property Item(ByVal index As Integer) As T\n Get\n Return CType(List.Item(index), T)\n End Get\n End Property\nEnd Class\n</code></pre>\n" }, { "answer_id": 885829, "author": "CRice", "author_id": 55693, "author_profile": "https://Stackoverflow.com/users/55693", "pm_score": 0, "selected": false, "text": "<pre><code>Public Function GetSizeInfoBySite(ByVal siteID As String) As IList(Of CategoryInfo)\n Dim strSQL As String = \"YES INLINE SQL!! :)\"\n\n 'reference the 2.0 System.Configuration, and add a connection string section to web.config\n ' &lt;connectionStrings&gt;\n ' &lt;add name=\"somename\" connectionString=\"someconnectionstring\" /&gt;\n ' &lt;/connectionStrings &gt;\n\n Using cn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings(\"somename\").ConnectionString\n\n Using cmd As New SqlCommand(strSQL, cn)\n\n cmd.Parameters.Add(New SqlParameter(\"@MySiteID\", SqlDbType.NVarChar, 2)).Value = siteID\n cn.Open()\n\n Using reader As IDataReader = cmd.ExecuteReader()\n\n Dim records As IList(Of CategoryInfo) = New List(Of CategoryInfo)\n\n 'get ordinal col indexes\n Dim ordinal_SomeId As Integer = reader.GetOrdinal(\"someID\")\n Dim ordinal_SomeName As Integer = reader.GetOrdinal(\"someName\")\n\n While reader.Read()\n Dim ci As CategoryInfo = New CategoryInfo(reader.GetInt32(ordinal_SomeId), reader.GetString(ordinal_SomeName))\n records.Add(ci)\n End While\n\n Return records\n\n End Using\n End Using\n End Using\n End Function\n</code></pre>\n\n<p>You could try something like the above, the using statements will handle connection closing and object disposal. This is available when the class implements IDisposable. Also build and return your IList of CategoryInfo.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4814/" ]
My present contract engagement is at a large E-Commerce company. Their code base which has origins going back to .Net 1.0 has caught me by surprise to contain many issues that raise the level of smell beyond the last crap I took. That notwithstanding and trying to diffuse my level of distraction from it, I go along merrily trying to add in features to either fix other problems or extend more crap. Where I touch the DAL/BLL the time it will take to fix the aforementioned will be done. However I wanted to get a vote of confidence from the experts to get some assurance of not wasting the clients time or worse having my credibility voted down by touching "stuff that works". Of course unit testing would solve or at least soften this worry. Perhaps this should also be added to the wtf.com? ``` Public Function GetSizeInfoBySite(ByVal siteID As String) As IList Dim strSQL As String = "YES INLINE SQL!! :)" Dim ci As CrapInfo Dim alAnArrayList As ArrayList Dim cn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim cmd As New SqlCommand(strSQL, cn) cmd.Parameters.Add(New SqlParameter("@MySiteID", SqlDbType.NVarChar, 2)).Value = siteID cn.Open() Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While rs.Read() ci = New CategoryInfo(rs("someID"), rs("someName")) If IsNothing(alAnArrayList) Then alAnArrayList = New ArrayList End If alAnArrayList.Add(ci) End While rs.Close() Return CType(alAnArrayList, IList) End Function ``` Does anyone see problems with this aside from the inline SQL which makes my gut churn? At the least wouldn't you ordinarily wrap the above in a try/catch/finally which most of us knows has been around since .Net v1.0? Even better would'nt it be wise to fix with Using statements? Does the SQLDataReader close really encapsulate the connection close automagically?
Nothing wrong with inline sql if the user input is properly parameterized, and this looks like it is. Other than that, yes you do need to close the connections. On a busy web site you could hit your limit and that would cause all kinds of weirdness. I also noticed it's still using an arraylist. Since they've moved on from .Net 1.0 it's time to update those to generic `List<T>`'s (and avoid the call to CType- you should be able to DirectCast() that instead).
286,191
<p>I have this query statement and want to only get records that has a certain column empty (<code>volunteers_2009.venue_id</code>)</p> <p>Table is <code>volunteers_2009</code>, column I am looking to see if it is empty: <code>venue_id</code></p> <p>Here is the current query:</p> <pre><code>SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort </code></pre> <p>I am trying to do this:</p> <pre><code>SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort WHERE volunteers_2009.venue_id == '' </code></pre> <p>How would I only list records that have an empty column (<code>venue_id</code>) within the table (<code>volunteers_2009</code>)?</p>
[ { "answer_id": 286201, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 2, "selected": false, "text": "<p>By empty do you mean null? If the <code>venue_id</code> field can contain nulls then you can compare using the <code>is</code> operator like this:</p>\n\n<pre><code>WHERE volunteers_2009.venue_id is null\n</code></pre>\n" }, { "answer_id": 286215, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<p>The WHERE clause is out of order in your 2nd query. It must go before the ORDER BY clause.</p>\n\n<p>Also, I don't imagine you have any venues with an empty id. Perhaps what you really want is this:</p>\n\n<pre><code>SELECT volunteers_2009.id, volunteers_2009.comments, \n volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, \n volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, \n venues.venue_name \nFROM volunteers_2009 \nLEFT JOIN venues ON venue_id = venues.id\nWHERE venues.id IS NULL\nORDER BY $order $sort\n</code></pre>\n\n<p>That will bring back only volunteers_2009 records that don't match any venues.</p>\n\n<p>Or this:</p>\n\n<pre><code>SELECT volunteers_2009.id, volunteers_2009.comments, \n volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, \n volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, \n venues.venue_name \nFROM venues\nLEFT JOIN volunteers_2009 ON volunteers_2009.venue_id = venues.id\nWHERE volunteers_2009.venue_id IS NULL\nORDER BY $order $sort\n</code></pre>\n\n<p>to find venues with no volunteers.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I have this query statement and want to only get records that has a certain column empty (`volunteers_2009.venue_id`) Table is `volunteers_2009`, column I am looking to see if it is empty: `venue_id` Here is the current query: ``` SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort ``` I am trying to do this: ``` SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort WHERE volunteers_2009.venue_id == '' ``` How would I only list records that have an empty column (`venue_id`) within the table (`volunteers_2009`)?
The WHERE clause is out of order in your 2nd query. It must go before the ORDER BY clause. Also, I don't imagine you have any venues with an empty id. Perhaps what you really want is this: ``` SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 LEFT JOIN venues ON venue_id = venues.id WHERE venues.id IS NULL ORDER BY $order $sort ``` That will bring back only volunteers\_2009 records that don't match any venues. Or this: ``` SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM venues LEFT JOIN volunteers_2009 ON volunteers_2009.venue_id = venues.id WHERE volunteers_2009.venue_id IS NULL ORDER BY $order $sort ``` to find venues with no volunteers.
286,207
<p>I am showing an addressbook view to the user and letting them click on a contact and select a phone number. If they select a phone number, I want to get the phone number as an integer and the contact's name as an NSString. </p> <p>I've tried doing it with the following code: </p> <pre><code> //printf("%s\n",[[(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier] UTF8String]); //CFArrayRef *arrayString = [[(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier] UTF8String]; NSArray *arrayString = [(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier]; printf("%s\n", arrayString); </code></pre> <p>This code is inside this method:</p> <pre><code>- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier </code></pre> <p>And I am checking if the user selected a phone number with this code:</p> <pre><code>if (propertyType == kABStringPropertyType) { [self wrongSelection]; } else if (propertyType == kABIntegerPropertyType) { [self wrongSelection]; } else if (propertyType == kABRealPropertyType) { [self wrongSelection]; } else if (propertyType == kABMultiStringPropertyType) { //This is the phone number... </code></pre> <p>I am able to get the phone number to display in the console with printf, however I can't figure out how to convert it into an integer and how to also get the contacts name even though the property selected is not a person's name. </p> <p>Also, what I'm doing seems very inefficient. Are there any better ways to do this?</p> <p>Edit: If I can't store them as an int, a string would be fine. I just can't figure out how to go from that array to an actual string. If I cast it or save it as a UTF8String I always get some error. </p>
[ { "answer_id": 286229, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 3, "selected": false, "text": "<p>You can't convert the phone number into an integer. Phone numbers are strings. The default entry Apple includes for itself has the number \"1-800-MYAPPLE\". </p>\n\n<p>Also, even if all components of a phone number are digits, there is no guarantee that phone numbers in all parts of the world are actually small enough to fit inside a 64 bit value, once you factor in area codes, country codes, internal extensions, etc. Users are free to put as much as they want in there.</p>\n" }, { "answer_id": 286281, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 4, "selected": false, "text": "<p>To get the property efficiently (as far as reading goes), you can do something like this in your callback method:</p>\n\n<pre><code>switch( propertyType ) {\n case kABMultiStringPropertyType:\n // this is the phone number, do something\n break;\n default:\n [self wrongSelection];\n break;\n}\n</code></pre>\n\n<p>I'm not sure you actually even need to parse that, though. To get the phone number from the record you could do (again, inside your callback method):</p>\n\n<pre><code>ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);\nNSArray* phoneNumbers = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);\nCFRelease(phoneNUmberProperty);\n\n// Do whatever you want with the phone numbers\nNSLog(@\"Phone numbers = %@\", phoneNumbers);\n[phoneNumbers release];\n</code></pre>\n" }, { "answer_id": 287241, "author": "Ed Marty", "author_id": 36007, "author_profile": "https://Stackoverflow.com/users/36007", "pm_score": 2, "selected": false, "text": "<pre><code>CFStringRef cfName = ABRecordCopyCompositeName(person);\nNSString *personName = [NSString stringWithString:(NSString *)cfName];\nCFRelease(cfName);\n\nABMultiValueRef container = ABRecordCopyValue(person, property);\nCFStringRef contactData = ABMultiValueCopyValueAtIndex(container, identifier);\nCFRelease(container);\nNSString *contactString = [NSString stringWithString:(NSString *)contactData];\nCFRelease(contactData);\n</code></pre>\n\n<p><code>contactString</code> contains the phone number selected, and <code>personName</code> contains the person's name. As stated above, you can't necessarily convert the string to numbers generically, as it may contain alphabetic characters. However, you could write your own handler to convert alphabetic characters to numbers and strip out everything else to get a numeric string only, which you could then convert to a long (phone numbers get pretty long) .</p>\n\n<p>I question the need to convert a phone number to a numeric value, though, since it may also contain other necessary characters like Pause. Also, a phone number represents a string of digits more than it represents one long number anyway, so the conceptual data format is more String than Int in any case.</p>\n" }, { "answer_id": 912060, "author": "Dan J", "author_id": 112705, "author_profile": "https://Stackoverflow.com/users/112705", "pm_score": 2, "selected": false, "text": "<p>Another reason not to use integers - some countries use leading zeros on phone numbers, e.g. all UK numbers start with a zero (usually written 01234 567890 or 0123 4567890)!</p>\n" }, { "answer_id": 8136033, "author": "nfriese", "author_id": 737872, "author_profile": "https://Stackoverflow.com/users/737872", "pm_score": 0, "selected": false, "text": "<p>Please be aware, that this code crashes in \"stringWithString\", if the Adressbook-Entry does not contain a name or a contacdata. cfName might be nil!</p>\n\n<pre><code>CFStringRef cfName = ABRecordCopyCompositeName(person);\nNSString *personName = [NSString stringWithString:(NSString *)cfName];\nCFRelease(cfName); \n</code></pre>\n\n<p>fix:</p>\n\n<pre><code>NSString *personName = nil;\nif ((cfName = ABRecordCopyCompositeName(person)) != nil) {\n personName = [NSString stringWithString:(NSString *)cfName];\n CFRelease(cfName); \n}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I am showing an addressbook view to the user and letting them click on a contact and select a phone number. If they select a phone number, I want to get the phone number as an integer and the contact's name as an NSString. I've tried doing it with the following code: ``` //printf("%s\n",[[(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier] UTF8String]); //CFArrayRef *arrayString = [[(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier] UTF8String]; NSArray *arrayString = [(NSArray *)ABMultiValueCopyArrayOfAllValues(theProperty) objectAtIndex:identifier]; printf("%s\n", arrayString); ``` This code is inside this method: ``` - (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier ``` And I am checking if the user selected a phone number with this code: ``` if (propertyType == kABStringPropertyType) { [self wrongSelection]; } else if (propertyType == kABIntegerPropertyType) { [self wrongSelection]; } else if (propertyType == kABRealPropertyType) { [self wrongSelection]; } else if (propertyType == kABMultiStringPropertyType) { //This is the phone number... ``` I am able to get the phone number to display in the console with printf, however I can't figure out how to convert it into an integer and how to also get the contacts name even though the property selected is not a person's name. Also, what I'm doing seems very inefficient. Are there any better ways to do this? Edit: If I can't store them as an int, a string would be fine. I just can't figure out how to go from that array to an actual string. If I cast it or save it as a UTF8String I always get some error.
To get the property efficiently (as far as reading goes), you can do something like this in your callback method: ``` switch( propertyType ) { case kABMultiStringPropertyType: // this is the phone number, do something break; default: [self wrongSelection]; break; } ``` I'm not sure you actually even need to parse that, though. To get the phone number from the record you could do (again, inside your callback method): ``` ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty); NSArray* phoneNumbers = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty); CFRelease(phoneNUmberProperty); // Do whatever you want with the phone numbers NSLog(@"Phone numbers = %@", phoneNumbers); [phoneNumbers release]; ```
286,238
<p>is it possible to throw a custom error message to a ThrowActivity, in windows workflow foundation?</p> <p>eg. Imagine i want to throw this exception, in my WF :-</p> <pre><code>CutomException("This is my custom error message", myNumber, myObect); </code></pre> <p>cheers :)</p>
[ { "answer_id": 287159, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "<p>Maybe I do not understand your question well, but you can set the specific exception with the <code>Fault</code> property of <code>ThrowActivity</code> in any place before the activity execution, e.g.:</p>\n\n<pre><code>throwActivity1.Fault = new CustomException(\"This is my custom error message\", myNumber, myObect);\n</code></pre>\n" }, { "answer_id": 364703, "author": "balaweblog", "author_id": 22162, "author_profile": "https://Stackoverflow.com/users/22162", "pm_score": 1, "selected": false, "text": "<p>You can throw any custom exception like this way.</p>\n\n<p>public DiscontinuedProductException discontinuedProductException1 = new DiscontinuedProductException();</p>\n\n<p>[SerializableAttribute()]\n public class DiscontinuedProductException : Exception\n {\n public DiscontinuedProductException()\n : base()\n {\n }</p>\n\n<pre><code> public DiscontinuedProductException(string message)\n : base(message)\n {\n }\n\n public DiscontinuedProductException(string message, Exception innerException)\n : base(message, innerException)\n {\n }\n\n protected DiscontinuedProductException(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n }\n}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
is it possible to throw a custom error message to a ThrowActivity, in windows workflow foundation? eg. Imagine i want to throw this exception, in my WF :- ``` CutomException("This is my custom error message", myNumber, myObect); ``` cheers :)
Maybe I do not understand your question well, but you can set the specific exception with the `Fault` property of `ThrowActivity` in any place before the activity execution, e.g.: ``` throwActivity1.Fault = new CustomException("This is my custom error message", myNumber, myObect); ```
286,250
<p>If I am evaluating two variables and not two method calls does it matter weather I use "&amp;&amp;" or "&amp;"</p> <pre><code>//some logic that sets bool values boolean X = true; boolean Y = true; if (X &amp; Y){ // perform some operation } if (X &amp;&amp; Y){ // perform some operation } </code></pre> <p>Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the &amp;&amp; operator, is the &amp; operator going away?</p>
[ { "answer_id": 286258, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 3, "selected": false, "text": "<p>Always use &amp;&amp; if you are performing a true/false logic test. A single &amp; performs a bit-wise 'and'. It make work like a logic test in some cases but it is not guaranteed to work for all logic cases. The most common use of a single &amp; is when applying a bit-mask.</p>\n\n<p>Examples (&amp;&amp;):</p>\n\n<pre><code>true &amp;&amp; true == true\n</code></pre>\n\n<p>Example (&amp;):</p>\n\n<pre><code>00101001 &amp; 00100001 = 00100001\n</code></pre>\n" }, { "answer_id": 286259, "author": "jpoh", "author_id": 4368, "author_profile": "https://Stackoverflow.com/users/4368", "pm_score": 1, "selected": false, "text": "<p>&amp; is a bitwise operator while &amp;&amp; is the AND operator. Two completely different operations.</p>\n\n<pre><code>int a = 1;\nint b = 2;\nassert (a &amp; b == 0) \nassert (a &amp;&amp; b == true) \n</code></pre>\n\n<p>EDIT: Ooops...this example doesn't work in C#. It should in C++. Hopefully it illustrates the intent and the difference between the two operators.</p>\n" }, { "answer_id": 286265, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 3, "selected": false, "text": "<p>If you use a single &amp; (And) the second part of the expression is evaluated. This could be bad if the second part relies on the first part being true. Usually always use &amp;&amp; as the second part is not evaluated if the first part is false. </p>\n\n<p>Logically the single &amp; does a bitwise operation as others have said, which is still valid for boolean comparison/evaluation. Really the only time a single &amp; (or |) should be used (or boolean evaluation) is if the second evaluation should always run (if it is a function call/modifier). This is bad practice through and probably why the book does not mention it.</p>\n\n<p>Single &amp; are useful with flag enums and bit masks.</p>\n\n<p>The following will throw an exception of obj is null:</p>\n\n<pre><code>bool b = obj != null &amp; obj.IsActive\n</code></pre>\n\n<p>But this will work:</p>\n\n<pre><code>bool b = obj != null &amp;&amp; obj.IsActive\n</code></pre>\n\n<p>This is bad:</p>\n\n<pre><code>bool b = obj.IsActive &amp;&amp; obj.SetActive(false);\nbool b = obj.IsActive &amp; obj.SetActive(false);\n</code></pre>\n\n<p>The &amp; operator is here to stay.</p>\n" }, { "answer_id": 286314, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>As has been observed, <code>&amp;</code> is the bitwise AND operator. Raw binary math is seeming to be less and less common over time, with an increasing number of developers not really understanding bitwise arithmetic. Which can be a pain at times.</p>\n\n<p>However there are a lot of tasks that are best solved with such, in particular anything that looks at data as flags. The <code>&amp;</code> operator is 100% necessary, and isn't going anywhere - it simply isn't used as frequently as the boolean short-circuiting <code>&amp;&amp;</code> operator.</p>\n\n<p>For example:</p>\n\n<pre><code>[Flags]\nenum SomeEnum { // formatted for space...\n None = 0, Foo = 1, Bar = 2 // 4, 8, 16, 32, ...\n}\nstatic void Main() {\n SomeEnum value = GetFlags();\n bool hasFoo = (value &amp; SomeEnum.Foo) != 0;\n}\nstatic SomeEnum GetFlags() { ... }\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35585/" ]
If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&" ``` //some logic that sets bool values boolean X = true; boolean Y = true; if (X & Y){ // perform some operation } if (X && Y){ // perform some operation } ``` Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?
As has been observed, `&` is the bitwise AND operator. Raw binary math is seeming to be less and less common over time, with an increasing number of developers not really understanding bitwise arithmetic. Which can be a pain at times. However there are a lot of tasks that are best solved with such, in particular anything that looks at data as flags. The `&` operator is 100% necessary, and isn't going anywhere - it simply isn't used as frequently as the boolean short-circuiting `&&` operator. For example: ``` [Flags] enum SomeEnum { // formatted for space... None = 0, Foo = 1, Bar = 2 // 4, 8, 16, 32, ... } static void Main() { SomeEnum value = GetFlags(); bool hasFoo = (value & SomeEnum.Foo) != 0; } static SomeEnum GetFlags() { ... } ```
286,253
<p>G'day everyone</p> <p>I'm a newbie to C++ and even more so to Borland Turbo C++ Explorer. I've just encountered this compile error. Any clues as to how to fix it? </p> <pre><code>[C++ Error] comsvcs.h(3209): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' [C++ Error] comsvcs.h(3275): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' [C++ Error] comsvcs.h(16197): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' [C++ Error] comsvcs.h(16293): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' </code></pre> <p>The code where the first one occurs is</p> <pre><code>EXTERN_C const IID IID_ICreateWithTransactionEx; #if defined(__cplusplus) &amp;&amp; !defined(CINTERFACE) MIDL_INTERFACE("455ACF57-5345-11d2-99CF-00C04F797BC9") ICreateWithTransactionEx : public IUnknown { public: virtual /* [helpstring][helpcontext] */ HRESULT STDMETHODCALLTYPE CreateInstance( /* [in] */ ITransaction *pTransaction, /* [in] */ REFCLSID rclsid, /* [in] */ REFIID riid, /* [iid_is][retval][out] */ void **pObject) = 0; }; </code></pre> <p>A couple of suggestions from another source:</p> <blockquote> <p>As the error message of the compiler tells there are 2 declarations of the ITransaction datatype in scope of the compilation unit. It seems the the ITransaction definition comes from Microsoft's comsvcs.h and that the OleDB::ITransaction is a implementation of the ITransaction interface from Borland. So you could try 2 things:</p> </blockquote> <ol> <li>eliminate the OleDB::ITransaction definition (don't know Turbo C++, but there may be a component dealing with oleDB. Try to get rid of this. Or it may be included by using another #include. Search for the text oledb::ITransaction in your include directory and you will hopefully find the relevant file. Modify the include path so it is not included any more).</li> <li>you could try to define CINTERFACE because the code resulting in the compile error will not be included if this is defined. But that may cause other problems... </li> </ol> <p>Does anyone have any other suggestions?</p> <p>Kind regards, Bruce.</p>
[ { "answer_id": 286303, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<p>It depends, with eclipse 3.4, SWT 3.4 is quite supported with <a href=\"http://www.eclipse.org/swt/macosx/\" rel=\"nofollow noreferrer\">MacOs</a>.</p>\n\n<p><img src=\"https://www.eclipse.org/swt/macosx/downloaded.png\" alt=\"alt text\"></p>\n\n<p>Now, SWT is OS specific, and you may not have the same flexibility than Swing, so you need to have good reason for looking for an alternative to Swing, especially when you consider there are good <a href=\"https://stackoverflow.com/questions/145972/how-can-i-setup-lookandfeel-files-in-java\">LAFs (look and feel)</a> for java.</p>\n" }, { "answer_id": 9476582, "author": "mikera", "author_id": 214010, "author_profile": "https://Stackoverflow.com/users/214010", "pm_score": 0, "selected": false, "text": "<p>You might consider <a href=\"http://javafx.com/\" rel=\"nofollow\">JavaFX 2.0</a>. </p>\n\n<p>Still early days but it looks quite promising for the kind of interactive / graphical applications that you might otherwise use Flash for.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426/" ]
G'day everyone I'm a newbie to C++ and even more so to Borland Turbo C++ Explorer. I've just encountered this compile error. Any clues as to how to fix it? ``` [C++ Error] comsvcs.h(3209): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' [C++ Error] comsvcs.h(3275): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' [C++ Error] comsvcs.h(16197): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' [C++ Error] comsvcs.h(16293): E2015 Ambiguity between 'ITransaction' and 'Oledb::ITransaction' ``` The code where the first one occurs is ``` EXTERN_C const IID IID_ICreateWithTransactionEx; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("455ACF57-5345-11d2-99CF-00C04F797BC9") ICreateWithTransactionEx : public IUnknown { public: virtual /* [helpstring][helpcontext] */ HRESULT STDMETHODCALLTYPE CreateInstance( /* [in] */ ITransaction *pTransaction, /* [in] */ REFCLSID rclsid, /* [in] */ REFIID riid, /* [iid_is][retval][out] */ void **pObject) = 0; }; ``` A couple of suggestions from another source: > > As the error message of the compiler tells there are 2 declarations of the ITransaction datatype in scope of the compilation unit. > It seems the the ITransaction definition comes from Microsoft's comsvcs.h and that the OleDB::ITransaction is a implementation of the ITransaction interface from Borland. So you could try 2 things: > > > 1. eliminate the OleDB::ITransaction definition (don't know Turbo C++, but there may be a component dealing with oleDB. Try to get rid of this. Or it may be included by using another #include. Search for the text oledb::ITransaction in your include directory and you will hopefully find the relevant file. Modify the include path so it is not included any more). 2. you could try to define CINTERFACE because the code resulting in the compile error will not be included if this is defined. But that may cause other problems... Does anyone have any other suggestions? Kind regards, Bruce.
It depends, with eclipse 3.4, SWT 3.4 is quite supported with [MacOs](http://www.eclipse.org/swt/macosx/). ![alt text](https://www.eclipse.org/swt/macosx/downloaded.png) Now, SWT is OS specific, and you may not have the same flexibility than Swing, so you need to have good reason for looking for an alternative to Swing, especially when you consider there are good [LAFs (look and feel)](https://stackoverflow.com/questions/145972/how-can-i-setup-lookandfeel-files-in-java) for java.
286,257
<p>I am currently refactoring an application that prints its status to the console window. At the moment I am doing something like this:</p> <pre><code> Console.Write("Print some status.....") //some code Console.WriteLine("Done!") </code></pre> <p>Now while this works fine, all the logic is hidden between console.writelines and I find makes it very hard to read.</p> <p>I don't know if there is a better way of doing this, but I just wanted to ask and see if anyone has come up with a better/more clean way of print application status to the console.</p> <p>Any ideas?</p>
[ { "answer_id": 286278, "author": "user35978", "author_id": 35978, "author_profile": "https://Stackoverflow.com/users/35978", "pm_score": 0, "selected": false, "text": "<p>Why not use a Logger object that write errors into a text file? You could come with some \"priority\" error messages such as: Logger.print(new priority(\"important\"), \"blabla\"); \nThis way, you could find in your file the exact time and all the message you want. </p>\n\n<p>If you absolutely want the console, you could use the priority on the console.. so it would only prints what you tell the logger to print, such as network error, etc..</p>\n" }, { "answer_id": 286365, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 3, "selected": true, "text": "<p>Take a look at Log4Net, it handles everything, but might be an overkill for your app, no idea. However knowing Log4Net will likely help you down the road someday so maybe this is a good chance too learn it.</p>\n" }, { "answer_id": 288836, "author": "Jamie Penney", "author_id": 68230, "author_profile": "https://Stackoverflow.com/users/68230", "pm_score": 1, "selected": false, "text": "<p>I second using Log4Net. It is pretty easy to use it without invoking the difficult parts - just do the following:\nIn your applications Main() method, call </p>\n\n<pre><code>log4net.Config.BasicConfigurator.Configure(new log4net.Appender.ConsoleAppender());\n</code></pre>\n\n<p>That sets up a basic Console logger that logs all messages to stdout.</p>\n\n<p>In the class that needs logging, create a new ILog like so:</p>\n\n<pre><code>private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof (MyClass));\n</code></pre>\n\n<p>Then in the method that needs logging, call </p>\n\n<pre><code>log.Debug(\"Print Some status ...\");\n</code></pre>\n\n<p>Once you have all of this set up and working. look through the Log4Net documentation on how to set up more useful logging. You can do a lot of different types of logging without changing the logging calls in your code at all.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
I am currently refactoring an application that prints its status to the console window. At the moment I am doing something like this: ``` Console.Write("Print some status.....") //some code Console.WriteLine("Done!") ``` Now while this works fine, all the logic is hidden between console.writelines and I find makes it very hard to read. I don't know if there is a better way of doing this, but I just wanted to ask and see if anyone has come up with a better/more clean way of print application status to the console. Any ideas?
Take a look at Log4Net, it handles everything, but might be an overkill for your app, no idea. However knowing Log4Net will likely help you down the road someday so maybe this is a good chance too learn it.
286,270
<p>What is the best way to password protect quicktime streaming videos using php/.htaccess. They are being streamed using rtsp, but I can use other formats if necessary.</p> <p>I know how to do authentication with php, but I'm not sure how to setup authentication so that will protect the streaming files urls so that a user can't just copy the url and share it.</p> <p>Or am I overthinking this and I can just use a normal authentication scheme and place the files in a protected directory?</p>
[ { "answer_id": 286307, "author": "cmptrgeekken", "author_id": 33212, "author_profile": "https://Stackoverflow.com/users/33212", "pm_score": 0, "selected": false, "text": "<p>First off, it is very easy to spoof a referer. This information is stored in the user's browser, so a user can simply telnet into your server and provide his own referer which matches your domain.</p>\n\n<p>A couple things you could try:</p>\n\n<p>First, more secure, but still spoofable. mod_rewrite provides the ability to check cookies. What you could do is set a cookie when the user visits your website that contains some obscure data. Then, you could modify your RerwriteCond to something like this: </p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_REFERER} !^$\nRewriteCond %{HTTP_COOKIE} obscurename=obscurevalue [NC]\nRewriteCond %{HTTP_REFERER} !^http://(www\\.)?yourdomain.com/.*$ [NC]\nRewriteRule \\.(asx¦ASX)$ http://www.yourdomain.com/images/leech.gif [R,L]\n</code></pre>\n\n<p>Another, better technique would involve working with PHP and mime-types. I'm not sure to what extent this would support streaming content, but I assume it'll work. What you can do is have all your video links point to a .php file (the query string will determine which video has been selected). Then, when a user tries to visit this link, you do something like so:</p>\n\n<pre><code>&lt;?php\n // You could also check some sort of session variable\n // that is set when the user visits another part of your\n // site\n if(!isLoggedIn()){\n header(\"Location: errorPage.htm\");\n exit;\n }else{\n // Get the name of the file specified\n $file = get_file_name($_GET['fileID']);\n\n // Specify the proper mime-type for the data you're sending\n // (this may have to change, depending on your situation)\n header(\"Content-type: video/vnd.rn-realvideo\");\n\n // Read the file and output it to the browser\n readfile($file);\n }\n?&gt;\n</code></pre>\n\n<p>From what I read, most servers know which mime-types are streaming mime-types, so the browser should be able to figure out how to handle the streaming file properly.</p>\n" }, { "answer_id": 286455, "author": "esmajic", "author_id": 31906, "author_profile": "https://Stackoverflow.com/users/31906", "pm_score": 1, "selected": false, "text": "<p>Try to use Amazon S3 service, it got it's quirks but it makes sense once you get familiar with it. </p>\n\n<p>There are hooks in their API to achieve temporally URL's that are active for specified time, so you can freely show url to visitor because it won't work 10 minutes or so later. </p>\n\n<p>It's almost trivial thing to do with php (around 15 lines of code), there are a lot of examples on their forums so you dont need to go from scratch and read full documentation on how to achieve this. </p>\n\n<p>What kind of authorization you will do before generate and show links it's up to you. </p>\n\n<p>You can also have it look like it's served from your domain like video.yourdomain.com instead of standard s3 URL's. </p>\n\n<p>Last thing, it's cheap - we payed around 2 US$ for the month of testing and deployment when I uploaded 8 GB and downloaded it 3 times completely and initialized download for around 100 times. The person I was doing this for is so satisfied by price that he wants to move all of his downloadable media to s3. </p>\n\n<p>Now, re reading everything I wrote it looks like commercial/spam but I'm so satisfied with service because I coded everything for audio files earlier, and it took days until everything worked just fine and this took couple of hours to implement (mostly getting familiar with service). </p>\n" }, { "answer_id": 286887, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 3, "selected": false, "text": "<p>Both nginx and lighttpd web servers have X-Send-File headers you can return from PHP. So you can do your checks in PHP and then conditionally server out the file.</p>\n\n<pre><code>if (check_user_can_access()){\n header('X-sendfile: /path/to/file');\n} else {\n header('HTTP/1.1 403 Fail!');\n}\n</code></pre>\n\n<p>Lighttpd also has a neat module called <a href=\"http://redmine.lighttpd.net/wiki/lighttpd/Docs#mod_secure_download\" rel=\"noreferrer\">mod_secure_download</a> that allows you to programatically generate a URL that will only be valid for a short time period.</p>\n\n<p>Nginx, and possibly lighttpd, allow you to cap the download speed, so you're not sending out streaming data faster than it can be consumed.</p>\n\n<p>Either way, you want to use your web server for serving files. Serving them through PHP is possible, but slow. </p>\n" }, { "answer_id": 286909, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 1, "selected": false, "text": "<p>You might want to take a look at:\n <a href=\"http://tn123.ath.cx/mod_xsendfile/\" rel=\"nofollow noreferrer\">mod_xsendfile (for apache)</a></p>\n\n<p>It enables you to internally redirect to a file.</p>\n\n<p>So you could point your download link to <code>checkCredentials.php</code></p>\n\n<pre><code>&lt;?php\nif ( isAuthorised($_POST['user'], $_POST['pass']) ) {\n header(\"X-Sendfile: $somefile\");\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Disposition: attachment; file=\\\"$somefile\\\"\");\n exit(0);\n} else {\n show403('bad credentials');\n}\n?&gt;\n</code></pre>\n\n<p>This module is also available for other webservers. If I remember correctly, the idea originally comes from lighttpd, but - as Josh states- is also available for nginx.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to password protect quicktime streaming videos using php/.htaccess. They are being streamed using rtsp, but I can use other formats if necessary. I know how to do authentication with php, but I'm not sure how to setup authentication so that will protect the streaming files urls so that a user can't just copy the url and share it. Or am I overthinking this and I can just use a normal authentication scheme and place the files in a protected directory?
Both nginx and lighttpd web servers have X-Send-File headers you can return from PHP. So you can do your checks in PHP and then conditionally server out the file. ``` if (check_user_can_access()){ header('X-sendfile: /path/to/file'); } else { header('HTTP/1.1 403 Fail!'); } ``` Lighttpd also has a neat module called [mod\_secure\_download](http://redmine.lighttpd.net/wiki/lighttpd/Docs#mod_secure_download) that allows you to programatically generate a URL that will only be valid for a short time period. Nginx, and possibly lighttpd, allow you to cap the download speed, so you're not sending out streaming data faster than it can be consumed. Either way, you want to use your web server for serving files. Serving them through PHP is possible, but slow.
286,275
<p>What's the best way (if any) to make an image appear "grayed out" with CSS (i.e., without loading a separate, grayed out version of the image)?</p> <p>My context is that I have rows in a table that all have buttons in the right most cell and some rows need to look lighter than others. So I can make the font lighter easily of course but I'd also like to make the images lighter without having to manage two versions of each image.</p>
[ { "answer_id": 286279, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 9, "selected": true, "text": "<p>Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a <code>&lt;div&gt;</code> overlay and set that to be gray (change the alpha to get the effect).</p>\n\n<ul>\n<li><p>html:</p>\n\n<pre><code>&lt;div id=\"wrapper\"&gt;\n &lt;img id=\"myImage\" src=\"something.jpg\" /&gt;\n&lt;/div&gt;\n</code></pre></li>\n<li><p>css:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#myImage {\n opacity: 0.4;\n filter: alpha(opacity=40); /* msie */\n}\n\n/* or */\n\n#wrapper {\n opacity: 0.4;\n filter: alpha(opacity=40); /* msie */\n background-color: #000;\n}\n</code></pre></li>\n</ul>\n" }, { "answer_id": 286305, "author": "Dave Jensen", "author_id": 35341, "author_profile": "https://Stackoverflow.com/users/35341", "pm_score": 2, "selected": false, "text": "<p>Here's an example that let's you set the color of the background. If you don't want to use float, then you might need to set the width and height manually. But even that really depends on the surrounding CSS/HTML.</p>\n\n<pre><code>&lt;style&gt;\n#color {\n background-color: red;\n float: left;\n}#opacity {\n opacity : 0.4;\n filter: alpha(opacity=40); \n}\n&lt;/style&gt;\n\n&lt;div id=\"color\"&gt;\n &lt;div id=\"opacity\"&gt;\n &lt;img src=\"image.jpg\" /&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 286315, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>Considering filter:expression is a Microsoft extension to CSS, so it will only work in Internet Explorer. If you want to grey it out, I would recommend that you set it's opacity to 50% using a bit of javascript. </p>\n\n<p><a href=\"http://lyxus.net/mv\" rel=\"nofollow noreferrer\">http://lyxus.net/mv</a> would be a good place to start, because it discusses an opacity\nscript that works with Firefox, Safari, KHTML, Internet Explorer and CSS3 capable browsers. </p>\n\n<p>You might also want to give it a grey border.</p>\n" }, { "answer_id": 288532, "author": "alexmeia", "author_id": 36587, "author_profile": "https://Stackoverflow.com/users/36587", "pm_score": 5, "selected": false, "text": "<p>Better to support all the browsers:</p>\n\n<pre><code>img.lessOpacity { \n opacity: 0.4;\n filter: alpha(opacity=40);\n zoom: 1; /* needed to trigger \"hasLayout\" in IE if no width or height is set */ \n}\n</code></pre>\n" }, { "answer_id": 291296, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 5, "selected": false, "text": "<p>If you don't mind using a bit of JavaScript, jQuery's <a href=\"http://api.jquery.com/fadeTo/\" rel=\"noreferrer\">fadeTo()</a> works nicely in every browser I've tried.</p>\n\n<pre><code>jQuery(selector).fadeTo(speed, opacity);\n</code></pre>\n" }, { "answer_id": 4039593, "author": "OsamaBinLogin", "author_id": 489632, "author_profile": "https://Stackoverflow.com/users/489632", "pm_score": 1, "selected": false, "text": "<p>You can use <code>rgba()</code> in css to define a color instead of <code>rgb()</code>. Like this:\n<code>style='background-color: rgba(128,128,128, 0.7);</code></p>\n\n<p>Gives you the same color as <code>rgb(128,128,128)</code> but with a 70% opacity so the stuff behind only shows thru 30%. CSS3 but it's worked in most browsers since 2008. Sorry, no #rrggbb syntax that I know of. Play with the numbers - you can wash out with white, shadow out with gray, whatever you want to dilute with.</p>\n\n<p>OK so you make a a rectangle in semi-transparent gray (or whatever color) and lay it on top of your image, maybe with position:absolute and a z-index higher than zero, and you put it just before your image and the default location for the rectangle will be the same upper-left corner of your image. Should work.</p>\n" }, { "answer_id": 11842712, "author": "nmsdvid", "author_id": 599880, "author_profile": "https://Stackoverflow.com/users/599880", "pm_score": 8, "selected": false, "text": "<p>Use the CSS3 filter property:</p>\n<pre><code>img {\n -webkit-filter: grayscale(100%);\n -moz-filter: grayscale(100%);\n -o-filter: grayscale(100%);\n -ms-filter: grayscale(100%);\n filter: grayscale(100%); \n}\n</code></pre>\n<p>The browser support is pretty decent, <a href=\"https://caniuse.com/css-filters\" rel=\"noreferrer\">https://caniuse.com/css-filters</a>.</p>\n" }, { "answer_id": 13909292, "author": "Sakata Gintoki", "author_id": 1852300, "author_profile": "https://Stackoverflow.com/users/1852300", "pm_score": 6, "selected": false, "text": "<p>Your here:</p>\n\n<pre><code>&lt;a href=\"#\"&gt;&lt;img src=\"img.jpg\" /&gt;&lt;/a&gt;\n</code></pre>\n\n<p>Css Gray:</p>\n\n<pre><code>img{\n filter: url(\"data:image/svg+xml;utf8,&lt;svg xmlns=\\'http://www.w3.org/2000/svg\\'&gt;&lt;filter id=\\'grayscale\\'&gt;&lt;feColorMatrix type=\\'matrix\\' values=\\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\\'/&gt;&lt;/filter&gt;&lt;/svg&gt;#grayscale\"); /* Firefox 10+, Firefox on Android */\n filter: grayscale(100%);\n -moz-filter: grayscale(100%);\n -ms-filter: grayscale(100%);\n -o-filter: grayscale(100%);\n filter: gray; /* IE6-9 */\n -webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */}\n</code></pre>\n\n<p>Ungray:</p>\n\n<pre><code>a:hover img{\n filter: url(\"data:image/svg+xml;utf8,&lt;svg xmlns=\\'http://www.w3.org/2000/svg\\'&gt;&lt;filter id=\\'grayscale\\'&gt;&lt;feColorMatrix type=\\'matrix\\' values=\\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\\'/&gt;&lt;/filter&gt;&lt;/svg&gt;#grayscale\");\n filter: grayscale(0%);\n -moz-filter: grayscale(0%);\n -ms-filter: grayscale(0%);\n -o-filter: grayscale(0%);\n filter: none ; /* IE6-9 */\n zoom:1; /* needed to trigger \"hasLayout\" in IE if no width or height is set */\n -webkit-filter: grayscale(0%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */\n }\n</code></pre>\n\n<p>I found it at: <a href=\"http://zkiwi.com/topic/chuyen-hinh-mau-thanh-trang-den-bang-css-nhu-the-nao\" rel=\"noreferrer\">http://zkiwi.com/topic/chuyen-hinh-mau-thanh-trang-den-bang-css-nhu-the-nao</a></p>\n\n<p><strong>Edit:</strong> IE10+ does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.\nYou can fix it, use one in two solutions below:</p>\n\n<ol>\n<li>Set IE10+ to render using IE9 standards mode using the following meta element in the head: <code>&lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\"&gt;</code></li>\n<li>Use an SVG overlay in IE10 to accomplish the greyscaling <a href=\"https://stackoverflow.com/questions/14813142/internet-explorer-10-howto-apply-grayscale-filter\">internet explorer 10 - howto apply grayscale filter?</a></li>\n</ol>\n" }, { "answer_id": 56421996, "author": "Константин Ван", "author_id": 4510033, "author_profile": "https://Stackoverflow.com/users/4510033", "pm_score": 3, "selected": false, "text": "<h1>To gray out:</h1>\n\n<h2>“to achromatize.”</h2>\n\n<pre><code>filter: grayscale(100%);\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@keyframes achromatization {\r\n 0% {}\r\n 25% {}\r\n 75% {filter: grayscale(100%);}\r\n 100% {filter: grayscale(100%);}\r\n}\r\n\r\np {\r\n font-size: 5em;\r\n color: yellow;\r\n animation: achromatization 2s ease-out infinite alternate;\r\n}\r\np:first-of-type {\r\n background-color: dodgerblue;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;\r\n ⚡ Bzzzt!\r\n&lt;/p&gt;\r\n&lt;p&gt;\r\n ⚡ Bzzzt!\r\n&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>“to fill with gray.”</h2>\n\n<pre><code>filter: contrast(0%);\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@keyframes gray-filling {\r\n 0% {}\r\n 25% {}\r\n 50% {filter: contrast(0%);}\r\n 60% {filter: contrast(0%);}\r\n 70% {filter: contrast(0%) brightness(0%) invert(100%);}\r\n 80% {filter: contrast(0%) brightness(0%) invert(100%);}\r\n 90% {filter: contrast(0%) brightness(0%);}\r\n 100% {filter: contrast(0%) brightness(0%);}\r\n}\r\n\r\np {\r\n font-size: 5em;\r\n color: yellow;\r\n animation: gray-filling 5s ease-out infinite alternate;\r\n}\r\np:first-of-type {\r\n background-color: dodgerblue;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;\r\n ⚡ Bzzzt!\r\n&lt;/p&gt;\r\n&lt;p&gt;\r\n ⚡ Bzzzt!\r\n&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h2>Helpful notes</h2>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/37621307/whats-the-difference-between-css3-filter-grayscale-and-saturate\">What&#39;s the difference between CSS3 filter grayscale and saturate?</a></p></li>\n<li><p><a href=\"https://www.w3.org/TR/filter-effects-1\" rel=\"nofollow noreferrer\">https://www.w3.org/TR/filter-effects-1</a></p></li>\n</ul>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26842/" ]
What's the best way (if any) to make an image appear "grayed out" with CSS (i.e., without loading a separate, grayed out version of the image)? My context is that I have rows in a table that all have buttons in the right most cell and some rows need to look lighter than others. So I can make the font lighter easily of course but I'd also like to make the images lighter without having to manage two versions of each image.
Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a `<div>` overlay and set that to be gray (change the alpha to get the effect). * html: ``` <div id="wrapper"> <img id="myImage" src="something.jpg" /> </div> ``` * css: ```css #myImage { opacity: 0.4; filter: alpha(opacity=40); /* msie */ } /* or */ #wrapper { opacity: 0.4; filter: alpha(opacity=40); /* msie */ background-color: #000; } ```
286,285
<p>In previous applications, I was able to get TinyMCE to work just fine. But in this web app, I get the rich editor to show up okay, but for some reason I cannot type into the rich editor field and when I click a button like for bolding, I get this error:</p> <pre><code>Error: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://mysite/tiny_mce/tiny_mce.js :: anonymous :: line 1" data: no] Source File: http://mysite/tiny_mce/tiny_mce.js Line: 1 </code></pre> <p>I'd like to know what I can do to debug what's going on here. What could be causing this strange error?</p> <p>Some background:</p> <p>This code loads the TinyMCE:</p> <pre><code>&lt;script type="text/javascript" src="http://mysite/tiny_mce/tiny_mce.js"&gt;&lt;/script&gt; &lt;script&gt; tinyMCE.init({ mode : 'none', editor_selector: 'mceAdvanced', theme : 'advanced', theme_advanced_toolbar_location : 'top', theme_advanced_toolbar_align : 'left', theme_advanced_buttons1 : 'fontsizeselect,bold,italic,|,bullist,numlist,|,outdent,indent,|,removeformat', theme_advanced_buttons2: '', theme_advanced_buttons3: '', theme_advanced_font_sizes: "1, 2, 3, 4", width: '600', height: '200', remove_script_host : true, cleanup_on_startup : true, cleanup: true, debug : true, convert_urls : false }); tinyMCE.execCommand('mceAddControl', true, 'fldOverview'); &lt;/script&gt; &lt;textarea id="fldOverview" name="fldOverview" class="textbox"&gt;&lt;?= OVERVIEW ?&gt;&lt;/textarea&gt; </code></pre> <p>Tested on:</p> <p>FF3 fails. Opera (latest stable) works. Windows IE7 works. Safari (latest stable) works.</p>
[ { "answer_id": 286291, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>Are you executing this in Firefox ?</p>\n\n<p>Because according to <a href=\"http://qualityobsession.com/blog/archives/72\" rel=\"nofollow noreferrer\">this</a>, it comes up when you disable popups in firefox because of the way pop up blocking is implemented.</p>\n\n<p>Enable pop ups and you are good to go!</p>\n" }, { "answer_id": 286329, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The answer is <a href=\"http://tinymce.moxiecode.com/punbb/viewtopic.php?pid=45174#p45174\" rel=\"noreferrer\">here</a>.</p>\n\n<p>The deal is this. Ever use Facebook? We were trying to implement a similar interface where you click to edit a profile section, it collapses and re-expands with a progress bar, then collapses and re-expands with a profile form. In that profile form, we had the TinyMCE rich editor.</p>\n\n<p>Well, it turns out that there's a quirk with DIVs being hidden and then shown to display the TinyMCE control. It gets the timing off or something? Anyway, we were using the slideToggle API in jQuery to collapse and re-expand a DIV with new contents that we pulled back via jQuery AJAX stuff. And when we did, somehow this slideToggle API hosed us up.</p>\n\n<p>The fix was to do the slideToggle like we normally do, but before we load the tinyMCE editor with the execCommand technique, we need to use the show API in jQuery to ensure our DIV is forced open and visible, first. When we did that, the problem went away.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In previous applications, I was able to get TinyMCE to work just fine. But in this web app, I get the rich editor to show up okay, but for some reason I cannot type into the rich editor field and when I click a button like for bolding, I get this error: ``` Error: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://mysite/tiny_mce/tiny_mce.js :: anonymous :: line 1" data: no] Source File: http://mysite/tiny_mce/tiny_mce.js Line: 1 ``` I'd like to know what I can do to debug what's going on here. What could be causing this strange error? Some background: This code loads the TinyMCE: ``` <script type="text/javascript" src="http://mysite/tiny_mce/tiny_mce.js"></script> <script> tinyMCE.init({ mode : 'none', editor_selector: 'mceAdvanced', theme : 'advanced', theme_advanced_toolbar_location : 'top', theme_advanced_toolbar_align : 'left', theme_advanced_buttons1 : 'fontsizeselect,bold,italic,|,bullist,numlist,|,outdent,indent,|,removeformat', theme_advanced_buttons2: '', theme_advanced_buttons3: '', theme_advanced_font_sizes: "1, 2, 3, 4", width: '600', height: '200', remove_script_host : true, cleanup_on_startup : true, cleanup: true, debug : true, convert_urls : false }); tinyMCE.execCommand('mceAddControl', true, 'fldOverview'); </script> <textarea id="fldOverview" name="fldOverview" class="textbox"><?= OVERVIEW ?></textarea> ``` Tested on: FF3 fails. Opera (latest stable) works. Windows IE7 works. Safari (latest stable) works.
The answer is [here](http://tinymce.moxiecode.com/punbb/viewtopic.php?pid=45174#p45174). The deal is this. Ever use Facebook? We were trying to implement a similar interface where you click to edit a profile section, it collapses and re-expands with a progress bar, then collapses and re-expands with a profile form. In that profile form, we had the TinyMCE rich editor. Well, it turns out that there's a quirk with DIVs being hidden and then shown to display the TinyMCE control. It gets the timing off or something? Anyway, we were using the slideToggle API in jQuery to collapse and re-expand a DIV with new contents that we pulled back via jQuery AJAX stuff. And when we did, somehow this slideToggle API hosed us up. The fix was to do the slideToggle like we normally do, but before we load the tinyMCE editor with the execCommand technique, we need to use the show API in jQuery to ensure our DIV is forced open and visible, first. When we did that, the problem went away.
286,297
<p>I have a suspicion that I'm using the <code>finally</code> block incorrectly, and that I don't understand the fundamentals of its purpose...</p> <pre><code> function myFunc() { try { if (true) { throw "An error"; } } catch (e) { alert (e); return false; } finally { return true; } } </code></pre> <p>This function will run the <code>catch</code> block, alert "An error", but then return true. Why doesn't it return false?</p>
[ { "answer_id": 286306, "author": "Gilean", "author_id": 6305, "author_profile": "https://Stackoverflow.com/users/6305", "pm_score": 7, "selected": true, "text": "<blockquote>\n <p>The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#The_finally_Block\" rel=\"noreferrer\">more</a></p>\n</blockquote>\n\n<p>The <code>finally</code> block will always run, try returning <code>true</code> after your <code>try</code> block</p>\n\n<pre><code>function myFunc() {\n try {\n if (true) {\n throw \"An error\";\n }\n return true;\n } catch (e) {\n alert (e);\n return false;\n } finally {\n //do cleanup, etc here\n }\n }\n</code></pre>\n" }, { "answer_id": 286340, "author": "Alan Oursland", "author_id": 37189, "author_profile": "https://Stackoverflow.com/users/37189", "pm_score": 3, "selected": false, "text": "<p>Finally blocks execute when you leave the try block. In your code this happens when you return false. That sets the return value to false and attempts to exit the function. But first it has to exit the try block which triggers the finally and overwrites the return value to true.</p>\n\n<p>It is considered by many to be a good programming practice to have a single return statement per function. Consider making a var retval at the beginning of your function and setting it to true or false as appropriate throughout your function and then structuring the code so that it falls correctly through to a single return at the bottom.</p>\n" }, { "answer_id": 28165868, "author": "Danny Mor", "author_id": 4497780, "author_profile": "https://Stackoverflow.com/users/4497780", "pm_score": 1, "selected": false, "text": "<pre><code>function getTheFinallyBlockPoint(someValue) {\n var result;\n try {\n if (someValue === 1) {\n throw new Error(\"Don't you know that '1' is not an option here?\");\n }\n result = someValue\n } catch (e) {\n console.log(e.toString());\n throw e;\n } finally {\n console.log(\"I'll write this no matter what!!!\");\n }\n\n return result;\n};\n\ngetTheFinallyBlockPoint(\"I wrote this only because 'someValue' was not 1!!!\");\ngetTheFinallyBlockPoint(1);\n</code></pre>\n\n<p>Run this on your browser's console and it might give you the answer you're looking for.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I have a suspicion that I'm using the `finally` block incorrectly, and that I don't understand the fundamentals of its purpose... ``` function myFunc() { try { if (true) { throw "An error"; } } catch (e) { alert (e); return false; } finally { return true; } } ``` This function will run the `catch` block, alert "An error", but then return true. Why doesn't it return false?
> > The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. [more](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#The_finally_Block) > > > The `finally` block will always run, try returning `true` after your `try` block ``` function myFunc() { try { if (true) { throw "An error"; } return true; } catch (e) { alert (e); return false; } finally { //do cleanup, etc here } } ```
286,321
<p>I would like to make my application somewhat REST compliant. I am using Rails on the backend and <a href="https://developers.google.com/web-toolkit/" rel="noreferrer">GWT</a> on the frontend. I would like to do updates and deletes. I realize I can do something like mydomain.com/:id/delete (GET) and accomplish the same thing. However, as I stated previously, I would like to have a REST compliant backend. Thus, I want to do mydomain.com/:id (DELETE) and have it implicitly call my delete method.</p> <p>Now, it's my understanding that if a browser (my browser is GWT RequestBuilder) doesn't support DELETE/GET, Rails somehow accomplishes this task with a POST and some other url parameter. So, how can I accomplish this with a GWT RequestBuilder?</p>
[ { "answer_id": 286463, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 4, "selected": true, "text": "<p>Rails does this with hidden attributes. The easiest way to figure this out would be to create a new rails application, generate a scaffold and have a look at the HTML in a browser.</p>\n\n<p>Try this:</p>\n\n<pre><code>rails jp\ncd jp\n./script/generate scaffold RequestBuilder name:string\nrake db:migrate\n./script/server \n</code></pre>\n\n<p>Then navigate to <a href=\"http://localhost:3000/request_builders\" rel=\"noreferrer\">http://localhost:3000/request_builders</a>, click on New and have a look at the HTML. You'll see something like:</p>\n\n<pre><code>&lt;form action=\"/request_builders\" class=\"new_request_builder\" \n id=\"new_request_builder\" method=\"post\"&gt;\n &lt;div style=\"margin:0;padding:0\"&gt;\n &lt;input name=\"authenticity_token\" type=\"hidden\" value=\"e76...\" /&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>This is a creation, method is POST. Enter a name, save then Edit:</p>\n\n<pre><code>&lt;form action=\"/request_builders/1\" class=\"edit_request_builder\" \n id=\"edit_request_builder_1\" method=\"post\"&gt;\n &lt;div style=\"margin:0;padding:0\"&gt;\n &lt;input name=\"_method\" type=\"hidden\" value=\"put\" /&gt;\n &lt;input name=\"authenticity_token\" type=\"hidden\" value=\"e76...\" /&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Of course the form is sent with POST, but Rails hads a hidden field to simulate a PUT request. Same for deletion, but the scaffold will do it with a bit of Javascript:</p>\n\n<pre><code>var m = document.createElement('input'); \nm.setAttribute('type', 'hidden'); \nm.setAttribute('name', '_method'); \nm.setAttribute('value', 'delete');\n</code></pre>\n\n<p>To have this work with another front-end, you'll have to both:</p>\n\n<ul>\n<li>Use the same style URL such as /request_builders/1 (RESTful URLs)</li>\n<li>Include the hidden fields (Rails trick)</li>\n</ul>\n" }, { "answer_id": 6210925, "author": "clacke", "author_id": 260122, "author_profile": "https://Stackoverflow.com/users/260122", "pm_score": 3, "selected": false, "text": "<p>Like @skrat said, the <code>_method=PUT</code> workaround doesn't work for any kind of body where <code>Content-Type</code> is not <code>x-www-form-urlencoded</code>, e.g. XML or JSON. Luckily, there is a header workaround as well:</p>\n\n<p><a href=\"https://zcox.wordpress.com/2009/06/17/override-the-http-request-method-in-jersey/\" rel=\"noreferrer\">https://zcox.wordpress.com/2009/06/17/override-the-http-request-method-in-jersey/</a></p>\n\n<p>So to update a REST resource, just do a POST to its address and add the header <code>X-HTTP-Method-Override: PUT</code>. Rails will interpret this as a PUT to the address.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I would like to make my application somewhat REST compliant. I am using Rails on the backend and [GWT](https://developers.google.com/web-toolkit/) on the frontend. I would like to do updates and deletes. I realize I can do something like mydomain.com/:id/delete (GET) and accomplish the same thing. However, as I stated previously, I would like to have a REST compliant backend. Thus, I want to do mydomain.com/:id (DELETE) and have it implicitly call my delete method. Now, it's my understanding that if a browser (my browser is GWT RequestBuilder) doesn't support DELETE/GET, Rails somehow accomplishes this task with a POST and some other url parameter. So, how can I accomplish this with a GWT RequestBuilder?
Rails does this with hidden attributes. The easiest way to figure this out would be to create a new rails application, generate a scaffold and have a look at the HTML in a browser. Try this: ``` rails jp cd jp ./script/generate scaffold RequestBuilder name:string rake db:migrate ./script/server ``` Then navigate to <http://localhost:3000/request_builders>, click on New and have a look at the HTML. You'll see something like: ``` <form action="/request_builders" class="new_request_builder" id="new_request_builder" method="post"> <div style="margin:0;padding:0"> <input name="authenticity_token" type="hidden" value="e76..." /> </div> ``` This is a creation, method is POST. Enter a name, save then Edit: ``` <form action="/request_builders/1" class="edit_request_builder" id="edit_request_builder_1" method="post"> <div style="margin:0;padding:0"> <input name="_method" type="hidden" value="put" /> <input name="authenticity_token" type="hidden" value="e76..." /> </div> ``` Of course the form is sent with POST, but Rails hads a hidden field to simulate a PUT request. Same for deletion, but the scaffold will do it with a bit of Javascript: ``` var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); ``` To have this work with another front-end, you'll have to both: * Use the same style URL such as /request\_builders/1 (RESTful URLs) * Include the hidden fields (Rails trick)
286,332
<p>I have subclassed the UITableView control, and the style is grouped, but I do not need the cell separators. I tried setting my table view's separatorStyle to none, but it doesn't work. Can any one help me out?</p>
[ { "answer_id": 286505, "author": "leonho", "author_id": 30883, "author_profile": "https://Stackoverflow.com/users/30883", "pm_score": 2, "selected": false, "text": "<p>How about setSeparatorColor to your cell's background color?</p>\n" }, { "answer_id": 456945, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Use this</p>\n\n<pre><code>tableView.separatorStyle = UITableViewCellSeparatorStyleNone;</code></pre>\n" }, { "answer_id": 1661079, "author": "Akshay Shah", "author_id": 200931, "author_profile": "https://Stackoverflow.com/users/200931", "pm_score": 2, "selected": false, "text": "<p>This did the trick for me:</p>\n\n<pre><code>[dayTableView setSeparatorColor:[UIColor whiteColor]]; //or your background color\n</code></pre>\n" }, { "answer_id": 3206569, "author": "Sam Soffes", "author_id": 118631, "author_profile": "https://Stackoverflow.com/users/118631", "pm_score": 7, "selected": false, "text": "<p>In a grouped table view, setting <code>separatorStyle</code> doesn't do anything. If you want to hide it, just do the following:</p>\n\n<pre><code>tableView.separatorColor = [UIColor clearColor];\n</code></pre>\n" }, { "answer_id": 13720494, "author": "Gabriel", "author_id": 1109715, "author_profile": "https://Stackoverflow.com/users/1109715", "pm_score": 3, "selected": false, "text": "<p>To remove the border of a table view write this line:</p>\n\n<pre><code>self.myTableView.separatorColor = [UIColor clearColor];\n</code></pre>\n\n<p>If you want to remove both the border of a table view but the border between cells too, you have to write both lines:</p>\n\n<pre><code>self.myTableView.separatorColor = [UIColor clearColor];\nself.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;\n</code></pre>\n" }, { "answer_id": 52786567, "author": "Noer Cholis", "author_id": 1286189, "author_profile": "https://Stackoverflow.com/users/1286189", "pm_score": 2, "selected": false, "text": "<p>swift 4 use</p>\n\n<pre><code>myTableView.separatorStyle = UITableViewCellSeparatorStyle.none\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have subclassed the UITableView control, and the style is grouped, but I do not need the cell separators. I tried setting my table view's separatorStyle to none, but it doesn't work. Can any one help me out?
In a grouped table view, setting `separatorStyle` doesn't do anything. If you want to hide it, just do the following: ``` tableView.separatorColor = [UIColor clearColor]; ```
286,334
<p>I have a table of events, I need to find all tail events of type 1 and all head events of type 1. </p> <p>So, for the set of events in this order [1, 1], 3, 1 ,4, 5, [1,1,1] the brackets denote head and tail events of type 1. </p> <p>This is much better illustrated in SQL:</p> <pre><code>drop table #event go create table #event (group_id int, [date] datetime, [type] int) create index idx1 on #event (group_id, date) insert into #event values (1, '2000-01-01', 1) insert into #event values (1, '2000-01-02', 1) insert into #event values (1, '2000-01-03', 3) insert into #event values (1, '2000-01-04', 2) insert into #event values (1, '2000-01-05', 1) insert into #event values (2, '2000-01-01', 2) insert into #event values (2, '2000-01-02', 2) insert into #event values (2, '2000-01-03', 3) insert into #event values (2, '2000-01-04', 2) insert into #event values (2, '2000-01-05', 1) insert into #event values (3, '2000-01-01', 1) insert into #event values (3, '2000-01-02', 2) insert into #event values (3, '2000-01-03', 1) insert into #event values (3, '2000-01-04', 2) insert into #event values (3, '2000-01-05', 2) insert into #event values (4, '2000-01-01', 2) insert into #event values (4, '2000-01-02', 2) insert into #event values (4, '2000-01-03', 3) insert into #event values (4, '2000-01-04', 1) insert into #event values (4, '2000-01-05', 1) go select e1.* from #event e1 where ( not exists ( select top 1 1 from #event e2 where e1.group_id = e2.group_id and e2.date &lt; e1.date and e2.type &lt;&gt; 1 ) or not exists ( select top 1 1 from #event e2 where e1.group_id = e2.group_id and e2.date &gt; e1.date and e2.type &lt;&gt; 1 ) ) and e1.type = 1 </code></pre> <p>Expected results: </p> <pre><code>1 2000-01-01 00:00:00.000 1 1 2000-01-02 00:00:00.000 1 1 2000-01-05 00:00:00.000 1 2 2000-01-05 00:00:00.000 1 3 2000-01-01 00:00:00.000 1 4 2000-01-04 00:00:00.000 1 4 2000-01-05 00:00:00.000 1 </code></pre> <p>This all works just fine and returns my expected results, but it scans through the table 3 times. Is there any way to make this perform faster and reduce the number of table scans? </p>
[ { "answer_id": 286343, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 0, "selected": false, "text": "<p>From what I understand you are after is the head and tail, ordered by day**, for each ID**. The head and tail being all the records until record where the type is not one is encountered.</p>\n\n<p>This is a different way of doing it, it may be faster</p>\n\n<pre><code>;WITH Ranked AS (\n SELECT \n *,\n Row_Number() OVER (ORDER BY date) as 'rnk'\n FROM #event\n)\n\n\nSELECT * \nFROM Ranked\nWHERE rnk not between \n (SELECT Min(rnk) FROM Ranked r WHERE r.type &lt;&gt; 1 AND ranked.id = r.id)\n AND (SELECT Max(rnk) FROM Ranked r WHERE r.type &lt;&gt; 1 AND ranked.id = r.id)\norder by id\n</code></pre>\n\n<p>You do not need to use TOP with the exists statement although it doesn't hurt.</p>\n" }, { "answer_id": 286376, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 0, "selected": false, "text": "<p>Basically looks like you are looking to get event of type 1 that are lesser than in timestamp than other events and greater than timestamp event of other date\nTry this, its written in Oracle Syntax, not sure about MSSQL.</p>\n<pre><code>select e1.* from e1 where \ne1.id = 1 and (e1.date &lt;=\n(\nselect min(e2.date) from e2 where\ne2.id &lt;&gt; 1\ngroup by e2.date\n)\nor \n(e1.date &gt;= \nselect max(e3.date) from e3 where\ne3.id &lt;&gt; 1\ngroup by e3.date\n)\n)\n</code></pre>\n" }, { "answer_id": 286377, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 0, "selected": false, "text": "<p>Consider</p>\n\n<p>create index idx2 on #event (type)</p>\n\n<p>I don't have SQL Server to check but in Oracle it will eliminate the top-level scan (for 'type=1' condition).</p>\n\n<p>Regarding the query itself - in MS SQL 2000 '[not] exists' and '[not] in' predicates almost always did full scan - we were replacing them with appropriate JOIN's. </p>\n" }, { "answer_id": 286416, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>With only 20 records the query optimizer may easily be concluding that 3 table scans is the quickest way to do it no matter how you express the query or what indexes you create. With small data records the entire table would probably load with one or a handful of disk reads; and within a read block there's not much optimization involved; the optimizer primarily is interested in minimizing disk activity, and all else is comparatively inconsequential. What the optimizer does with so few records is not a good indication of how it will handle larger volumes.</p>\n\n<p>Do you have a real table with more data in it? I can't imagine you can perceive any exectuion time at all.</p>\n" }, { "answer_id": 286446, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": true, "text": "<p>To generate a large subset of data you can use this: </p>\n\n<pre><code>declare @i int \nset @i = 10000\nwhile @i &gt; 5 \nbegin\n insert into #event values (@i, '2000-01-01', 1) \n insert into #event values (@i, '2000-01-02', 1) \n insert into #event values (@i, '2000-01-03', 3) \n insert into #event values (@i, '2000-01-04', 2) \n insert into #event values (@i, '2000-01-05', 1) \n set @i = @i -1 \nend \n</code></pre>\n\n<p>Also, to include lots of events per group try this: </p>\n\n<pre><code>declare @j int \nset @j = 0 \nwhile @j &lt; 10\nbegin \n set nocount on \n declare @i int \n set @i = 0\n while @i &lt; 10000 \n begin\n insert into #event values (@j, DateAdd(d, @i, '2000-01-01'), rand(10) * 10) \n\n set @i = @i +1 \n end\n set @j = @j + 1 \nend\nset nocount off\n</code></pre>\n\n<p>In all my testing it seems my original query only produces 3 table scans and I am not really sure if performance can be improved here. </p>\n" }, { "answer_id": 286832, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 0, "selected": false, "text": "<p>Here is a version with joins:</p>\n\n<pre><code>select distinct e1.* from #event e1 \nleft outer join #event e2 ON \n e1.id = e2.id \n and e2.date &lt; e1.date \n and e2.type &lt;&gt; 1\nleft outer join #event e3 ON\n e1.id = e3.id \n and e3.date &gt; e1.date \n and e3.type &lt;&gt; 1\nwhere e1.type = 1 AND (e2.id is null or e3.id is null)\n</code></pre>\n\n<p>This still has three table scans plus a distinct clause, but it still seems to be faster than the original query.</p>\n" }, { "answer_id": 287929, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>Here's a query whose showplan at least doesn't say &quot;table scan&quot; in it, and gives the same answer.</p>\n<p>I don't understand the query in logical terms yet though.</p>\n<pre><code>SELECT DISTINCT e1.* FROM #event e1 \nWHERE e1.type = 1 \n AND \n ( \n NOT EXISTS ( \n SELECT 1 FROM #event \n WHERE type != 1 \n AND id = e1.id \n AND date &lt; e1.date \n ) \n OR NOT EXISTS ( \n SELECT 1 FROM #event \n WHERE type != 1 \n AND id = e1.id \n AND date &gt; e1.date \n ) \n ) \n</code></pre>\n" }, { "answer_id": 288024, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>This is better than the last one:</p>\n<pre><code>SELECT e1.* FROM event e1 \nWHERE e1.type = 1 \n AND NOT EXISTS \n ( \n SELECT 1 FROM event \n WHERE type != 1 \n AND id = e1.id \n AND date &lt; e1.date \n ) \nUNION ALL\nSELECT e1.* FROM event e1 \nWHERE e1.type = 1 \n AND NOT EXISTS \n ( \n SELECT 1 FROM event \n WHERE type != 1 \n AND id = e1.id \n AND date &gt; e1.date \n ) \n</code></pre>\n<p>It gets the same result. But your query, and my previous one, are awful. Here's the IO statistics:</p>\n<p>(29985 row(s) affected)</p>\n<p>Table 'event'. Scan count 9997, logical reads 20477, physical reads 0, read-ahead reads 0.<br />\nTable 'Worktable'. Scan count 39979, logical reads 99950, physical reads 0, read-ahead reads 0.</p>\n<p>Here's the same for the most recent query:</p>\n<p>(29985 row(s) affected)</p>\n<p>Table 'event'. Scan count 4, logical reads 652, physical reads 0, read-ahead reads 0.</p>\n<p>Two things to notice --</p>\n<ol>\n<li>Even worst case, the whole table gets loaded and there are no physical reads.</li>\n<li>The bad ones have 9997 + 39979 table scans. Not just 4.</li>\n</ol>\n<p>Please describe the intent of the query.</p>\n" }, { "answer_id": 363436, "author": "adamant7", "author_id": 45775, "author_profile": "https://Stackoverflow.com/users/45775", "pm_score": 1, "selected": false, "text": "<p>I think this is better:</p>\n<pre><code>select e1.group_id, e1.date, e1.type&lt;br&gt;\nfrom #event e1, #event e2&lt;br&gt;\nwhere e1.type = 1&lt;br&gt;\nand e2.type &lt;&gt; 1&lt;br&gt;\nand e1.group_id= e2.group_id&lt;br&gt;\ngroup by e1.group_id, e1.date, e1.type, e2.group_id&lt;br&gt;\nhaving e1.date &lt; min(e2.date) or e1.date &gt; max(e2.date)\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
I have a table of events, I need to find all tail events of type 1 and all head events of type 1. So, for the set of events in this order [1, 1], 3, 1 ,4, 5, [1,1,1] the brackets denote head and tail events of type 1. This is much better illustrated in SQL: ``` drop table #event go create table #event (group_id int, [date] datetime, [type] int) create index idx1 on #event (group_id, date) insert into #event values (1, '2000-01-01', 1) insert into #event values (1, '2000-01-02', 1) insert into #event values (1, '2000-01-03', 3) insert into #event values (1, '2000-01-04', 2) insert into #event values (1, '2000-01-05', 1) insert into #event values (2, '2000-01-01', 2) insert into #event values (2, '2000-01-02', 2) insert into #event values (2, '2000-01-03', 3) insert into #event values (2, '2000-01-04', 2) insert into #event values (2, '2000-01-05', 1) insert into #event values (3, '2000-01-01', 1) insert into #event values (3, '2000-01-02', 2) insert into #event values (3, '2000-01-03', 1) insert into #event values (3, '2000-01-04', 2) insert into #event values (3, '2000-01-05', 2) insert into #event values (4, '2000-01-01', 2) insert into #event values (4, '2000-01-02', 2) insert into #event values (4, '2000-01-03', 3) insert into #event values (4, '2000-01-04', 1) insert into #event values (4, '2000-01-05', 1) go select e1.* from #event e1 where ( not exists ( select top 1 1 from #event e2 where e1.group_id = e2.group_id and e2.date < e1.date and e2.type <> 1 ) or not exists ( select top 1 1 from #event e2 where e1.group_id = e2.group_id and e2.date > e1.date and e2.type <> 1 ) ) and e1.type = 1 ``` Expected results: ``` 1 2000-01-01 00:00:00.000 1 1 2000-01-02 00:00:00.000 1 1 2000-01-05 00:00:00.000 1 2 2000-01-05 00:00:00.000 1 3 2000-01-01 00:00:00.000 1 4 2000-01-04 00:00:00.000 1 4 2000-01-05 00:00:00.000 1 ``` This all works just fine and returns my expected results, but it scans through the table 3 times. Is there any way to make this perform faster and reduce the number of table scans?
To generate a large subset of data you can use this: ``` declare @i int set @i = 10000 while @i > 5 begin insert into #event values (@i, '2000-01-01', 1) insert into #event values (@i, '2000-01-02', 1) insert into #event values (@i, '2000-01-03', 3) insert into #event values (@i, '2000-01-04', 2) insert into #event values (@i, '2000-01-05', 1) set @i = @i -1 end ``` Also, to include lots of events per group try this: ``` declare @j int set @j = 0 while @j < 10 begin set nocount on declare @i int set @i = 0 while @i < 10000 begin insert into #event values (@j, DateAdd(d, @i, '2000-01-01'), rand(10) * 10) set @i = @i +1 end set @j = @j + 1 end set nocount off ``` In all my testing it seems my original query only produces 3 table scans and I am not really sure if performance can be improved here.
286,375
<p>Hi i am encountering problems trying to post a WebRequest under Https. </p> <p>i received the following errors</p> <h1>1.-The underlying connection was closed: Unable to connect to the remote server.</h1> <h1>2.-the operation TimeOut</h1> <h1>3-The underlying connection was closed: Could not establish secure channel for SSL/TLS.</h1> <p>i tried with about 3 or 4 different proxies of my company and the customer company and not even when i am directly with the ISP provider with no restrictions, i get the above errors when executing the following method</p> <pre><code>WebRequest.GetRequestStream() </code></pre> <p>this occurs behind a proxy or not, the request can only be succesfully post from one single PC which is behind a proxy. the proxy doesn't have a client certificate installed.</p> <p>this is under .net framework 1.1 and the request already contains network credentials.</p> <p>what could be?</p> <h1>Update</h1> <p>the inner exception the 3rd error is the following: The function completed successfully, but must be called again to complete the context</p> <p>according to iisper.h <a href="http://doc.ddart.net/msdn/header/include/issperr.h.html" rel="nofollow noreferrer">documentation</a> this error belongs to the </p> <pre><code>// // MessageId: SEC_I_CONTINUE_NEEDED // // MessageText: // // The function completed successfully, but must be called // again to complete the context // #define SEC_I_CONTINUE_NEEDED ((HRESULT)0x00090312L) </code></pre> <p>on <a href="http://msdn.microsoft.com/en-us/library/aa375924(VS.85).aspx" rel="nofollow noreferrer">MSDN</a> this refers to </p> <p>SEC_I_CONTINUE_NEEDED The client must send the output token to the server and wait for a return token. The returned token is then passed in another call to InitializeSecurityContext (Schannel). The output token can be empty.</p> <p>does this means the PC lacks a client certificate?</p>
[ { "answer_id": 286393, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 0, "selected": false, "text": "<p>The SSL certificate name probably doesn't match. This is often the case with selfsigned certificates.</p>\n\n<p>The solution is to write your own authentication routine where you either always return true or do the necessary authentication to make sure the certificate is valid.</p>\n\n<pre><code>// .NET 2.0+\n...\nServicePointManager.ServerCertificateValidationCallback += MyValidationCallback\n...\npublic bool MyValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors err)\n{\n return true;\n}\n\n// .NET 1.1\npublic class MyCertificatePolicy : ICertificatePolicy\n{\n public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)\n {\n return true;\n }\n}\n...\nServicePointManager.CertificatePolicy = new MyCertificatePolicy();\n...\n</code></pre>\n" }, { "answer_id": 286396, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 2, "selected": true, "text": "<p>There are a whole number of things that could be complicating things, as far as inconsistencies with the SSL certs, etc. But first, you should do some basic debugging to rule out the obvious things:</p>\n\n<p>-- Did you try sending a simple web request to other servers? Try both (unsecured) http and (secured) https</p>\n\n<p>-- Did you try connecting from another computer, or from another network? You mentioned that the client is behind a proxy; try a computer w/o a proxy first, to rule that out.</p>\n\n<p>-- Are you making multiple WebRequests within the session? There is a hard-limit on the number of open requests, so make sure you're closing them after you get the WebResponse. Perhaps make a test program with just one request.</p>\n\n<p>If that doesn't narrow it down, then it's probably something more complicated, with their the server or the proxy. You can track outgoing network packets with a program such as netshark to try to track down where things are getting stuck.</p>\n" }, { "answer_id": 286417, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 1, "selected": false, "text": "<p>You could make a trace of the HTTP traffic using <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a> or a network packet sniffing tool like <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\"><s>Ethereal</s> Whireshark</a> on the machine where it is working, and on one of the other machines, and compare the results. This is fairly low-level, but might throw some light on the issue.</p>\n" }, { "answer_id": 286424, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 1, "selected": false, "text": "<ul>\n<li>If you can telnet from different machines to 443 then it is not the first two, as that means the client machine is receiving requests on that port.</li>\n</ul>\n\n<p>On windows that would be </p>\n\n<pre><code>telnet &lt;domainname&gt; 443\n</code></pre>\n\n<p>and if it connects the screen will go blank (hit return a few times to exit)</p>\n\n<ul>\n<li><p>The proxies may or may not actually care about your request if it is under HTTPS as they can't read it. </p></li>\n<li><p>Do the other machines have the client certificate and the certificate chain installed?</p></li>\n</ul>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14440/" ]
Hi i am encountering problems trying to post a WebRequest under Https. i received the following errors 1.-The underlying connection was closed: Unable to connect to the remote server. ================================================================================ 2.-the operation TimeOut ======================== 3-The underlying connection was closed: Could not establish secure channel for SSL/TLS. ======================================================================================= i tried with about 3 or 4 different proxies of my company and the customer company and not even when i am directly with the ISP provider with no restrictions, i get the above errors when executing the following method ``` WebRequest.GetRequestStream() ``` this occurs behind a proxy or not, the request can only be succesfully post from one single PC which is behind a proxy. the proxy doesn't have a client certificate installed. this is under .net framework 1.1 and the request already contains network credentials. what could be? Update ====== the inner exception the 3rd error is the following: The function completed successfully, but must be called again to complete the context according to iisper.h [documentation](http://doc.ddart.net/msdn/header/include/issperr.h.html) this error belongs to the ``` // // MessageId: SEC_I_CONTINUE_NEEDED // // MessageText: // // The function completed successfully, but must be called // again to complete the context // #define SEC_I_CONTINUE_NEEDED ((HRESULT)0x00090312L) ``` on [MSDN](http://msdn.microsoft.com/en-us/library/aa375924(VS.85).aspx) this refers to SEC\_I\_CONTINUE\_NEEDED The client must send the output token to the server and wait for a return token. The returned token is then passed in another call to InitializeSecurityContext (Schannel). The output token can be empty. does this means the PC lacks a client certificate?
There are a whole number of things that could be complicating things, as far as inconsistencies with the SSL certs, etc. But first, you should do some basic debugging to rule out the obvious things: -- Did you try sending a simple web request to other servers? Try both (unsecured) http and (secured) https -- Did you try connecting from another computer, or from another network? You mentioned that the client is behind a proxy; try a computer w/o a proxy first, to rule that out. -- Are you making multiple WebRequests within the session? There is a hard-limit on the number of open requests, so make sure you're closing them after you get the WebResponse. Perhaps make a test program with just one request. If that doesn't narrow it down, then it's probably something more complicated, with their the server or the proxy. You can track outgoing network packets with a program such as netshark to try to track down where things are getting stuck.
286,392
<p>How to use batch file to check if an application still running or not? If the application still running, this process will loop again and again. Else, there will be error message.</p> <p>Thank you very much</p>
[ { "answer_id": 286397, "author": "javamonkey79", "author_id": 27657, "author_profile": "https://Stackoverflow.com/users/27657", "pm_score": 0, "selected": false, "text": "<p>Perhaps you mean tasklist? You can run that from the command line to get all running processes in windows...for the rest of what you are asking I think you will need to be more specific. </p>\n" }, { "answer_id": 286403, "author": "Mark", "author_id": 37254, "author_profile": "https://Stackoverflow.com/users/37254", "pm_score": 2, "selected": false, "text": "<p>Linux ?</p>\n\n<p>ps aux | grep task | wc -l</p>\n\n<p>where task is the name of the task (e.g. \"apache2\" - quotes not needed)</p>\n" }, { "answer_id": 286453, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>in windows you kan use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx\" rel=\"noreferrer\">pstools</a> pslist to check if a process name is running by using a .cmd script like the following. Pslist will return ERRORLEVEL 0 if the process is running, 1 if not.</p>\n\n<pre><code>@echo off\n\nCommandYouWillRun.exe\n\nrem waiting for the process to start\n:startcmd\nsleep 1\nc:\\path\\to\\pslist.exe CommandYouWillRun &gt; NUL\nIF ERRORLEVEL 1 goto startcmd\n\nrem the process has now started\n\n:waitforcmd\nsleep 1\nc:\\path\\to\\pslist.exe CommandYouWillRun &gt; NUL\nIF ERRORLEVEL 1 got finished\ngoto waitforcmd\n\n:finished\necho \"This is an error message\"\n</code></pre>\n" }, { "answer_id": 286461, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": 1, "selected": false, "text": "<p>You can write a powershell-script and use get-process with filtering.</p>\n\n<p><a href=\"http://www.computerperformance.co.uk/powershell/powershell_process.htm\" rel=\"nofollow noreferrer\">http://www.computerperformance.co.uk/powershell/powershell_process.htm</a></p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How to use batch file to check if an application still running or not? If the application still running, this process will loop again and again. Else, there will be error message. Thank you very much
in windows you kan use [pstools](http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx) pslist to check if a process name is running by using a .cmd script like the following. Pslist will return ERRORLEVEL 0 if the process is running, 1 if not. ``` @echo off CommandYouWillRun.exe rem waiting for the process to start :startcmd sleep 1 c:\path\to\pslist.exe CommandYouWillRun > NUL IF ERRORLEVEL 1 goto startcmd rem the process has now started :waitforcmd sleep 1 c:\path\to\pslist.exe CommandYouWillRun > NUL IF ERRORLEVEL 1 got finished goto waitforcmd :finished echo "This is an error message" ```
286,399
<p>I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this</p> <pre><code>string[,] array = new string[,] { {"a", "b"}, {"c", "d"}, {"e", "f"}, {"g", "h"} } </code></pre> <p>Doing</p> <pre><code>List&lt;string[]&gt; list = new List&lt;string[]&gt;(); list.Add(new string[2] {"a", "b"}); list.Add(new string[2] {"c", "d"}); list.Add(new string[2] {"e", "f"}); list.Add(new string[2] {"g", "h"}); list.ToArray(); </code></pre> <p>gives me </p> <pre><code>string[][] </code></pre> <p>but not </p> <pre><code>string[,] </code></pre> <p>array.</p> <p>Just curious, is there some trick to build dynamically</p> <pre><code>string[,] </code></pre> <p>array somehow?</p>
[ { "answer_id": 286420, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 0, "selected": false, "text": "<p>This isn't possible with a <code>List&lt;string[]&gt;</code>, as the type <code>string[,]</code> is different from <code>string[]</code>.</p>\n" }, { "answer_id": 286428, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "<p>The only way to do it would be to implement the <code>ToArray()</code> function yourself. You could implement it within your own collection (i.e. <code>StringTupleCollection</code>). This could work the same as <code>ArrayList</code> (i.e. internal array increasing in size as needed).</p>\n\n<p>However I'm not sure the advantage of <code>[x,2]</code> over <code>[x][2]</code> (or even <code>List&lt;string[2]&gt;</code> would be significant enough to warrant the effort.</p>\n\n<p>You could also write a <code>StringTupple</code> class as:</p>\n\n<pre><code>public class StringTupple : KeyValuePair&lt;string, string&gt;\n{\n}\n</code></pre>\n" }, { "answer_id": 286445, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>Well, you could reasonably easily write an extension method to do it. Something like this (only tested very slightly):</p>\n\n<pre><code>public static T[,] ToRectangularArray&lt;T&gt;(this IEnumerable&lt;T[]&gt; source)\n{\n if (!source.Any())\n {\n return new T[0,0];\n }\n\n int width = source.First().Length;\n if (source.Any(array =&gt; array.Length != width))\n {\n throw new ArgumentException(\"All elements must have the same length\");\n }\n\n T[,] ret = new T[source.Count(), width];\n int row = 0;\n foreach (T[] array in source)\n {\n for (int col=0; col &lt; width; col++)\n {\n ret[row, col] = array[col];\n }\n row++;\n }\n return ret;\n}\n</code></pre>\n\n<p>It's a slight shame that the above code uses T[] as the element type. Due to generic invariance I can't currently make source <code>IEnumerable&lt;IEnumerable&lt;T&gt;&gt;</code> which would be nice. An alternative might be to introduce a new type parameter with a constraint:</p>\n\n<pre><code>public static T[,] ToRectangularArray&lt;T,U&gt;(this IEnumerable&lt;U&gt; source)\n where U : IEnumerable&lt;T&gt;\n</code></pre>\n\n<p>Somewhat hairy, but it should work. (Obviously the implementation needs some changes too, but the basic principle is the same.)</p>\n" }, { "answer_id": 10671635, "author": "Terrence", "author_id": 1405975, "author_profile": "https://Stackoverflow.com/users/1405975", "pm_score": 4, "selected": false, "text": "<p>You can do this.</p>\n\n<pre><code>List&lt;KeyValuePair&lt;string, string&gt;&gt;\n</code></pre>\n\n<p>The idea being that the Key Value Pair would mimic the array of strings you replicated.</p>\n" }, { "answer_id": 12289885, "author": "hagensoft", "author_id": 1608243, "author_profile": "https://Stackoverflow.com/users/1608243", "pm_score": 0, "selected": false, "text": "<p>KeyValuePair did not work for me when I had to retrieve the values of the checkboxes on the controller as my model.Roles list was null. </p>\n\n<pre><code>foreach (KeyValuePair&lt;string, bool&gt; Role in model.Roles){...}\n</code></pre>\n\n<p>The KeyValuePair structure doesn't have a default parameterless constructor and can't be instantiated by the model binder. I recommend a custom model class for your view that has just those properties. <a href=\"https://stackoverflow.com/questions/8538846/asp-net-mvc-3-binding-user-control-of-type-keyvaluepair-to-viewmodel\">ASP.NET MVC 3 binding user control of type KeyValuePair to ViewModel</a></p>\n\n<p>I found an implementation of a checkboxlist without the use of html helper at the following link <a href=\"https://stackoverflow.com/questions/4872192/checkboxlist-in-mvc3-0\">CheckboxList in MVC3.0</a></p>\n" }, { "answer_id": 62598372, "author": "TheJoe", "author_id": 8412763, "author_profile": "https://Stackoverflow.com/users/8412763", "pm_score": 1, "selected": false, "text": "<p>You could just use a struct. I do this when comparing XML Nodes manually.</p>\n<pre><code>private struct XmlPair\n{\n public string Name { set; get; }\n public string Value { set; get; }\n}\n\nList&lt;XmlPair&gt; Pairs = new List&lt;XmlPair&gt;();\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this ``` string[,] array = new string[,] { {"a", "b"}, {"c", "d"}, {"e", "f"}, {"g", "h"} } ``` Doing ``` List<string[]> list = new List<string[]>(); list.Add(new string[2] {"a", "b"}); list.Add(new string[2] {"c", "d"}); list.Add(new string[2] {"e", "f"}); list.Add(new string[2] {"g", "h"}); list.ToArray(); ``` gives me ``` string[][] ``` but not ``` string[,] ``` array. Just curious, is there some trick to build dynamically ``` string[,] ``` array somehow?
Well, you could reasonably easily write an extension method to do it. Something like this (only tested very slightly): ``` public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source) { if (!source.Any()) { return new T[0,0]; } int width = source.First().Length; if (source.Any(array => array.Length != width)) { throw new ArgumentException("All elements must have the same length"); } T[,] ret = new T[source.Count(), width]; int row = 0; foreach (T[] array in source) { for (int col=0; col < width; col++) { ret[row, col] = array[col]; } row++; } return ret; } ``` It's a slight shame that the above code uses T[] as the element type. Due to generic invariance I can't currently make source `IEnumerable<IEnumerable<T>>` which would be nice. An alternative might be to introduce a new type parameter with a constraint: ``` public static T[,] ToRectangularArray<T,U>(this IEnumerable<U> source) where U : IEnumerable<T> ``` Somewhat hairy, but it should work. (Obviously the implementation needs some changes too, but the basic principle is the same.)
286,402
<p>I have a couple of array's:</p> <pre><code>const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"}; const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"}; </code></pre> <p>which i then need to parse out for '=' and then put the values in the struct. (the rc key maps to the fc key in the struct), which is in the form of:</p> <pre><code>struct predict_cache_key { pck() : av_id(0), sz_id(0), cr_id(0), cp_id(0), cv_id(0), ct_id(0), fc(0), gnd(0), ag(0), pc(0), prl_id(0) { } int av_id; int sz_id; int cr_id; int cp_id; int cv_id; int ct_id; int fc; char gnd; int ag; int pc; long prl_id; }; </code></pre> <p>The problem I am encountering is that the array's are not in sequence or in the same sequence as the struct fields. So, I need to check each and then come up with a scheme to put the same into the struct.</p> <p>Any help in using C or C++ to solve the above?</p>
[ { "answer_id": 286450, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 3, "selected": false, "text": "<p>Probably I didn't get it correctly, but obvious solutions is to split each array element into <code>key</code> and <code>value</code> and then write lo-o-ong <code>if-else-if-else ...</code> sequence like</p>\n\n<pre><code>if (!strcmp(key, \"cr\"))\n my_struct.cr = value;\nelse if (!strcmp(key, \"ag\"))\n my_struct.ag = value;\n...\n</code></pre>\n\n<p>You can automate the creation of such sequence with the help of C preprocessor, e.g.</p>\n\n<p><code>#define PROC_KEY_VALUE_PAIR(A) else if (!strcmp(key,#A)) my_struct.##A = value</code></p>\n\n<p>Because of leading <code>else</code> you write the code this way:</p>\n\n<pre><code>if (0);\nPROC_KEY_VALUE_PAIR(cr);\nPROC_KEY_VALUE_PAIR(ag);\n...\n</code></pre>\n\n<p>The only problem that some of you struct fields have <code>_id</code> sufffix - for them you'd need to create a bit different macro that will paste <code>_id</code> suffix</p>\n" }, { "answer_id": 286667, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 3, "selected": true, "text": "<p>This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g.</p>\n\n<p><code>const string a_strs[] = {\"cr=1\", \"ag=2\", \"gnd=U\", NULL};</code></p>\n\n<p>Then I would write a (private) helper function that parse the string:</p>\n\n<pre><code>\nbool\nparse_string(const string &str, char *buffer, size_t b_size, int *num)\n{\n char *ptr;\n\n strncpy(buffer, str.c_str(), b_size);\n buffer[b_size - 1] = 0;\n\n /* find the '=' */\n ptr = strchr(buffer, '=');\n\n if (!ptr) return false;\n\n *ptr = '\\0';\n ptr++;\n\n *num = atoi(ptr);\n\n return true;\n}\n</code></pre>\n\n<p>then you can do what qrdl has suggested.</p>\n\n<p>in a simple for loop:</p>\n\n<pre><code>\nfor (const string *cur_str = array; *cur_str; cur_str++)\n{\n char key[128];\n int value = 0;\n\n if (!parse_string(*cur_string, key, sizeof(key), &value)\n continue;\n\n /* and here what qrdl suggested */\n if (!strcmp(key, \"cr\")) cr_id = value;\n else if ...\n}\n</code></pre>\n\n<p>EDIT: you should probably use long instead of int and atol instead of atoi, because your prl_id is of the type long. Second if there could be wrong formated numbers after the '=', you should use strtol, which can catch errors.</p>\n" }, { "answer_id": 286693, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 0, "selected": false, "text": "<p>The problem is you dont have the metainformation to refer to the struct elements at run time (Something like structVar.$ElementName = ..., where $ElementName is not the element name but a (char?)variable containing the element name which should be used). \nMy solution would be to add this metainformation.\nThis should be an array with the offset of the elements in the struct. </p>\n\n<p>Quick-n-Dirty solution: you add an array with the strings, the resulting code should look like this:</p>\n\n<pre><code>const char * wordlist[] = {\"pc\",\"gnd\",\"ag\",\"prl_id\",\"fc\"};\nconst int offsets[] = { offsetof(mystruct, pc), offsetof(mystruct, gnd), offsetof(mystruct, ag), offsetof(mystruct, prl_id), offsetof(mystruct, fc)};\nconst int sizes[] = { sizeof(mystruct.pc), sizeof(mystruct.gnd), sizeof(mystruct.ag), sizeof(mystruct.prl_id), sizeof(mystruct.fc)}\n</code></pre>\n\n<p>to enter something you would then something like this:</p>\n\n<pre><code>index = 0;\nwhile (strcmp(wordlist[index], key) &amp;&amp; index &lt; 5)\n index++;\nif (index &lt;5)\n memcpy(&amp;mystructvar + offsets[index], &amp;value, sizes[index]);\nelse\n fprintf(stderr, \"Key not valid\\n\"); \n</code></pre>\n\n<p>This loop for the inserts can get costly if you have bigger structures, but C doenst allow array indexing with strings. But the computer science found a solution for this problem: perfect hashes.</p>\n\n<p>So it would afterwards look like this:</p>\n\n<pre><code>hash=calc_perf_hash(key);\nmemcpy(&amp;mystruct + offsets[hash], &amp;value, sizes[hash]);\n</code></pre>\n\n<p>But how to obtain these perfect hash functions (I called it calc_perf_hash)?\nThere exist algorithms for it where you just stuff your keywords in, and the functions comes out, and luckily someone even programmed them: look for the \"gperf\" tool/package in your faviourite OS/distribution. \nThere you would just input the 6 element names and he outputs you the ready to use C code for a perfect hash function (in generates per default a function \"hash\" which returnes the hash, and an \"in_word_set\" function which decides if a given key is in the word list). \nBecause the hash is in different order, you have of course to initilize the offsetof and size arrays in the order of the hashes.</p>\n\n<p>Another problem you have (and which the other answers doesnt take into account) is the type conversion. The others make an assignment, I have (not better) memcopy. \nHere I would suggest you change the sizes array into another array:</p>\n\n<pre><code>const char * modifier[]={\"%i\",\"%c\", ...\n</code></pre>\n\n<p>Where each string describes the sscanf modifier to read it in. This way you can replace the assignment/copy by </p>\n\n<pre><code>sscanf(valueString, modifier[hash], &amp;mystructVar + offsets(hash));\n</code></pre>\n\n<p>Cf course you can vary here, by including the \"element=\" into the string or similar. So you can put the complete string into value and dont have to preprocess it, I think this depends strongly on the rest of you parse routine.</p>\n" }, { "answer_id": 286820, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "<p>Indeed, like many answered, there is a need to separate the parsing problem from the object construction problem. The Factory pattern is suited well for that.</p>\n\n<p>The Boost.Spirit library also solves the parse->function problem in a very elegant way (uses EBNF notation).</p>\n\n<p>I always like to separate the 'business logic' from the framework code. </p>\n\n<p>You can achieve this by start writing \"what you want to do\" in a very convenient way and work to \"how do you do it\" from there.</p>\n\n<pre><code> const CMemberSetter&lt;predict_cache_key&gt;* setters[] = \n #define SETTER( tag, type, member ) new TSetter&lt;predict_cache_key,type&gt;( #tag, &amp;predict_cache_key::##member )\n { SETTER( \"av\", int, av_id )\n , SETTER( \"sz\", int, sz_id )\n , SETTER( \"cr\", int, cr_id )\n , SETTER( \"cp\", int, cp_id )\n , SETTER( \"cv\", int, cv_id )\n , SETTER( \"ct\", int, ct_id )\n , SETTER( \"fc\", int, fc )\n , SETTER( \"gnd\", char, gnd )\n , SETTER( \"ag\", int, ag )\n , SETTER( \"pc\", int, pc )\n , SETTER( \"prl\", long, prl_id )\n };\n\n PCKFactory&lt;predict_cache_key&gt; factory ( setters );\n\n predict_cache_key a = factory.factor( a_strs );\n predict_cache_key b = factory.factor( b_strs );\n</code></pre>\n\n<p>And the framework to achieve this:</p>\n\n<pre><code> // conversion from key=value pair to \"set the value of a member\"\n // this class merely recognises a key and extracts the value part of the key=value string\n //\n template&lt; typename BaseClass &gt;\n struct CMemberSetter {\n\n const std::string key;\n CMemberSetter( const string&amp; aKey ): key( aKey ){}\n\n bool try_set_value( BaseClass&amp; p, const string&amp; key_value ) const {\n if( key_value.find( key ) == 0 ) {\n size_t value_pos = key_value.find( \"=\" ) + 1;\n action( p, key_value.substr( value_pos ) );\n return true;\n }\n else return false;\n }\n virtual void action( BaseClass&amp; p, const string&amp; value ) const = 0;\n };\n\n // implementation of the action method\n //\n template&lt; typename BaseClass, typename T &gt;\n struct TSetter : public CMemberSetter&lt;BaseClass&gt; {\n typedef T BaseClass::*TMember;\n TMember member;\n\n TSetter( const string&amp; aKey, const TMember t ): CMemberSetter( aKey ), member(t){}\n virtual void action( BaseClass&amp; p, const std::string&amp; valuestring ) const {\n // get value\n T value ();\n stringstream ( valuestring ) &gt;&gt; value;\n (p.*member) = value;\n }\n };\n\n\n template&lt; typename BaseClass &gt;\n struct PCKFactory {\n std::vector&lt;const CMemberSetter&lt;BaseClass&gt;*&gt; aSetters;\n\n template&lt; size_t N &gt;\n PCKFactory( const CMemberSetter&lt;BaseClass&gt;* (&amp;setters)[N] )\n : aSetters( setters, setters+N ) {}\n\n template&lt; size_t N &gt;\n BaseClass factor( const string (&amp;key_value_pairs) [N] ) const {\n BaseClass pck;\n\n // process each key=value pair\n for( const string* pair = key_value_pairs; pair != key_value_pairs + _countof( key_value_pairs); ++pair ) \n {\n std::vector&lt;const CMemberSetter&lt;BaseClass&gt;*&gt;::const_iterator itSetter = aSetters.begin();\n while( itSetter != aSetters.end() ) { // optimalization possible\n if( (*itSetter)-&gt;try_set_value( pck, *pair ) )\n break;\n ++itSetter;\n }\n }\n\n return pck;\n }\n };\n</code></pre>\n" }, { "answer_id": 287353, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<p>I've written some little code that allows you to initialize fields, without having to worry too much about whether your fields are going out of order with the initialization.</p>\n\n<p>Here is how you use it in your own code:</p>\n\n<pre><code>/* clients using the above classes derive from lookable_fields */\nstruct predict_cache_key : private lookable_fields&lt;predict_cache_key&gt; {\n predict_cache_key(std::vector&lt;std::string&gt; const&amp; vec) {\n for(std::vector&lt;std::string&gt;::const_iterator it = vec.begin();\n it != vec.end(); ++it) {\n std::size_t i = it-&gt;find('=');\n set_member(it-&gt;substr(0, i), it-&gt;substr(i + 1));\n }\n }\n\n long get_prl() const {\n return prl_id;\n }\n\nprivate:\n\n /* ... and define the members that can be looked up. i've only\n * implemented int, char and long for this answer. */\n BEGIN_FIELDS(predict_cache_key)\n FIELD(av_id);\n FIELD(sz_id);\n FIELD(gnd);\n FIELD(prl_id);\n END_FIELDS()\n\n int av_id;\n int sz_id;\n char gnd;\n long prl_id;\n /* ... */\n};\n\nint main() {\n std::string const a[] = { \"av_id=10\", \"sz_id=10\", \"gnd=c\",\n \"prl_id=1192\" };\n predict_cache_key haha(std::vector&lt;std::string&gt;(a, a + 4));\n}\n</code></pre>\n\n<p>The framework is below</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct entry {\n enum type { tchar, tint, tlong } type_name;\n\n /* default ctor, so we can std::map it */\n entry() { }\n\n template&lt;typename R&gt;\n entry(R (T::*ptr)) {\n set_ptr(ptr);\n }\n\n void set_ptr(char (T::*ptr)) {\n type_name = tchar;\n charp = ptr;\n };\n\n void set_ptr(int (T::*ptr)) {\n type_name = tint;\n intp = ptr; \n };\n\n void set_ptr(long (T::*ptr)) {\n type_name = tlong;\n longp = ptr; \n };\n\n union {\n char (T::*charp);\n int (T::*intp);\n long (T::*longp);\n };\n};\n\n#define BEGIN_FIELDS(CLASS) \\\n friend struct lookable_fields&lt;CLASS&gt;; \\\n private: \\\n static void init_fields_() { \\\n typedef CLASS parent_class;\n\n#define FIELD(X) \\\n lookable_fields&lt;parent_class&gt;::entry_map[#X].set_ptr(&amp;parent_class::X)\n\n#define END_FIELDS() \\\n } \n\ntemplate&lt;typename Derived&gt;\nstruct lookable_fields {\nprotected:\n lookable_fields() {\n (void) &amp;initializer; /* instantiate the object */\n }\n\n void set_member(std::string const&amp; member, std::string const&amp; value) {\n typename entry_map_t::iterator it = entry_map.find(member);\n if(it == entry_map.end()) {\n std::ostringstream os;\n os &lt;&lt; \"member '\" &lt;&lt; member &lt;&lt; \"' not found\";\n throw std::invalid_argument(os.str());\n }\n\n Derived * derived = static_cast&lt;Derived*&gt;(this);\n\n std::istringstream ss(value);\n switch(it-&gt;second.type_name) {\n case entry_t::tchar: {\n /* convert to char */\n ss &gt;&gt; (derived-&gt;*it-&gt;second.charp);\n break;\n }\n case entry_t::tint: {\n /* convert to int */\n ss &gt;&gt; (derived-&gt;*it-&gt;second.intp);\n break;\n }\n case entry_t::tlong: {\n /* convert to long */\n ss &gt;&gt; (derived-&gt;*it-&gt;second.longp);\n break;\n }\n }\n }\n\n typedef entry&lt;Derived&gt; entry_t;\n typedef std::map&lt;std::string, entry_t&gt; entry_map_t;\n static entry_map_t entry_map;\n\nprivate:\n struct init_helper {\n init_helper() {\n Derived::init_fields_();\n }\n };\n\n /* will call the derived class's static init function */\n static init_helper initializer;\n};\n\ntemplate&lt;typename T&gt; \nstd::map&lt; std::string, entry&lt;T&gt; &gt; lookable_fields&lt;T&gt;::entry_map;\n\ntemplate&lt;typename T&gt; \ntypename lookable_fields&lt;T&gt;::init_helper lookable_fields&lt;T&gt;::initializer;\n</code></pre>\n\n<p>It works using the lesser known data-member-pointers, which you can take from a class using the syntax <code>&amp;classname::member</code>.</p>\n" }, { "answer_id": 287518, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "<p>Were I to do this in straight C, I wouldn't use the mother of all if's. Instead, I would do something like this:</p>\n\n<pre><code>typedef struct {\n const char *fieldName;\n int structOffset;\n int fieldSize;\n} t_fieldDef;\n\ntypedef struct {\n int fieldCount;\n t_fieldDef *defs;\n} t_structLayout;\n\nt_memberDef *GetFieldDefByName(const char *name, t_structLayout *layout)\n{\n t_fieldDef *defs = layout-&gt;defs;\n int count = layout-&gt;fieldCount;\n for (int i=0; i &lt; count; i++) {\n if (strcmp(name, defs-&gt;fieldName) == 0)\n return defs;\n defs++;\n }\n return NULL;\n}\n\n/* meta-circular usage */\nstatic t_fieldDef metaFieldDefs[] = {\n { \"fieldName\", offsetof(t_fieldDef, fieldName), sizeof(const char *) },\n { \"structOffset\", offsetof(t_fieldDef, structOffset), sizeof(int) },\n { \"fieldSize\", offsetof(t_fieldDef, fieldSize), sizeof(int) }\n};\nstatic t_structLayout metaFieldDefLayout =\n { sizeof(metaFieldDefs) / sizeof(t_fieldDef), metaFieldDefs };\n</code></pre>\n\n<p>This lets you look up the field by name at runtime with a compact collection of the struct layout. This is fairly easy to maintain, but I don't like the <code>sizeof(mumble)</code> in the actual usage code - that requires that all struct definitions get labeled with comments saying, \"don't effing change the types or content without changing them in the <code>t_fieldDef</code> array for this structure\". There also needs to be <code>NULL</code> checking. </p>\n\n<p>I'd also prefer that the lookup be either binary search or hash, but this is probably good enough for most cases. If I were to do hash, I'd put a pointer to a <code>NULL</code> hashtable into the <code>t_structLayout</code> and on first search, build the hash.</p>\n" }, { "answer_id": 1812302, "author": "israel", "author_id": 220430, "author_profile": "https://Stackoverflow.com/users/220430", "pm_score": 0, "selected": false, "text": "<p>tried your idea and got an</p>\n\n<pre><code>error: ISO C++ forbids declaration of ‘map’ with no type\n</code></pre>\n\n<p>in linux ubuntu eclipse cdt.</p>\n\n<p>I wish to notify that one should include <code>&lt;map&gt;</code> in the \"*.h\" file\nin order to use your code without this error message.</p>\n\n<pre><code>#include &lt;map&gt;\n\n// a framework\n\ntemplate&lt;typename T&gt;\nstruct entry {\n enum type { tchar, tint, tlong } type_name;\n\n /* default ctor, so we can std::map it */\n entry() { }\n\n template&lt;typename R&gt;\n entry(R (T::*ptr)) {\n</code></pre>\n\n<p>etc' etc'......</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
I have a couple of array's: ``` const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"}; const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"}; ``` which i then need to parse out for '=' and then put the values in the struct. (the rc key maps to the fc key in the struct), which is in the form of: ``` struct predict_cache_key { pck() : av_id(0), sz_id(0), cr_id(0), cp_id(0), cv_id(0), ct_id(0), fc(0), gnd(0), ag(0), pc(0), prl_id(0) { } int av_id; int sz_id; int cr_id; int cp_id; int cv_id; int ct_id; int fc; char gnd; int ag; int pc; long prl_id; }; ``` The problem I am encountering is that the array's are not in sequence or in the same sequence as the struct fields. So, I need to check each and then come up with a scheme to put the same into the struct. Any help in using C or C++ to solve the above?
This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g. `const string a_strs[] = {"cr=1", "ag=2", "gnd=U", NULL};` Then I would write a (private) helper function that parse the string: ``` bool parse_string(const string &str, char *buffer, size_t b_size, int *num) { char *ptr; strncpy(buffer, str.c_str(), b_size); buffer[b_size - 1] = 0; /* find the '=' */ ptr = strchr(buffer, '='); if (!ptr) return false; *ptr = '\0'; ptr++; *num = atoi(ptr); return true; } ``` then you can do what qrdl has suggested. in a simple for loop: ``` for (const string *cur_str = array; *cur_str; cur_str++) { char key[128]; int value = 0; if (!parse_string(*cur_string, key, sizeof(key), &value) continue; /* and here what qrdl suggested */ if (!strcmp(key, "cr")) cr_id = value; else if ... } ``` EDIT: you should probably use long instead of int and atol instead of atoi, because your prl\_id is of the type long. Second if there could be wrong formated numbers after the '=', you should use strtol, which can catch errors.
286,426
<p>I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close().</p> <p>I have full control over P1 and P2, so I can add JavaScript code to both P1 and P2 as needed. Suggestions on how to resolve this?</p>
[ { "answer_id": 286472, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>It's impossible, I am afraid. JavaScript from an iframe that is loaded to a different site then the one it is being rendered on is strictly prohibited due to security issues.</p>\n\n<p>However, if the iframe is pointed to the same site you can get to it like:</p>\n\n<pre><code>&lt;iframe name = \"frame1\" src = \"http://yoursite\"&gt;\n&lt;/iframe&gt;\n\n&lt;script type = \"text/javascript\"&gt;\n alert(window.frames[\"frame1\"].document);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 286516, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 0, "selected": false, "text": "<p>If they originated from the same domain, you can modify the security-restrictions to allow modification between sub-domains.</p>\n\n<p>set document.domain = \"domain.com\"; //on both pages and they are allowed to modify eachother.</p>\n\n<p>It might work to just set them to a bogus-domain, haven't tried that, or just simply \".com\" or something.</p>\n" }, { "answer_id": 286916, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 0, "selected": false, "text": "<p>It looks like <a href=\"http://blog.johnmckerrell.com/2006/10/22/resizing-iframes-across-domains/\" rel=\"nofollow noreferrer\">this guy</a> got cross domain JavaScript working between iframes.</p>\n" }, { "answer_id": 3073442, "author": "lacker", "author_id": 2652, "author_profile": "https://Stackoverflow.com/users/2652", "pm_score": 0, "selected": false, "text": "<p>You can use Flash to do this. Send the user to a new top-level page that you control with a URLRequest with a _top target, and have that page contain javascript that does a window.close().</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close(). I have full control over P1 and P2, so I can add JavaScript code to both P1 and P2 as needed. Suggestions on how to resolve this?
It's impossible, I am afraid. JavaScript from an iframe that is loaded to a different site then the one it is being rendered on is strictly prohibited due to security issues. However, if the iframe is pointed to the same site you can get to it like: ``` <iframe name = "frame1" src = "http://yoursite"> </iframe> <script type = "text/javascript"> alert(window.frames["frame1"].document); </script> ```
286,427
<p>Inspired by this <a href="https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f">question</a> and <a href="https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f#283638">answer</a>, how do I create a generic permutations algorithm in F#? Google doesn't give any useful answers to this.</p> <p>EDIT: I provide my best answer below, but I suspect that Tomas's is better (certainly shorter!)</p>
[ { "answer_id": 286544, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 1, "selected": false, "text": "<p>My latest best answer</p>\n\n<pre><code>//mini-extension to List for removing 1 element from a list\nmodule List = \n let remove n lst = List.filter (fun x -&gt; x &lt;&gt; n) lst\n\n//Node type declared outside permutations function allows us to define a pruning filter\ntype Node&lt;'a&gt; =\n | Branch of ('a * Node&lt;'a&gt; seq)\n | Leaf of 'a\n\nlet permutations treefilter lst =\n //Builds a tree representing all possible permutations\n let rec nodeBuilder lst x = //x is the next element to use\n match lst with //lst is all the remaining elements to be permuted\n | [x] -&gt; seq { yield Leaf(x) } //only x left in list -&gt; we are at a leaf\n | h -&gt; //anything else left -&gt; we are at a branch, recurse \n let ilst = List.remove x lst //get new list without i, use this to build subnodes of branch\n seq { yield Branch(x, Seq.map_concat (nodeBuilder ilst) ilst) }\n\n //converts a tree to a list for each leafpath\n let rec pathBuilder pth n = // pth is the accumulated path, n is the current node\n match n with\n | Leaf(i) -&gt; seq { yield List.rev (i :: pth) } //path list is constructed from root to leaf, so have to reverse it\n | Branch(i, nodes) -&gt; Seq.map_concat (pathBuilder (i :: pth)) nodes\n\n let nodes = \n lst //using input list\n |&gt; Seq.map_concat (nodeBuilder lst) //build permutations tree\n |&gt; Seq.choose treefilter //prune tree if necessary\n |&gt; Seq.map_concat (pathBuilder []) //convert to seq of path lists\n\n nodes\n</code></pre>\n\n<p>The permutations function works by constructing an n-ary tree representing all possible permutations of the list of 'things' passed in, then traversing the tree to construct a list of lists. Using 'Seq' dramatically improves performance as it makes everything lazy.</p>\n\n<p>The second parameter of the permutations function allows the caller to define a filter for 'pruning' the tree before generating the paths (see my example below, where I don't want any leading zeros).</p>\n\n<p>Some example usage: Node&lt;'a> is generic, so we can do permutations of 'anything':</p>\n\n<pre><code>let myfilter n = Some(n) //i.e., don't filter\npermutations myfilter ['A';'B';'C';'D'] \n\n//in this case, I want to 'prune' leading zeros from my list before generating paths\nlet noLeadingZero n = \n match n with\n | Branch(0, _) -&gt; None\n | n -&gt; Some(n)\n\n//Curry myself an int-list permutations function with no leading zeros\nlet noLZperm = permutations noLeadingZero\nnoLZperm [0..9] \n</code></pre>\n\n<p>(Special thanks to <a href=\"https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f#283638\">Tomas Petricek</a>, any comments welcome)</p>\n" }, { "answer_id": 286821, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 5, "selected": true, "text": "<p>you can also write something like this:</p>\n\n<pre><code>let rec permutations list taken = \n seq { if Set.count taken = List.length list then yield [] else\n for l in list do\n if not (Set.contains l taken) then \n for perm in permutations list (Set.add l taken) do\n yield l::perm }\n</code></pre>\n\n<p>The 'list' argument contains all the numbers that you want to permute and 'taken' is a set that contains numbers already used. The function returns empty list when all numbers all taken.\nOtherwise, it iterates over all numbers that are still available, gets all possible permutations of the remaining numbers (recursively using 'permutations') and appends the current number to each of them before returning (l::perm).</p>\n\n<p>To run this, you'll give it an empty set, because no numbers are used at the beginning:</p>\n\n<pre><code>permutations [1;2;3] Set.empty;;\n</code></pre>\n" }, { "answer_id": 2184129, "author": "Johan Kullbom", "author_id": 72165, "author_profile": "https://Stackoverflow.com/users/72165", "pm_score": 4, "selected": false, "text": "<p>I like this implementation (but can't remember the source of it):</p>\n\n<pre><code>let rec insertions x = function\n | [] -&gt; [[x]]\n | (y :: ys) as l -&gt; (x::l)::(List.map (fun x -&gt; y::x) (insertions x ys))\n\nlet rec permutations = function\n | [] -&gt; seq [ [] ]\n | x :: xs -&gt; Seq.concat (Seq.map (insertions x) (permutations xs))\n</code></pre>\n" }, { "answer_id": 2636471, "author": "Holoed", "author_id": 316376, "author_profile": "https://Stackoverflow.com/users/316376", "pm_score": 1, "selected": false, "text": "<p>Take a look at this one:</p>\n\n<p><a href=\"http://fsharpcode.blogspot.com/2010/04/permutations.html\" rel=\"nofollow noreferrer\">http://fsharpcode.blogspot.com/2010/04/permutations.html</a></p>\n\n<pre><code>let length = Seq.length\nlet take = Seq.take\nlet skip = Seq.skip\nlet (++) = Seq.append\nlet concat = Seq.concat\nlet map = Seq.map\n\nlet (|Empty|Cons|) (xs:seq&lt;'a&gt;) : Choice&lt;Unit, 'a * seq&lt;'a&gt;&gt; =\n if (Seq.isEmpty xs) then Empty else Cons(Seq.head xs, Seq.skip 1 xs)\n\nlet interleave x ys =\n seq { for i in [0..length ys] -&gt;\n (take i ys) ++ seq [x] ++ (skip i ys) }\n\nlet rec permutations xs =\n match xs with\n | Empty -&gt; seq [seq []]\n | Cons(x,xs) -&gt; concat(map (interleave x) (permutations xs))\n</code></pre>\n" }, { "answer_id": 3180680, "author": "Stephen Swensen", "author_id": 236255, "author_profile": "https://Stackoverflow.com/users/236255", "pm_score": 2, "selected": false, "text": "<p>Tomas' solution is quite elegant: it's short, purely functional, and lazy. I think it may even be tail-recursive. Also, it produces permutations lexicographically. However, we can improve performance two-fold using an imperative solution internally while still exposing a functional interface externally.</p>\n\n<p>The function <code>permutations</code> takes a generic sequence <code>e</code> as well as a generic comparison function <code>f : ('a -&gt; 'a -&gt; int)</code> and lazily yields immutable permutations lexicographically. The comparison functional allows us to generate permutations of elements which are not necessarily <code>comparable</code> as well as easily specify reverse or custom orderings.</p>\n\n<p>The inner function <code>permute</code> is the imperative implementation of the algorithm described <a href=\"https://stackoverflow.com/questions/352203/generating-permutations-lazily/353248#353248\">here</a>. The conversion function <code>let comparer f = { new System.Collections.Generic.IComparer&lt;'a&gt; with member self.Compare(x,y) = f x y }</code> allows us to use the <code>System.Array.Sort</code> overload which does in-place sub-range custom sorts using an <code>IComparer</code>.</p>\n\n<pre><code>let permutations f e =\n ///Advances (mutating) perm to the next lexical permutation.\n let permute (perm:'a[]) (f: 'a-&gt;'a-&gt;int) (comparer:System.Collections.Generic.IComparer&lt;'a&gt;) : bool =\n try\n //Find the longest \"tail\" that is ordered in decreasing order ((s+1)..perm.Length-1).\n //will throw an index out of bounds exception if perm is the last permuation,\n //but will not corrupt perm.\n let rec find i =\n if (f perm.[i] perm.[i-1]) &gt;= 0 then i-1\n else find (i-1)\n let s = find (perm.Length-1)\n let s' = perm.[s]\n\n //Change the number just before the tail (s') to the smallest number bigger than it in the tail (perm.[t]).\n let rec find i imin =\n if i = perm.Length then imin\n elif (f perm.[i] s') &gt; 0 &amp;&amp; (f perm.[i] perm.[imin]) &lt; 0 then find (i+1) i\n else find (i+1) imin\n let t = find (s+1) (s+1)\n\n perm.[s] &lt;- perm.[t]\n perm.[t] &lt;- s'\n\n //Sort the tail in increasing order.\n System.Array.Sort(perm, s+1, perm.Length - s - 1, comparer)\n true\n with\n | _ -&gt; false\n\n //permuation sequence expression \n let c = f |&gt; comparer\n let freeze arr = arr |&gt; Array.copy |&gt; Seq.readonly\n seq { let e' = Seq.toArray e\n yield freeze e'\n while permute e' f c do\n yield freeze e' }\n</code></pre>\n\n<p>Now for convenience we have the following where <code>let flip f x y = f y x</code>: </p>\n\n<pre><code>let permutationsAsc e = permutations compare e\nlet permutationsDesc e = permutations (flip compare) e\n</code></pre>\n" }, { "answer_id": 3550869, "author": "Emile", "author_id": 18756, "author_profile": "https://Stackoverflow.com/users/18756", "pm_score": 1, "selected": false, "text": "<p>If you need distinct permuations (when the original set has duplicates), you can use this:</p>\n\n<pre><code>let rec insertions pre c post =\n seq {\n if List.length post = 0 then\n yield pre @ [c]\n else\n if List.forall (fun x-&gt;x&lt;&gt;c) post then\n yield pre@[c]@post\n yield! insertions (pre@[post.Head]) c post.Tail\n }\n\nlet rec permutations l =\n seq {\n if List.length l = 1 then\n yield l\n else\n let subperms = permutations l.Tail\n for sub in subperms do\n yield! insertions [] l.Head sub\n }\n</code></pre>\n\n<p>This is a straight-forward translation from <a href=\"https://stackoverflow.com/questions/361/generate-list-of-all-possible-permutations-of-a-string/3178268#3178268\">this</a> C# code. I am open to suggestions for a more functional look-and-feel.</p>\n" }, { "answer_id": 56072410, "author": "gmlion", "author_id": 5743444, "author_profile": "https://Stackoverflow.com/users/5743444", "pm_score": 0, "selected": false, "text": "<p>If you need permutations with repetitions, this is the \"by the book\" approach using List.indexed instead of element comparison to filter out elements while constructing a permutation.</p>\n\n<pre><code>let permutations s =\n let rec perm perms carry rem =\n match rem with\n | [] -&gt; carry::perms\n | l -&gt;\n let li = List.indexed l\n let permutations =\n seq { for ci in li -&gt;\n let (i, c) = ci\n (perm\n perms\n (c::carry)\n (li |&gt; List.filter (fun (index, _) -&gt; i &lt;&gt; index) |&gt; List.map (fun (_, char) -&gt; char))) }\n\n permutations |&gt; Seq.fold List.append []\n perm [] [] s\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11410/" ]
Inspired by this [question](https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f) and [answer](https://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f#283638), how do I create a generic permutations algorithm in F#? Google doesn't give any useful answers to this. EDIT: I provide my best answer below, but I suspect that Tomas's is better (certainly shorter!)
you can also write something like this: ``` let rec permutations list taken = seq { if Set.count taken = List.length list then yield [] else for l in list do if not (Set.contains l taken) then for perm in permutations list (Set.add l taken) do yield l::perm } ``` The 'list' argument contains all the numbers that you want to permute and 'taken' is a set that contains numbers already used. The function returns empty list when all numbers all taken. Otherwise, it iterates over all numbers that are still available, gets all possible permutations of the remaining numbers (recursively using 'permutations') and appends the current number to each of them before returning (l::perm). To run this, you'll give it an empty set, because no numbers are used at the beginning: ``` permutations [1;2;3] Set.empty;; ```
286,441
<pre><code>from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "single.py"}], zipfile = None, ) </code></pre> <p>in this setup file for py2exe where it says single.py is that where I place the name of my program?</p>
[ { "answer_id": 286484, "author": "TheObserver", "author_id": 20879, "author_profile": "https://Stackoverflow.com/users/20879", "pm_score": 2, "selected": false, "text": "<p>Yes. Are you making a windowing application or a console application? See the example setup.py files that came with py2exe.</p>\n" }, { "answer_id": 286495, "author": "Denes Tarjan", "author_id": 17617, "author_profile": "https://Stackoverflow.com/users/17617", "pm_score": 3, "selected": false, "text": "<p>I don't know your py2exe tool, but we usually use this way to convert py to exe:</p>\n\n<ol>\n<li><p>Download and install Standard Python Software:\n<a href=\"http://www.python.org/download/\" rel=\"nofollow noreferrer\">http://www.python.org/download/</a></p></li>\n<li><p>Download PyInstaller via link below:\n<a href=\"http://pyinstaller.python-hosting.com/\" rel=\"nofollow noreferrer\">http://pyinstaller.python-hosting.com/</a></p></li>\n<li><p>Unpack the archive, that you have downloaded! \nIn this examople, the directory of the unpacked files: </p></li>\n<li><p>In the <code>&lt;UNPACKED_FILES_DIR&gt;</code> directory, run Configure.py. \nIt must be run before trying to build anything.</p></li>\n<li><p>Create a spec file for your project:</p>\n\n<pre><code>python Makespec.py -F -p &lt;PYTHON_LIB_PATH&gt; &lt;PYTHON_SCRIPT&gt;\n -F: Produce a single file deployment.\n -p &lt;PYTHON_LIB_PATH&gt;: Set base path for import (like using PYTHONPATH).\n ( e.g.: C:\\Program Files\\Python24\\Lib\\ )\n &lt;PYTHON_SCRIPT&gt;: Path to python script.\n</code></pre></li>\n</ol>\n\n<p>6 Build your project!</p>\n\n<pre><code> python Build.py &lt;SPECFILE&gt;\n &lt;SPECFILE&gt;: Path to the specfile, that have been created in step 4! \n\n The full path to &lt;SPECFILE&gt;:\n &lt;UNPACKED_FILES_DIR&gt;/&lt;PYTHON_SCRIPT&gt;/&lt;PYTHON_SCRIPT&gt;.spec\n</code></pre>\n\n<ol start=\"7\">\n<li>The binary file will be placed in the directory of <code>&lt;SPECFILE&gt;</code>.</li>\n</ol>\n" }, { "answer_id": 7978609, "author": "Cees Timmerman", "author_id": 819417, "author_profile": "https://Stackoverflow.com/users/819417", "pm_score": 2, "selected": false, "text": "<p>If you can restrict your code, then <a href=\"http://shed-skin.blogspot.com/\" rel=\"nofollow noreferrer\">Shed Skin</a>, <a href=\"http://www.rfk.id.au/blog/entry/compiling-rpython-programs/\" rel=\"nofollow noreferrer\">PyPy</a>, or <a href=\"https://stackoverflow.com/questions/2581784/can-cython-compile-to-an-exe\">Cython</a> make true, fast executables.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file\">Py2exe, PyInstaller, or bbfreeze</a> can package Python up to 2.7 into single executables.</p>\n\n<p><a href=\"https://stackoverflow.com/q/2553886/819417\">Cx_Freeze</a> packages Python up to 3.x into an executable plus many other files.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "single.py"}], zipfile = None, ) ``` in this setup file for py2exe where it says single.py is that where I place the name of my program?
I don't know your py2exe tool, but we usually use this way to convert py to exe: 1. Download and install Standard Python Software: <http://www.python.org/download/> 2. Download PyInstaller via link below: <http://pyinstaller.python-hosting.com/> 3. Unpack the archive, that you have downloaded! In this examople, the directory of the unpacked files: 4. In the `<UNPACKED_FILES_DIR>` directory, run Configure.py. It must be run before trying to build anything. 5. Create a spec file for your project: ``` python Makespec.py -F -p <PYTHON_LIB_PATH> <PYTHON_SCRIPT> -F: Produce a single file deployment. -p <PYTHON_LIB_PATH>: Set base path for import (like using PYTHONPATH). ( e.g.: C:\Program Files\Python24\Lib\ ) <PYTHON_SCRIPT>: Path to python script. ``` 6 Build your project! ``` python Build.py <SPECFILE> <SPECFILE>: Path to the specfile, that have been created in step 4! The full path to <SPECFILE>: <UNPACKED_FILES_DIR>/<PYTHON_SCRIPT>/<PYTHON_SCRIPT>.spec ``` 7. The binary file will be placed in the directory of `<SPECFILE>`.
286,459
<p>I'm using VB .NET 2005 and Exchange Server 2003 installed I have found some code which gives me the ability to connect in an Exchange Server and create an appointment. The thing is that I cannot find the CDO. Appointment. Where can I find it and make the below code to work ? I have tried all the examples with CDO and Outlook. I believe that the below code need to be produced in an Exchange environment and use CDOEX.DLL ? Appreciate any help or ideas you can give me. Thank you</p> <p>[Sample Code]</p> <pre><code>sURL = "http://ExchangeServername/Exchange/testuser/calendar" Dim oCn As ADODB.Connection = New ADODB.Connection() 'oCn.Provider = "exoledb.datasource"; 'I am using the below provider because I am in the client side oCn.Provider = "MSDAIPP.DSO" oCn.Open(sURL, "testuser", "q1w2e3r4t5", 0) If oCn.State = 1 Then MsgBox("Good Connection") Else MsgBox("Bad Connection") Return End If Dim iConfg As CDO.Configuration = New CDO.Configuration() Dim oFields As ADODB.Fields oFields = iConfg.Fields oFields.Item(CDO.CdoCalendar.cdoTimeZoneIDURN).Value = CDO.CdoTimeZoneId.cdoAthens 'oFields.Item(CDO.CdoConfiguration.cdoSendEmailAddress).Value = "[email protected]" oFields.Update() Dim oApp As CDO.Appointment = New CDO.Appointment() oApp.Configuration = iConfg oApp.StartTime = Convert.ToDateTime("10/11/2001 10:00:00 AM") oApp.EndTime = Convert.ToDateTime("10/11/2001 11:00:00 AM") oApp.Location = "My Location" oApp.Subject = "Test: Create Meeting in VB.NET" oApp.TextBody = "Hello..." '' Add recurring appointment '' Every Thursday starting today, and repeat 3 times. '' Save to the folder oApp.DataSource.SaveToContainer(sURL, , _ ADODB.ConnectModeEnum.adModeReadWrite, _ ADODB.RecordCreateOptionsEnum.adCreateNonCollection, _ ADODB.RecordOpenOptionsEnum.adOpenSource, _ "", "") oCn.Close() oApp = Nothing oCn = Nothing oFields = Nothing </code></pre>
[ { "answer_id": 293356, "author": "Patrick de Kleijn", "author_id": 33221, "author_profile": "https://Stackoverflow.com/users/33221", "pm_score": 2, "selected": false, "text": "<p>CDO.Appointment indeed is part of cdoex.dll (Collaboration Data Objects for Exchange) that comes with some versions of Exchange, SPS and Office. You can download and register cdoex.dll on your machine, and reference it in your VB.Net application.</p>\n\n<p>These posts should be helpful:</p>\n\n<ul>\n<li><a href=\"http://support.microsoft.com/kb/310557\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/310557</a></li>\n<li><a href=\"http://mrspeaker.webeisteddfod.com/2005/05/02/cdoex/\" rel=\"nofollow noreferrer\">http://mrspeaker.webeisteddfod.com/2005/05/02/cdoex/</a></li>\n</ul>\n" }, { "answer_id": 293360, "author": "Patrick de Kleijn", "author_id": 33221, "author_profile": "https://Stackoverflow.com/users/33221", "pm_score": 0, "selected": false, "text": "<p>If you cannot find a copy of <code>cdoex.dll</code> on your local PC or server, try these downloads:</p>\n\n<p><a href=\"http://www.google.nl/search?q=download+CDOEX.DLL\" rel=\"nofollow noreferrer\">http://www.google.nl/search?q=download+CDOEX.DLL</a></p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using VB .NET 2005 and Exchange Server 2003 installed I have found some code which gives me the ability to connect in an Exchange Server and create an appointment. The thing is that I cannot find the CDO. Appointment. Where can I find it and make the below code to work ? I have tried all the examples with CDO and Outlook. I believe that the below code need to be produced in an Exchange environment and use CDOEX.DLL ? Appreciate any help or ideas you can give me. Thank you [Sample Code] ``` sURL = "http://ExchangeServername/Exchange/testuser/calendar" Dim oCn As ADODB.Connection = New ADODB.Connection() 'oCn.Provider = "exoledb.datasource"; 'I am using the below provider because I am in the client side oCn.Provider = "MSDAIPP.DSO" oCn.Open(sURL, "testuser", "q1w2e3r4t5", 0) If oCn.State = 1 Then MsgBox("Good Connection") Else MsgBox("Bad Connection") Return End If Dim iConfg As CDO.Configuration = New CDO.Configuration() Dim oFields As ADODB.Fields oFields = iConfg.Fields oFields.Item(CDO.CdoCalendar.cdoTimeZoneIDURN).Value = CDO.CdoTimeZoneId.cdoAthens 'oFields.Item(CDO.CdoConfiguration.cdoSendEmailAddress).Value = "[email protected]" oFields.Update() Dim oApp As CDO.Appointment = New CDO.Appointment() oApp.Configuration = iConfg oApp.StartTime = Convert.ToDateTime("10/11/2001 10:00:00 AM") oApp.EndTime = Convert.ToDateTime("10/11/2001 11:00:00 AM") oApp.Location = "My Location" oApp.Subject = "Test: Create Meeting in VB.NET" oApp.TextBody = "Hello..." '' Add recurring appointment '' Every Thursday starting today, and repeat 3 times. '' Save to the folder oApp.DataSource.SaveToContainer(sURL, , _ ADODB.ConnectModeEnum.adModeReadWrite, _ ADODB.RecordCreateOptionsEnum.adCreateNonCollection, _ ADODB.RecordOpenOptionsEnum.adOpenSource, _ "", "") oCn.Close() oApp = Nothing oCn = Nothing oFields = Nothing ```
CDO.Appointment indeed is part of cdoex.dll (Collaboration Data Objects for Exchange) that comes with some versions of Exchange, SPS and Office. You can download and register cdoex.dll on your machine, and reference it in your VB.Net application. These posts should be helpful: * <http://support.microsoft.com/kb/310557> * <http://mrspeaker.webeisteddfod.com/2005/05/02/cdoex/>
286,486
<p>In relation to <a href="https://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated">another question</a>, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".</p> <p>What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.</p> <p>I want the program to be cross-platform, but I expect I may have to use <strong>os.name</strong> or something to determine which path code block to use.</p>
[ { "answer_id": 286499, "author": "TheObserver", "author_id": 20879, "author_profile": "https://Stackoverflow.com/users/20879", "pm_score": 0, "selected": false, "text": "<p>If your file is always in the same directory as your program then:</p>\n\n<pre><code>def _isInProductionMode():\n \"\"\" returns True when running the exe, \n False when running from a script, ie development mode.\n \"\"\"\n return (hasattr(sys, \"frozen\") or # new py2exe\n hasattr(sys, \"importers\") # old py2exe\n or imp.is_frozen(\"__main__\")) #tools/freeze\n\ndef _getAppDir():\n \"\"\" returns the directory name of the script or the directory \n name of the exe\n \"\"\"\n if _isInProductionMode():\n return os.path.dirname(sys.executable)\n return os.path.dirname(__file__)\n</code></pre>\n\n<p>should work. Also, I've used py2exe for my own application, and haven't tested it with other exe conversion apps. </p>\n" }, { "answer_id": 286801, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>What -- specifically -- do you mean by \"calling a file...foo.py\"?</p>\n\n<ol>\n<li><p>Import? If so, the path is totally outside of your program. Set the <code>PYTHONPATH</code> environment variable with <code>.</code> or <code>c:\\</code> or whatever at the shell level. You can, for example, write 2-line shell scripts to set an environment variable and run Python.</p>\n\n<p>Windows</p>\n\n<pre><code>SET PYTHONPATH=C:\\path\\to\\library\npython myapp.py\n</code></pre>\n\n<p>Linux</p>\n\n<pre><code>export PYTHONPATH=./relative/path\npython myapp.py\n</code></pre></li>\n<li><p>Execfile? Consider using import.</p></li>\n<li><p>Read and Eval? Consider using import.</p></li>\n</ol>\n\n<p>If the PYTHONPATH is too complicated, then put your module in the Python lib/site-packages directory, where it's put onto the PYTHONPATH by default for you.</p>\n" }, { "answer_id": 286802, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 4, "selected": true, "text": "<p>Simple answer: You work out the absolute path based on the environment.</p>\n\n<p>What you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows).</p>\n\n<p>So, first some general things:</p>\n\n<ol>\n<li><code>os.path</code> - standard library module with lots of cross-platform path manipulation. Your best friend. \"Follow the os.path\" I once read in a book.</li>\n<li><code>__file__</code> - The location of the current module.</li>\n<li><code>sys.executable</code> - The location of the running Python.</li>\n</ol>\n\n<p>Now you can fairly much glean anything you want from these three sources. The functions from os.path will help you get around the tree:</p>\n\n<ul>\n<li><code>os.path.join('path1', 'path2')</code> - join path segments in a cross-platform way</li>\n<li><code>os.path.expanduser('a_path')</code> - find the path <code>a_path</code> in the user's home directory</li>\n<li><code>os.path.abspath('a_path')</code> - convert a relative path to an absolute path</li>\n<li><code>os.path.dirname('a_path')</code> - get the directory that a path is in</li>\n<li>many many more...</li>\n</ul>\n\n<p>So combining this, for example:</p>\n\n<pre><code># script1.py\n# Get the path to the script2.py in the same directory\nimport os\nthis_script_path = os.path.abspath(__file__)\nthis_dir_path = os.path.dirname(this_script_path)\nscript2_path = os.path.join(this_dir_path, 'script2.py')\nprint script2_path\n</code></pre>\n\n<p>And running it:</p>\n\n<pre><code>ali@work:~/tmp$ python script1.py \n/home/ali/tmp/script2.py\n</code></pre>\n\n<p>Now for your specific case, it seems you are slightly confused between the concept of a \"working directory\" and the \"directory that a script is in\". These can be the same, but they can also be different. For example the \"working directory\" can be changed, and so functions that use it might be able to find what they are looking for sometimes but not others. <code>subprocess.Popen</code> is an example of this.</p>\n\n<p>If you always pass paths absolutely, you will never get into working directory issues.</p>\n" }, { "answer_id": 286914, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": -1, "selected": false, "text": "<p>I figured out by using <strong>os.getcwd()</strong>. I also learned about using <strong>os.path.join</strong> to automatically determine the correct path format based on the OS. Here's the code:</p>\n\n<pre><code>def openNewRecord(self, event): # wxGlade: CharSheet.&lt;event_handler&gt;\n \"\"\"Create a new, blank record sheet.\"\"\"\n path = os.getcwd()\n subprocess.Popen(os.path.join(path, \"TW2K_char_rec_sheet.py\"), shell=True).stdout\n</code></pre>\n\n<p>It appears to be working. Thanks for the ideas.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
In relation to [another question](https://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated), how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in \*nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python\_project\foo.py". What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code. I want the program to be cross-platform, but I expect I may have to use **os.name** or something to determine which path code block to use.
Simple answer: You work out the absolute path based on the environment. What you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows). So, first some general things: 1. `os.path` - standard library module with lots of cross-platform path manipulation. Your best friend. "Follow the os.path" I once read in a book. 2. `__file__` - The location of the current module. 3. `sys.executable` - The location of the running Python. Now you can fairly much glean anything you want from these three sources. The functions from os.path will help you get around the tree: * `os.path.join('path1', 'path2')` - join path segments in a cross-platform way * `os.path.expanduser('a_path')` - find the path `a_path` in the user's home directory * `os.path.abspath('a_path')` - convert a relative path to an absolute path * `os.path.dirname('a_path')` - get the directory that a path is in * many many more... So combining this, for example: ``` # script1.py # Get the path to the script2.py in the same directory import os this_script_path = os.path.abspath(__file__) this_dir_path = os.path.dirname(this_script_path) script2_path = os.path.join(this_dir_path, 'script2.py') print script2_path ``` And running it: ``` ali@work:~/tmp$ python script1.py /home/ali/tmp/script2.py ``` Now for your specific case, it seems you are slightly confused between the concept of a "working directory" and the "directory that a script is in". These can be the same, but they can also be different. For example the "working directory" can be changed, and so functions that use it might be able to find what they are looking for sometimes but not others. `subprocess.Popen` is an example of this. If you always pass paths absolutely, you will never get into working directory issues.
286,493
<p>I use db2 v.9.1 on windows 2003 server so it can not use LPAD or RPAD functions scalar. because that functions support only z/OS right?</p> <p>Now, I use this way for pad zero when COLUMN1 type is VARCHAR</p> <pre><code> RIGHT('0000' || COLUMN1 ,4) AS RPAD LEFT('0000' || COLUMN1 ,4) AS LPAD </code></pre> <p>Have better way for replace LPAD or RPAD function?</p>
[ { "answer_id": 287402, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 1, "selected": false, "text": "<p>I think you probably want the <a href=\"http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0000842.htm\" rel=\"nofollow noreferrer\">REPEAT</a> scalar function.</p>\n" }, { "answer_id": 61216244, "author": "JOHN HOUZOURIS", "author_id": 13315027, "author_profile": "https://Stackoverflow.com/users/13315027", "pm_score": 0, "selected": false, "text": "<pre><code>REPEAT('0',4) || column_name\n</code></pre>\n\n<p>Now if you want to limit the 0 based on the number of characters you can use the <code>RIGHT</code> function and it would look something like this assuming your column is <code>varchar(10)</code>:</p>\n\n<p><code>RIGHT(REPEAT('0',4) || column_name, 10)</code> in this case if you have characters it will fill it with 4 preceding 0s but if you have 7 characters it would fill it with 3 0s.</p>\n\n<p>So you would have:<br>\n00001,<br>\n000012,<br>\n0000123,<br>\n00001234,<br>\n000012345,<br>\n0000123456,<br>\n0001234567,<br>\n0012345678,<br>\netc.</p>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24550/" ]
I use db2 v.9.1 on windows 2003 server so it can not use LPAD or RPAD functions scalar. because that functions support only z/OS right? Now, I use this way for pad zero when COLUMN1 type is VARCHAR ``` RIGHT('0000' || COLUMN1 ,4) AS RPAD LEFT('0000' || COLUMN1 ,4) AS LPAD ``` Have better way for replace LPAD or RPAD function?
I think you probably want the [REPEAT](http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0000842.htm) scalar function.
286,531
<p>Env.: Vista SP1, SQL Server Express 2005</p> <p>I'm able to connect to my localhost SQL Server using SQL Server Management Studio, using Windows authentication and, to the best of my knowledge, all default parameters, including network protocol.</p> <p>Now I try to connect using sqlcmd.exe to no avail:</p> <pre><code>C:\Program Files\Microsoft SQL Server\90\Tools\Binn&gt;sqlcmd -S \\PCSERGEHOME\SQLE XPRESS HResult 0x57, Level 16, State 1 Named Pipes Provider: Invalid parameter(s) found [87]. Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establi shing a connection to the server. When connecting to SQL Server 2005, this failu re may be caused by the fact that under the default settings SQL Server does not allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired. </code></pre> <p>I also tried to use -U PCSERGEHOME\Serge. I'm then prompted for my password but the result is the same.</p> <p>TIA for your help.</p>
[ { "answer_id": 286535, "author": "Dave", "author_id": 32938, "author_profile": "https://Stackoverflow.com/users/32938", "pm_score": 3, "selected": true, "text": "<p>Lose the leading \\\\</p>\n\n<p>Actually, try .\\XPRESS (period slash instance)</p>\n" }, { "answer_id": 286536, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 0, "selected": false, "text": "<p>Try </p>\n\n<ul>\n<li>Disabling the firewall</li>\n<li>Using localhost instead</li>\n<li>Check the Server setup (in management studio) to make sure remote connections are enabled</li>\n<li>Check the settings in Surface Area configuration and make sure all the transports are enabled and remote connections are enabled</li>\n</ul>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
Env.: Vista SP1, SQL Server Express 2005 I'm able to connect to my localhost SQL Server using SQL Server Management Studio, using Windows authentication and, to the best of my knowledge, all default parameters, including network protocol. Now I try to connect using sqlcmd.exe to no avail: ``` C:\Program Files\Microsoft SQL Server\90\Tools\Binn>sqlcmd -S \\PCSERGEHOME\SQLE XPRESS HResult 0x57, Level 16, State 1 Named Pipes Provider: Invalid parameter(s) found [87]. Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establi shing a connection to the server. When connecting to SQL Server 2005, this failu re may be caused by the fact that under the default settings SQL Server does not allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired. ``` I also tried to use -U PCSERGEHOME\Serge. I'm then prompted for my password but the result is the same. TIA for your help.
Lose the leading \\ Actually, try .\XPRESS (period slash instance)
286,533
<p>I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application. I'm trying to go in a file and read the lines and print them on the console.</p> <p>I've been able to do it with a while-loop, but I want to try it with a foreach loop.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace testing { public class Program { public static void Main(string[] args) { string file = @"C:\Temp\New Folder\New Text Document.txt"; using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { using(StreamReader sr = new StreamReader(fs)) { foreach(string line in file) { Console.WriteLine(line); } } } } } } </code></pre> <p>The error I keep getting for this is: Cannot convert type 'char' to 'string'</p> <p>The while loop, which does work, looks like this:</p> <pre><code>while((line = sr.ReadLine()) != null) { Console.WriteLine(line); } </code></pre> <p>I'm probably overlooking something really basic, but I can't see it.</p>
[ { "answer_id": 286539, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "<p>The problem is in:</p>\n\n<pre><code>foreach(string line in file)\n{\n Console.WriteLine(line);\n}\n</code></pre>\n\n<p>Its because the \"file\" is string, and string implements IEnumerable. But this enumerator returns \"char\" and \"char\" can not be implictly converted to string.</p>\n\n<p>You should use the while loop, as you sayd.</p>\n" }, { "answer_id": 286541, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": 0, "selected": false, "text": "<p>You are enumerating a string, and when you do that, you take one char at the time.</p>\n\n<p>Are you sure this is what you want?</p>\n\n<pre><code>foreach(string line in file)\n</code></pre>\n" }, { "answer_id": 286547, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "<p>Looks like homework to me ;)</p>\n\n<p>You're iterating over the filename (a string) itself which gives you one character at a time. Just use the while approach that correctly uses sr.ReadLine().</p>\n" }, { "answer_id": 286551, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 1, "selected": false, "text": "<p>Instead of using a <code>StreamReader</code> and then trying to find lines inside the <code>String file</code> variable, you can simply use <code>File.ReadAllLines</code>:</p>\n\n<pre><code>string[] lines = File.ReadAllLines(file);\nforeach(string line in lines)\n Console.WriteLine(line);\n</code></pre>\n" }, { "answer_id": 286552, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 0, "selected": false, "text": "<p>A simplistic (not memory efficient) approach of iterating every line in a file is</p>\n\n<pre><code>foreach (string line in File.ReadAllLines(file))\n{\n ..\n}\n</code></pre>\n" }, { "answer_id": 286553, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "<p>If you want to read a file line-by-line via foreach (in a reusable fashion), consider the following iterator block:</p>\n\n<pre><code> public static IEnumerable&lt;string&gt; ReadLines(string path)\n {\n using (StreamReader reader = File.OpenText(path))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n }\n</code></pre>\n\n<p>Note that this this is lazily evaluated - there is none of the buffering that you would associate with <code>File.ReadAllLines()</code>. The <code>foreach</code> syntax will ensure that the iterator is <code>Dispose()</code>d correctly even for exceptions, closing the file:</p>\n\n<pre><code>foreach(string line in ReadLines(file))\n{\n Console.WriteLine(line);\n}\n</code></pre>\n\n<hr>\n\n<p>(this bit is added just for interest...)</p>\n\n<p>Another advantage of this type of abstraction is that it plays beautifully with LINQ - i.e. it is easy to do transformations / filters etc with this approach:</p>\n\n<pre><code> DateTime minDate = new DateTime(2000,1,1);\n var query = from line in ReadLines(file)\n let tokens = line.Split('\\t')\n let person = new\n {\n Forname = tokens[0],\n Surname = tokens[1],\n DoB = DateTime.Parse(tokens[2])\n }\n where person.DoB &gt;= minDate\n select person;\n foreach (var person in query)\n {\n Console.WriteLine(\"{0}, {1}: born {2}\",\n person.Surname, person.Forname, person.DoB);\n }\n</code></pre>\n\n<p>And again, all evaluated lazily (no buffering).</p>\n" }, { "answer_id": 286554, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 0, "selected": false, "text": "<p>I presume you want something like this:</p>\n\n<pre><code>using ( FileStream fileStream = new FileStream( file, FileMode.Open, FileAccess.Read ) )\n{\n using ( StreamReader streamReader = new StreamReader( fileStream ) )\n {\n string line = \"\";\n while ( null != ( line = streamReader.ReadLine() ) )\n {\n Console.WriteLine( line );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 286556, "author": "Aleksandar", "author_id": 29511, "author_profile": "https://Stackoverflow.com/users/29511", "pm_score": 6, "selected": true, "text": "<p>To read all lines in New Text Document.txt:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace testing\n{\n public class Program\n {\n public static void Main(string[] args)\n {\n string file = @\"C:\\Temp\\New Folder\\New Text Document.txt\";\n using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))\n { \n using(StreamReader sr = new StreamReader(fs))\n {\n while(!sr.EndOfStream)\n {\n Console.WriteLine(sr.ReadLine());\n }\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 286598, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>I have a <code>LineReader</code> class in my <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"noreferrer\">MiscUtil</a> project. It's slightly more general than the solutions given here, mostly in terms of the way you can construct it:</p>\n\n<ul>\n<li>From a function returning a stream, in which case it will use UTF-8</li>\n<li>From a function returning a stream, and an encoding</li>\n<li>From a function which returns a text reader</li>\n<li>From just a filename, in which case it will use UTF-8</li>\n<li>From a filename and an encoding</li>\n</ul>\n\n<p>The class \"owns\" whatever resources it uses, and closes them appropriately. However, it does this without implementing <code>IDisposable</code> itself. This is why it takes <code>Func&lt;Stream&gt;</code> and <code>Func&lt;TextReader&gt;</code> instead of the stream or the reader directly - it needs to be able to defer the opening until it needs it. It's the iterator itself (which is automatically disposed by a <code>foreach</code> loop) which closes the resource.</p>\n\n<p>As Marc pointed out, this works really well in LINQ. One example I like to give is:</p>\n\n<pre><code>var errors = from file in Directory.GetFiles(logDirectory, \"*.log\")\n from line in new LineReader(file)\n select new LogEntry(line) into entry\n where entry.Severity == Severity.Error\n select entry;\n</code></pre>\n\n<p>This will stream all the errors from a whole bunch of log files, opening and closing as it goes. Combined with Push LINQ, you can do all kinds of nice stuff :)</p>\n\n<p>It's not a particularly \"tricky\" class, but it's really handy. Here's the full source, for convenience if you don't want to download MiscUtil. The licence for the source code is <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/licence.txt\" rel=\"noreferrer\">here</a>.</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nnamespace MiscUtil.IO\n{\n /// &lt;summary&gt;\n /// Reads a data source line by line. The source can be a file, a stream,\n /// or a text reader. In any case, the source is only opened when the\n /// enumerator is fetched, and is closed when the iterator is disposed.\n /// &lt;/summary&gt;\n public sealed class LineReader : IEnumerable&lt;string&gt;\n {\n /// &lt;summary&gt;\n /// Means of creating a TextReader to read from.\n /// &lt;/summary&gt;\n readonly Func&lt;TextReader&gt; dataSource;\n\n /// &lt;summary&gt;\n /// Creates a LineReader from a stream source. The delegate is only\n /// called when the enumerator is fetched. UTF-8 is used to decode\n /// the stream into text.\n /// &lt;/summary&gt;\n /// &lt;param name=\"streamSource\"&gt;Data source&lt;/param&gt;\n public LineReader(Func&lt;Stream&gt; streamSource)\n : this(streamSource, Encoding.UTF8)\n {\n }\n\n /// &lt;summary&gt;\n /// Creates a LineReader from a stream source. The delegate is only\n /// called when the enumerator is fetched.\n /// &lt;/summary&gt;\n /// &lt;param name=\"streamSource\"&gt;Data source&lt;/param&gt;\n /// &lt;param name=\"encoding\"&gt;Encoding to use to decode the stream\n /// into text&lt;/param&gt;\n public LineReader(Func&lt;Stream&gt; streamSource, Encoding encoding)\n : this(() =&gt; new StreamReader(streamSource(), encoding))\n {\n }\n\n /// &lt;summary&gt;\n /// Creates a LineReader from a filename. The file is only opened\n /// (or even checked for existence) when the enumerator is fetched.\n /// UTF8 is used to decode the file into text.\n /// &lt;/summary&gt;\n /// &lt;param name=\"filename\"&gt;File to read from&lt;/param&gt;\n public LineReader(string filename)\n : this(filename, Encoding.UTF8)\n {\n }\n\n /// &lt;summary&gt;\n /// Creates a LineReader from a filename. The file is only opened\n /// (or even checked for existence) when the enumerator is fetched.\n /// &lt;/summary&gt;\n /// &lt;param name=\"filename\"&gt;File to read from&lt;/param&gt;\n /// &lt;param name=\"encoding\"&gt;Encoding to use to decode the file\n /// into text&lt;/param&gt;\n public LineReader(string filename, Encoding encoding)\n : this(() =&gt; new StreamReader(filename, encoding))\n {\n }\n\n /// &lt;summary&gt;\n /// Creates a LineReader from a TextReader source. The delegate\n /// is only called when the enumerator is fetched\n /// &lt;/summary&gt;\n /// &lt;param name=\"dataSource\"&gt;Data source&lt;/param&gt;\n public LineReader(Func&lt;TextReader&gt; dataSource)\n {\n this.dataSource = dataSource;\n }\n\n /// &lt;summary&gt;\n /// Enumerates the data source line by line.\n /// &lt;/summary&gt;\n public IEnumerator&lt;string&gt; GetEnumerator()\n {\n using (TextReader reader = dataSource())\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Enumerates the data source line by line.\n /// &lt;/summary&gt;\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 4373533, "author": "Bob", "author_id": 533193, "author_profile": "https://Stackoverflow.com/users/533193", "pm_score": 2, "selected": false, "text": "<p>Slightly more elegant is the following...</p>\n\n<pre><code>using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))\n{\n using (var streamReader = new StreamReader(fileStream))\n {\n while (!streamReader.EndOfStream)\n {\n yield return reader.ReadLine();\n }\n }\n}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application. I'm trying to go in a file and read the lines and print them on the console. I've been able to do it with a while-loop, but I want to try it with a foreach loop. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace testing { public class Program { public static void Main(string[] args) { string file = @"C:\Temp\New Folder\New Text Document.txt"; using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { using(StreamReader sr = new StreamReader(fs)) { foreach(string line in file) { Console.WriteLine(line); } } } } } } ``` The error I keep getting for this is: Cannot convert type 'char' to 'string' The while loop, which does work, looks like this: ``` while((line = sr.ReadLine()) != null) { Console.WriteLine(line); } ``` I'm probably overlooking something really basic, but I can't see it.
To read all lines in New Text Document.txt: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace testing { public class Program { public static void Main(string[] args) { string file = @"C:\Temp\New Folder\New Text Document.txt"; using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { using(StreamReader sr = new StreamReader(fs)) { while(!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); } } } } } } ```
286,543
<p>I have a checkbox in GridViewColumn which i use for show/change database value. The click event for the checkbox is used for change value in the database. For handling the state of property "IsChecked" I'm using datatrigger and a setter, se xaml code below:</p> <pre><code>&lt;Style TargetType="CheckBox"&gt; &lt;Setter Property="IsEnabled" Value="True" /&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding Path=ID, Converter={StaticResource Converter}}" Value="true"&gt; &lt;Setter Property="IsChecked" Value="True"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>The binding works great until I click the checkbox. After I clicked the checkbox for the first time the state of the property "IsChecked" don't updates if a manually in the Database change the value which i mapped to the property "IsChecked". If I map for example the same value to the property "Content" of the checkbox the trigger works fine even after I've clicked the checkbox. </p> <p>Does anyone no whats the problem is?</p>
[ { "answer_id": 286764, "author": "OliK", "author_id": 23578, "author_profile": "https://Stackoverflow.com/users/23578", "pm_score": 0, "selected": false, "text": "<p>You can try to add a second data trigger to set the checkbox to false. As I can see from your code you set the IsChecked only to true, but never to false.</p>\n" }, { "answer_id": 286901, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 0, "selected": false, "text": "<p>In stead of using Click to determine the changes, perhaps you can use the Checked and Unchecked events ?</p>\n" }, { "answer_id": 286918, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": true, "text": "<p>Shouldn't </p>\n\n<pre><code>&lt;Style TargetType=\"CheckBox\"&gt;\n</code></pre>\n\n<p>instead be:</p>\n\n<pre><code> &lt;Style TargetType=\"{x:Type CheckBox}\"&gt;\n</code></pre>\n\n<p>Edit:</p>\n\n<p>you could try this:</p>\n\n<pre><code> &lt;Style TargetType=\"{x:Type CheckBox}\" &gt;\n &lt;Setter Property=\"IsChecked\" Value=\"{Binding Path=ID, Converter={StaticResource Converter}}\" /&gt;\n &lt;/Style&gt;\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37271/" ]
I have a checkbox in GridViewColumn which i use for show/change database value. The click event for the checkbox is used for change value in the database. For handling the state of property "IsChecked" I'm using datatrigger and a setter, se xaml code below: ``` <Style TargetType="CheckBox"> <Setter Property="IsEnabled" Value="True" /> <Style.Triggers> <DataTrigger Binding="{Binding Path=ID, Converter={StaticResource Converter}}" Value="true"> <Setter Property="IsChecked" Value="True"/> </DataTrigger> </Style.Triggers> </Style> ``` The binding works great until I click the checkbox. After I clicked the checkbox for the first time the state of the property "IsChecked" don't updates if a manually in the Database change the value which i mapped to the property "IsChecked". If I map for example the same value to the property "Content" of the checkbox the trigger works fine even after I've clicked the checkbox. Does anyone no whats the problem is?
Shouldn't ``` <Style TargetType="CheckBox"> ``` instead be: ``` <Style TargetType="{x:Type CheckBox}"> ``` Edit: you could try this: ``` <Style TargetType="{x:Type CheckBox}" > <Setter Property="IsChecked" Value="{Binding Path=ID, Converter={StaticResource Converter}}" /> </Style> ```
286,549
<p>Can PL/SQL procedure in Oracle know it's own name?</p> <p>Let me explain:</p> <pre><code>CREATE OR REPLACE procedure some_procedure is v_procedure_name varchar2(32); begin v_procedure_name := %%something%%; end; </code></pre> <p>After <code>%%something%%</code> executes, variable <code>v_procedure_name</code> should contain 'SOME_PROCEDURE'. It is also OK if it contains <code>object_id</code> of that procedure, so I can look up name in <code>all_objects</code>.</p>
[ { "answer_id": 286569, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 6, "selected": true, "text": "<p>Try:</p>\n\n<pre><code>v_procedure_name := $$PLSQL_UNIT;\n</code></pre>\n\n<p>There's also $$PLSQL_LINE if you want to know which line number you are on.</p>\n" }, { "answer_id": 286668, "author": "Gary Myers", "author_id": 25714, "author_profile": "https://Stackoverflow.com/users/25714", "pm_score": 2, "selected": false, "text": "<p>If you are pre-10g, you can 'dig' (parse) it out of\ndbms_utility.format_call_stack\nProcedures/functions in packages can be overloaded (and nested), so the package name/line number is normally better than the name.</p>\n" }, { "answer_id": 18705074, "author": "T. L. Jones", "author_id": 2762494, "author_profile": "https://Stackoverflow.com/users/2762494", "pm_score": 2, "selected": false, "text": "<p>In 10g and 11g I use the \"owa_util.get_procedure\" function. I normally use this in packages as it will also return the name of an internal procedure or function as part of the package name, i.e. (package_name).(procedure name). I use this to provide a generic <code>EXCEPTION</code> template for identifying where an exception occured.</p>\n\n<pre><code>CREATE OR REPLACE procedure some_procedure is\n v_procedure_name varchar2(32);\nbegin\n v_procedure_name := owa_util.get_procedure;\nend;\n\nCREATE OR REPLACE PACKAGE some_package\nAS\n FUNCTION v_function_name\n RETURN DATE;\nEND;\n/\nCREATE OR REPLACE PACKAGE BODY some_package\nAS\n FUNCTION v_function_name\n RETURN DATE\n IS\n BEGIN\n RETURN SYSDATE;\n EXCEPTION\n WHEN OTHERS THEN\n DBMS_OUTPUT.PUT_LINE('ERROR IN '||owa_util.get_procedure);\n DBMS_OUTPUT.PUT_LINE(SQLERRM);\n END;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 51368272, "author": "Howard Shulman", "author_id": 10089985, "author_profile": "https://Stackoverflow.com/users/10089985", "pm_score": 0, "selected": false, "text": "<p>Here's a neat function that takes advantage of REGEXP_SUBSTR.\nI've tested it in a package (and it even works if another procedure in the package calls it):</p>\n\n<pre><code>FUNCTION SET_PROC RETURN VARCHAR2 IS\nBEGIN\n RETURN NVL(REGEXP_SUBSTR(DBMS_UTILITY.FORMAT_CALL_STACK, \n 'procedure.+\\.(.+)\\s', 1,1,'i',1), 'UNDEFINED');\nEND SET_PROC;\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23220/" ]
Can PL/SQL procedure in Oracle know it's own name? Let me explain: ``` CREATE OR REPLACE procedure some_procedure is v_procedure_name varchar2(32); begin v_procedure_name := %%something%%; end; ``` After `%%something%%` executes, variable `v_procedure_name` should contain 'SOME\_PROCEDURE'. It is also OK if it contains `object_id` of that procedure, so I can look up name in `all_objects`.
Try: ``` v_procedure_name := $$PLSQL_UNIT; ``` There's also $$PLSQL\_LINE if you want to know which line number you are on.
286,565
<p>I'm using a QTableWidget to display several rows. Some of these rows should reflect an error and their text color is changed :</p> <p>Rows reflecting that there is no error are displayed with a default color (black text on white background on my computer).<br> Rows reflecting that there is an error are displayed with a red text color (which is red text on white background on my computer).</p> <p>This is all fine as long as there is no selection. As soon as a row is selected, no matter of the unselected text color, the text color becomes always white (on my computer) over a blue background.</p> <p>This is something I would like to change to get the following :<br> When a row is selected, if the row is reflecting there is no error, I would like it to be displayed with white text on blue background (default behavior).<br> If the row is reflecting an error and is selected, I would like it to be displayed with red text on blue background.</p> <p>So far I have only been able to change the selection color for the whole QTableWidget, which is not what I want !</p>
[ { "answer_id": 287660, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 0, "selected": false, "text": "<p>You could, of course, inherit from the table widget and override the paint event, but I don't think that is what you want to do.</p>\n\n<p>Instead, should use the <code>QAbstractItemDelegate</code> functionality. You could either create one to always be used for error rows, and set the error rows to use that delegate, or make a general one that knows how to draw both types of rows. The second method is what I would recommend. Then, your delegate draws the rows appropriately, even for the selected row.</p>\n" }, { "answer_id": 298160, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 4, "selected": true, "text": "<p>Answering myself, here is what I ended up doing : a delegate.</p>\n\n<p>This delegate will check the foreground color role of the item. If this foreground color is not the default WindowText color of the palette, that means a specific color is set and this specific color is used for the highlighted text color.</p>\n\n<p>I'm not sure if this is very robust, but at least it is working fine on Windows.</p>\n\n<pre><code>class MyItemDelegate: public QItemDelegate\n{\npublic:\n MyItemDelegate(QObject* pParent = 0) : QItemDelegate(pParent)\n {\n }\n\n void paint(QPainter* pPainter, const QStyleOptionViewItem&amp; rOption, const QModelIndex&amp; rIndex) const \n {\n QStyleOptionViewItem ViewOption(rOption);\n\n QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value&lt;QColor&gt;();\n if (ItemForegroundColor.isValid())\n {\n if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))\n {\n ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);\n }\n }\n QItemDelegate::paint(pPainter, ViewOption, rIndex);\n }\n};\n</code></pre>\n\n<p>Here is how to use it :</p>\n\n<pre><code>QTableWidget* pTable = new QTableWidget(...);\npTable-&gt;setItemDelegate(new MyItemDelegate(this));\n</code></pre>\n" }, { "answer_id": 326736, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 1, "selected": false, "text": "<p>It looks ok, but you might want to look at the documentation of <code>QStyleOption</code> it can tell you wether the item drawn is selected or not, you don't have to look at the draw color to do that. I would probably give the model class a user role that returns whether the data is valid or not and then make the color decision based on that. I.e. <code>rIndex.data(ValidRole)</code> would return wether the data at this index is valid or not.</p>\n\n<p>I don't know if you tried overriding data for the BackgroundRole and returning a custom color, Qt might do the right thing if you change the color there</p>\n" }, { "answer_id": 406653, "author": "Henrik Hartz", "author_id": 50830, "author_profile": "https://Stackoverflow.com/users/50830", "pm_score": 0, "selected": false, "text": "<p>You could use e.g. a <a href=\"http://doc.trolltech.com/4.4/qsortfilterproxymodel.html\" rel=\"nofollow noreferrer\">proxy model</a> for this where you return a different color if you have an error for the specific modelindex;</p>\n\n<pre><code> QVariant MySortFilterProxyModel::data(const QModelIndex &amp; index, int role = Qt::DisplayRole) {\n // assuming error state and modelindex row match\n if (role==Qt::BackgroundRole)\n return Qt::red;\n }\n</code></pre>\n" }, { "answer_id": 1009553, "author": "Krsna", "author_id": 105627, "author_profile": "https://Stackoverflow.com/users/105627", "pm_score": 2, "selected": false, "text": "<p>What you'll want to do is connect the <code>selectionChanged()</code> signal emitted by the QTableWidget's QItemSelectionModel to a slot, say <code>OnTableSelectionChanged()</code>. In your slot, you could then use QStyleSheets to set the selection colours as follows:</p>\n\n<pre><code>if (noError)\n{\n pTable-&gt;setStyleSheet(\"QTableView {selection-background-color: #000000; selection-color: #FFFFFF;}\");\n}\nelse\n{\n pTable-&gt;setStyleSheet(\"QTableView {selection-background-color: #FF0000; selection-color: #0000FF;}\");\n}\n</code></pre>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796/" ]
I'm using a QTableWidget to display several rows. Some of these rows should reflect an error and their text color is changed : Rows reflecting that there is no error are displayed with a default color (black text on white background on my computer). Rows reflecting that there is an error are displayed with a red text color (which is red text on white background on my computer). This is all fine as long as there is no selection. As soon as a row is selected, no matter of the unselected text color, the text color becomes always white (on my computer) over a blue background. This is something I would like to change to get the following : When a row is selected, if the row is reflecting there is no error, I would like it to be displayed with white text on blue background (default behavior). If the row is reflecting an error and is selected, I would like it to be displayed with red text on blue background. So far I have only been able to change the selection color for the whole QTableWidget, which is not what I want !
Answering myself, here is what I ended up doing : a delegate. This delegate will check the foreground color role of the item. If this foreground color is not the default WindowText color of the palette, that means a specific color is set and this specific color is used for the highlighted text color. I'm not sure if this is very robust, but at least it is working fine on Windows. ``` class MyItemDelegate: public QItemDelegate { public: MyItemDelegate(QObject* pParent = 0) : QItemDelegate(pParent) { } void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const { QStyleOptionViewItem ViewOption(rOption); QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>(); if (ItemForegroundColor.isValid()) { if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText)) { ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor); } } QItemDelegate::paint(pPainter, ViewOption, rIndex); } }; ``` Here is how to use it : ``` QTableWidget* pTable = new QTableWidget(...); pTable->setItemDelegate(new MyItemDelegate(this)); ```