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
130,396
<p>Is there a way to use constants in <strong>JavaScript</strong>?</p> <p>If not, what's the common practice for specifying variables that are used as constants?</p>
[ { "answer_id": 130398, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": false, "text": "<p>No, not in general. Firefox implements <code>const</code> but I know IE doesn't.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/130396#130399\"><strong>@John</strong></a> points to a common naming practice for consts that has been used for years in other languages, I see no reason why you couldn't use that. Of course that doesn't mean someone will not write over the variable's value anyway. :)</p>\n" }, { "answer_id": 130399, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 11, "selected": true, "text": "<p>Since <a href=\"https://www.ecma-international.org/ecma-262/6.0/\" rel=\"noreferrer\">ES2015</a>, JavaScript has a notion of <a href=\"https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations\" rel=\"noreferrer\"><code>const</code></a>:</p>\n\n<pre><code>const MY_CONSTANT = \"some-value\";\n</code></pre>\n\n<p>This will work in <a href=\"https://caniuse.com/#search=const\" rel=\"noreferrer\">pretty much all browsers except IE 8, 9 and 10</a>. Some may also need <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"noreferrer\">strict mode</a> enabled.</p>\n\n<p>You can use <code>var</code> with conventions like ALL_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code:</p>\n\n<pre><code>var MY_CONSTANT = \"some-value\";\n</code></pre>\n" }, { "answer_id": 130425, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>I use <code>const</code> instead of <code>var</code> in my Greasemonkey scripts, but it is because they will run only on Firefox...<br>\nName convention can be indeed the way to go, too (I do both!).</p>\n" }, { "answer_id": 130596, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": false, "text": "<p>For a while, I specified \"constants\" (which still weren't actually constants) in object literals passed through to <code>with()</code> statements. I thought it was so clever. Here's an example:</p>\n\n<pre><code>with ({\n MY_CONST : 'some really important value'\n}) {\n alert(MY_CONST);\n}\n</code></pre>\n\n<p>In the past, I also have created a <code>CONST</code> namespace where I would put all of my constants. Again, with the overhead. Sheesh.</p>\n\n<p>Now, I just do <code>var MY_CONST = 'whatever';</code> to <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">KISS</a>.</p>\n" }, { "answer_id": 131286, "author": "Burke", "author_id": 21980, "author_profile": "https://Stackoverflow.com/users/21980", "pm_score": 8, "selected": false, "text": "<p>Are you trying to protect the variables against modification? If so, then you can use a module pattern:</p>\n\n<pre><code>var CONFIG = (function() {\n var private = {\n 'MY_CONST': '1',\n 'ANOTHER_CONST': '2'\n };\n\n return {\n get: function(name) { return private[name]; }\n };\n})();\n\nalert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1\n\nCONFIG.MY_CONST = '2';\nalert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1\n\nCONFIG.private.MY_CONST = '2'; // error\nalert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1\n</code></pre>\n\n<p>Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.</p>\n\n<p>If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.</p>\n" }, { "answer_id": 687457, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 7, "selected": false, "text": "<p>The <code>const</code> keyword is in <a href=\"http://wiki.ecmascript.org/doku.php?id=harmony:const\" rel=\"noreferrer\">the ECMAScript 6 draft</a> but it thus far only enjoys a smattering of browser support: <a href=\"http://kangax.github.io/compat-table/es6/\" rel=\"noreferrer\">http://kangax.github.io/compat-table/es6/</a>. The syntax is:</p>\n\n<pre><code>const CONSTANT_NAME = 0;\n</code></pre>\n" }, { "answer_id": 1626809, "author": "C Nagle", "author_id": 196851, "author_profile": "https://Stackoverflow.com/users/196851", "pm_score": 6, "selected": false, "text": "<p>IE does support constants, sort of, e.g.:</p>\n\n<pre><code>&lt;script language=\"VBScript\"&gt;\n Const IE_CONST = True\n&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n if (typeof TEST_CONST == 'undefined') {\n const IE_CONST = false;\n }\n alert(IE_CONST);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 4270878, "author": "MTS", "author_id": 519307, "author_profile": "https://Stackoverflow.com/users/519307", "pm_score": 4, "selected": false, "text": "<p>In JavaScript, my preference is to use functions to return constant values. </p>\n\n<pre><code>function MY_CONSTANT() {\n return \"some-value\";\n}\n\n\nalert(MY_CONSTANT());\n</code></pre>\n" }, { "answer_id": 4637056, "author": "Not a Name", "author_id": 568455, "author_profile": "https://Stackoverflow.com/users/568455", "pm_score": 6, "selected": false, "text": "<p>ECMAScript 5 does introduce <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"noreferrer\"><code>Object.defineProperty</code></a>:</p>\n\n<pre><code>Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });\n</code></pre>\n\n<p>It's <a href=\"http://kangax.github.io/compat-table/es5/\" rel=\"noreferrer\">supported in every modern browser</a> (as well as IE ≥ 9).</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/3830800/object-defineproperty-in-es5\">Object.defineProperty in ES5?</a></p>\n" }, { "answer_id": 4714062, "author": "Rene Saarsoo", "author_id": 15982, "author_profile": "https://Stackoverflow.com/users/15982", "pm_score": 2, "selected": false, "text": "<p>In JavaScript my practice has been to avoid constants as much as I can and use strings instead. Problems with constants appear when you want to expose your constants to the outside world:</p>\n\n<p>For example one could implement the following Date API:</p>\n\n<pre><code>date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)\n</code></pre>\n\n<p>But it's much shorter and more natural to simply write:</p>\n\n<pre><code>date.add(5, \"days\").add(12, \"hours\")\n</code></pre>\n\n<p>This way \"days\" and \"hours\" really act like constants, because you can't change from the outside how many seconds \"hours\" represents. But it's easy to overwrite <code>MyModule.Date.HOUR</code>.</p>\n\n<p>This kind of approach will also aid in debugging. If Firebug tells you <code>action === 18</code> it's pretty hard to figure out what it means, but when you see <code>action === \"save\"</code> then it's immediately clear.</p>\n" }, { "answer_id": 5591741, "author": "Keith", "author_id": 698164, "author_profile": "https://Stackoverflow.com/users/698164", "pm_score": 4, "selected": false, "text": "<p>You can easily equip your script with a mechanism for constants that can be set but not altered. An attempt to alter them will generate an error. </p>\n\n<pre><code>/* author Keith Evetts 2009 License: LGPL \nanonymous function sets up: \nglobal function SETCONST (String name, mixed value) \nglobal function CONST (String name) \nconstants once set may not be altered - console error is generated \nthey are retrieved as CONST(name) \nthe object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided \n*/\n\n(function(){ \n var constants = {}; \n self.SETCONST = function(name,value) { \n if (typeof name !== 'string') { throw new Error('constant name is not a string'); } \n if (!value) { throw new Error(' no value supplied for constant ' + name); } \n else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); } \n else { \n constants[name] = value; \n return true; \n } \n }; \n self.CONST = function(name) { \n if (typeof name !== 'string') { throw new Error('constant name is not a string'); } \n if ( name in constants ) { return constants[name]; } \n else { throw new Error('constant ' + name + ' has not been defined'); } \n }; \n}()) \n\n\n// ------------- demo ---------------------------- \nSETCONST( 'VAT', 0.175 ); \nalert( CONST('VAT') );\n\n\n//try to alter the value of VAT \ntry{ \n SETCONST( 'VAT', 0.22 ); \n} catch ( exc ) { \n alert (exc.message); \n} \n//check old value of VAT remains \nalert( CONST('VAT') ); \n\n\n// try to get at constants object directly \nconstants['DODO'] = \"dead bird\"; // error \n</code></pre>\n" }, { "answer_id": 5840971, "author": "mgutt", "author_id": 318765, "author_profile": "https://Stackoverflow.com/users/318765", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\">Mozillas MDN Web Docs</a> contain good examples and explanations about <code>const</code>. Excerpt:</p>\n\n<pre><code>// define MY_FAV as a constant and give it the value 7\nconst MY_FAV = 7;\n\n// this will throw an error - Uncaught TypeError: Assignment to constant variable.\nMY_FAV = 20;\n</code></pre>\n\n<p>But it is sad that IE9/10 still does not support <code>const</code>. And the reason it's <a href=\"http://blogs.msdn.com/b/ie/archive/2010/08/25/chakra-interoperability-means-more-than-just-standards.aspx\" rel=\"nofollow noreferrer\">absurd</a>:</p>\n\n<blockquote>\n <p>So, what is IE9 doing with const? So\n far, our decision has been to not\n support it. It isn’t yet a consensus\n feature as it has never been available\n on all browsers.</p>\n \n <p>...</p>\n \n <p>In the end, it seems like the best\n long term solution for the web is to\n leave it out and to wait for\n standardization processes to run their\n course.</p>\n</blockquote>\n\n<p>They don't implement it because other browsers didn't implement it correctly?! Too afraid of making it better? Standards definitions or not, a constant is a constant: set once, never changed.</p>\n\n<p>And to all the ideas: Every function can be overwritten (XSS etc.). So there is no difference in <code>var</code> or <code>function(){return}</code>. <code>const</code> is the only real constant.</p>\n\n<p>Update:\nIE11 <a href=\"https://blogs.msdn.microsoft.com/ie/2013/11/07/ie11-for-windows-7-globally-available-for-consumers-and-businesses/\" rel=\"nofollow noreferrer\">supports</a> <code>const</code>:</p>\n\n<blockquote>\n <p>IE11 includes support for the well-defined and commonly used features of the emerging ECMAScript 6 standard including let, <strong><code>const</code></strong>, <code>Map</code>, <code>Set</code>, and <code>WeakMap</code>, as well as <code>__proto__</code> for improved interoperability.</p>\n</blockquote>\n" }, { "answer_id": 6501627, "author": "Webveloper", "author_id": 424671, "author_profile": "https://Stackoverflow.com/users/424671", "pm_score": 2, "selected": false, "text": "<p>Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.</p>\n\n<p>Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.</p>\n\n<p>Safari and Opera support the const keyword, but <em>you can change the const's value</em>.</p>\n\n<p>In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.</p>\n\n<pre><code>try{\n // i can haz const?\n eval(\"const FOO='{0}';\");\n // for reals?\n var original=FOO;\n try{\n FOO='?NO!';\n }catch(err1){\n // no err from Firefox/Chrome - fails silently\n alert('err1 '+err1);\n }\n alert('const '+FOO);\n if(FOO=='?NO!'){\n // changed in Sf/Op - set back to original value\n FOO=original;\n }\n}catch(err2){\n // IE fail\n alert('err2 '+err2);\n // set var (no var keyword - Chrome/Firefox complain about redefining const)\n FOO='{0}';\n alert('var '+FOO);\n}\nalert('FOO '+FOO);\n</code></pre>\n\n<p>What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least <em>some</em> browsers won't let bookmarklets or third-party script modify the value.</p>\n\n<p>Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.</p>\n" }, { "answer_id": 6742534, "author": "Derek 朕會功夫", "author_id": 283863, "author_profile": "https://Stackoverflow.com/users/283863", "pm_score": 4, "selected": false, "text": "<p>Forget IE and use the <code>const</code> keyword.</p>\n" }, { "answer_id": 9223523, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Introducing constants into JavaScript is at best a hack.</p>\n\n<p>A nice way of making persistent and globally accessible values in JavaScript would be declaring an object literal with some \"read-only\" properties like this:</p>\n\n<pre><code> my={get constant1(){return \"constant 1\"},\n get constant2(){return \"constant 2\"},\n get constant3(){return \"constant 3\"},\n get constantN(){return \"constant N\"}\n }\n</code></pre>\n\n<p>you'll have all your constants grouped in one single \"my\" accessory object where you can look for your stored values or anything else you may have decided to put there for that matter. Now let's test if it works: </p>\n\n<pre><code> my.constant1; &gt;&gt; \"constant 1\" \n my.constant1 = \"new constant 1\";\n my.constant1; &gt;&gt; \"constant 1\" \n</code></pre>\n\n<p>As we can see, the \"my.constant1\" property has preserved its original value. You've made yourself some nice 'green' temporary constants...</p>\n\n<p>But of course this will only guard you from accidentally modifying, altering, nullifying, or emptying your property constant value with a direct access as in the given example. </p>\n\n<p>Otherwise I still think that constants are for dummies. \nAnd I still think that exchanging your great freedom for a small corner of deceptive security is the worst trade possible.</p>\n" }, { "answer_id": 11789234, "author": "Steven Kapaun", "author_id": 1573097, "author_profile": "https://Stackoverflow.com/users/1573097", "pm_score": 3, "selected": false, "text": "<p>I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I've come up with a viable solution to this.</p>\n\n<p>It seems that most of the answers that I've come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts' answer that the constants object can not be accessed by the outside, but only from the functions on the inside.</p>\n\n<p>So I came up with this solution:</p>\n\n<p>Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the 'real' functions by having other functions call the 'real' functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are 'protected' on the inside and cannot be changed.</p>\n\n<pre><code>/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/\n\n(function(){\n /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST).\n They're the same just as he did them, the only things I changed are the variable names and the text\n of the error messages.\n */\n\n //object literal to hold the constants\n var j = {};\n\n /*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants.\n The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has\n to exist. If there is already a property with the same name in the object holder, then we throw an error.\n If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't\n see any of your coding call this function. You call the _makeDef() in your code and that function calls\n this function. - You can change the error messages to whatever you want them to say.\n */\n self._define = function(h,m) {\n if (typeof h !== 'string') { throw new Error('I don\\'t know what to do.'); }\n if (!m) { throw new Error('I don\\'t know what to do.'); }\n else if ((h in j) ) { throw new Error('We have a problem!'); }\n else {\n j[h] = m;\n return true;\n }\n };\n\n /*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this\n function. The argument 't' is the name of the const and doesn't need to be all caps because I set it\n to upper case within the function, 'y' is the value of the value of the const and has to exist. I\n make different variables to make it harder for a user to figure out whats going on. We then call the\n _define function with the two new variables. You call this function in your code to set the constant.\n You can change the error message to whatever you want it to say.\n */\n self._makeDef = function(t, y) {\n if(!y) { throw new Error('I don\\'t know what to do.'); return false; }\n q = t.toUpperCase();\n w = y;\n _define(q, w);\n };\n\n /*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The\n argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case\n within the function. I make a different variable to make it harder for a user to figure out whats going\n on. The function returns the _access function call. I pass the new variable and the original string\n along to the _access function. I do this because if a user is trying to get the value of something, if\n there is an error the argument doesn't get displayed with upper case in the error message. You call this\n function in your code to get the constant.\n */\n self._getDef = function(s) {\n z = s.toUpperCase();\n return _access(z, s);\n };\n\n /*Global function _access(String g, String f). I named it access because we 'access' the constant through\n this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name\n of the const, but its the original string that was passed to the _getDef() function. If there is an\n error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the\n constants are being stored. If there is a property with the same name in the object holder, we return\n the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and\n throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this\n function. You call the _getDef() function in your code and that function calls this function.\n You can change the error messages to whatever you want them to say.\n */\n self._access = function(g, f) {\n if (typeof g !== 'string') { throw new Error('I don\\'t know what to do.'); }\n if ( g in j ) { return j[g]; }\n else { if(!f) { f = g; } throw new Error('I don\\'t know what to do. I have no idea what \\''+f+'\\' is.'); }\n };\n\n /*The four variables below are private and cannot be accessed from the outside script except for the\n functions inside this anonymous function. These variables are strings of the four above functions and\n will be used by the all-dreaded eval() function to set them back to their original if any of them should\n be changed by a user trying to hack your code.\n */\n var _define_func_string = \"function(h,m) {\"+\" if (typeof h !== 'string') { throw new Error('I don\\\\'t know what to do.'); }\"+\" if (!m) { throw new Error('I don\\\\'t know what to do.'); }\"+\" else if ((h in j) ) { throw new Error('We have a problem!'); }\"+\" else {\"+\" j[h] = m;\"+\" return true;\"+\" }\"+\" }\";\n var _makeDef_func_string = \"function(t, y) {\"+\" if(!y) { throw new Error('I don\\\\'t know what to do.'); return false; }\"+\" q = t.toUpperCase();\"+\" w = y;\"+\" _define(q, w);\"+\" }\";\n var _getDef_func_string = \"function(s) {\"+\" z = s.toUpperCase();\"+\" return _access(z, s);\"+\" }\";\n var _access_func_string = \"function(g, f) {\"+\" if (typeof g !== 'string') { throw new Error('I don\\\\'t know what to do.'); }\"+\" if ( g in j ) { return j[g]; }\"+\" else { if(!f) { f = g; } throw new Error('I don\\\\'t know what to do. I have no idea what \\\\''+f+'\\\\' is.'); }\"+\" }\";\n\n /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions'\n The argument 'u' is the name of any of the four above function names you want to check. This function will\n check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then\n we use the eval() function to set the function back to its original coding using the function string\n variables above. This function will also throw an error depending upon the doError variable being set to true\n This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the\n doCodeCheck() function and that function calls this function. - You can change the error messages to\n whatever you want them to say.\n */\n self._doFunctionCheck = function(u) {\n var errMsg = 'We have a BIG problem! You\\'ve changed my code.';\n var doError = true;\n d = u;\n switch(d.toLowerCase())\n {\n case \"_getdef\":\n if(_getDef.toString().indexOf(\"z = s.toUpperCase();\") != -1) { /*do nothing*/ }\n else { eval(\"_getDef = \"+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n case \"_makedef\":\n if(_makeDef.toString().indexOf(\"q = t.toUpperCase();\") != -1) { /*do nothing*/ }\n else { eval(\"_makeDef = \"+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n case \"_define\":\n if(_define.toString().indexOf(\"else if((h in j) ) {\") != -1) { /*do nothing*/ }\n else { eval(\"_define = \"+_define_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n case \"_access\":\n if(_access.toString().indexOf(\"else { if(!f) { f = g; }\") != -1) { /*do nothing*/ }\n else { eval(\"_access = \"+_access_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n default:\n if(doError === true) { throw new Error('I don\\'t know what to do.'); }\n }\n };\n\n /*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument\n 'v' is the name of one of the first four functions in this script that you want to check. I make a different\n variable to make it harder for a user to figure out whats going on. You call this function in your code to check\n if any of the functions has been changed by the user.\n */\n self._doCodeCheck = function(v) {\n l = v;\n _doFunctionCheck(l);\n };\n}())\n</code></pre>\n\n<p>It also seems that security is really a problem and there is not way to 'hide' you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: <a href=\"http://javascriptcompressor.com/\">http://javascriptcompressor.com/</a>. (This is not my site, don't worry I'm not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.</p>\n\n<ol>\n<li>Copy all the code in the above script and paste it into the top textarea on the javascriptcompressor.com page.</li>\n<li>Check the Base62 encode checkbox, check the Shrink Variables checkbox.</li>\n<li>Press the Compress button.</li>\n<li>Paste and save it all in a .js file and add it to your page in the head of your page.</li>\n</ol>\n" }, { "answer_id": 13118516, "author": "user1635543", "author_id": 1635543, "author_profile": "https://Stackoverflow.com/users/1635543", "pm_score": 3, "selected": false, "text": "<p>My opinion (works only with objects).</p>\n\n<pre><code>var constants = (function(){\n var a = 9;\n\n //GLOBAL CONSTANT (through \"return\")\n window.__defineGetter__(\"GCONST\", function(){\n return a;\n });\n\n //LOCAL CONSTANT\n return {\n get CONST(){\n return a;\n }\n }\n})();\n\nconstants.CONST = 8; //9\nalert(constants.CONST); //9\n</code></pre>\n\n<p>Try! But understand - this is object, but not simple variable.</p>\n\n<p>Try also just:</p>\n\n<pre><code>const a = 9;\n</code></pre>\n" }, { "answer_id": 13194609, "author": "tenshou", "author_id": 778623, "author_profile": "https://Stackoverflow.com/users/778623", "pm_score": 4, "selected": false, "text": "<p>with the \"new\" Object api you can do something like this: </p>\n\n<pre><code>var obj = {};\nObject.defineProperty(obj, 'CONSTANT', {\n configurable: false\n enumerable: true,\n writable: false,\n value: \"your constant value\"\n});\n</code></pre>\n\n<p>take a look at <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty\">this</a> on the Mozilla MDN for more specifics. It's not a first level variable, as it is attached to an object, but if you have a scope, anything, you can attach it to that. <code>this</code> should work as well. \nSo for example doing this in the global scope will declare a pseudo constant value on the window (which is a really bad idea, you shouldn't declare global vars carelessly)</p>\n\n<pre><code>Object.defineProperty(this, 'constant', {\n enumerable: true, \n writable: false, \n value: 7, \n configurable: false\n});\n\n&gt; constant\n=&gt; 7\n&gt; constant = 5\n=&gt; 7\n</code></pre>\n\n<p>note: assignment will give you back the assigned value in the console, but the variable's value will not change</p>\n" }, { "answer_id": 13235597, "author": "isomorphismes", "author_id": 563329, "author_profile": "https://Stackoverflow.com/users/563329", "pm_score": 2, "selected": false, "text": "<p><code>Rhino.js</code> implements <code>const</code> in addition to what was mentioned above.</p>\n" }, { "answer_id": 13326757, "author": "codemuncher", "author_id": 1815283, "author_profile": "https://Stackoverflow.com/users/1815283", "pm_score": 3, "selected": false, "text": "<p>Clearly this shows the need for a standardized cross-browser const keyword.</p>\n\n<p>But for now:</p>\n\n<pre><code>var myconst = value;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Object['myconst'] = value;\n</code></pre>\n\n<p>Both seem sufficient and anything else is like shooting a fly with a bazooka.</p>\n" }, { "answer_id": 14723455, "author": "Sudhanshu Yadav", "author_id": 1906306, "author_profile": "https://Stackoverflow.com/users/1906306", "pm_score": 3, "selected": false, "text": "<p>Yet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.</p>\n\n<p>But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.</p>\n\n<p>Proper namespacing like</p>\n\n<pre><code>var iw_constant={\n name:'sudhanshu',\n age:'23'\n //all varibale come like this\n}\n</code></pre>\n\n<p>so while using it will be <code>iw_constant.name</code> or <code>iw_constant.age</code></p>\n\n<p>You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.</p>\n\n<p>ex: </p>\n\n<pre><code>Object.freeze(iw_constant);\n</code></pre>\n\n<p>For older browser you can use <a href=\"https://stackoverflow.com/questions/13117771/javascript-object-doesnt-support-method-freeze\">polyfill</a> for freeze method.</p>\n\n<hr>\n\n<p>If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants\nex:</p>\n\n<pre><code>var iw_constant= (function(){\n var allConstant={\n name:'sudhanshu',\n age:'23'\n //all varibale come like this\n\n };\n\n return function(key){\n allConstant[key];\n }\n };\n</code></pre>\n\n<p>//to get the value use\n<code>iw_constant('name')</code> or <code>iw_constant('age')</code></p>\n\n<hr>\n\n<p>** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)</p>\n" }, { "answer_id": 18954989, "author": "Krishna Kumar Chourasiya", "author_id": 1563174, "author_profile": "https://Stackoverflow.com/users/1563174", "pm_score": 2, "selected": false, "text": "<p>const keyword available in javscript language but it does not support IE browser. Rest all browser supported.</p>\n" }, { "answer_id": 20846329, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 4, "selected": false, "text": "<p>If you don't mind using functions:</p>\n\n<pre><code>var constant = function(val) {\n return function() {\n return val;\n }\n}\n</code></pre>\n\n<p>This approach gives you functions instead of regular variables, but it guarantees<sup>*</sup> that no one can alter the value once it's set.</p>\n\n<pre><code>a = constant(10);\n\na(); // 10\n\nb = constant(20);\n\nb(); // 20\n</code></pre>\n\n<p>I personally find this rather pleasant, specially after having gotten used to this pattern from knockout observables.</p>\n\n<p><sup><sub>*Unless someone redefined the function <code>constant</code> before you called it</sub></sup></p>\n" }, { "answer_id": 23462960, "author": "sam", "author_id": 822138, "author_profile": "https://Stackoverflow.com/users/822138", "pm_score": 6, "selected": false, "text": "<pre><code>\"use strict\";\n\nvar constants = Object.freeze({\n \"π\": 3.141592653589793 ,\n \"e\": 2.718281828459045 ,\n \"i\": Math.sqrt(-1)\n});\n\nconstants.π; // -&gt; 3.141592653589793\nconstants.π = 3; // -&gt; TypeError: Cannot assign to read only property 'π' …\nconstants.π; // -&gt; 3.141592653589793\n\ndelete constants.π; // -&gt; TypeError: Unable to delete property.\nconstants.π; // -&gt; 3.141592653589793\n</code></pre>\n\n<p>See <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"noreferrer\">Object.freeze</a>. You can <a href=\"https://stackoverflow.com/a/687457/822138\">use <code>const</code></a> if you want to make the <code>constants</code> reference read-only as well.</p>\n" }, { "answer_id": 25547960, "author": "rounce", "author_id": 1592759, "author_profile": "https://Stackoverflow.com/users/1592759", "pm_score": 2, "selected": false, "text": "<p>Another alternative is something like:</p>\n\n<pre><code>var constants = {\n MY_CONSTANT : \"myconstant\",\n SOMETHING_ELSE : 123\n }\n , constantMap = new function ConstantMap() {};\n\nfor(var c in constants) {\n !function(cKey) {\n Object.defineProperty(constantMap, cKey, {\n enumerable : true,\n get : function(name) { return constants[cKey]; }\n })\n }(c);\n}\n</code></pre>\n\n<p>Then simply: <code>var foo = constantMap.MY_CONSTANT</code></p>\n\n<p>If you were to <code>constantMap.MY_CONSTANT = \"bar\"</code> it would have no effect as we're trying to use an assignment operator with a getter, hence <code>constantMap.MY_CONSTANT === \"myconstant\"</code> would remain true.</p>\n" }, { "answer_id": 27646549, "author": "Şafak Gür", "author_id": 704144, "author_profile": "https://Stackoverflow.com/users/704144", "pm_score": 2, "selected": false, "text": "<p>An improved version of <a href=\"https://stackoverflow.com/a/131286/704144\">Burke's answer</a> that lets you do <code>CONFIG.MY_CONST</code> instead of <code>CONFIG.get('MY_CONST')</code>.</p>\n\n<p>It requires IE9+ or a real web browser.</p>\n\n<pre><code>var CONFIG = (function() {\n var constants = {\n 'MY_CONST': 1,\n 'ANOTHER_CONST': 2\n };\n\n var result = {};\n for (var n in constants)\n if (constants.hasOwnProperty(n))\n Object.defineProperty(result, n, { value: constants[n] });\n\n return result;\n}());\n</code></pre>\n\n<p><sub><em>* The properties are read-only, only if the initial values are immutable.</em></sub></p>\n" }, { "answer_id": 27646695, "author": "Muhammad Reda", "author_id": 863380, "author_profile": "https://Stackoverflow.com/users/863380", "pm_score": 2, "selected": false, "text": "<p>If it is worth mentioning, you can define constants in <a href=\"http://angularjs.org/\" rel=\"nofollow\">angular</a> using <a href=\"https://docs.angularjs.org/api/auto/service/$provide#constant\" rel=\"nofollow\"><code>$provide.constant()</code></a></p>\n\n<pre><code>angularApp.constant('YOUR_CONSTANT', 'value');\n</code></pre>\n" }, { "answer_id": 29994502, "author": "Gelin Luo", "author_id": 391227, "author_profile": "https://Stackoverflow.com/users/391227", "pm_score": 0, "selected": false, "text": "<p>Checkout <a href=\"https://www.npmjs.com/package/constjs\" rel=\"nofollow\">https://www.npmjs.com/package/constjs</a>, which provides three functions to create enum, string const and bitmap. The returned result is either <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow\">frozen</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal\" rel=\"nofollow\">sealed</a> thus you can't change/delete the properties after they are created, you can neither add new properties to the returned result</p>\n\n<p>create Enum:</p>\n\n<pre><code>var ConstJs = require('constjs');\n\nvar Colors = ConstJs.enum(\"blue red\");\n\nvar myColor = Colors.blue;\n\nconsole.log(myColor.isBlue()); // output true \nconsole.log(myColor.is('blue')); // output true \nconsole.log(myColor.is('BLUE')); // output true \nconsole.log(myColor.is(0)); // output true \nconsole.log(myColor.is(Colors.blue)); // output true \n\nconsole.log(myColor.isRed()); // output false \nconsole.log(myColor.is('red')); // output false \n\nconsole.log(myColor._id); // output blue \nconsole.log(myColor.name()); // output blue \nconsole.log(myColor.toString()); // output blue \n\n// See how CamelCase is used to generate the isXxx() functions \nvar AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');\nvar curMode = AppMode.LOG_IN;\n\nconsole.log(curMode.isLogIn()); // output true \nconsole.log(curMode.isSignUp()); // output false \nconsole.log(curMode.isForgotPassword()); // output false \n</code></pre>\n\n<p>Create String const:</p>\n\n<pre><code>var ConstJs = require('constjs');\n\nvar Weekdays = ConstJs.const(\"Mon, Tue, Wed\");\nconsole.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'} \n\nvar today = Weekdays.Wed;\nconsole.log(today); // output: 'Wed'; \n</code></pre>\n\n<p>Create Bitmap:</p>\n\n<pre><code>var ConstJs = require('constjs');\n\nvar ColorFlags = ConstJs.bitmap(\"blue red\");\nconsole.log(ColorFlags.blue); // output false \n\nvar StyleFlags = ConstJs.bitmap(true, \"rustic model minimalist\");\nconsole.log(StyleFlags.rustic); // output true \n\nvar CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});\nconsole.log(CityFlags.Chengdu); //output true \nconsole.log(CityFlags.Sydney); // output false \n\nvar DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});\nconsole.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean \n</code></pre>\n\n<p>For more information please checkout </p>\n\n<ul>\n<li><a href=\"https://www.npmjs.com/package/constjs\" rel=\"nofollow\">https://www.npmjs.com/package/constjs</a></li>\n<li>or <a href=\"https://github.com/greenlaw110/constjs\" rel=\"nofollow\">https://github.com/greenlaw110/constjs</a></li>\n</ul>\n\n<p>Disclaim: I am the author if this tool.</p>\n" }, { "answer_id": 30034356, "author": "Erik Lucio", "author_id": 3512957, "author_profile": "https://Stackoverflow.com/users/3512957", "pm_score": 2, "selected": false, "text": "<p>in Javascript already exists <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow\">constants</a>. You define a constant like this:</p>\n\n<pre><code>const name1 = value;\n</code></pre>\n\n<p>This cannot change through reassignment.</p>\n" }, { "answer_id": 31185636, "author": "Manohar Reddy Poreddy", "author_id": 984471, "author_profile": "https://Stackoverflow.com/users/984471", "pm_score": 4, "selected": false, "text": "<p>Group constants into structures where possible: </p>\n\n<p>Example, in my current game project, I have used below:</p>\n\n<pre><code>var CONST_WILD_TYPES = {\n REGULAR: 'REGULAR',\n EXPANDING: 'EXPANDING',\n STICKY: 'STICKY',\n SHIFTING: 'SHIFTING'\n};\n</code></pre>\n\n<p>Assignment:</p>\n\n<pre><code>var wildType = CONST_WILD_TYPES.REGULAR;\n</code></pre>\n\n<p>Comparision:</p>\n\n<pre><code>if (wildType === CONST_WILD_TYPES.REGULAR) {\n // do something here\n}\n</code></pre>\n\n<p>More recently I am using, for comparision:</p>\n\n<pre><code>switch (wildType) {\n case CONST_WILD_TYPES.REGULAR:\n // do something here\n break;\n case CONST_WILD_TYPES.EXPANDING:\n // do something here\n break;\n}\n</code></pre>\n\n<p>IE11 is with new ES6 standard that has 'const' declaration.<br>\nAbove works in earlier browsers like IE8, IE9 &amp; IE10.</p>\n" }, { "answer_id": 31674187, "author": "Ritumoni Sharma", "author_id": 4440103, "author_profile": "https://Stackoverflow.com/users/4440103", "pm_score": 2, "selected": false, "text": "<p>The keyword 'const' was proposed earlier and now it has been officially included in ES6. By using the const keyword, you can pass a value/string that will act as an immutable string.</p>\n" }, { "answer_id": 37781134, "author": "le_m", "author_id": 1647737, "author_profile": "https://Stackoverflow.com/users/1647737", "pm_score": 2, "selected": false, "text": "<p>JavaScript ES6 (re-)introduced the <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow\"><code>const</code> keyword</a> which is supported in <a href=\"http://caniuse.com/#feat=const\" rel=\"nofollow\">all major browsers</a>.</p>\n\n<blockquote>\n <p>Variables declared via <code>const</code> cannot be re-declared or re-assigned.</p>\n</blockquote>\n\n<p>Apart from that, <code>const</code> behaves similar to <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow\"><code>let</code></a>.</p>\n\n<p>It behaves as expected for primitive datatypes (Boolean, Null, Undefined, Number, String, Symbol):</p>\n\n<pre><code>const x = 1;\nx = 2;\nconsole.log(x); // 1 ...as expected, re-assigning fails\n</code></pre>\n\n<p><strong>Attention:</strong> Be aware of the pitfalls regarding objects:</p>\n\n<pre><code>const o = {x: 1};\no = {x: 2};\nconsole.log(o); // {x: 1} ...as expected, re-assigning fails\n\no.x = 2;\nconsole.log(o); // {x: 2} !!! const does not make objects immutable!\n\nconst a = [];\na = [1];\nconsole.log(a); // 1 ...as expected, re-assigning fails\n\na.push(1);\nconsole.log(a); // [1] !!! const does not make objects immutable\n</code></pre>\n\n<p>If you really need an immutable and absolutely constant object: Just use <code>const ALL_CAPS</code> to make your intention clear. It is a good convention to follow for all <code>const</code> declarations anyway, so just rely on it.</p>\n" }, { "answer_id": 51112979, "author": "Srikrushna", "author_id": 5852550, "author_profile": "https://Stackoverflow.com/users/5852550", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Declare a readonly named constatnt. </p>\n \n <p>Variables declared via const cannot be re-declared or re-assigned.</p>\n \n <p>Constants can be declared with uppercase or lowercase, but a common\n convention is to use all-uppercase letters.</p>\n</blockquote>\n\n<pre><code>// const c;\n// c = 9; //intialization and declearation at same place\nconst c = 9;\n// const c = 9;// re-declare and initialization is not possible\nconsole.log(c);//9\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
Is there a way to use constants in **JavaScript**? If not, what's the common practice for specifying variables that are used as constants?
Since [ES2015](https://www.ecma-international.org/ecma-262/6.0/), JavaScript has a notion of [`const`](https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations): ``` const MY_CONSTANT = "some-value"; ``` This will work in [pretty much all browsers except IE 8, 9 and 10](https://caniuse.com/#search=const). Some may also need [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) enabled. You can use `var` with conventions like ALL\_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code: ``` var MY_CONSTANT = "some-value"; ```
130,404
<p>I'm trying to find a way to &quot;pretty print&quot; a JavaScript data structure in a human-readable form for debugging.</p> <p>I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.</p> <p>All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.</p>
[ { "answer_id": 130420, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "<p>In <code>Firebug</code>, if you just <code>console.debug (\"%o\", my_object)</code> you can click on it in the console and enter an interactive object explorer. It shows the entire object, and lets you expand nested objects.</p>\n" }, { "answer_id": 130430, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://wrongnotes.blogspot.com/2007/09/flexjson-15-is-live.html\" rel=\"nofollow noreferrer\">flexjson</a> includes a prettyPrint() function that might give you what you want.</p>\n" }, { "answer_id": 130479, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": false, "text": "<p>Use <a href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\" rel=\"noreferrer\"><strong>Crockford's JSON.stringify</strong></a> like this:</p>\n\n<pre><code>var myArray = ['e', {pluribus: 'unum'}];\nvar text = JSON.stringify(myArray, null, '\\t'); //you can specify a number instead of '\\t' and that many spaces will be used for indentation...\n</code></pre>\n\n<p>Variable <code>text</code> would look like this:</p>\n\n<pre><code>[\n \"e\",\n {\n \"pluribus\": \"unum\"\n }\n]\n</code></pre>\n\n<hr>\n\n<p>By the way, this requires nothing more than that JS file - it will work with any library, etc.</p>\n" }, { "answer_id": 130504, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": true, "text": "<p>I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue.</p>\n\n<p>Here is the \"simple\" version:</p>\n\n<pre><code>function DumpObject(obj)\n{\n var od = new Object;\n var result = \"\";\n var len = 0;\n\n for (var property in obj)\n {\n var value = obj[property];\n if (typeof value == 'string')\n value = \"'\" + value + \"'\";\n else if (typeof value == 'object')\n {\n if (value instanceof Array)\n {\n value = \"[ \" + value + \" ]\";\n }\n else\n {\n var ood = DumpObject(value);\n value = \"{ \" + ood.dump + \" }\";\n }\n }\n result += \"'\" + property + \"' : \" + value + \", \";\n len++;\n }\n od.dump = result.replace(/, $/, \"\");\n od.len = len;\n\n return od;\n}\n</code></pre>\n\n<p>I will look at improving it a bit.<br>\nNote 1: To use it, do <code>od = DumpObject(something)</code> and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string.<br>\nNote 2: it doesn't handle loops in references.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I made the indented version.</p>\n\n<pre><code>function DumpObjectIndented(obj, indent)\n{\n var result = \"\";\n if (indent == null) indent = \"\";\n\n for (var property in obj)\n {\n var value = obj[property];\n if (typeof value == 'string')\n value = \"'\" + value + \"'\";\n else if (typeof value == 'object')\n {\n if (value instanceof Array)\n {\n // Just let JS convert the Array to a string!\n value = \"[ \" + value + \" ]\";\n }\n else\n {\n // Recursive dump\n // (replace \" \" by \"\\t\" or something else if you prefer)\n var od = DumpObjectIndented(value, indent + \" \");\n // If you like { on the same line as the key\n //value = \"{\\n\" + od + \"\\n\" + indent + \"}\";\n // If you prefer { and } to be aligned\n value = \"\\n\" + indent + \"{\\n\" + od + \"\\n\" + indent + \"}\";\n }\n }\n result += indent + \"'\" + property + \"' : \" + value + \",\\n\";\n }\n return result.replace(/,\\n$/, \"\");\n}\n</code></pre>\n\n<p>Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one.</p>\n\n<p>... I see you whipped up your own version, which is good. Visitors will have a choice.</p>\n" }, { "answer_id": 130633, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Taking PhiLho's lead (thanks very much :)), I ended up writing my own as I couldn't quite get his to do what I wanted. It's pretty rough and ready, but it does the job I need. Thank you all for the excellent suggestions.</p>\n\n<p>It's not brilliant code, I know, but for what it's worth, here it is. Someone might find it useful:</p>\n\n<pre><code>// Usage: dump(object)\nfunction dump(object, pad){\n var indent = '\\t'\n if (!pad) pad = ''\n var out = ''\n if (object.constructor == Array){\n out += '[\\n'\n for (var i=0; i&lt;object.length; i++){\n out += pad + indent + dump(object[i], pad + indent) + '\\n'\n }\n out += pad + ']'\n }else if (object.constructor == Object){\n out += '{\\n'\n for (var i in object){\n out += pad + indent + i + ': ' + dump(object[i], pad + indent) + '\\n'\n }\n out += pad + '}'\n }else{\n out += object\n }\n return out\n}\n</code></pre>\n" }, { "answer_id": 2292443, "author": "Peter Rust", "author_id": 194758, "author_profile": "https://Stackoverflow.com/users/194758", "pm_score": 1, "selected": false, "text": "<p>This is really just a comment on Jason Bunting's \"Use Crockford's JSON.stringify\", but I wasn't able to add a comment to that answer.</p>\n\n<p>As noted in the comments, JSON.stringify doesn't play well with the Prototype (www.prototypejs.org) library. However, it is fairly easy to make them play well together by temporarily removing the Array.prototype.toJSON method that prototype adds, run Crockford's stringify(), then put it back like this:</p>\n\n<pre><code> var temp = Array.prototype.toJSON;\n delete Array.prototype.toJSON;\n $('result').value += JSON.stringify(profile_base, null, 2);\n Array.prototype.toJSON = temp;\n</code></pre>\n" }, { "answer_id": 2292543, "author": "NVI", "author_id": 16185, "author_profile": "https://Stackoverflow.com/users/16185", "pm_score": 2, "selected": false, "text": "<h2><a href=\"http://github.com/NV/jsDump\" rel=\"nofollow noreferrer\">jsDump</a></h2>\n\n<pre><code>jsDump.parse([\n window,\n document,\n { a : 5, '1' : 'foo' },\n /^[ab]+$/g,\n new RegExp('x(.*?)z','ig'),\n alert, \n function fn( x, y, z ){\n return x + y; \n },\n true,\n undefined,\n null,\n new Date(),\n document.body,\n document.getElementById('links')\n])</code></pre>\n\n<p>becomes</p>\n\n<pre><code>[\n [Window],\n [Document],\n {\n \"1\": \"foo\",\n \"a\": 5\n },\n /^[ab]+$/g,\n /x(.*?)z/gi,\n function alert( a ){\n [code]\n },\n function fn( a, b, c ){\n [code]\n },\n true,\n undefined,\n null,\n \"Fri Feb 19 2010 00:49:45 GMT+0300 (MSK)\",\n &lt;body id=\"body\" class=\"node\">&lt;/body>,\n &lt;div id=\"links\">\n]</code></pre>\n\n<p><a href=\"http://github.com/jquery/qunit\" rel=\"nofollow noreferrer\">QUnit</a> (Unit-testing framework used by jQuery) using slightly patched version of jsDump.</p>\n\n<hr>\n\n<p>JSON.stringify() is not best choice on some cases.</p>\n\n<pre><code>JSON.stringify({f:function(){}}) // \"{}\"\nJSON.stringify(document.body) // TypeError: Converting circular structure to JSON\n</code></pre>\n" }, { "answer_id": 5475761, "author": "GTM", "author_id": 189218, "author_profile": "https://Stackoverflow.com/users/189218", "pm_score": 1, "selected": false, "text": "<p>I thought J. Buntings response on using JSON.stringify was good as well. A an aside, you can use JSON.stringify via YUIs JSON object if you happen to be using YUI. In my case I needed to dump to HTML so it was easier to just tweak/cut/paste PhiLho response.</p>\n\n<pre><code>function dumpObject(obj, indent) \n{\n var CR = \"&lt;br /&gt;\", SPC = \"&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;\", result = \"\";\n if (indent == null) indent = \"\";\n\n for (var property in obj)\n {\n var value = obj[property];\n\n if (typeof value == 'string')\n {\n value = \"'\" + value + \"'\";\n }\n else if (typeof value == 'object')\n {\n if (value instanceof Array)\n {\n // Just let JS convert the Array to a string!\n value = \"[ \" + value + \" ]\";\n }\n else\n {\n var od = dumpObject(value, indent + SPC);\n value = CR + indent + \"{\" + CR + od + CR + indent + \"}\";\n }\n }\n result += indent + \"'\" + property + \"' : \" + value + \",\" + CR;\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 5617276, "author": "knowtheory", "author_id": 333795, "author_profile": "https://Stackoverflow.com/users/333795", "pm_score": 3, "selected": false, "text": "<p>I'm programming in <code>Rhino</code> and I wasn't satisfied with any of the answers that were posted here. So I've written my own pretty printer:</p>\n\n<pre><code>function pp(object, depth, embedded) { \n typeof(depth) == \"number\" || (depth = 0)\n typeof(embedded) == \"boolean\" || (embedded = false)\n var newline = false\n var spacer = function(depth) { var spaces = \"\"; for (var i=0;i&lt;depth;i++) { spaces += \" \"}; return spaces }\n var pretty = \"\"\n if ( typeof(object) == \"undefined\" ) { pretty += \"undefined\" }\n else if ( typeof(object) == \"boolean\" || \n typeof(object) == \"number\" ) { pretty += object.toString() } \n else if ( typeof(object) == \"string\" ) { pretty += \"\\\"\" + object + \"\\\"\" } \n else if ( object == null) { pretty += \"null\" } \n else if ( object instanceof(Array) ) {\n if ( object.length &gt; 0 ) {\n if (embedded) { newline = true }\n var content = \"\"\n for each (var item in object) { content += pp(item, depth+1) + \",\\n\" + spacer(depth+1) }\n content = content.replace(/,\\n\\s*$/, \"\").replace(/^\\s*/,\"\")\n pretty += \"[ \" + content + \"\\n\" + spacer(depth) + \"]\"\n } else { pretty += \"[]\" }\n } \n else if (typeof(object) == \"object\") {\n if ( Object.keys(object).length &gt; 0 ){\n if (embedded) { newline = true }\n var content = \"\"\n for (var key in object) { \n content += spacer(depth + 1) + key.toString() + \": \" + pp(object[key], depth+2, true) + \",\\n\" \n }\n content = content.replace(/,\\n\\s*$/, \"\").replace(/^\\s*/,\"\")\n pretty += \"{ \" + content + \"\\n\" + spacer(depth) + \"}\"\n } else { pretty += \"{}\"}\n }\n else { pretty += object.toString() }\n return ((newline ? \"\\n\" + spacer(depth) : \"\") + pretty)\n}\n</code></pre>\n\n<p>The output looks like this:</p>\n\n<pre><code>js&gt; pp({foo:\"bar\", baz: 1})\n{ foo: \"bar\",\n baz: 1\n}\njs&gt; var taco\njs&gt; pp({foo:\"bar\", baz: [1,\"taco\",{\"blarg\": \"moo\", \"mine\": \"craft\"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})\n{ foo: \"bar\",\n baz: \n [ 1,\n \"taco\",\n { blarg: \"moo\",\n mine: \"craft\"\n },\n null,\n undefined,\n {}\n ],\n bleep: \n { a: null,\n b: undefined,\n c: []\n }\n}\n</code></pre>\n\n<p>I've also posted it as a <a href=\"https://gist.github.com/913112\" rel=\"nofollow noreferrer\">Gist here</a> for whatever future changes may be required.</p>\n" }, { "answer_id": 7666217, "author": "Davem M", "author_id": 636938, "author_profile": "https://Stackoverflow.com/users/636938", "pm_score": 4, "selected": false, "text": "<p>For Node.js, use:</p>\n\n<pre><code>util.inspect(object, [options]);\n</code></pre>\n\n<p><a href=\"http://nodejs.org/api/util.html#util_util_inspect_object_options\" rel=\"noreferrer\">API Documentation</a></p>\n" }, { "answer_id": 11607018, "author": "Dharmanshu Kamra", "author_id": 1109467, "author_profile": "https://Stackoverflow.com/users/1109467", "pm_score": 4, "selected": false, "text": "<p>You can use the following</p>\n\n<pre><code>&lt;pre id=\"dump\"&gt;&lt;/pre&gt;\n&lt;script&gt;\n var dump = JSON.stringify(sampleJsonObject, null, 4); \n $('#dump').html(dump)\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 15552420, "author": "mm2001", "author_id": 19506, "author_profile": "https://Stackoverflow.com/users/19506", "pm_score": 1, "selected": false, "text": "<p>Lots of people writing code in this thread, with many comments about various gotchas. I liked this solution because it seemed complete and was a single file with no dependencies. </p>\n\n<p><a href=\"http://www.eslinstructor.net/vkbeautify/\" rel=\"nofollow\">browser</a></p>\n\n<p><a href=\"http://www.eslinstructor.net/pretty-data/\" rel=\"nofollow\">nodejs</a></p>\n\n<p>It worked \"out of the box\" and has both node and browser versions (presumably just different wrappers but I didn't dig to confirm).</p>\n\n<p>The library also supports pretty printing XML, SQL and CSS, but I haven't tried those features.</p>\n" }, { "answer_id": 17236125, "author": "RaphaelDDL", "author_id": 684932, "author_profile": "https://Stackoverflow.com/users/684932", "pm_score": 3, "selected": false, "text": "<p>For those looking for an awesome way to see your object, <a href=\"https://github.com/padolsey/prettyPrint.js\" rel=\"noreferrer\">check prettyPrint.js</a> </p>\n\n<p>Creates a table with configurable view options to be printed somewhere on your doc. Better to look than in the <code>console</code>.</p>\n\n<pre><code>var tbl = prettyPrint( myObject, { /* options such as maxDepth, etc. */ });\ndocument.body.appendChild(tbl);\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/MGG1I.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 25574176, "author": "aliteralmind", "author_id": 2736496, "author_profile": "https://Stackoverflow.com/users/2736496", "pm_score": 0, "selected": false, "text": "<p>A simple one for printing the elements as strings:</p>\n\n<pre><code>var s = \"\";\nvar len = array.length;\nvar lenMinus1 = len - 1\nfor (var i = 0; i &lt; len; i++) {\n s += array[i];\n if(i &lt; lenMinus1) {\n s += \", \";\n }\n}\nalert(s);\n</code></pre>\n" }, { "answer_id": 29753128, "author": "Phrogz", "author_id": 405017, "author_profile": "https://Stackoverflow.com/users/405017", "pm_score": 0, "selected": false, "text": "<p>My <a href=\"https://github.com/Phrogz/NeatJSON\" rel=\"nofollow\">NeatJSON</a> library has both Ruby and <a href=\"https://github.com/Phrogz/NeatJSON/tree/master/javascript\" rel=\"nofollow\">JavaScript versions</a>. It is freely available under a (permissive) MIT License. You can view an online demo/converter at:<br>\n<a href=\"http://phrogz.net/JS/neatjson/neatjson.html\" rel=\"nofollow\">http://phrogz.net/JS/neatjson/neatjson.html</a></p>\n\n<p>Some features (all optional):</p>\n\n<ul>\n<li>Wrap to a specific width; if an object or array can fit on the line, it is kept on one line.</li>\n<li>Align the colons for all keys in an object.</li>\n<li>Sort the keys to an object alphabetically.</li>\n<li>Format floating point numbers to a specific number of decimals.</li>\n<li>When wrapping, use a 'short' version that puts the open/close brackets for arrays and objects on the same line as the first/last value.</li>\n<li>Control the whitespace for arrays and objects in a granular manner (inside brackets, before/after colons and commas).</li>\n<li>Works in the web browser and as a Node.js module.</li>\n</ul>\n" }, { "answer_id": 66169644, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<h2>For anyone checking this question out in 2021 or post-2021</h2>\n<p><a href=\"https://stackoverflow.com/a/7220510\">Check out this Other StackOverflow Answer</a> by <a href=\"https://stackoverflow.com/users/2359679/hassan\">hassan</a></p>\n<p>TLDR:</p>\n<pre class=\"lang-js prettyprint-override\"><code>JSON.stringify(data,null,2)\n</code></pre>\n<p>here the third parameter is the tab/spaces</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17121/" ]
I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging. I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI. All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.
I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue. Here is the "simple" version: ``` function DumpObject(obj) { var od = new Object; var result = ""; var len = 0; for (var property in obj) { var value = obj[property]; if (typeof value == 'string') value = "'" + value + "'"; else if (typeof value == 'object') { if (value instanceof Array) { value = "[ " + value + " ]"; } else { var ood = DumpObject(value); value = "{ " + ood.dump + " }"; } } result += "'" + property + "' : " + value + ", "; len++; } od.dump = result.replace(/, $/, ""); od.len = len; return od; } ``` I will look at improving it a bit. Note 1: To use it, do `od = DumpObject(something)` and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string. Note 2: it doesn't handle loops in references. **EDIT** I made the indented version. ``` function DumpObjectIndented(obj, indent) { var result = ""; if (indent == null) indent = ""; for (var property in obj) { var value = obj[property]; if (typeof value == 'string') value = "'" + value + "'"; else if (typeof value == 'object') { if (value instanceof Array) { // Just let JS convert the Array to a string! value = "[ " + value + " ]"; } else { // Recursive dump // (replace " " by "\t" or something else if you prefer) var od = DumpObjectIndented(value, indent + " "); // If you like { on the same line as the key //value = "{\n" + od + "\n" + indent + "}"; // If you prefer { and } to be aligned value = "\n" + indent + "{\n" + od + "\n" + indent + "}"; } } result += indent + "'" + property + "' : " + value + ",\n"; } return result.replace(/,\n$/, ""); } ``` Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one. ... I see you whipped up your own version, which is good. Visitors will have a choice.
130,427
<p>Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not.</p> <p>Basically something like this (pardon the architecture, this is purely as an example): </p> <pre><code>public class ProductService : WebService { public AuthHeader AuthenticationHeader; [WebMethod(Description="Returns true")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsTrue() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return true; } [WebMethod(Description="Returns false")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsFalse() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return false; } private bool Validate(AuthHeader authHeader) { return authHeader.Username == "gooduser" &amp;&amp; authHeader.Password == "goodpassword"; } } </code></pre> <p>As you can see, the method <code>Validate</code> has to be called in each method. I'm looking for a way to be able to call that method, while still being able to access the soap headers in a sane way. I've looked at the events in the <code>global.asax</code>, but I don't think I can access the headers in that class... Can I?</p>
[ { "answer_id": 130584, "author": "GregK", "author_id": 8653, "author_profile": "https://Stackoverflow.com/users/8653", "pm_score": 2, "selected": false, "text": "<p>You can implement the so-called SOAP extension by deriving from <a href=\"http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx\" rel=\"nofollow noreferrer\">SoapExtension base</a> class. That way you will be able to inspect an incoming SOAP message and perform validate logic before a particular web method is called.</p>\n" }, { "answer_id": 130690, "author": "Timothy Lee Russell", "author_id": 12919, "author_profile": "https://Stackoverflow.com/users/12919", "pm_score": 4, "selected": true, "text": "<p>Here is what you need to do to get this to work correctly.</p>\n\n<p>It is possible to create your own custom SoapHeader:</p>\n\n<pre><code>public class ServiceAuthHeader : SoapHeader\n{\n public string SiteKey;\n public string Password;\n\n public ServiceAuthHeader() {}\n}\n</code></pre>\n\n<p>Then you need a SoapExtensionAttribute:</p>\n\n<pre><code>public class AuthenticationSoapExtensionAttribute : SoapExtensionAttribute\n{\n private int priority;\n\n public AuthenticationSoapExtensionAttribute()\n {\n }\n\n public override Type ExtensionType\n {\n get\n {\n return typeof(AuthenticationSoapExtension);\n }\n }\n\n public override int Priority\n {\n get\n {\n return priority;\n }\n set\n {\n priority = value;\n }\n }\n}\n</code></pre>\n\n<p>And a custom SoapExtension:</p>\n\n<pre><code>public class AuthenticationSoapExtension : SoapExtension\n{\n private ServiceAuthHeader authHeader;\n\n public AuthenticationSoapExtension()\n {\n }\n\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n\n public override void Initialize(object initializer)\n { \n }\n\n public override void ProcessMessage(SoapMessage message)\n {\n if (message.Stage == SoapMessageStage.AfterDeserialize)\n {\n foreach (SoapHeader header in message.Headers)\n {\n if (header is ServiceAuthHeader)\n {\n authHeader = (ServiceAuthHeader)header;\n\n if(authHeader.Password == TheCorrectUserPassword)\n {\n return; //confirmed\n }\n }\n }\n\n throw new SoapException(\"Unauthorized\", SoapException.ClientFaultCode);\n }\n }\n}\n</code></pre>\n\n<p>Then, in your web service add the following header to your method:</p>\n\n<pre><code>public ServiceAuthHeader AuthenticationSoapHeader;\n\n[WebMethod]\n[SoapHeader(\"AuthenticationSoapHeader\")]\n[AuthenticationSoapExtension]\npublic string GetSomeStuffFromTheCloud(string IdOfWhatYouWant)\n{\n return WhatYouWant;\n}\n</code></pre>\n\n<p>When you consume this service, you must instantiate the custom header with the correct values and attach it to the request:</p>\n\n<pre><code>private ServiceAuthHeader header;\nprivate PublicService ps;\n\nheader = new ServiceAuthHeader();\nheader.SiteKey = \"Thekey\";\nheader.Password = \"Thepassword\";\nps.ServiceAuthHeaderValue = header;\n\nstring WhatYouWant = ps.GetSomeStuffFromTheCloud(SomeId);\n</code></pre>\n" }, { "answer_id": 131004, "author": "Sean Campbell", "author_id": 5136, "author_profile": "https://Stackoverflow.com/users/5136", "pm_score": 2, "selected": false, "text": "<p>I'd take a look at adding a security aspect to the methods you're looking to secure. Take a look at <a href=\"http://www.postsharp.org\" rel=\"nofollow noreferrer\">PostSharp</a>, and in particular the OnMethodBoundryAspect type, and OnEntry method.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909/" ]
Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not. Basically something like this (pardon the architecture, this is purely as an example): ``` public class ProductService : WebService { public AuthHeader AuthenticationHeader; [WebMethod(Description="Returns true")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsTrue() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return true; } [WebMethod(Description="Returns false")] [SoapHeader("AuthenticationHeader")] public bool MethodWhichReturnsFalse() { if(Validate(AuthenticationHeader)) { throw new SecurityException("Access Denied"); } return false; } private bool Validate(AuthHeader authHeader) { return authHeader.Username == "gooduser" && authHeader.Password == "goodpassword"; } } ``` As you can see, the method `Validate` has to be called in each method. I'm looking for a way to be able to call that method, while still being able to access the soap headers in a sane way. I've looked at the events in the `global.asax`, but I don't think I can access the headers in that class... Can I?
Here is what you need to do to get this to work correctly. It is possible to create your own custom SoapHeader: ``` public class ServiceAuthHeader : SoapHeader { public string SiteKey; public string Password; public ServiceAuthHeader() {} } ``` Then you need a SoapExtensionAttribute: ``` public class AuthenticationSoapExtensionAttribute : SoapExtensionAttribute { private int priority; public AuthenticationSoapExtensionAttribute() { } public override Type ExtensionType { get { return typeof(AuthenticationSoapExtension); } } public override int Priority { get { return priority; } set { priority = value; } } } ``` And a custom SoapExtension: ``` public class AuthenticationSoapExtension : SoapExtension { private ServiceAuthHeader authHeader; public AuthenticationSoapExtension() { } public override object GetInitializer(Type serviceType) { return null; } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override void Initialize(object initializer) { } public override void ProcessMessage(SoapMessage message) { if (message.Stage == SoapMessageStage.AfterDeserialize) { foreach (SoapHeader header in message.Headers) { if (header is ServiceAuthHeader) { authHeader = (ServiceAuthHeader)header; if(authHeader.Password == TheCorrectUserPassword) { return; //confirmed } } } throw new SoapException("Unauthorized", SoapException.ClientFaultCode); } } } ``` Then, in your web service add the following header to your method: ``` public ServiceAuthHeader AuthenticationSoapHeader; [WebMethod] [SoapHeader("AuthenticationSoapHeader")] [AuthenticationSoapExtension] public string GetSomeStuffFromTheCloud(string IdOfWhatYouWant) { return WhatYouWant; } ``` When you consume this service, you must instantiate the custom header with the correct values and attach it to the request: ``` private ServiceAuthHeader header; private PublicService ps; header = new ServiceAuthHeader(); header.SiteKey = "Thekey"; header.Password = "Thepassword"; ps.ServiceAuthHeaderValue = header; string WhatYouWant = ps.GetSomeStuffFromTheCloud(SomeId); ```
130,506
<p>I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. </p> <p>In the code he defines a constant;</p> <pre><code>// number of threads public static final int THREADS = Runtime.getRuntime().availableProcessors(); </code></pre> <p>Which then sets the number of threads that are used to create the image.</p> <p>I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)?</p> <p>EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.</p>
[ { "answer_id": 130527, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 2, "selected": false, "text": "<p>The number that your application needs; no more, and no less.</p>\n\n<p>Obviously, if you're writing an application which contains some parallelisable algorithm, then you can probably start benchmarking to find a good balance in the number of threads, but bear in mind that hundreds of threads won't speed up any operation.</p>\n\n<p>If your algorithm can't be parallelised, then no number of additional threads is going to help.</p>\n" }, { "answer_id": 130538, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 4, "selected": false, "text": "<p>On the one hand, you'd like to think Threads == CPU/Cores makes perfect sense. Why have a thread if there's nothing to run it?</p>\n\n<p>The detail boils down to \"what are the threads doing\". A thread that's idle waiting for a network packet or a disk block is CPU time wasted.</p>\n\n<p>If your threads are CPU heavy, then a 1:1 correlation makes some sense. If you have a single \"read the DB\" thread that feeds the other threads, and a single \"Dump the data\" thread and pulls data from the CPU threads and create output, those two could most likely easily share a CPU while the CPU heavy threads keep churning away.</p>\n\n<p>The real answer, as with all sorts of things, is to measure it. Since the number is configurable (apparently), configure it! Run it with 1:1 threads to CPUs, 2:1, 1.5:1, whatever, and time the results. Fast one wins.</p>\n" }, { "answer_id": 130541, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 2, "selected": false, "text": "<p>Yes, that's a perfectly reasonable approach. One thread per processor/core will maximize processing power and minimize context switching. I'd probably leave that as-is unless I found a problem via benchmarking/profiling.</p>\n\n<p>One thing to note is that the JVM does not guarantee <code>availableProcessors()</code> will be constant, so technically, you should check it immediately before spawning your threads. I doubt that this value is likely to change at runtime on typical computers, though.</p>\n\n<p>P.S. As others have pointed out, if your process is not CPU-bound, this approach is unlikely to be optimal. Since you say these threads are being used to generate images, though, I assume you <em>are</em> CPU bound.</p>\n" }, { "answer_id": 130549, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 1, "selected": false, "text": "<p>number of processors is a good start; but if those threads do a lot of i/o, then might be better with more... or less.</p>\n\n<p>first think of what are the resources available and what do you want to optimise (least time to finish, least impact to other tasks, etc). then do the math.</p>\n\n<p>sometimes it could be better if you dedicate a thread or two to each i/o resource, and the others fight for CPU. the analisys is usually easier on these designs.</p>\n" }, { "answer_id": 130563, "author": "user19113", "author_id": 19113, "author_profile": "https://Stackoverflow.com/users/19113", "pm_score": 0, "selected": false, "text": "<p>The benefit of using threads is to reduce wall-clock execution time of your program by allowing your program to work on a different part of the job while another part is waiting for something to happen (usually I/O). If your program is totally CPU bound adding threads will only slow it down. If it is fully or partially I/O bound, adding threads may help but there's a balance point to be struck between the overhead of adding threads and the additional work that will get accomplished. To make the number of threads equal to the number of processors will yield peak performance if the program is totally, or near-totally CPU-bound.</p>\n\n<p>As with many questions with the word \"should\" in them, the answer is, \"It depends\". If you think you can get better performance, adjust the number of threads up or down and benchmark the application's performance. Also take into account any other factors that might influence the decision (if your application is eating 100% of the computer's available horsepower, the performance of other applications will be reduced).</p>\n\n<p>This assumes that the multi-threaded code is written properly etc. If the original developer only had one CPU, he would never have had a chance to experience problems with poorly-written threading code. So you should probably test behaviour as well as performance when adjusting the number of threads.</p>\n\n<p>By the way, you might want to consider allowing the number of threads to be configured at run time instead of compile time to make this whole process easier.</p>\n" }, { "answer_id": 130599, "author": "user19113", "author_id": 19113, "author_profile": "https://Stackoverflow.com/users/19113", "pm_score": 0, "selected": false, "text": "<p>After seeing your edit, it's quite possible that one thread per CPU is as good as it gets. Your application seems quite parallelizable. If you have extra hardware you can use GridGain to grid-enable your app and have it run on multiple machines. That's probably about the only thing, beyond buying faster / more cores, that will speed it up.</p>\n" }, { "answer_id": 131524, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 5, "selected": true, "text": "<p>Threads are fine, but as others have noted, you have to be highly aware of your bottlenecks. Your algorithm sounds like it would be susceptible to cache contention between multiple CPUs - this is particularly nasty because it has the potential to hit the performance of all of your threads (normally you think of using multiple threads to continue processing while waiting for slow or high latency IO operations).</p>\n\n<p>Cache contention is a very important aspect of using multi CPUs to process a highly parallelized algorithm: Make sure that you take your memory utilization into account. If you can construct your data objects so each thread has it's own memory that it is working on, you can greatly reduce cache contention between the CPUs. For example, it may be easier to have a big array of ints and have different threads working on different parts of that array - but in Java, the bounds checks on that array are going to be trying to access the same address in memory, which can cause a given CPU to have to reload data from L2 or L3 cache.</p>\n\n<p>Splitting the data into it's own data structures, and configure those data structures so they are thread local (might even be more optimal to use <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html\" rel=\"noreferrer\">ThreadLocal</a> - that actually uses constructs in the OS that provide guarantees that the CPU can use to optimize cache.</p>\n\n<p>The best piece of advice I can give you is test, test, test. Don't make assumptions about how CPUs will perform - there is a <em>huge</em> amount of magic going on in CPUs these days, often with counterintuitive results. Note also that the JIT runtime optimization will add an additional layer of complexity here (maybe good, maybe not). </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7613/" ]
I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. In the code he defines a constant; ``` // number of threads public static final int THREADS = Runtime.getRuntime().availableProcessors(); ``` Which then sets the number of threads that are used to create the image. I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)? EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.
Threads are fine, but as others have noted, you have to be highly aware of your bottlenecks. Your algorithm sounds like it would be susceptible to cache contention between multiple CPUs - this is particularly nasty because it has the potential to hit the performance of all of your threads (normally you think of using multiple threads to continue processing while waiting for slow or high latency IO operations). Cache contention is a very important aspect of using multi CPUs to process a highly parallelized algorithm: Make sure that you take your memory utilization into account. If you can construct your data objects so each thread has it's own memory that it is working on, you can greatly reduce cache contention between the CPUs. For example, it may be easier to have a big array of ints and have different threads working on different parts of that array - but in Java, the bounds checks on that array are going to be trying to access the same address in memory, which can cause a given CPU to have to reload data from L2 or L3 cache. Splitting the data into it's own data structures, and configure those data structures so they are thread local (might even be more optimal to use [ThreadLocal](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html) - that actually uses constructs in the OS that provide guarantees that the CPU can use to optimize cache. The best piece of advice I can give you is test, test, test. Don't make assumptions about how CPUs will perform - there is a *huge* amount of magic going on in CPUs these days, often with counterintuitive results. Note also that the JIT runtime optimization will add an additional layer of complexity here (maybe good, maybe not).
130,547
<p>Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database.</p> <h2>Contents of <code>database.yml</code></h2> <pre><code>development: adapter: sqlserver database: APPS_SETUP Host: WindowsVT06\SQLEXPRESS Username: se Password: paswd </code></pre> <p>Run <code>rake db:migrate</code> from myapp directory</p> <pre><code>---------- rake aborted! no such file to load -- deprecated </code></pre> <h2><strong>ADO</strong></h2> <p>I have dbi 0.4.0 installed and have created the ADO folder in</p> <p><code>C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO</code></p> <p>I got the ado.rb from the dbi 0.2.2</p> <p>What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres.</p> <p>****UPDATE****</p> <p>I have installed the activerecord-sqlserver-adapter gem from --source=<a href="http://gems.rubyonrails.org" rel="nofollow noreferrer">http://gems.rubyonrails.org</a></p> <p>Still not working.</p> <p>I have verified that I can connect to the database by logging into SQL Management Studio with the credentials.</p> <hr> <p><strong>rake db:migrate --trace</strong></p> <hr> <pre><code>PS C:\Inetpub\wwwroot\myapp&gt; rake db:migrate --trace (in C:/Inetpub/wwwroot/myapp) ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate rake aborted! no such file to load -- deprecated C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48 C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin gs' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver _adapter.rb:29:in `sqlserver_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `send' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `connection=' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:260:in `retrieve_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:78:in `connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate' C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99 C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain' C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31 C:/Ruby/bin/rake:19:in `load' C:/Ruby/bin/rake:19 PS C:\Inetpub\wwwroot\myapp&gt; </code></pre>
[ { "answer_id": 131501, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 2, "selected": false, "text": "<p>Did you install the SQL Server adapter?</p>\n\n<pre><code>gem install activerecord-sqlserver-adapter --source=http://gems.rubyonrails.org\n</code></pre>\n" }, { "answer_id": 153695, "author": "djenryte", "author_id": 23828, "author_profile": "https://Stackoverflow.com/users/23828", "pm_score": 4, "selected": true, "text": "<p>I ran into the same problem yesterday. Apparently 'deprecated' is a gem, so you want to run \"gem install deprecated\" to grab and install the latest version. Good luck.</p>\n" }, { "answer_id": 1268226, "author": "Amol", "author_id": 189654, "author_profile": "https://Stackoverflow.com/users/189654", "pm_score": 0, "selected": false, "text": "<p>I too had faced this problem. There is another work around.\nYou can create a DSN for the app db from control panel->admin tools->Odbc.\nDatabase.yml file should look like below:</p>\n\n<pre><code>adapter: sqlserver\nmode: odbc\ndsn: DSN_NAME\nhost: localhost\ndatabase: App_development\nusername: uname\npassword: password\n</code></pre>\n\n<p>I tried using the deprecated gem, wasn't of much use.\nI had tried installing an ADO adaptor too which rendered useless.</p>\n" }, { "answer_id": 1689383, "author": "Jarrod", "author_id": 100589, "author_profile": "https://Stackoverflow.com/users/100589", "pm_score": 2, "selected": false, "text": "<p>If you're on a 64 bit machine, there are two ODBC administrator programs, one for 32 bit and one for 64 bit. activerecord-sqlserver-adapter looks for DSNs set up with the 32 bit version.</p>\n" }, { "answer_id": 1981774, "author": "John Naegle", "author_id": 29680, "author_profile": "https://Stackoverflow.com/users/29680", "pm_score": 2, "selected": false, "text": "<p>I used and ODBC data source and the SQL Server adapter on Windows Server 2008 against SQL Server 2000 running on a remote instance.</p>\n\n<p><strong>Install SQL Server Adapter</strong></p>\n\n<pre><code>gem.bat install activerecord-sqlserver-adapter\n Successfully installed deprecated-2.0.1\n Successfully installed dbi-0.4.1\n Successfully installed dbd-odbc-0.2.4\n Successfully installed activerecord-sqlserver-adapter-2.2.22\n 4 gems installed\n</code></pre>\n\n<p><strong>Create an ODBC datasource</strong></p>\n\n<ul>\n<li>Type: SQL Server</li>\n<li>Name: rails_development</li>\n<li>Description: rails_development</li>\n<li>Server: SERVER</li>\n<li>SQL Authentication (sa/12345)</li>\n<li>Default Database: DATABASE</li>\n</ul>\n\n<p><strong>Setup database.yml</strong></p>\n\n<pre><code>development:\n adapter: sqlserver\n mode: odbc\n dsn: rails_development\n username: sa\n password: 12345\n</code></pre>\n\n<p><strong>YMMV</strong></p>\n\n<p>A couple of helpful links:</p>\n\n<ul>\n<li><a href=\"http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html\" rel=\"nofollow noreferrer\">http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html</a></li>\n<li><a href=\"http://wiki.rubyonrails.org/rails/pages/HowToUseLegacySchemas\" rel=\"nofollow noreferrer\">http://wiki.rubyonrails.org/rails/pages/HowToUseLegacySchemas</a></li>\n</ul>\n" }, { "answer_id": 3526526, "author": "minikermit", "author_id": 425784, "author_profile": "https://Stackoverflow.com/users/425784", "pm_score": 1, "selected": false, "text": "<p>Correct link is <a href=\"http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html\" rel=\"nofollow noreferrer\">http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453046/" ]
Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database. Contents of `database.yml` -------------------------- ``` development: adapter: sqlserver database: APPS_SETUP Host: WindowsVT06\SQLEXPRESS Username: se Password: paswd ``` Run `rake db:migrate` from myapp directory ``` ---------- rake aborted! no such file to load -- deprecated ``` **ADO** ------- I have dbi 0.4.0 installed and have created the ADO folder in `C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO` I got the ado.rb from the dbi 0.2.2 What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres. \*\*\*\*UPDATE\*\*\*\* I have installed the activerecord-sqlserver-adapter gem from --source=<http://gems.rubyonrails.org> Still not working. I have verified that I can connect to the database by logging into SQL Management Studio with the credentials. --- **rake db:migrate --trace** --- ``` PS C:\Inetpub\wwwroot\myapp> rake db:migrate --trace (in C:/Inetpub/wwwroot/myapp) ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate rake aborted! no such file to load -- deprecated C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48 C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin gs' C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_ or_gem' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver _adapter.rb:29:in `sqlserver_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `send' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:292:in `connection=' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:260:in `retrieve_connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio n.rb:78:in `connection' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up' C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate' C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99 C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain' C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run' C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31 C:/Ruby/bin/rake:19:in `load' C:/Ruby/bin/rake:19 PS C:\Inetpub\wwwroot\myapp> ```
I ran into the same problem yesterday. Apparently 'deprecated' is a gem, so you want to run "gem install deprecated" to grab and install the latest version. Good luck.
130,561
<p>I am building an application where a page will load user controls (x.ascx) dynamically based on query string. </p> <p>I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages. </p> <p>I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl.</p> <p>Also, I want to avoid using sessions or querystring.</p>
[ { "answer_id": 130671, "author": "Jorge Alves", "author_id": 6195, "author_profile": "https://Stackoverflow.com/users/6195", "pm_score": 0, "selected": false, "text": "<p>Assuming you're talking about asp's validator controls, making them work with the validation summary should be easy: use the same Validation Group. Normally, I derive all usercontrols from a base class that adds a ValidationGroup property whose setter calls a overriden method that changes all internal validators to the same validation group.</p>\n\n<p>The tricky part is making them behave when added dynamically. There are some gotchas you should be aware of, mainly concerning the page cycle and when you add them to your Page object. If you know all the possible user controls you'll use during design time, I'd try to add them statically using EnableViewState and Visible to minimize overhead, even if there are too many of them.</p>\n" }, { "answer_id": 131486, "author": "ManojN", "author_id": 709, "author_profile": "https://Stackoverflow.com/users/709", "pm_score": 2, "selected": true, "text": "<p><b>Found a way of doing this:</b></p>\n\n<p>Step 1: Create a Base User Control and define Delegates and Events in this control.</p>\n\n<p>Step 2: Create a Public function in the base user control to Raise Events defined in Step1.</p>\n\n<pre>\n'SourceCode for Step 1 and Step 2\nPublic Delegate Sub UpdatePageHeaderHandler(ByVal PageHeading As String)\nPublic Class CommonUserControl\n Inherits System.Web.UI.UserControl\n\n Public Event UpdatePageHeaderEvent As UpdatePageHeaderHandler\n Public Sub UpdatePageHeader(ByVal PageHeadinga As String)\n RaiseEvent UpdatePageHeaderEvent(PageHeadinga)\n End Sub\nEnd Class\n</pre>\n\n<p>Step 3: Inherit your Web User Control from the base user control that you created in Step1.</p>\n\n<p>Step 4: From your Web User Control - Call the MyBase.FunctionName that you defined in Step2.</p>\n\n<pre>\n'SourceCode for Step 3 and Step 4\nPartial Class DerievedUserControl\n Inherits CommonUserControl\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n MyBase.PageHeader(\"Test Header\")\n End Sub\nEnd Class\n</pre>\n\n<p>Step 5: In your page, Load the control dynamically using Page.LoadControl and Cast the control as the Base user control.</p>\n\n<p>Step 6: Attach Event Handlers with this Control.</p>\n\n<pre>\n'SourceCode for Step 5 and Step 6\nPrivate Sub LoadDynamicControl()\n Try\n 'Try to load control\n Dim c As CommonUserControl = CType(LoadControl(\"/Common/Controls/Test.ascx\", CommonUserControl))\n 'Attach Event Handlers to the LoadedControl\n AddHandler c.UpdatePageHeaderEvent, AddressOf PageHeaders\n DynamicControlPlaceHolder.Controls.Add(c)\n Catch ex As Exception\n 'Log Error\n End Try\nEnd Sub</pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/709/" ]
I am building an application where a page will load user controls (x.ascx) dynamically based on query string. I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages. I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl. Also, I want to avoid using sessions or querystring.
**Found a way of doing this:** Step 1: Create a Base User Control and define Delegates and Events in this control. Step 2: Create a Public function in the base user control to Raise Events defined in Step1. ``` 'SourceCode for Step 1 and Step 2 Public Delegate Sub UpdatePageHeaderHandler(ByVal PageHeading As String) Public Class CommonUserControl Inherits System.Web.UI.UserControl Public Event UpdatePageHeaderEvent As UpdatePageHeaderHandler Public Sub UpdatePageHeader(ByVal PageHeadinga As String) RaiseEvent UpdatePageHeaderEvent(PageHeadinga) End Sub End Class ``` Step 3: Inherit your Web User Control from the base user control that you created in Step1. Step 4: From your Web User Control - Call the MyBase.FunctionName that you defined in Step2. ``` 'SourceCode for Step 3 and Step 4 Partial Class DerievedUserControl Inherits CommonUserControl Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load MyBase.PageHeader("Test Header") End Sub End Class ``` Step 5: In your page, Load the control dynamically using Page.LoadControl and Cast the control as the Base user control. Step 6: Attach Event Handlers with this Control. ``` 'SourceCode for Step 5 and Step 6 Private Sub LoadDynamicControl() Try 'Try to load control Dim c As CommonUserControl = CType(LoadControl("/Common/Controls/Test.ascx", CommonUserControl)) 'Attach Event Handlers to the LoadedControl AddHandler c.UpdatePageHeaderEvent, AddressOf PageHeaders DynamicControlPlaceHolder.Controls.Add(c) Catch ex As Exception 'Log Error End Try End Sub ```
130,570
<p>We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. </p> <p>We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.</p> <p>We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.</p> <p>Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?</p>
[ { "answer_id": 130757, "author": "Chris Tybur", "author_id": 741, "author_profile": "https://Stackoverflow.com/users/741", "pm_score": 0, "selected": false, "text": "<p>There are MSI properties you can look at that will tell you if a product is already installed or if an uninstall is taking place. The Installed property will be true if the product is already there, so you can use it in a Boolean expression (Ex: Not Installed). The REMOVE property will be set to \"ALL\" if an uninstall is taking place. You might be able to condition your Firebird installation logic on these properties, which you can retrieve using the <a href=\"http://msdn.microsoft.com/en-us/library/aa370134(VS.85).aspx\" rel=\"nofollow noreferrer\">MsiGetProperty</a> function.</p>\n\n<p>Note: Property names mean different things based on case, so make sure you use the cases above.</p>\n\n<p>I couldn't find any reference in the IS online help or Google to the DefaultFeatureInstalled event. Is your InstallShield project Basic MSI or InstallScript?</p>\n" }, { "answer_id": 133830, "author": "Ray Jenkins", "author_id": 12425, "author_profile": "https://Stackoverflow.com/users/12425", "pm_score": 0, "selected": false, "text": "<p>I am doing an InstallScript project.</p>\n\n<p>I double checked the event and the function that I am using is DefaultFeature_Installed with an underscore. I have searched the Net and IS's website and have found mention of it but no definition. I asked the developer here who originally moved the code to this event, and she can't remember where or why she moved the code to this event.</p>\n\n<p>I will look into MsiGetProperty this morning. Thanks for the pointer.</p>\n" }, { "answer_id": 144881, "author": "Chris Tybur", "author_id": 741, "author_profile": "https://Stackoverflow.com/users/741", "pm_score": 0, "selected": false, "text": "<p>You can add this code to the DefaultFeature_Installed event:</p>\n\n<pre><code>string sRemove;\nnumber nBuffer;\n\nnBuffer = 256;\nif (MsiGetProperty(ISMSI_HANDLE, \"REMOVE\", sRemove, nBuffer) = ERROR_SUCCESS) then\n //do something\nendif;\n</code></pre>\n\n<p>Note: the function name is case sensitive. The ISMSI_HANDLE value is a handle to the InstallShield install engine. If sRemove is equal to \"ALL\", which indicates an uninstall is taking place, you can skip the Firebird installation.</p>\n" }, { "answer_id": 153638, "author": "Ray Jenkins", "author_id": 12425, "author_profile": "https://Stackoverflow.com/users/12425", "pm_score": 1, "selected": false, "text": "<p>Chris, I had trouble getting the MsiGetProperty to work at all. Just adding the code that you have </p>\n\n<pre><code>string sRemove;\nnumber nBuffer;\n\nnBuffer = 256;\nif (MsiGetProperty(ISMSI_HANDLE, \"REMOVE\", sRemove, nBuffer) = ERROR_SUCCESS) then\n //do something\nendif;\n</code></pre>\n\n<p>I get \"undefined identifier\". I tried several things to get IS to recognize it without success. After some more poking around, I realized that IS was not calling the function on uninstall in the first place. I had another function, onEnd I think that was calling the same things. After cleaning that up, I was getting the result I had expected in the beginning.</p>\n\n<p>So the correct answer would be that you don't have to do anything for the code in the DefaultFeature_Installed event not to be called on uninstall.</p>\n" }, { "answer_id": 187115, "author": "epotter", "author_id": 26339, "author_profile": "https://Stackoverflow.com/users/26339", "pm_score": 0, "selected": false, "text": "<p>If you are using an InstallScript or InstallScript MSI project, you will want to handle the OnFirstUIBefore event. It is called the first time the installer is run. When the installer is launch again, the OnMaintUIBefore event is raised in its place.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425/" ]
We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently. We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again. Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?
Chris, I had trouble getting the MsiGetProperty to work at all. Just adding the code that you have ``` string sRemove; number nBuffer; nBuffer = 256; if (MsiGetProperty(ISMSI_HANDLE, "REMOVE", sRemove, nBuffer) = ERROR_SUCCESS) then //do something endif; ``` I get "undefined identifier". I tried several things to get IS to recognize it without success. After some more poking around, I realized that IS was not calling the function on uninstall in the first place. I had another function, onEnd I think that was calling the same things. After cleaning that up, I was getting the result I had expected in the beginning. So the correct answer would be that you don't have to do anything for the code in the DefaultFeature\_Installed event not to be called on uninstall.
130,573
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx" rel="nofollow noreferrer"><code>FILETIME</code> structure</a> counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?</p>
[ { "answer_id": 130659, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": -1, "selected": false, "text": "<p>A very crude summary:</p>\n\n<p>UTC = (Atomic Time) + (Leap Seconds) ~~ (Mean Solar Time)</p>\n\n<p>The MS documentation says, specifically, \"UTC\", and so should include the leap seconds. As always with MS, your mileage may vary.</p>\n" }, { "answer_id": 133302, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>Leap seconds are added unpredictably by the IERS. 23 seconds have been added since 1972, when UTC and leap seconds were defined. Wikipedia says \"because the Earth's rotation rate is unpredictable in the long term, it is not possible to predict the need for them more than six months in advance.\"</p>\n\n<p>Since you'd have to keep a history of when leap seconds were inserted, and keep updating the OS to keep a reference of when they had been inserted, and the difference is so small, it's fair not to expect a general-purpose OS to compensate for leap seconds.</p>\n\n<p>In addition, regular clock drift, of the simple electronic clock in your PC compared to UTC, is so much larger than the compensation required for leap seconds. If you need the kind of precision to compensate for leap seconds, you shouldn't use the highly-inaccurate PC clock.</p>\n" }, { "answer_id": 143027, "author": "Lawrence D'Anna", "author_id": 10168, "author_profile": "https://Stackoverflow.com/users/10168", "pm_score": 0, "selected": false, "text": "<p>According to this <a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/02/26/80492.aspx#81867\" rel=\"nofollow noreferrer\">comment</a> windows is totally unaware of leap seconds. If you add 24 * 60 * 60 seconds to a FILETIME that represents 1:39:45 today, you get a FILETIME that represents 1:39:45 tomorrow, no matter what. </p>\n" }, { "answer_id": 1250277, "author": "Chris Smith", "author_id": 9073, "author_profile": "https://Stackoverflow.com/users/9073", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://devblogs.microsoft.com/oldnewthing/20090306-00/?p=18913\" rel=\"nofollow noreferrer\">Here</a>'s some more info about why that particular date was chosen.</p>\n\n<blockquote>\n <p>The FILETIME structure records time in\n the form of 100-nanosecond intervals\n since January 1, 1601. Why was that\n date chosen?</p>\n \n <p>The Gregorian calendar operates on a\n 400-year cycle, and 1601 is the first\n year of the cycle that was active at\n the time Windows NT was being\n designed. In other words, it was\n chosen to make the math come out\n nicely.</p>\n \n <p>I actually have the email from Dave\n Cutler confirming this.</p>\n</blockquote>\n" }, { "answer_id": 1518159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>There can be no single answer to this question without first deciding: What is the Windows FILETIME actually counting? The Microsoft docs say it counts 100 nanosecond intervals since 1601 UTC, but this is problematic.</p>\n\n<p>No form of internationally coordinated time existed prior to the year 1960. The name UTC itself does not occur in any literature prior to 1964. The name UTC as an official designation did not exist until 1970. But it gets worse. The Royal Greenwich Observatory was not established until 1676, so even trying to interpret the FILETIME as GMT has no clear meaning, and it was only around then that pendulum clocks with accurate escapements began to give accuracies of 1 second.</p>\n\n<p>If FILETIME is interpreted as mean solar seconds then the number of leap seconds since 1601 is zero, for UT has no leap seconds. If FILETIME is interpreted as if there had been atomic chronometers then the number of leap seconds since 1601 is about -60 (that's negative 60 leap seconds).</p>\n\n<p>That is ancient history, what about the era since atomic chronometers? It is no better because national governments have not made the distinction between mean solar seconds and SI seconds. For a decade the ITU-R has been discussing abandoning leap seconds, but they have not achieved international consensus. Part of the reason for that can be seen in the\n<a href=\"http://www.ucolick.org/~sla/leapsecs/epochtime.html\" rel=\"noreferrer\">javascript on this page</a> (also see the delta-T link on that page for plots of the ancient history). Because national governments have not made a clear distinction, any attempt to define the count of seconds since 1972 runs the risk of being invalid according to the laws of some jurisdiction. The delegates to ITU-R are aware of this complexity, as are the folks on the POSIX committee. Until the diplomatic issues are worked out, until national governments and international standards make a clear distinction and choice between mean solar and SI seconds, there is little hope that the computer standards can follow suit.</p>\n" }, { "answer_id": 3603011, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": true, "text": "<p>The question shouldn't be if <code>FILETIME</code> includes leap seconds. </p>\n\n<p>It should be:</p>\n\n<blockquote>\n <p>Do the people, functions, and libraries, who interpret a <code>FILETIME</code> (i.e. <code>FileTimeToSystemTime</code>) include leap seconds when counting the duration?</p>\n</blockquote>\n\n<p>The simple answer is <em>\"no\"</em>. <code>FileTimeToSystemTime</code> returns seconds as <code>0..59</code>. </p>\n\n<hr>\n\n<p>The simpler answer is: \"<em>of course not, how could it?</em>\". </p>\n\n<p>My Windows 2000 machine doesn't know that there were 2 leap seconds added in the decade since it was released. Any interpretation it makes of a <code>FILETIME</code> is wrong.</p>\n\n<hr>\n\n<p>Finally, rather than relying on logic, we can determine by direct experimental observation, the answer to the posters question:</p>\n\n<pre class=\"lang-pascal prettyprint-override\"><code>var\n systemTime: TSystemTime;\n fileTime: TFileTime;\nbegin\n //Construct a system-time for the 12/31/2008 11:59:59 pm\n ZeroMemory(@systemTime, SizeOf(systemTime));\n systemtime.wYear := 2008;\n systemTime.wMonth := 12;\n systemTime.wDay := 31;\n systemTime.wHour := 23;\n systemtime.wMinute := 59;\n systemtime.wSecond := 59;\n\n //Convert it to a file time\n SystemTimeToFileTime(systemTime, {var}fileTime);\n\n //There was a leap second 12/31/2008 11:59:60 pm\n //Add one second to our filetime to reach the leap second\n filetime.dwLowDateTime := fileTime.dwLowDateTime+10000000; //10,000,000 * 100ns = 1s\n\n //Convert the filetime, sitting on a leap second, to a displayable system time\n FileTimeToSystemTime(fileTime, {var}systemTime);\n\n //And now print the system time\n ShowMessage(DateTimeToStr(SystemTimeToDateTime(systemTime)));\n</code></pre>\n\n<p>Adding one second to </p>\n\n<pre><code>12/31/2008 11:59:59pm\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>1/1/2009 12:00:00am\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>1/1/2009 11:59:60pm\n</code></pre>\n\n<p>Q.E.D.</p>\n\n<p>Original poster might not like it, but god intentionally rigged it so that a year is not evenly divisible by a day. He did it just to screw up programmers.</p>\n" }, { "answer_id": 53015905, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 2, "selected": false, "text": "<p>The answer to this question used to be no, but has changed to: <strong>YES, sort of, sometimes</strong>...</p>\n\n<p>Per <a href=\"https://blogs.technet.microsoft.com/networking/2018/10/24/leap-seconds-for-the-appdev-what-you-should-know/\" rel=\"nofollow noreferrer\">the Windows Networking team blog article</a>:</p>\n\n<blockquote>\n <p>Starting in Server 2019 and the Windows 10 October [2018] update time APIs will now take into account all leap seconds the Operating System is aware of when it translates FILETIME to SystemTime. </p>\n</blockquote>\n\n<p>As there have been no leap seconds issued since the time of this feature being added, the operating system is still unaware of any leap seconds. However, when the next official leap second makes its way into the world, Windows computers that have this new feature enabled will keep track of it, and thus <code>FILETIME</code> values will be offset by the number of leap seconds on the computer at the time they are interpreted.</p>\n\n<p>The blog post goes on to describe:</p>\n\n<blockquote>\n <p>No change is made to FILETIME. It still represents the number of 100 ns intervals since the start of the epoch. What has changed is the interpretation of that number when it is converted to SYSTEMTIME and back. Here is a list of affected APIs:</p>\n \n <ul>\n <li>GetSystemTime</li>\n <li>GetLocalTime</li>\n <li>FileTimeToSystemTime</li>\n <li>FileTimeToLocalTime</li>\n <li>SystemTimeToFileTime</li>\n <li>SetSystemTime</li>\n <li>SetLocalTime</li>\n </ul>\n \n <p>Previous to this release, SYSTEMTIME had valid values for wSecond between 0 and 59. SYSTEMTIME has now been updated to allow a value of 60, provided the year, month, and day represents day in which a leap second is valid.</p>\n \n <p>...</p>\n \n <p>In order receive the 60 second in the SYSTEMTIME structure a process must explicitly opt-in. </p>\n</blockquote>\n\n<p>Note that the opt-in applies to the behavior within the functions listed on how a <code>FILETIME</code> is mapped to a <code>SYSTEMTIME</code>. Regardless of whether you opt-in or not, the operating system will still offset <code>FILETIME</code> values according to the leap seconds it is aware of.</p>\n\n<p>With regard to compatibility, the article states:</p>\n\n<blockquote>\n <p>Applications that rely on 3rd party frameworks should ensure their framework’s implementation on Windows is also calling into the correct APIs to calculate the correct time, or else the application will have the wrong time reported.</p>\n</blockquote>\n\n<p>And also provides a links to <a href=\"https://blogs.technet.microsoft.com/networking/2018/10/17/leapseconds-for-the-itpro/\" rel=\"nofollow noreferrer\">an earlier post</a> which describes how to disable the entire feature, as follows:</p>\n\n<blockquote>\n <p>... you can revert to the prior operating system behavior and disable leap seconds across the board by adding the following registry key:</p>\n \n <ul>\n <li><code>HKLM:\\SYSTEM\\CurrentControlSet\\Control\\LeapSecondInformation</code></li>\n <li>Type: \"REG_DWORD\"</li>\n <li>Name: Enabled</li>\n <li>Value: <code>0</code> Disables the system-wide setting</li>\n <li>Value: <code>1</code> Enables the system-wide setting</li>\n </ul>\n \n <p>Next, restart your system.</p>\n</blockquote>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10168/" ]
The [`FILETIME` structure](http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx) counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?
The question shouldn't be if `FILETIME` includes leap seconds. It should be: > > Do the people, functions, and libraries, who interpret a `FILETIME` (i.e. `FileTimeToSystemTime`) include leap seconds when counting the duration? > > > The simple answer is *"no"*. `FileTimeToSystemTime` returns seconds as `0..59`. --- The simpler answer is: "*of course not, how could it?*". My Windows 2000 machine doesn't know that there were 2 leap seconds added in the decade since it was released. Any interpretation it makes of a `FILETIME` is wrong. --- Finally, rather than relying on logic, we can determine by direct experimental observation, the answer to the posters question: ```pascal var systemTime: TSystemTime; fileTime: TFileTime; begin //Construct a system-time for the 12/31/2008 11:59:59 pm ZeroMemory(@systemTime, SizeOf(systemTime)); systemtime.wYear := 2008; systemTime.wMonth := 12; systemTime.wDay := 31; systemTime.wHour := 23; systemtime.wMinute := 59; systemtime.wSecond := 59; //Convert it to a file time SystemTimeToFileTime(systemTime, {var}fileTime); //There was a leap second 12/31/2008 11:59:60 pm //Add one second to our filetime to reach the leap second filetime.dwLowDateTime := fileTime.dwLowDateTime+10000000; //10,000,000 * 100ns = 1s //Convert the filetime, sitting on a leap second, to a displayable system time FileTimeToSystemTime(fileTime, {var}systemTime); //And now print the system time ShowMessage(DateTimeToStr(SystemTimeToDateTime(systemTime))); ``` Adding one second to ``` 12/31/2008 11:59:59pm ``` gives ``` 1/1/2009 12:00:00am ``` rather than ``` 1/1/2009 11:59:60pm ``` Q.E.D. Original poster might not like it, but god intentionally rigged it so that a year is not evenly divisible by a day. He did it just to screw up programmers.
130,574
<p>I seek an algorithm that will let me represent an incoming sequence of bits as letters ('a' .. 'z' ), in a minimal matter such that the stream of bits can be regenerated from the letters, without ever holding the entire sequence in memory.</p> <p>That is, given an external bit source (each read returns a practically random bit), and user input of a number of bits, I would like to print out the minimal number of characters that can represent those bits.</p> <p>Ideally there should be a parameterization - how much memory versus maximum bits before some waste is necessary.</p> <p>Efficiency Goal - The same number of characters as the base-26 representation of the bits. </p> <p>Non-solutions: </p> <ol> <li><p>If sufficient storage was present, store the entire sequence and use a big-integer MOD 26 operation. </p></li> <li><p>Convert every 9 bits to 2 characters - This seems suboptimal, wasting 25% of information capacity of the letters output.</p></li> </ol>
[ { "answer_id": 130597, "author": "Smashery", "author_id": 14902, "author_profile": "https://Stackoverflow.com/users/14902", "pm_score": 2, "selected": false, "text": "<p>Could <a href=\"http://en.wikipedia.org/wiki/Huffman_coding\" rel=\"nofollow noreferrer\">Huffman coding</a> be what you're looking for? It's a compression algorithm, which pretty much represents any information with a minimum of wasted bits.</p>\n" }, { "answer_id": 130603, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 1, "selected": false, "text": "<p>Any solution you use is going to be space-inefficient because 26 is not a power of 2. As far as an algorithm goes, I'd rather use a lookup table than an on-the-fly calculation for each series of 9 bits. Your lookup table would 512 entries long.</p>\n" }, { "answer_id": 130670, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 3, "selected": false, "text": "<p>If you assign a different number of bits per letter, you should be able to exactly encode the bits in the twenty-six letters allowed without wasting any bits. (This is a lot like a Huffman code, only with a pre-built balanced tree.)</p>\n\n<p>To encode bits into letters: Accumulate bits until you match exactly one of the bit codes in the lookup table. Output that letter, clear the bit buffer, and keep going.</p>\n\n<p>To decode letters into bits: For each letter, output the bit sequence in the table.</p>\n\n<p>Implementing in code is left as an exercise to the reader. (Or to me, if I get bored later.)</p>\n\n<pre><code>a 0000\nb 0001\nc 0010\nd 0011\ne 0100\nf 0101\ng 01100\nh 01101\ni 01110\nj 01111\nk 10000\nl 10001\nm 10010\nn 10011\no 10100\np 10101\nq 10110\nr 10111\ns 11000\nt 11001\nu 11010\nv 11011\nw 11100\nx 11101\ny 11110\nz 11111\n</code></pre>\n" }, { "answer_id": 130678, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "<p>Convert each block of 47 bits to a base 26 number of 10 digits. This gives you more than 99.99% efficiency.</p>\n\n<p>This method, as well as others like Huffman, needs a padding mechanism to support variable-length input. This introduces some inefficiency which is less significant with longer inputs.</p>\n\n<p>At the end of the bit stream, append an extra <code>1</code> bit. This must be done in all cases, even when the length of the bit stream is a multiple of 47. Any high-order letters of \"zero\" value can be skipped in the last block of encoded output.</p>\n\n<p>When decoding the letters, a truncated final block can be filled out with \"zero\" letters and converted to a 47-bit base 2 representation. The final <code>1</code> bit is not data, but marks the end of the bit stream.</p>\n" }, { "answer_id": 131602, "author": "SteinNorheim", "author_id": 19220, "author_profile": "https://Stackoverflow.com/users/19220", "pm_score": 1, "selected": false, "text": "<p>If you want the binary footprint of each letter to have the same size, the optimal solution would be given by <a href=\"http://en.wikipedia.org/wiki/Arithmetic_encoding\" rel=\"nofollow noreferrer\">Arithmetic Encoding</a>. However, it will not reach your goal of a mean representation of 4.5 bits/char. Given 26 different characters (not including space etc) 4.7 would be the best you can reach without using variable-length encoding (Huffman, for instance. See Jaegers's answer) or other compression algoritms.</p>\n\n<p>A suboptimal, although simpler, solution could be to find a feasible number of characters to fit into a big integer. For instance, if you form a 32-bit integer out of every 6 charachter chunk (which is possible as 26^6 &lt; 2^32), you use 5.33 bits/char. You can actually even fit 13 letters into a 64 bit integer (4.92 bits/char). This is quite close to the optimal solution, and still rather easy to implement. Using bigger ints than 64 bits can be tricky due to missing native support in many progamming languages.</p>\n\n<p>If you want even better compression rates for text, you should definitely also look into dictionary-based compression algorithms, such as LZW or Deflate.</p>\n" }, { "answer_id": 131648, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "<p>Zero waste would be log_2(26) bits per letter. As pointed out earlier, you can get to 4.7 by reading 47 bits and converting them to 10 letters. However, you can get to 4.67 by converting every 14 bits into 3 characters. This has the advantage that it fits into an integer. If you have storage space and run time is important, you can create a lookup table with 17,576 entries mapping the possible 14 bits into 3 letters. Otherwise, you can do mod and div operations to compute the 3 letters.</p>\n\n<pre><code>number of letters number of bits bits/letter\n 1 4 4\n 2 9 4.5\n 3 14 4.67\n 4 18 4.5\n 5 23 4.6\n 6 28 4.67\n 7 32 4.57\n 8 37 4.63\n 9 42 4.67\n10 47 4.7\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I seek an algorithm that will let me represent an incoming sequence of bits as letters ('a' .. 'z' ), in a minimal matter such that the stream of bits can be regenerated from the letters, without ever holding the entire sequence in memory. That is, given an external bit source (each read returns a practically random bit), and user input of a number of bits, I would like to print out the minimal number of characters that can represent those bits. Ideally there should be a parameterization - how much memory versus maximum bits before some waste is necessary. Efficiency Goal - The same number of characters as the base-26 representation of the bits. Non-solutions: 1. If sufficient storage was present, store the entire sequence and use a big-integer MOD 26 operation. 2. Convert every 9 bits to 2 characters - This seems suboptimal, wasting 25% of information capacity of the letters output.
If you assign a different number of bits per letter, you should be able to exactly encode the bits in the twenty-six letters allowed without wasting any bits. (This is a lot like a Huffman code, only with a pre-built balanced tree.) To encode bits into letters: Accumulate bits until you match exactly one of the bit codes in the lookup table. Output that letter, clear the bit buffer, and keep going. To decode letters into bits: For each letter, output the bit sequence in the table. Implementing in code is left as an exercise to the reader. (Or to me, if I get bored later.) ``` a 0000 b 0001 c 0010 d 0011 e 0100 f 0101 g 01100 h 01101 i 01110 j 01111 k 10000 l 10001 m 10010 n 10011 o 10100 p 10101 q 10110 r 10111 s 11000 t 11001 u 11010 v 11011 w 11100 x 11101 y 11110 z 11111 ```
130,587
<p><em>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a>.]</em></p> <p>Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:</p> <pre> ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ </pre> <p>Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):</p> <pre> ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt </pre> <p>Of these, only four (<code>FrameworkDir</code>, <code>FrameworkSDKDir</code>, <code>VCInstallDir</code> and <code>VSInstallDir</code>) are set in the environment used for build-events.</p> <p>As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.</p> <p>I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:</p> <pre> postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" </pre> <p>Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.</p> <p>Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?</p>
[ { "answer_id": 130773, "author": "TonyOssa", "author_id": 3276, "author_profile": "https://Stackoverflow.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>This is a bit hacky, but it could work.</p>\n\n<p>Why not call multiple .py scripts in a row?</p>\n\n<p>Each scripts can pass in a small subset of the parameters, and the values to a temp text file. The final script will read and work off of the temp text file.</p>\n\n<p>I agree that this method is filled with danger and WTF's, but sometimes you have to just hack stuff together.</p>\n" }, { "answer_id": 135078, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 2, "selected": false, "text": "<p>You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user macros. When you add a macro using this mechanism, there is a checkbox for setting the user macro as an environment variable. We use this type of mechanism in our build system to rapidly set up projects to perform out-of-place builds. Our various build directories are all defined as user macros. I have not actually verified that the environment variables are set in an external script called from post-build. I tend to use these macros as command line arguments to my post-build scripts - but I would expect accessing them as environment variables should work for you.</p>\n" }, { "answer_id": 4695601, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 1, "selected": true, "text": "<p>As far as I can tell, the method described in the question is the only way to pass build variables to a Python script.</p>\n\n<p>Perhaps Visual Studio 2010 has something better?</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
*[NOTE: This questions is similar to but **not the same** as [this one](https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events).]* Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples: ``` ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ ``` Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled): ``` ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt ``` Of these, only four (`FrameworkDir`, `FrameworkSDKDir`, `VCInstallDir` and `VSInstallDir`) are set in the environment used for build-events. As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros. I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like: ``` postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" ``` Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated. Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?
As far as I can tell, the method described in the question is the only way to pass build variables to a Python script. Perhaps Visual Studio 2010 has something better?
130,604
<p>I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. </p> <p>ie. </p> <p>50 + 100 = 150</p> <p>int.Max + 50 = int.Max and not int.Min + 50 </p>
[ { "answer_id": 130660, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": true, "text": "<pre><code>int penaltySum(int a, int b)\n{\n return (int.MaxValue - a &lt; b) ? int.MaxValue : a + b;\n}\n</code></pre>\n\n<p>Update: If your penalties can be negative, this would be more appropriate:</p>\n\n<pre><code>int penaltySum(int a, int b)\n{\n if (a &gt; 0 &amp;&amp; b &gt; 0)\n {\n return (int.MaxValue - a &lt; b) ? int.MaxValue : a + b;\n }\n\n if (a &lt; 0 &amp;&amp; b &lt; 0)\n {\n return (int.MinValue - a &gt; b) ? int.MinValue : a + b;\n }\n\n return a + b;\n}\n</code></pre>\n" }, { "answer_id": 130856, "author": "Ben Griswold", "author_id": 4115, "author_profile": "https://Stackoverflow.com/users/4115", "pm_score": 3, "selected": false, "text": "<p>This answer...</p>\n\n<pre><code>int penaltySum(int a, int b)\n{\n return (int.MaxValue - a &lt; b) ? int.MaxValue : a + b;\n}\n</code></pre>\n\n<p>fails the following test:</p>\n\n<pre><code>[TestMethod]\npublic void PenaltySumTest()\n{\n int x = -200000; \n int y = 200000; \n int z = 0;\n\n Assert.AreEqual(z, penaltySum(x, y));\n}\n</code></pre>\n\n<p>I would suggest implementing penaltySum() as follows:</p>\n\n<pre><code>private int penaltySum(int x, int y, int max)\n{\n long result = (long) x + y;\n return result &gt; max ? max : (int) result;\n}\n</code></pre>\n\n<p>Notice I'm passing in the max value, but you could hardcode in the int.MaxValue if you would like.</p>\n\n<p>Alternatively, you could force the arithmetic operation overflow check and do the following:</p>\n\n<pre><code>private int penaltySum(int x, int y, int max)\n{\n int result = int.MaxValue;\n\n checked\n {\n try\n {\n result = x + y;\n }\n catch\n {\n // Arithmetic operation resulted in an overflow.\n }\n }\n\n return result;\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 214525, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 0, "selected": false, "text": "<p>Does it overflow a lot, or is that an error condition? How about using try/catch (overflow exception)?</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ]
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. ie. 50 + 100 = 150 int.Max + 50 = int.Max and not int.Min + 50
``` int penaltySum(int a, int b) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } ``` Update: If your penalties can be negative, this would be more appropriate: ``` int penaltySum(int a, int b) { if (a > 0 && b > 0) { return (int.MaxValue - a < b) ? int.MaxValue : a + b; } if (a < 0 && b < 0) { return (int.MinValue - a > b) ? int.MinValue : a + b; } return a + b; } ```
130,605
<p>I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:</p> <pre>select * from [User] where UserRolesBitmask | 22 = 22</pre> <p>This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.</p>
[ { "answer_id": 130691, "author": "KevDog", "author_id": 13139, "author_profile": "https://Stackoverflow.com/users/13139", "pm_score": 4, "selected": true, "text": "<p>I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV. </p>\n\n<pre><code>from u in DataContext.Users\nwhere UserRolesBitmask | 22 == 22\nselect u\n</code></pre>\n" }, { "answer_id": 130716, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 0, "selected": false, "text": "<p>If that doesn't work you could always use <code>ExecuteCommand</code>:</p>\n\n<pre><code>DataContext.ExecuteCommand(\"select * from [User] where UserRolesBitmask | {0} = {0}\", 22);\n</code></pre>\n" }, { "answer_id": 1318415, "author": "Eric", "author_id": 47350, "author_profile": "https://Stackoverflow.com/users/47350", "pm_score": 4, "selected": false, "text": "<p>As a side note though for my fellow googlers:\n<code>UserRolesBitmask | 22 == 22</code> selects all users that don't have any other flags (its not a filter, its like saying <code>1==1</code>).</p>\n\n<p>What you want is either:</p>\n\n<ul>\n<li><code>UserRolesBitmask &amp; 22 == 22</code> which selects users which have all the roles in their bitmask or:</li>\n<li><code>UserRolesBitmask &amp; 22 != 0</code> which selects users which have at least one of the roles in their bitmask</li>\n</ul>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example: ``` select * from [User] where UserRolesBitmask | 22 = 22 ``` This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.
I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV. ``` from u in DataContext.Users where UserRolesBitmask | 22 == 22 select u ```
130,614
<p>I've got a dictionary, something like</p> <pre><code>Dictionary&lt;Foo,String&gt; fooDict </code></pre> <p>I step through everything in the dictionary, e.g.</p> <pre><code>foreach (Foo foo in fooDict.Keys) MessageBox.show(fooDict[foo]); </code></pre> <p>It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned.</p> <p>How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."</p>
[ { "answer_id": 130653, "author": "Statement", "author_id": 2166173, "author_profile": "https://Stackoverflow.com/users/2166173", "pm_score": 0, "selected": false, "text": "<p>I am <em>not fully educated in the domain</em> to properly answer the question, but I have <strong>a feeling</strong> that the dictionary sorts the values according to the key, in order to perform quick key search. This would suggest that the dictionary is sorted by key values according to key comparison. However, looking at <strong>object</strong> methods, I assume they are using hash codes to compare different objects considering there is no requirement on the type used for keys. This is only a guess. Someone more knowledgey should fill in with more detail. </p>\n\n<p>Why are you interested in manipulating the \"index\" of a dictionary when its purpose is to index with arbitrary types?</p>\n" }, { "answer_id": 130668, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 4, "selected": true, "text": "<p>If you read the documentation on MSDN you'll see this:</p>\n\n<p>\"The order in which the items are returned is undefined.\"</p>\n\n<p>You can't gaurantee the order, because a Dictionary is not a list or an array. It's meant to look up a value by the key, and any ability to iterate values is just a convenience but the order is not behavior you should depend on.</p>\n" }, { "answer_id": 130816, "author": "Asmor", "author_id": 18210, "author_profile": "https://Stackoverflow.com/users/18210", "pm_score": 0, "selected": false, "text": "<p>I don't know if anyone will find this useful, but here's what I ended up figuring out. It seems to work (by which I mean it doesn't throw any exceptions), but I'm still a ways away from being able to test that it works as I hope it does. I have done a similar thing before, though.</p>\n\n<pre><code> public void sortSections()\n {\n //OMG THIS IS UGLY!!!\n KeyValuePair&lt;ListViewItem, TextSection&gt;[] sortable = textSecs.ToArray();\n IOrderedEnumerable&lt;KeyValuePair&lt;ListViewItem, TextSection&gt;&gt; sorted = sortable.OrderBy(kvp =&gt; kvp.Value.cardinality);\n\n foreach (KeyValuePair&lt;ListViewItem, TextSection&gt; kvp in sorted)\n {\n TextSection sec = kvp.Value;\n ListViewItem key = kvp.Key;\n\n textSecs.Remove(key);\n textSecs.Add(key, sec);\n }\n }\n</code></pre>\n" }, { "answer_id": 130841, "author": "Michael Lang", "author_id": 19452, "author_profile": "https://Stackoverflow.com/users/19452", "pm_score": 0, "selected": false, "text": "<p>The short answer is that there shouldn't be a way since a Dictionary \"Represents a collection of keys and values.\" which does not imply any sort of ordering. Any hack you might find is outside the definition of the class and may be liable to change.</p>\n\n<p>You should probably first ask yourself if a Dictionary is really called for in this situation, or if you can get away with using a List of KeyValuePairs.</p>\n\n<p>Otherwise, something like this might be useful:</p>\n\n<pre><code>public class IndexableDictionary&lt;T1, T2&gt; : Dictionary&lt;T1, T2&gt;\n{\n private SortedDictionary&lt;int, T1&gt; _sortedKeys;\n\n public IndexableDictionary()\n {\n _sortedKeys = new SortedDictionary&lt;int, T1&gt;();\n }\n public new void Add(T1 key, T2 value)\n {\n _sortedKeys.Add(_sortedKeys.Count + 1, key);\n base.Add(key, value);\n }\n\n private IEnumerable&lt;KeyValuePair&lt;T1, T2&gt;&gt; Enumerable()\n {\n foreach (T1 key in _sortedKeys.Values)\n {\n yield return new KeyValuePair&lt;T1, T2&gt;(key, this[key]);\n }\n }\n\n public new IEnumerator&lt;KeyValuePair&lt;T1, T2&gt;&gt; GetEnumerator()\n {\n return Enumerable().GetEnumerator();\n }\n\n public KeyValuePair&lt;T1, T2&gt; this[int index]\n {\n get\n {\n return new KeyValuePair&lt;T1, T2&gt; (_sortedKeys[index], base[_sortedKeys[index]]);\n }\n set\n {\n _sortedKeys[index] = value.Key;\n base[value.Key] = value.Value;\n }\n\n }\n\n\n}\n</code></pre>\n\n<p>With client code looking something like this:</p>\n\n<pre><code> static void Main(string[] args)\n {\n IndexableDictionary&lt;string, string&gt; fooDict = new IndexableDictionary&lt;string, string&gt;();\n\n fooDict.Add(\"One\", \"One\");\n fooDict.Add(\"Two\", \"Two\");\n fooDict.Add(\"Three\", \"Three\");\n\n // Print One, Two, Three\n foreach (KeyValuePair&lt;string, string&gt; kvp in fooDict)\n Console.WriteLine(kvp.Value);\n\n\n\n KeyValuePair&lt;string, string&gt; temp = fooDict[1];\n fooDict[1] = fooDict[2];\n fooDict[2] = temp;\n\n\n // Print Two, One, Three\n foreach (KeyValuePair&lt;string, string&gt; kvp in fooDict)\n Console.WriteLine(kvp.Value);\n\n Console.ReadLine();\n }\n</code></pre>\n\n<p><strong>UPDATE:</strong> For some reason it won't let me comment on my own answer. </p>\n\n<p>Anyways, IndexableDictionary is different from OrderedDictionary in that </p>\n\n<ol>\n<li>\"The elements of an OrderedDictionary are not sorted in any way.\" So foreach's would not pay attention to the numerical indices</li>\n<li>It is strongly typed, so you don't have to mess around with casting things out of DictionaryEntry structs</li>\n</ol>\n" }, { "answer_id": 130911, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 3, "selected": false, "text": "<p>You may be interested in the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary\" rel=\"nofollow noreferrer\"><code>OrderedDicationary</code></a> class that comes in <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized\" rel=\"nofollow noreferrer\"><code>System.Collections.Specialized</code></a> namespace.</p>\n<p>If you look at the comments at the very bottom, someone from MSFT has posted this interesting note:</p>\n<blockquote>\n<p>This type is actually misnamed; it is not an 'ordered' dictionary as such, but rather an 'indexed' dictionary. Although, today there is no equivalent generic version of this type, if we add one in the future it is likely that we will name such as type 'IndexedDictionary'.</p>\n</blockquote>\n<p>I think it would be trivial to derive from this class and make a generic version of OrderedDictionary.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18210/" ]
I've got a dictionary, something like ``` Dictionary<Foo,String> fooDict ``` I step through everything in the dictionary, e.g. ``` foreach (Foo foo in fooDict.Keys) MessageBox.show(fooDict[foo]); ``` It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned. How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."
If you read the documentation on MSDN you'll see this: "The order in which the items are returned is undefined." You can't gaurantee the order, because a Dictionary is not a list or an array. It's meant to look up a value by the key, and any ability to iterate values is just a convenience but the order is not behavior you should depend on.
130,616
<p>I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).</p> <p>Am I doing something wrong or is this "by design"?</p> <p>The code to register this service:</p> <pre><code> SC_HANDLE schService = CreateService( schSCManager, strNameNoSpaces, strServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, strUser, (strPassword.IsEmpty())?NULL:strPassword); </code></pre>
[ { "answer_id": 130658, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>You need to specify an empty string, not NULL if there is no password. NULL is not a valid empty string, \"\" is. Probably you should just pass <code>strPassword</code> for the last parameter.</p>\n\n<pre><code>SC_HANDLE schService = CreateService( \n schSCManager, \n strNameNoSpaces, \n strServiceName, \n SERVICE_ALL_ACCESS, \n SERVICE_WIN32_OWN_PROCESS, \n SERVICE_AUTO_START, \n SERVICE_ERROR_NORMAL, \n szPath, \n NULL, \n NULL, \n NULL, \n strUser,\n\n// change this line to:\n strPassword.IsEmpty() ? L\"\" : strPassword);\n// or maybe\n strPassword);\n</code></pre>\n" }, { "answer_id": 130696, "author": "dennisV", "author_id": 20208, "author_profile": "https://Stackoverflow.com/users/20208", "pm_score": 0, "selected": false, "text": "<p>Thank you - I've tried that first actually, but to no avail.</p>\n\n<p>If I start services.msc, manually go into service properties and clear the 2 password fields, then press \"Apply\" and try to start it, it also fails.</p>\n" }, { "answer_id": 130849, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": true, "text": "<p>It may be due to an OS security requirement or security policy. Check the security policies to see if anything is relevant there.</p>\n" }, { "answer_id": 130925, "author": "dennisV", "author_id": 20208, "author_profile": "https://Stackoverflow.com/users/20208", "pm_score": 2, "selected": false, "text": "<p>Yes, it was indeed related to the security policy. To elaborate:</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/bb457114.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/bb457114.aspx</a></p>\n\n<p>\"If you want to disable the restriction against logging on to the network without a password, you can do so through Local Security Policy. The policy setting that controls blank password restriction can be modified using the Local Security Policy or Group Policy MMC snap-ins. You can use either tool to find this policy option at <strong>Security Settings\\Local Policies\\Security Options</strong>. The name of the policy is Accounts: <strong>Limit local account use of blank passwords to console logon only</strong>. It is enabled by default.\"</p>\n\n<p>After disabling that, it all works fine.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error). Am I doing something wrong or is this "by design"? The code to register this service: ``` SC_HANDLE schService = CreateService( schSCManager, strNameNoSpaces, strServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, strUser, (strPassword.IsEmpty())?NULL:strPassword); ```
It may be due to an OS security requirement or security policy. Check the security policies to see if anything is relevant there.
130,617
<p>I got a program that writes some data to a file using a method like the one below.</p> <pre><code> public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine(text); } } </code></pre> <p>When running the program I get an error:</p> <blockquote> <p>Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea bFromProxy)</p> </blockquote> <p>Question: What code do I need to catch this and how do I grant the access?</p>
[ { "answer_id": 130641, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 7, "selected": true, "text": "<p><strong>UPDATE:</strong></p>\n\n<p>Modified the code based on <a href=\"https://stackoverflow.com/a/4397002/11702\">this answer</a> to get rid of obsolete methods.</p>\n\n<p>You can use the Security namespace to check this:</p>\n\n<pre><code>public void ExportToFile(string filename)\n{\n var permissionSet = new PermissionSet(PermissionState.None); \n var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);\n permissionSet.AddPermission(writePermission);\n\n if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))\n {\n using (FileStream fstream = new FileStream(filename, FileMode.Create))\n using (TextWriter writer = new StreamWriter(fstream))\n {\n // try catch block for write permissions \n writer.WriteLine(\"sometext\");\n\n\n }\n }\n else\n {\n //perform some recovery action here\n }\n\n}\n</code></pre>\n\n<p>As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)</p>\n" }, { "answer_id": 462329, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 5, "selected": false, "text": "<p>When your code does the following:</p>\n\n<ol>\n<li>Checks the current user has permission to do something.</li>\n<li>Carries out the action that needs the entitlements checked in 1.</li>\n</ol>\n\n<p>You run the risk that the permissions change between <em>1</em> and <em>2</em> because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an <em>UnauthorisedAccessException</em> is thrown even if you have previously checked permissions. </p>\n\n<p>Note that the <em>SecurityManager</em> class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, <em>IsGranted</em> will always return true for locally running applications.</p>\n\n<p><strong>Example</strong> (derived from <a href=\"https://stackoverflow.com/questions/130617/how-do-you-check-for-permissions-to-write-to-a-directory-or-file#130641\">Josh's example</a>):</p>\n\n<pre><code>//1. Provide early notification that the user does not have permission to write.\nFileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);\nif(!SecurityManager.IsGranted(writePermission))\n{\n //No permission. \n //Either throw an exception so this can be handled by a calling function\n //or inform the user that they do not have permission to write to the folder and return.\n}\n\n//2. Attempt the action but handle permission changes.\ntry\n{\n using (FileStream fstream = new FileStream(filename, FileMode.Create))\n using (TextWriter writer = new StreamWriter(fstream))\n {\n writer.WriteLine(\"sometext\");\n }\n}\ncatch (UnauthorizedAccessException ex)\n{\n //No permission. \n //Either throw an exception so this can be handled by a calling function\n //or inform the user that they do not have permission to write to the folder and return.\n}\n</code></pre>\n\n<p>It's tricky and <strong>not recommended</strong> to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the <em>System.Security.AccessControl</em> classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/208347aa99a2de3b\" rel=\"nofollow noreferrer\">This</a> post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.</p>\n" }, { "answer_id": 1801847, "author": "RockWorld", "author_id": 185550, "author_profile": "https://Stackoverflow.com/users/185550", "pm_score": 2, "selected": false, "text": "<p>You can try following code block to check if the directory is having Write Access.</p>\n\n<p>It checks the FileSystemAccessRule.</p>\n\n<pre><code> string directoryPath = \"C:\\\\XYZ\"; //folderBrowserDialog.SelectedPath;\n bool isWriteAccess = false;\n try\n {\n AuthorizationRuleCollection collection = Directory.GetAccessControl(directoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));\n foreach (FileSystemAccessRule rule in collection)\n {\n if (rule.AccessControlType == AccessControlType.Allow)\n {\n isWriteAccess = true;\n break;\n }\n }\n }\n catch (UnauthorizedAccessException ex)\n {\n isWriteAccess = false;\n }\n catch (Exception ex)\n {\n isWriteAccess = false;\n }\n if (!isWriteAccess)\n {\n //handle notifications \n }\n</code></pre>\n" }, { "answer_id": 3422394, "author": "Pablonete", "author_id": 73130, "author_profile": "https://Stackoverflow.com/users/73130", "pm_score": 3, "selected": false, "text": "<p>Sorry, but none of the previous solutions helped me. I need to check both sides: SecurityManager and SO permissions. I have learned a lot with Josh code and with iain answer, but I'm afraid I need to use Rakesh code (also thanks to him). Only one bug: I found that he only checks for Allow and not for Deny permissions. So my proposal is:</p>\n\n<pre><code> string folder;\n AuthorizationRuleCollection rules;\n try {\n rules = Directory.GetAccessControl(folder)\n .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));\n } catch(Exception ex) { //Posible UnauthorizedAccessException\n throw new Exception(\"No permission\", ex);\n }\n\n var rulesCast = rules.Cast&lt;FileSystemAccessRule&gt;();\n if(rulesCast.Any(rule =&gt; rule.AccessControlType == AccessControlType.Deny)\n || !rulesCast.Any(rule =&gt; rule.AccessControlType == AccessControlType.Allow))\n throw new Exception(\"No permission\");\n\n //Here I have permission, ole!\n</code></pre>\n" }, { "answer_id": 21972598, "author": "JGU", "author_id": 2777695, "author_profile": "https://Stackoverflow.com/users/2777695", "pm_score": 2, "selected": false, "text": "<p>None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Test a directory for create file access permissions\n/// &lt;/summary&gt;\n/// &lt;param name=\"DirectoryPath\"&gt;Full directory path&lt;/param&gt;\n/// &lt;returns&gt;State [bool]&lt;/returns&gt;\npublic static bool DirectoryCanCreate(string DirectoryPath)\n{\n if (string.IsNullOrEmpty(DirectoryPath)) return false;\n\n try\n {\n AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n WindowsIdentity identity = WindowsIdentity.GetCurrent();\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (identity.Groups.Contains(rule.IdentityReference))\n {\n if ((FileSystemRights.CreateFiles &amp; rule.FileSystemRights) == FileSystemRights.CreateFiles)\n {\n if (rule.AccessControlType == AccessControlType.Allow)\n return true;\n }\n }\n }\n }\n catch {}\n return false;\n}\n</code></pre>\n" }, { "answer_id": 25333202, "author": "MaxOvrdrv", "author_id": 1583649, "author_profile": "https://Stackoverflow.com/users/1583649", "pm_score": 3, "selected": false, "text": "<p>Since this isn't closed, i would like to submit a new entry for anyone looking to have something working properly for them... using an amalgamation of what i found here, as well as using DirectoryServices to debug the code itself and find the proper code to use, here's what i found that works for me in every situation... note that my solution extends DirectoryInfo object... :</p>\n\n<pre><code> public static bool IsReadable(this DirectoryInfo me)\n {\n\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (Exception ex)\n { //Posible UnauthorizedAccessException\n return false;\n }\n\n bool isAllow=false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) &amp;&amp; rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) &amp;&amp; rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n }\n }\n\n return isAllow;\n }\n\n public static bool IsWriteable(this DirectoryInfo me)\n {\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (Exception ex)\n { //Posible UnauthorizedAccessException\n return false;\n }\n\n bool isAllow = false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) &amp;&amp; rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) &amp;&amp; rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n }\n }\n\n return me.IsReadable() &amp;&amp; isAllow;\n }\n</code></pre>\n" }, { "answer_id": 31040692, "author": "xmen", "author_id": 836308, "author_profile": "https://Stackoverflow.com/users/836308", "pm_score": 4, "selected": false, "text": "<p>Its a fixed version of MaxOvrdrv's <a href=\"https://stackoverflow.com/a/25333202/836308\">Code</a>.</p>\n\n<pre><code>public static bool IsReadable(this DirectoryInfo di)\n{\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (UnauthorizedAccessException uae)\n {\n Debug.WriteLine(uae.ToString());\n return false;\n }\n\n bool isAllow = false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) &amp;&amp; rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) &amp;&amp;\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) &amp;&amp;\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) &amp;&amp; rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n\n }\n }\n return isAllow;\n}\n\npublic static bool IsWriteable(this DirectoryInfo me)\n{\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (UnauthorizedAccessException uae)\n {\n Debug.WriteLine(uae.ToString());\n return false;\n }\n\n bool isAllow = false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) &amp;&amp; rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) &amp;&amp;\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) &amp;&amp;\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) &amp;&amp;\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) &amp;&amp;\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) &amp;&amp; rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n\n }\n }\n return isAllow;\n}\n</code></pre>\n" }, { "answer_id": 46452349, "author": "jinzai", "author_id": 3843815, "author_profile": "https://Stackoverflow.com/users/3843815", "pm_score": 0, "selected": false, "text": "<p>Wow...there is a lot of low-level security code in this thread -- most of which did not work for me, either -- although I learned a lot in the process. One thing that I learned is that most of this code is not geared to applications seeking per user access rights -- it is for Administrators wanting to alter rights programmatically, which -- as has been pointed out -- is <em>not</em> a good thing. As a developer, I cannot use the \"easy way out\" -- by running as Administrator -- which -- I am not one on the machine that runs the code, nor are my users -- so, as clever as these solutions are -- they are not for my situation, and probably not for most rank and file developers, either.</p>\n\n<p>Like most posters of this type of question -- I initially felt it was \"hackey\", too -- I have since decided that it is perfectly alright to try it and let the possible exception tell you exactly what the user's rights are -- because the information I got did not tell me what the rights actually were. The code below -- did.</p>\n\n<pre><code> Private Function CheckUserAccessLevel(folder As String) As Boolean\nTry\n Dim newDir As String = String.Format(\"{0}{1}{2}\",\n folder,\n If(folder.EndsWith(\"\\\"),\n \"\",\n \"\\\"),\n \"LookWhatICanDo\")\n Dim lookWhatICanDo = Directory.CreateDirectory(newDir)\n\n Directory.Delete(newDir)\n Return True\n\nCatch ex As Exception\n Return False\nEnd Try\n</code></pre>\n\n<p>End Function</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1361/" ]
I got a program that writes some data to a file using a method like the one below. ``` public void ExportToFile(string filename) { using(FileStream fstream = new FileStream(filename,FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine(text); } } ``` When running the program I get an error: > > Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied. > at System.IO.\_\_Error.WinIOError(Int32 errorCode, String maybeFullPath) > at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, > nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions > ptions, SECURITY\_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) > at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access > FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea > bFromProxy) > > > Question: What code do I need to catch this and how do I grant the access?
**UPDATE:** Modified the code based on [this answer](https://stackoverflow.com/a/4397002/11702) to get rid of obsolete methods. You can use the Security namespace to check this: ``` public void ExportToFile(string filename) { var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { using (FileStream fstream = new FileStream(filename, FileMode.Create)) using (TextWriter writer = new StreamWriter(fstream)) { // try catch block for write permissions writer.WriteLine("sometext"); } } else { //perform some recovery action here } } ``` As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)
130,618
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p> <pre><code>if (datetime.now() - self.timestamp) &gt; 100 # Where 100 is either seconds or minutes </code></pre> <p>This generates a type error. </p> <p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime" rel="noreferrer">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p> <p>Please post lists of datetime best practices.</p>
[ { "answer_id": 130623, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>You can subtract two <a href=\"http://docs.python.org/lib/module-datetime.html\" rel=\"nofollow noreferrer\">datetime</a> objects to find the difference between them.<br>\nYou can use <code>datetime.fromtimestamp</code> to parse a POSIX time stamp.</p>\n" }, { "answer_id": 130647, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 1, "selected": false, "text": "<p>You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:</p>\n\n<pre><code>def seconds_difference(stamp1, stamp2):\n delta = stamp1 - stamp2\n return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.\n</code></pre>\n\n<p>Use abs() in the answer if you always want a positive number of seconds.</p>\n\n<p>To discover how many seconds into the past a timestamp is, you can use it like this:</p>\n\n<pre><code>if seconds_difference(datetime.datetime.now(), timestamp) &lt; 100:\n pass\n</code></pre>\n" }, { "answer_id": 130652, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 3, "selected": false, "text": "<p>Compare the difference to a timedelta that you create:</p>\n\n<pre><code>if datetime.datetime.now() - timestamp &gt; datetime.timedelta(seconds = 5):\n print 'older'\n</code></pre>\n" }, { "answer_id": 130665, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 8, "selected": true, "text": "<p>Use the <code>datetime.timedelta</code> class:</p>\n\n<pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta\n&gt;&gt;&gt; then = datetime.now() - timedelta(hours = 2)\n&gt;&gt;&gt; now = datetime.now()\n&gt;&gt;&gt; (now - then) &gt; timedelta(days = 1)\nFalse\n&gt;&gt;&gt; (now - then) &gt; timedelta(hours = 1)\nTrue\n</code></pre>\n\n<p>Your example could be written as:</p>\n\n<pre><code>if (datetime.now() - self.timestamp) &gt; timedelta(seconds = 100)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (datetime.now() - self.timestamp) &gt; timedelta(minutes = 100)\n</code></pre>\n" }, { "answer_id": 130669, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 0, "selected": false, "text": "<p>Like so:</p>\n\n<pre><code># self.timestamp should be a datetime object\nif (datetime.now() - self.timestamp).seconds &gt; 100:\n print \"object is over 100 seconds old\"\n</code></pre>\n" }, { "answer_id": 10546316, "author": "Chong Ying Fan", "author_id": 1388716, "author_profile": "https://Stackoverflow.com/users/1388716", "pm_score": 3, "selected": false, "text": "<p>Alternative:</p>\n\n<pre><code>if (datetime.now() - self.timestamp).total_seconds() &gt; 100:\n</code></pre>\n\n<p>Assuming self.timestamp is an datetime instance</p>\n" }, { "answer_id": 67727197, "author": "Golden Lion", "author_id": 4001177, "author_profile": "https://Stackoverflow.com/users/4001177", "pm_score": 0, "selected": false, "text": "<p>Convert your time delta into seconds and then use conversion back to hours elapsed and remaining minutes.</p>\n<pre><code>start_time=datetime(\n year=2021,\n month=5,\n day=27,\n hour=10,\n minute=24,\n microsecond=0)\n\n end_time=datetime.now()\n delta=(end_time-start_time)\n\n seconds_in_day = 24 * 60 * 60\n seconds_in_hour= 1 * 60 * 60\n\n elapsed_seconds=delta.days * seconds_in_day + delta.seconds\n\n hours= int(elapsed_seconds/seconds_in_hour)\n minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)\n\n print(&quot;Hours {} Minutes {}&quot;.format(hours,minutes))\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20794/" ]
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: ``` if (datetime.now() - self.timestamp) > 100 # Where 100 is either seconds or minutes ``` This generates a type error. What is the proper way to do date time comparison in python? I already looked at [WorkingWithTime](http://wiki.python.org/moin/WorkingWithTime) which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. Please post lists of datetime best practices.
Use the `datetime.timedelta` class: ``` >>> from datetime import datetime, timedelta >>> then = datetime.now() - timedelta(hours = 2) >>> now = datetime.now() >>> (now - then) > timedelta(days = 1) False >>> (now - then) > timedelta(hours = 1) True ``` Your example could be written as: ``` if (datetime.now() - self.timestamp) > timedelta(seconds = 100) ``` or ``` if (datetime.now() - self.timestamp) > timedelta(minutes = 100) ```
130,636
<p>When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure:</p> <pre><code>Configure findings: FFI: no (user requested: default) readline: yes (user requested: yes) libsigsegv: no, consider installing GNU libsigsegv ./configure: libsigsegv was not detected, thus some features, such as generational garbage collection and stack overflow detection in interpreted Lisp code cannot be provided. Please do this: mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz tar xfz libsigsegv-2.5.tar.gz cd libsigsegv-2.5 ./configure --prefix=${prefix} &amp;&amp; make &amp;&amp; make check &amp;&amp; make install cd ../.. ./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp If you insist on building without libsigsegv, please pass --ignore-absence-of-libsigsegv to this script: ./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp </code></pre> <p>I've tried doing as requested, but it didn't help: it seems to ignore the <code>--with-libsigsegv-prefix</code> option. I also tried putting installing libsigsegv in a standard location (<code>/usr/local</code>). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system.</p> <p>I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).</p>
[ { "answer_id": 130655, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 1, "selected": false, "text": "<p>If you look at 'config.log' it might tell you why configure is not finding libsigsegv</p>\n" }, { "answer_id": 130752, "author": "Luís Oliveira", "author_id": 2967, "author_profile": "https://Stackoverflow.com/users/2967", "pm_score": 3, "selected": true, "text": "<p>Here are my notes from compiling CLISP on Ubuntu in the past, hope this helps:</p>\n\n<pre><code>sudo apt-get install libsigsegv-dev libreadline5-dev\n\n# as of 7.10, Ubuntu's libffcall1-dev is broken and I had to get it from CVS\n# and make sure CLISP didn't use Ubuntu's version.\nsudo apt-get remove libffcall1-dev libffcall1\ncvs -z3 -d:pserver:[email protected]:/sources/libffcall co -P ffcall\ncd ffcall; ./configure; make\nsudo make install\n\ncvs -z3 -d:pserver:[email protected]:/cvsroot/clisp co -P clisp\ncd clisp\n./configure --with-libffcall-prefix=/usr/local --prefix=/home/luis/Software\nulimit -s 16384\ncd src; make install\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure: ``` Configure findings: FFI: no (user requested: default) readline: yes (user requested: yes) libsigsegv: no, consider installing GNU libsigsegv ./configure: libsigsegv was not detected, thus some features, such as generational garbage collection and stack overflow detection in interpreted Lisp code cannot be provided. Please do this: mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz tar xfz libsigsegv-2.5.tar.gz cd libsigsegv-2.5 ./configure --prefix=${prefix} && make && make check && make install cd ../.. ./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp If you insist on building without libsigsegv, please pass --ignore-absence-of-libsigsegv to this script: ./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp ``` I've tried doing as requested, but it didn't help: it seems to ignore the `--with-libsigsegv-prefix` option. I also tried putting installing libsigsegv in a standard location (`/usr/local`). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system. I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).
Here are my notes from compiling CLISP on Ubuntu in the past, hope this helps: ``` sudo apt-get install libsigsegv-dev libreadline5-dev # as of 7.10, Ubuntu's libffcall1-dev is broken and I had to get it from CVS # and make sure CLISP didn't use Ubuntu's version. sudo apt-get remove libffcall1-dev libffcall1 cvs -z3 -d:pserver:[email protected]:/sources/libffcall co -P ffcall cd ffcall; ./configure; make sudo make install cvs -z3 -d:pserver:[email protected]:/cvsroot/clisp co -P clisp cd clisp ./configure --with-libffcall-prefix=/usr/local --prefix=/home/luis/Software ulimit -s 16384 cd src; make install ```
130,640
<p>I would like to be able to say things like</p> <p><strong>cd [.fred]</strong> and have my default directory go there, and my prompt change to indicate the full path to my current location.</p>
[ { "answer_id": 131235, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>My DCL is <em>really</em> rusty, but can't you create an alias for SET DEFAULT named CD?</p>\n" }, { "answer_id": 131275, "author": "chimp", "author_id": 18364, "author_profile": "https://Stackoverflow.com/users/18364", "pm_score": 3, "selected": false, "text": "<p>Just type</p>\n\n<p><code>cd:==set default</code> </p>\n\n<p>at the command prompt. You can also put this in your LOGIN.COM file, but be sure to put a $ in front, i.e.</p>\n\n<p><code>$ cd:==set default</code></p>\n\n<p>To change your prompt to show your default, something like this may work up to a point</p>\n\n<p><code>$ set prompt='f$env(\"default\")'</code></p>\n\n<p>There is a problem though with the fact that VMS prompt has maximum 32 characters, and your default might be longer than that. Have a look at <a href=\"http://www.phrack.com/issues.html?issue=19&amp;id=2\" rel=\"noreferrer\">this page</a> for a way around that problem.</p>\n" }, { "answer_id": 223455, "author": "Luc M", "author_id": 14673, "author_profile": "https://Stackoverflow.com/users/14673", "pm_score": 3, "selected": true, "text": "<p>Here's my setup:</p>\n\n<p>You need 2 files (typed below) : godir.com and prompt.com in your sys$login</p>\n\n<p>You may define a symbole</p>\n\n<pre><code>CD == \"@sys$login:godir.com\"\n</code></pre>\n\n<p>But I suggest you to use something else... (ie SD == \"@sys$login:godir.com\")</p>\n\n<p>I modify the help text. It was in french...</p>\n\n<p>You will have to retype the escape caracters into godir.com \nReplace ESC by the real escape into GRAPH_BOUCLE: (see bottom of godir.com)</p>\n\n<p>Then to use it:</p>\n\n<pre><code>SD ?\nSD a_directory\n...\n</code></pre>\n\n<p>Hope it helps.</p>\n\n<hr>\n\n<p>Here's prompt.com</p>\n\n<pre><code>$ noeud = f$trnlnm(\"SYS$NODE\") - \"::\"\n$ if noeud .eqs. \"HQSVYC\" then noeud = \"¥\"\n$!\n$ noeud = noeud - \"MQO\"\n$ def_dir = f$directory()\n$ def_dir = f$extract(1,f$length(def_dir)-2,def_dir)\n$boucle:\n$ i = f$locate(\".\",def_dir)\n$ if i .eq. f$length(def_dir) then goto fin_boucle\n$ def_dir = f$extract(i+1,f$length(def_dir)-1,def_dir)\n$ goto boucle\n$!\n$fin_boucle:\n$! temp = \"''noeud' ''def_dir' \" + \"''car_prompt'\"\n$ temp = \"''noeud'\" -\n + \" ''def_dir' \" -\n + \"''f$logical(\"\"environnement\"\")'\" -\n + \"''car_prompt'\"\n$! temp = \"''noeud'\" -\n$! + \"''def_dir'\" -\n$! + \"''f$logical(\"\"environnement\"\")'\" -\n$! + \"''car_prompt'\"\n$ set prompt=\"''temp' \"\n$!\n$! PROMPT.COM\n$!\n</code></pre>\n\n<p>Here's godir.com</p>\n\n<pre><code>$!\n$! GODIR.COM\n$!\n$ set noon\n$ set_prompt = \"@sys$login:prompt.com\"\n$ if f$type(TAB_DIR_N) .nes. \"\" then goto 10$\n$ goto 20$\n$ INIT:\n$ temp2 = \"INIT\"\n$ CLEAR:\n$ temp = 0\n$\n$ INIT2:\n$ temp = temp +1\n$ if temp .gt. TAB_DIR_N then goto INIT3\n$ delete/symb/glo TAB_DIR_'temp'\n$ goto INIT2\n$\n$ INIT3:\n$ P1 = \"\"\n$ if temp2 .eqs. \"INIT\" then goto 20$\n$ delete/symb/glo TAB_DIR_N\n$ delete/symb/glo TAB_DIR_P\n$ delete/symb/glo TAB_DIR_I\n$ exit\n$\n$ 20$:\n$ TAB_DIR_N == 1\n$ TAB_DIR_P == 1\n$ TAB_DIR_I == 1\n$ if \"''car_prompt'\" .eqs. \"\" then car_prompt == \"&gt;\"\n$ TAB_DIR_1 == f$parse(f$dir(),,,\"device\")+f$dir()\n$ 10$:\n$ if P1 .eqs. \"\" then goto LIST\n$ if P1 .eqs. \"?\" then goto SHOW\n$ if P1 .eqs. \".\" then P1 = \"[]\"\n$ if P1 .eqs. \"^\" then goto SET_CUR\n$ if (P1 .eqs. \"&lt;\") .or. (P1 .eqs. \"&gt;\") .or. -\n (P1 .eqs. \"..\") then P1 = \"[-]\"\n$ if (P1 .eqs. \"*\") .or. (P1 .eqs. \"0\") then goto HOME\n$ if (P1 .eqs. \"P\") .or. (P1 .eqs. \"p\") then goto PREVIOUS\n$ if (P1 .eqs. \"H\") .or. (P1 .eqs. \"h\") then goto HELP\n$ if (P1 .eqs. \"S\") .or. (P1 .eqs. \"s\") then goto SET_PROMPT\n$ if (P1 .eqs. \"G\") .or. (P1 .eqs. \"g\") then goto SET_PROMPT_GRAPHIC\n$ temp2 = \"\"\n$ if (P1 .eqs. \"~INIT\") .or. (P1 .eqs. \"~init\") then goto INIT\n$ if (P1 .eqs. \"~CLEAR\") .or. (P1 .eqs. \"~clear\") then goto CLEAR\n$\n$! *** Specification par un numero\n$ temp = f$extract(0,1,P1)\n$ if temp .eqs. \"-\" then goto DELETE\n$ temp2 = \"\"\n$boucle_reculer:\n$ if temp .nes. \"\\\" then goto fin_reculer\n$ temp2 = temp2 + \"-.\"\n$ P1 = P1 - \"\\\"\n$ temp = f$extract(0,1,P1)\n$ goto boucle_reculer\n$!\n$fin_reculer:\n$ P1 = temp2 + P1\n$ if (P1 .lts. \"0\") .or. (P1 .gts. \"9\") then goto SPEC\n$ temp = f$integer(\"''P1'\")\n$ if temp .eq. 0 then goto HOME\n$ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == temp\n$ goto SET2\n$\n$ SPEC:\n$! *** Specification relative de directory\n$\n$ temp = f$parse(\"[.''P1']\",\"missing.mis\")\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$ if DD .nes. \"\" then goto SET1\n$\n$! *** Specification de directory principal\n$\n$ temp = f$parse(\"[''P1']\",\"missing.mis\")\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$ if DD .nes. \"\" then goto SET1\n$\n$ temp = f$parse(\"[''P1']\",\"sys$login:missing.mis\")\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$ if DD .nes. \"\" then goto SET1\n$\n$! *** Specification exacte de directory\n$\n$ temp = f$parse(P1,\"missing.mis\")\n$ if f$locate(\"]\"+P1,temp) .ne. f$length(temp) then goto ERR\n$ if f$locate(\".][\",temp) .ne. f$length(temp) then temp = temp - \"][\"\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW\n$ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2\n$ if DD .nes. \"\" then goto SET1\n$\n$ temp = f$parse(P1,\"sys$login:missing.mis\")\n$ if f$locate(\"]\"+P1,temp) .ne. f$length(temp) then goto ERR\n$ if f$locate(\".][\",temp) .ne. f$length(temp) then temp = temp - \"][\"\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW\n$ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2\n$ if DD .nes. \"\" then goto SET1\n$\n$ goto ERR\n$\n$ HOME:\n$ DD = \"SYS$LOGIN\"\n$\n$ SET1:\n$ Set On\n$ On error then goto ERR1\n$ set message/nofac/noid/nosever/notext\n$ Set def 'DD'\n$ dir/output=nl:\n$ set message/fac/id/sever/text\n$ temp = f$parse(f$dir()) - \".;\"\n$ if temp .nes. \"\" then goto SET1F\n$ ERR1:\n$ set message/fac/id/sever/text\n$ temp = TAB_DIR_'TAB_DIR_I'\n$ Set def 'temp'\n$ goto ERR\n$ SET1F:\n$ I = 0\n$ LOOP1:\n$ I = I + 1\n$ if temp .eqs. TAB_DIR_'I' then goto FOUND\n$ if I .lt. TAB_DIR_N then goto LOOP1\n$\n$ TAB_DIR_N == TAB_DIR_N + 1\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == TAB_DIR_N\n$ TAB_DIR_'TAB_DIR_I' == temp\n$ goto SHOW\n$\n$ FOUND:\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == I\n$ goto SET2\n$\n$ SET_PROMPT:\n$ car_prompt == \"''P2'\"\n$ set_prompt\n$ exit\n$\n$ PREVIOUS:\n$ temp = TAB_DIR_P\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == temp\n$\n$ SET_CUR:\n$ SET2:\n$ DD = TAB_DIR_'TAB_DIR_I'\n$ set def 'DD'\n$\n$ SHOW:\n$ temp = TAB_DIR_'TAB_DIR_I'\n$ ws \" ''TAB_DIR_I' * ''temp'\"\n$ set_prompt\n$ exit\n$\n$ LIST:\n$ I = 0\n$ LOOP2:\n$ I = I + 1\n$ temp = TAB_DIR_'I'\n$ if I .eq. TAB_DIR_I then goto L_CUR\n$ if I .eq. TAB_DIR_P then GOTO L_PRE\n$ ws \" ''I' = ''temp'\"\n$ goto F_LOOP2\n$ L_CUR:\n$ ws \" ''I' * ''temp'\"\n$ goto F_LOOP2\n$ L_PRE:\n$ ws \" ''I' + ''temp'\"\n$\n$ F_LOOP2:\n$ if I .lt. TAB_DIR_N then goto LOOP2\n$ set_prompt\n$\n$ exit\n$\n$ DELETE:\n$ P1 = P1 - \"-\"\n$ temp2 = f$integer(\"''P1'\")\n$ DEL_1:\n$ temp = f$integer(\"''P1'\")\n$ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR\n$ if temp .eq. TAB_DIR_I then goto ERR\n$ if temp .lt. TAB_DIR_I then TAB_DIR_I == TAB_DIR_I - 1\n$ if temp .eq. TAB_DIR_P then TAB_DIR_P == TAB_DIR_I\n$ if temp .lt. TAB_DIR_P then TAB_DIR_P == TAB_DIR_P - 1\n$ LOOP3:\n$ if temp .eq. TAB_DIR_N then goto F_LOOP3\n$ temp3 = temp + 1\n$ TAB_DIR_'temp' == TAB_DIR_'temp3'\n$ temp = temp + 1\n$ goto LOOP3\n$ F_LOOP3:\n$ delete/symb/glo tab_dir_'tab_dir_n'\n$ TAB_DIR_N == TAB_DIR_N - 1\n$ if P2 .eqs. \"\" then goto FIN_DEL\n$ temp2 = temp2 + 1\n$ if temp2 .le. f$integer(\"''P2'\") then goto DEL_1\n$ FIN_DEL:\n$ goto LIST\n$\n$ ERR:\n$ ws \"*** ERREUR ***\"\n$ exit\n$\n$ HELP:\n$ ws \" H Show this menu\"\n$ ws \" null Show a list of directories\"\n$ ws \" ? Show current directory\"\n$ ws \" &lt; or [-] or\"\n$ ws \" &gt; or .. Remonte d'un niveau de directory\"\n$ ws \" * ou 0 Return to SYS$LOGIN\"\n$ ws \" P Last directory \"\n$ ws \" . ou [] Set cureent directory\"\n$ ws \" ^ Return to next directory\"\n$ ws \" x Set def to number x\"\n$ ws \" -x Remove the number x\"\n$ ws \" -x y Remove from x to y\"\n$ ws \" ddd Set def to [ddd] or [.ddd] or ddd:\"\n$ ws \" \\ddd Set def to [-.ddd]\"\n$ ws \" S \"\"&gt;&gt;\"\" Modify prompt for &gt;&gt;\"\n$ ws \" ~INIT Initialize to current directory \"\n$ ws \" (and delete all others references)\"\n$ ws \" ~CLEAR Remove all references\n$ ws \"\"\n$\n$ exit\n$\n$ SET_PROMPT_GRAPHIC:\n$ temp = \"''P2'\"\n$ i=0\n$ car_prompt == \"\"\n$ GRAPH_BOUCLE:\n$ t=f$extract(i,1,temp)\n$ if (t .eqs. \"e\") .or. (t .eqs. \"E\") then t=\"ESC\"\n$ if (t .eqs. \"g\") .or. (t .eqs. \"G\") then t=\"ESC(0\"\n$ V° (} .L-_. \"N\") .-_. (} .L-_. \"H\") }NL+ }=\"ESC(B\"\n$ car_prompt == car_prompt + t\n$ i = i+1\n$ if i .lts. f$length(temp) then goto GRAPH_BOUCLE\n$\n$ set_prompt\n$ exit\n</code></pre>\n" }, { "answer_id": 8545335, "author": "Peter Hofman", "author_id": 1000917, "author_profile": "https://Stackoverflow.com/users/1000917", "pm_score": 1, "selected": false, "text": "<p>Use HGSD which implements an SD (short for SET DEFAULT) command. Just google it. It is an improved version by Hunter Goatley of an older implementation.</p>\n\n<p>The only thing it cannot handle (yet), are logicals with multiple translations. Other than that, It works like a charm, and you do not need to type in complete directory names. You can even move to the next directory on the same level. </p>\n\n<p>It can also set the prompt if you have the right privileges in one go, so your prompt will reflect your default directory, just like in the old days on DOS.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
I would like to be able to say things like **cd [.fred]** and have my default directory go there, and my prompt change to indicate the full path to my current location.
Here's my setup: You need 2 files (typed below) : godir.com and prompt.com in your sys$login You may define a symbole ``` CD == "@sys$login:godir.com" ``` But I suggest you to use something else... (ie SD == "@sys$login:godir.com") I modify the help text. It was in french... You will have to retype the escape caracters into godir.com Replace ESC by the real escape into GRAPH\_BOUCLE: (see bottom of godir.com) Then to use it: ``` SD ? SD a_directory ... ``` Hope it helps. --- Here's prompt.com ``` $ noeud = f$trnlnm("SYS$NODE") - "::" $ if noeud .eqs. "HQSVYC" then noeud = "¥" $! $ noeud = noeud - "MQO" $ def_dir = f$directory() $ def_dir = f$extract(1,f$length(def_dir)-2,def_dir) $boucle: $ i = f$locate(".",def_dir) $ if i .eq. f$length(def_dir) then goto fin_boucle $ def_dir = f$extract(i+1,f$length(def_dir)-1,def_dir) $ goto boucle $! $fin_boucle: $! temp = "''noeud' ''def_dir' " + "''car_prompt'" $ temp = "''noeud'" - + " ''def_dir' " - + "''f$logical(""environnement"")'" - + "''car_prompt'" $! temp = "''noeud'" - $! + "''def_dir'" - $! + "''f$logical(""environnement"")'" - $! + "''car_prompt'" $ set prompt="''temp' " $! $! PROMPT.COM $! ``` Here's godir.com ``` $! $! GODIR.COM $! $ set noon $ set_prompt = "@sys$login:prompt.com" $ if f$type(TAB_DIR_N) .nes. "" then goto 10$ $ goto 20$ $ INIT: $ temp2 = "INIT" $ CLEAR: $ temp = 0 $ $ INIT2: $ temp = temp +1 $ if temp .gt. TAB_DIR_N then goto INIT3 $ delete/symb/glo TAB_DIR_'temp' $ goto INIT2 $ $ INIT3: $ P1 = "" $ if temp2 .eqs. "INIT" then goto 20$ $ delete/symb/glo TAB_DIR_N $ delete/symb/glo TAB_DIR_P $ delete/symb/glo TAB_DIR_I $ exit $ $ 20$: $ TAB_DIR_N == 1 $ TAB_DIR_P == 1 $ TAB_DIR_I == 1 $ if "''car_prompt'" .eqs. "" then car_prompt == ">" $ TAB_DIR_1 == f$parse(f$dir(),,,"device")+f$dir() $ 10$: $ if P1 .eqs. "" then goto LIST $ if P1 .eqs. "?" then goto SHOW $ if P1 .eqs. "." then P1 = "[]" $ if P1 .eqs. "^" then goto SET_CUR $ if (P1 .eqs. "<") .or. (P1 .eqs. ">") .or. - (P1 .eqs. "..") then P1 = "[-]" $ if (P1 .eqs. "*") .or. (P1 .eqs. "0") then goto HOME $ if (P1 .eqs. "P") .or. (P1 .eqs. "p") then goto PREVIOUS $ if (P1 .eqs. "H") .or. (P1 .eqs. "h") then goto HELP $ if (P1 .eqs. "S") .or. (P1 .eqs. "s") then goto SET_PROMPT $ if (P1 .eqs. "G") .or. (P1 .eqs. "g") then goto SET_PROMPT_GRAPHIC $ temp2 = "" $ if (P1 .eqs. "~INIT") .or. (P1 .eqs. "~init") then goto INIT $ if (P1 .eqs. "~CLEAR") .or. (P1 .eqs. "~clear") then goto CLEAR $ $! *** Specification par un numero $ temp = f$extract(0,1,P1) $ if temp .eqs. "-" then goto DELETE $ temp2 = "" $boucle_reculer: $ if temp .nes. "\" then goto fin_reculer $ temp2 = temp2 + "-." $ P1 = P1 - "\" $ temp = f$extract(0,1,P1) $ goto boucle_reculer $! $fin_reculer: $ P1 = temp2 + P1 $ if (P1 .lts. "0") .or. (P1 .gts. "9") then goto SPEC $ temp = f$integer("''P1'") $ if temp .eq. 0 then goto HOME $ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == temp $ goto SET2 $ $ SPEC: $! *** Specification relative de directory $ $ temp = f$parse("[.''P1']","missing.mis") $ DD = f$extract(0,f$locate("]",temp)+1,temp) $ if DD .nes. "" then goto SET1 $ $! *** Specification de directory principal $ $ temp = f$parse("[''P1']","missing.mis") $ DD = f$extract(0,f$locate("]",temp)+1,temp) $ if DD .nes. "" then goto SET1 $ $ temp = f$parse("[''P1']","sys$login:missing.mis") $ DD = f$extract(0,f$locate("]",temp)+1,temp) $ if DD .nes. "" then goto SET1 $ $! *** Specification exacte de directory $ $ temp = f$parse(P1,"missing.mis") $ if f$locate("]"+P1,temp) .ne. f$length(temp) then goto ERR $ if f$locate(".][",temp) .ne. f$length(temp) then temp = temp - "][" $ DD = f$extract(0,f$locate("]",temp)+1,temp) $! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW $ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2 $ if DD .nes. "" then goto SET1 $ $ temp = f$parse(P1,"sys$login:missing.mis") $ if f$locate("]"+P1,temp) .ne. f$length(temp) then goto ERR $ if f$locate(".][",temp) .ne. f$length(temp) then temp = temp - "][" $ DD = f$extract(0,f$locate("]",temp)+1,temp) $! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW $ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2 $ if DD .nes. "" then goto SET1 $ $ goto ERR $ $ HOME: $ DD = "SYS$LOGIN" $ $ SET1: $ Set On $ On error then goto ERR1 $ set message/nofac/noid/nosever/notext $ Set def 'DD' $ dir/output=nl: $ set message/fac/id/sever/text $ temp = f$parse(f$dir()) - ".;" $ if temp .nes. "" then goto SET1F $ ERR1: $ set message/fac/id/sever/text $ temp = TAB_DIR_'TAB_DIR_I' $ Set def 'temp' $ goto ERR $ SET1F: $ I = 0 $ LOOP1: $ I = I + 1 $ if temp .eqs. TAB_DIR_'I' then goto FOUND $ if I .lt. TAB_DIR_N then goto LOOP1 $ $ TAB_DIR_N == TAB_DIR_N + 1 $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == TAB_DIR_N $ TAB_DIR_'TAB_DIR_I' == temp $ goto SHOW $ $ FOUND: $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == I $ goto SET2 $ $ SET_PROMPT: $ car_prompt == "''P2'" $ set_prompt $ exit $ $ PREVIOUS: $ temp = TAB_DIR_P $ TAB_DIR_P == TAB_DIR_I $ TAB_DIR_I == temp $ $ SET_CUR: $ SET2: $ DD = TAB_DIR_'TAB_DIR_I' $ set def 'DD' $ $ SHOW: $ temp = TAB_DIR_'TAB_DIR_I' $ ws " ''TAB_DIR_I' * ''temp'" $ set_prompt $ exit $ $ LIST: $ I = 0 $ LOOP2: $ I = I + 1 $ temp = TAB_DIR_'I' $ if I .eq. TAB_DIR_I then goto L_CUR $ if I .eq. TAB_DIR_P then GOTO L_PRE $ ws " ''I' = ''temp'" $ goto F_LOOP2 $ L_CUR: $ ws " ''I' * ''temp'" $ goto F_LOOP2 $ L_PRE: $ ws " ''I' + ''temp'" $ $ F_LOOP2: $ if I .lt. TAB_DIR_N then goto LOOP2 $ set_prompt $ $ exit $ $ DELETE: $ P1 = P1 - "-" $ temp2 = f$integer("''P1'") $ DEL_1: $ temp = f$integer("''P1'") $ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR $ if temp .eq. TAB_DIR_I then goto ERR $ if temp .lt. TAB_DIR_I then TAB_DIR_I == TAB_DIR_I - 1 $ if temp .eq. TAB_DIR_P then TAB_DIR_P == TAB_DIR_I $ if temp .lt. TAB_DIR_P then TAB_DIR_P == TAB_DIR_P - 1 $ LOOP3: $ if temp .eq. TAB_DIR_N then goto F_LOOP3 $ temp3 = temp + 1 $ TAB_DIR_'temp' == TAB_DIR_'temp3' $ temp = temp + 1 $ goto LOOP3 $ F_LOOP3: $ delete/symb/glo tab_dir_'tab_dir_n' $ TAB_DIR_N == TAB_DIR_N - 1 $ if P2 .eqs. "" then goto FIN_DEL $ temp2 = temp2 + 1 $ if temp2 .le. f$integer("''P2'") then goto DEL_1 $ FIN_DEL: $ goto LIST $ $ ERR: $ ws "*** ERREUR ***" $ exit $ $ HELP: $ ws " H Show this menu" $ ws " null Show a list of directories" $ ws " ? Show current directory" $ ws " < or [-] or" $ ws " > or .. Remonte d'un niveau de directory" $ ws " * ou 0 Return to SYS$LOGIN" $ ws " P Last directory " $ ws " . ou [] Set cureent directory" $ ws " ^ Return to next directory" $ ws " x Set def to number x" $ ws " -x Remove the number x" $ ws " -x y Remove from x to y" $ ws " ddd Set def to [ddd] or [.ddd] or ddd:" $ ws " \ddd Set def to [-.ddd]" $ ws " S "">>"" Modify prompt for >>" $ ws " ~INIT Initialize to current directory " $ ws " (and delete all others references)" $ ws " ~CLEAR Remove all references $ ws "" $ $ exit $ $ SET_PROMPT_GRAPHIC: $ temp = "''P2'" $ i=0 $ car_prompt == "" $ GRAPH_BOUCLE: $ t=f$extract(i,1,temp) $ if (t .eqs. "e") .or. (t .eqs. "E") then t="ESC" $ if (t .eqs. "g") .or. (t .eqs. "G") then t="ESC(0" $ V° (} .L-_. "N") .-_. (} .L-_. "H") }NL+ }="ESC(B" $ car_prompt == car_prompt + t $ i = i+1 $ if i .lts. f$length(temp) then goto GRAPH_BOUCLE $ $ set_prompt $ exit ```
130,698
<p>I want to wrap a <a href="https://en.wikipedia.org/wiki/One-liner_program#Perl" rel="nofollow noreferrer">Perl one-liner</a> in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:</p> <pre><code>perl -e 'print localtime() . "\n"' </code></pre> <p>But DOS chokes on that with this helpful error message:</p> <blockquote> <p>Can't find string terminator "'" anywhere before EOF at -e line 1.</p> </blockquote> <p>What's the best way to do this within a <a href="https://en.wikipedia.org/wiki/Batch_file" rel="nofollow noreferrer">.bat file</a>?</p>
[ { "answer_id": 130726, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": true, "text": "<p>For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs:</p>\n\n<pre><code>perl -e \"print scalar localtime() . qq(\\n)\"\n</code></pre>\n\n<p>If you just need a newline at the end of the print, you can let the <code>-l</code> switch do that for you:</p>\n\n<pre><code>perl -le \"print scalar localtime()\"\n</code></pre>\n\n<p>For other cool things you can do with switches, see the <a href=\"http://perldoc.perl.org/perlrun.html\" rel=\"nofollow noreferrer\">perlrun</a> documentation.</p>\n" }, { "answer_id": 130728, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 3, "selected": false, "text": "<p>In Windows' \"DOS prompt\" (cmd.exe) you need to use double quotes not single quotes. For inside the quoted Perl code, Perl gives you a lot of options. Three are:</p>\n\n<pre><code>perl -e \"print localtime() . qq(\\n)\"\nperl -e \"print localtime() . $/\"\nperl -le \"print ''.localtime()\"\n</code></pre>\n\n<p>If you have Perl 5.10 or newer:</p>\n\n<pre><code>perl -E \"say scalar localtime()\"\n</code></pre>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/4279/jf-sebastian\">J.F. Sebastian</a>'s comment.</p>\n" }, { "answer_id": 130731, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 1, "selected": false, "text": "<p>In DOS, you use the \"\" around your Perl command. The DOS shell doesn't do single quotes like the normal Unix shell:</p>\n\n<pre><code>perl -e \"print localtime();\"\n</code></pre>\n" }, { "answer_id": 131086, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 1, "selected": false, "text": "<p>First, any answer you get to this is command-specific, because the DOS shell doesn't parse the command-line like a uniq one does; it passes the entire unparsed string to the command, which does any splitting. That said, if using /subsystem:console the C runtime provides splitting before calling main(), and most commands use this.</p>\n\n<p>If an application is using this splitting, the way you type a literal double-quote is by doubling it. So you'd do</p>\n\n<pre><code>perl -e \"print localtime() . \"\"\\n\"\"\"\n</code></pre>\n" }, { "answer_id": 162528, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 2, "selected": false, "text": "<p>For general batch files under Windows NT+, the ^ character escapes lots of things (&lt;>|&amp;), but for quotes, doubling them works wonders:</p>\n\n<pre><code>C:\\&gt;perl -e \"print localtime() . \"\"\\n\"\"\"\nThu Oct 2 09:17:32 2008\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21938/" ]
I want to wrap a [Perl one-liner](https://en.wikipedia.org/wiki/One-liner_program#Perl) in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this: ``` perl -e 'print localtime() . "\n"' ``` But DOS chokes on that with this helpful error message: > > Can't find string terminator "'" anywhere before EOF at -e line 1. > > > What's the best way to do this within a [.bat file](https://en.wikipedia.org/wiki/Batch_file)?
For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs: ``` perl -e "print scalar localtime() . qq(\n)" ``` If you just need a newline at the end of the print, you can let the `-l` switch do that for you: ``` perl -le "print scalar localtime()" ``` For other cool things you can do with switches, see the [perlrun](http://perldoc.perl.org/perlrun.html) documentation.
130,720
<p>In certain cases, I can't seem to get components to receive events.</p> <p>[edit] </p> <p>To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects.</p> <p>I ended up using parentApplication to dispatch and receive the event I needed to handle.</p> <p>[/edit]</p> <p>If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()"&gt; &lt;mx:Script&gt; &lt;![CDATA[ import mx.controls.Menu; import mx.managers.PopUpManager; // Add listeners public function init():void { this.addEventListener("child", handleChild); this.addEventListener("stepchild", handleStepchild); } // Handle the no pop button event public function noPop(event:Event):void { dispatchEvent(new Event("child")); } // Handle the pop up public function popUp(event:Event):void { var menu:Menu = new Menu(); var btnMenu:Button = new Button(); btnMenu.label = "stepchild"; menu.addChild(btnMenu); PopUpManager.addPopUp(menu, this); // neither of these work... this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]); btnMenu.dispatchEvent(new Event("stepchild", true)); } // Event handlers public function handleChild(event:Event):void { trace("I handled child"); } public function handleStepchild(event:Event):void { trace("I handled stepchild"); } ]]&gt; &lt;/mx:Script&gt; &lt;mx:VBox&gt; &lt;mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/&gt; &lt;mx:Button label="PopUp" id="btnPop" click="popUp(event)"/&gt; &lt;/mx:VBox&gt; &lt;/mx:Application&gt; </code></pre> <p><strong>I can think of work-arounds, but it seems like there ought to be some central event bus...</strong> </p> <p>Am I missing something?</p>
[ { "answer_id": 131046, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "<p>You are attaching the listener to <code>this</code> when the event is getting dispatched from <code>btnMenu</code>.</p>\n\n<p>This should work:</p>\n\n<pre>\ndispatchEvent(new Event(\"stepchild\", true));\n</pre>\n\n<p>ps. There is really no reason to put an unnecessary '<code>this</code>' everywhere, unless it's explicitly required to overcome scope issues. In this case you can just leave every <code>this</code> out.</p>\n" }, { "answer_id": 133032, "author": "Verdant", "author_id": 450527, "author_profile": "https://Stackoverflow.com/users/450527", "pm_score": 3, "selected": true, "text": "<p>Above is correct.\nYou are dispatching the event from btnMenu, but you are not listening for events on btnMenu - you are listening for events on the Application.</p>\n\n<p>Either dispatch from Application:</p>\n\n<pre><code>dispatchEvent(new Event(\"stepchild\", true));\n</code></pre>\n\n<p>or listen on the btnMenu</p>\n\n<pre><code>btnMenu.addEventListener(\"stepchild\",handleStepChild);\nbtnMenu.dispatchEvent(new Event(\"stepchild\",true));\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16258/" ]
In certain cases, I can't seem to get components to receive events. [edit] To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects. I ended up using parentApplication to dispatch and receive the event I needed to handle. [/edit] If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work): ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()"> <mx:Script> <![CDATA[ import mx.controls.Menu; import mx.managers.PopUpManager; // Add listeners public function init():void { this.addEventListener("child", handleChild); this.addEventListener("stepchild", handleStepchild); } // Handle the no pop button event public function noPop(event:Event):void { dispatchEvent(new Event("child")); } // Handle the pop up public function popUp(event:Event):void { var menu:Menu = new Menu(); var btnMenu:Button = new Button(); btnMenu.label = "stepchild"; menu.addChild(btnMenu); PopUpManager.addPopUp(menu, this); // neither of these work... this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]); btnMenu.dispatchEvent(new Event("stepchild", true)); } // Event handlers public function handleChild(event:Event):void { trace("I handled child"); } public function handleStepchild(event:Event):void { trace("I handled stepchild"); } ]]> </mx:Script> <mx:VBox> <mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/> <mx:Button label="PopUp" id="btnPop" click="popUp(event)"/> </mx:VBox> </mx:Application> ``` **I can think of work-arounds, but it seems like there ought to be some central event bus...** Am I missing something?
Above is correct. You are dispatching the event from btnMenu, but you are not listening for events on btnMenu - you are listening for events on the Application. Either dispatch from Application: ``` dispatchEvent(new Event("stepchild", true)); ``` or listen on the btnMenu ``` btnMenu.addEventListener("stepchild",handleStepChild); btnMenu.dispatchEvent(new Event("stepchild",true)); ```
130,730
<p>I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case.</p> <p><strong>Simple Example</strong></p> <p>This class is defined in Assembly1:</p> <pre><code>public class Class2Test { private readonly string _StringProperty; public Class2Test() { _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; } } </code></pre> <p>This class is defined in Assembly2:</p> <pre><code>[TestClass] public class TestClass { [TestMethod] public void Class2Test_Default_Constructor() { Class2Test x = new Class2Test(); //what do I assert to validate that the field was set properly? } } </code></pre> <p><strong>EDIT 1</strong>: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it.</p> <p>This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?</p> <p><strong>EDIT 2</strong>: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.</p>
[ { "answer_id": 130732, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "<p>I have properly enabled <code>[InternalsVisibleTo]</code> on Assembly1 (code) so that there is a trust relationship with Assembly2 (tests).</p>\n\n<pre><code>public class Class2Test\n{\n private readonly string _StringProperty;\n internal string StringProperty { get { return _StringProperty; } }\n\n public Class2Test(string stringProperty)\n {\n _StringProperty = stringProperty;\n }\n}\n</code></pre>\n\n<p>Which allows me to assert this:</p>\n\n<pre><code>Assert.AreEqual(x.StringProperty, \"something\");\n</code></pre>\n\n<p>The only thing I don't really like about this is that it's not clear (without a comment) when you are just looking at <code>Class2Test</code> what the purpose of the internal property is.</p>\n\n<p>Additional thoughts would be greatly appreciated.</p>\n" }, { "answer_id": 130735, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 4, "selected": true, "text": "<p>Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works.</p>\n\n<p>If you are using that field in a method or something, call that method and assert on that.</p>\n\n<p>Edit: </p>\n\n<blockquote>\n <p>assume the constructor has some more complex logic</p>\n</blockquote>\n\n<p>You shouldn't be performing any logic in constructors.</p>\n\n<p>Edit 2:</p>\n\n<blockquote>\n<pre><code>public Class2Test()\n{\n _StringProperty = ConfigurationManager.AppSettings[\"stringProperty\"];\n}\n</code></pre>\n</blockquote>\n\n<p>Don't do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the <code>ConfigurationManager.AppSettings</code> call. Pass an instance of that SettingsReader class into the constructor of <code>Class2Test</code>. Then, in your <em>unit test</em>, you can mock your <code>WebConfigSettingsReader</code> and stub out a response to any calls you might make to it.</p>\n" }, { "answer_id": 130785, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 1, "selected": false, "text": "<p>In your edit, you now have a dependancy on ConfigurationManager that is hard to test. </p>\n\n<p>One suggestion is to extract an interface to it and then make the Class2Test ctor take an IConfigManager instance as a parameter. Now you can use a fake/mock object to set up its state, such that any methods that rely on Configuration can be tested to see if they utilize the correct values...</p>\n\n<pre><code> public interface IConfigManager\n {\n string FooSetting { get; set; }\n }\n\n public class Class2Test\n {\n private IConfigManager _config;\n public Class2Test(IConfigManager configManager)\n {\n _config = configManager; \n }\n\n public void methodToTest()\n {\n //do something important with ConfigManager.FooSetting\n var important = _config.FooSetting;\n return important;\n }\n }\n\n [TestClass]\n public class When_doing_something_important\n {\n [TestMethod]\n public void Should_use_configuration_values()\n {\n IConfigManager fake = new FakeConfigurationManager();\n //setup state\n fake.FooSetting = \"foo\";\n var sut = new Class2Test(fake);\n Assert.AreEqual(\"foo\", sut.methodToTest());\n }\n }\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case. **Simple Example** This class is defined in Assembly1: ``` public class Class2Test { private readonly string _StringProperty; public Class2Test() { _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; } } ``` This class is defined in Assembly2: ``` [TestClass] public class TestClass { [TestMethod] public void Class2Test_Default_Constructor() { Class2Test x = new Class2Test(); //what do I assert to validate that the field was set properly? } } ``` **EDIT 1**: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it. This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work? **EDIT 2**: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.
Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works. If you are using that field in a method or something, call that method and assert on that. Edit: > > assume the constructor has some more complex logic > > > You shouldn't be performing any logic in constructors. Edit 2: > > > ``` > public Class2Test() > { > _StringProperty = ConfigurationManager.AppSettings["stringProperty"]; > } > > ``` > > Don't do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the `ConfigurationManager.AppSettings` call. Pass an instance of that SettingsReader class into the constructor of `Class2Test`. Then, in your *unit test*, you can mock your `WebConfigSettingsReader` and stub out a response to any calls you might make to it.
130,734
<p>It's been a while since I've had to do any HTML-like code in <code>Vim</code>, but recently I came across this again. Say I'm writing some simple <code>HTML</code>:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;This is a title&lt;/title&gt;&lt;/head&gt;&lt;/html&gt; </code></pre> <p>How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.</p> <p>Of course I can use <kbd>Ctrl</kbd><kbd>P</kbd> to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.</p>
[ { "answer_id": 130741, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 6, "selected": true, "text": "<p>Check this out..</p>\n\n<p>closetag.vim </p>\n\n<pre><code>Functions and mappings to close open HTML/XML tags\n</code></pre>\n\n<p><a href=\"https://www.vim.org/scripts/script.php?script_id=13\" rel=\"nofollow noreferrer\">https://www.vim.org/scripts/script.php?script_id=13</a></p>\n\n<p>I use something similar.</p>\n" }, { "answer_id": 134990, "author": "hakamadare", "author_id": 17597, "author_profile": "https://Stackoverflow.com/users/17597", "pm_score": 6, "selected": false, "text": "<p>I find using the <a href=\"https://www.vim.org/scripts/script.php?script_id=301\" rel=\"noreferrer\">xmledit</a> plugin pretty useful. it adds two pieces of functionality:</p>\n\n<ol>\n<li>When you open a tag (<em>e.g.</em> type <code>&lt;p&gt;</code>), it expands the tag as soon as you type the closing <code>&gt;</code> into <code>&lt;p&gt;&lt;/p&gt;</code> and places the cursor inside the tag in insert mode.</li>\n<li><p>If you then immediately type another <code>&gt;</code> (<em>e.g.</em> you type <code>&lt;p&gt;&gt;</code>), it expands that into</p>\n\n<p><code>&lt;p&gt;</code> </p>\n\n<p><code>&lt;/p&gt;</code></p></li>\n</ol>\n\n<p>and places the cursor inside the tag, indented once, in insert mode.</p>\n\n<p>The <a href=\"http://www.vim.org/scripts/script.php?script_id=1397\" rel=\"noreferrer\">xml</a> vim plugin adds code folding and nested tag matching to these features.</p>\n\n<p>Of course, you don't have to worry about closing tags at all if you write your HTML content in <a href=\"http://daringfireball.net/projects/markdown/\" rel=\"noreferrer\">Markdown</a> and use <code>%!</code> to filter your Vim buffer through the Markdown processor of your choice :)</p>\n" }, { "answer_id": 144168, "author": "Krzysiek Goj", "author_id": 23018, "author_profile": "https://Stackoverflow.com/users/23018", "pm_score": 6, "selected": false, "text": "<p>I find it more convinient to make vim write both opening and closing tag for me, instead of just the closing one. You can use excellent <a href=\"http://www.vim.org/scripts/script.php?script_id=1896\" rel=\"noreferrer\">ragtag plugin</a> by Tim Pope. Usage looks like this (let | mark cursor position)\nyou type:</p>\n\n<pre>span|</pre>\n\n<p>press <kbd>CTRL</kbd>+<kbd>x</kbd> <kbd>SPACE</kbd></p>\n\n<p>and you get</p>\n\n<pre>&lt;span&gt;|&lt;/span&gt;</pre>\n\n<p>You can also use <kbd>CTRL</kbd>+<kbd>x</kbd> <kbd>ENTER</kbd> instead of <kbd>CTRL</kbd>+<kbd>x</kbd> <kbd>SPACE</kbd>, and you get</p>\n\n<pre>&lt;span&gt;\n|\n&lt;/span&gt;</pre>\n\n<p>Ragtag can do more than just it (eg. insert &lt;%= stuff around this %&gt; or DOCTYPE). You probably want to check out other plugins by <a href=\"http://www.vim.org/account/profile.php?user_id=9012\" rel=\"noreferrer\">author of ragtag</a>, especially <a href=\"http://www.vim.org/scripts/script.php?script_id=1697\" rel=\"noreferrer\">surround</a>.</p>\n" }, { "answer_id": 532656, "author": "sjh", "author_id": 64591, "author_profile": "https://Stackoverflow.com/users/64591", "pm_score": 6, "selected": false, "text": "<p>I like minimal things, </p>\n\n<pre><code>imap ,/ &lt;/&lt;C-X&gt;&lt;C-O&gt;\n</code></pre>\n" }, { "answer_id": 2934483, "author": "kimilhee", "author_id": 353491, "author_profile": "https://Stackoverflow.com/users/353491", "pm_score": 3, "selected": false, "text": "<p>allml (now Ragtag ) and Omni-completion ( &lt;C-X&gt;&lt;C-O&gt; )\ndoesn't work in a file like .py or .java.</p>\n\n<p>if you want to close tag automatically in those file,\nyou can map like this.</p>\n\n<pre>\nimap &lt;C-j&gt; &lt;ESC&gt;F&lt;lyt&gt;$a&lt;/^R\"&gt;\n</pre>\n\n<p>( ^R is Contrl+R : you can type like this Control+v and then Control+r )</p>\n\n<p>(| is cursor position )\nnow if you type..</p>\n\n<p>&lt;p&gt;abcde|</p>\n\n<p>and type ^j</p>\n\n<p>then it close the tag like this..</p>\n\n<p>&lt;p&gt;abcde&lt;/p&gt;|</p>\n" }, { "answer_id": 4439015, "author": "thanthese", "author_id": 412407, "author_profile": "https://Stackoverflow.com/users/412407", "pm_score": 5, "selected": false, "text": "<p>If you're doing anything elaborate, <a href=\"https://github.com/rstacruz/sparkup\" rel=\"noreferrer\">sparkup</a> is very good.</p>\n\n<p>An example from their site:</p>\n\n<p><code>ul &gt; li.item-$*3</code> expands to:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li class=\"item-1\"&gt;&lt;/li&gt;\n &lt;li class=\"item-2\"&gt;&lt;/li&gt;\n &lt;li class=\"item-3\"&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>with a <code>&lt;C-e&gt;</code>.</p>\n\n<p>To do the example given in the question, </p>\n\n<pre><code>html &gt; head &gt; title{This is a title}\n</code></pre>\n\n<p>yields</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;This is a title&lt;/title&gt;\n &lt;/head&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 8424959, "author": "Preet Kukreti", "author_id": 1086804, "author_profile": "https://Stackoverflow.com/users/1086804", "pm_score": 4, "selected": false, "text": "<p>There is also a zencoding vim plugin: <a href=\"https://github.com/mattn/zencoding-vim\" rel=\"noreferrer\">https://github.com/mattn/zencoding-vim</a></p>\n\n<p>tutorial: <a href=\"https://github.com/mattn/zencoding-vim/blob/master/TUTORIAL\" rel=\"noreferrer\">https://github.com/mattn/zencoding-vim/blob/master/TUTORIAL</a></p>\n\n<hr>\n\n<p><strong>Update:</strong> this now called <strong><em>Emmet</em></strong>: <a href=\"http://emmet.io/\" rel=\"noreferrer\">http://emmet.io/</a></p>\n\n<hr>\n\n<p>An excerpt from the tutorial:</p>\n\n<pre><code>1. Expand Abbreviation\n\n Type abbreviation as 'div&gt;p#foo$*3&gt;a' and type '&lt;c-y&gt;,'.\n ---------------------\n &lt;div&gt;\n &lt;p id=\"foo1\"&gt;\n &lt;a href=\"\"&gt;&lt;/a&gt;\n &lt;/p&gt;\n &lt;p id=\"foo2\"&gt;\n &lt;a href=\"\"&gt;&lt;/a&gt;\n &lt;/p&gt;\n &lt;p id=\"foo3\"&gt;\n &lt;a href=\"\"&gt;&lt;/a&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n ---------------------\n\n2. Wrap with Abbreviation\n\n Write as below.\n ---------------------\n test1\n test2\n test3\n ---------------------\n Then do visual select(line wize) and type '&lt;c-y&gt;,'.\n If you request 'Tag:', then type 'ul&gt;li*'.\n ---------------------\n &lt;ul&gt;\n &lt;li&gt;test1&lt;/li&gt;\n &lt;li&gt;test2&lt;/li&gt;\n &lt;li&gt;test3&lt;/li&gt;\n &lt;/ul&gt;\n ---------------------\n\n...\n\n12. Make anchor from URL\n\n Move cursor to URL\n ---------------------\n http://www.google.com/\n ---------------------\n Type '&lt;c-y&gt;a'\n ---------------------\n &lt;a href=\"http://www.google.com/\"&gt;Google&lt;/a&gt;\n ---------------------\n</code></pre>\n" }, { "answer_id": 11925400, "author": "Keith Pinson", "author_id": 834176, "author_profile": "https://Stackoverflow.com/users/834176", "pm_score": 4, "selected": false, "text": "<h2>Mapping</h2>\n\n<p>I like to have my block tags (as opposed to inline) closed immediately and with as simple a shortcut as possible (I like to avoid special keys like <kbd>CTRL</kbd> where possible, though I do use <code>closetag.vim</code> to close my inline tags.) I like to use this shortcut when starting blocks of tags (thanks to @kimilhee; this is a take-off of his answer):</p>\n\n<pre><code>inoremap &gt;&lt;Tab&gt; &gt;&lt;Esc&gt;F&lt;lyt&gt;o&lt;/&lt;C-r&gt;\"&gt;&lt;Esc&gt;O&lt;Space&gt;\n</code></pre>\n\n<h2>Sample usage</h2>\n\n<p>Type—</p>\n\n<pre><code>&lt;p&gt;[Tab]\n</code></pre>\n\n<p>Result—</p>\n\n<pre><code>&lt;p&gt;\n |\n&lt;/p&gt;\n</code></pre>\n\n<p>where <code>|</code> indicates cursor position.</p>\n\n<h2>Explanation</h2>\n\n<ul>\n<li><code>inoremap</code> <em>means</em> create the mapping in insert mode</li>\n<li><code>&gt;&lt;Tab&gt;</code> <em>means</em> a closing angle brackets and a tab character; this is what is matched</li>\n<li><code>&gt;&lt;Esc&gt;</code> <em>means</em> end the first tag and escape from insert into normal mode</li>\n<li><code>F&lt;</code> <em>means</em> find the last opening angle bracket</li>\n<li><code>l</code> <em>means</em> move the cursor right one (don't copy the opening angle bracket)</li>\n<li><code>yt&gt;</code> <em>means</em> yank from cursor position to up until before the next closing angle bracket (i.e. copy tags contents)</li>\n<li><code>o&lt;/</code> <em>means</em> start new line in insert mode and add an opening angle bracket and slash</li>\n<li><code>&lt;C-r&gt;\"</code> <em>means</em> paste in insert mode from the default register (<code>\"</code>)</li>\n<li><code>&gt;&lt;Esc&gt;</code> <em>means</em> close the closing tag and escape from insert mode</li>\n<li><code>O&lt;Space&gt;</code> <em>means</em> start a new line in insert mode above the cursor and insert a space</li>\n</ul>\n" }, { "answer_id": 13086685, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 3, "selected": false, "text": "<p>Here is yet another simple solution based on easily foundable Web writing:</p>\n\n<ol>\n<li><p><a href=\"http://vim.wikia.com/wiki/Auto_closing_an_HTML_tag\" rel=\"noreferrer\">Auto closing an HTML tag</a></p>\n\n<p><code>:iabbrev &lt;/ &lt;/&lt;C-X&gt;&lt;C-O&gt;</code></p></li>\n<li><p><a href=\"http://amix.dk/blog/post/19021#Vim-7-Turning-completion-on\" rel=\"noreferrer\">Turning completion on</a></p>\n\n<p><code>autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags</code></p></li>\n</ol>\n" }, { "answer_id": 39022513, "author": "Nick Erhardt", "author_id": 6619924, "author_profile": "https://Stackoverflow.com/users/6619924", "pm_score": 3, "selected": false, "text": "<p>Building off of the excellent answer by @KeithPinson (sorry, not enough reputation points to comment on your answer yet), this alternative will prevent the autocomplete from copying anything extra that might be inside the html tag (e.g. classes, ids, etc...) but should not be copied to the closing tag.</p>\n\n<p><strong>UPDATE</strong> I have updated my response to work with <code>filename.html.erb</code> files.<br>\nI noticed my original response didn't work in files commonly used in Rails views, like <code>some_file.html.erb</code> when I was using embedded ruby (e.g. <code>&lt;p&gt;Year: &lt;%= @year %&gt;&lt;p&gt;</code>). The code below <em>will</em> work with <code>.html.erb</code> files.</p>\n\n<pre><code>inoremap &gt;&lt;Tab&gt; &gt;&lt;Esc&gt;?&lt;[a-z]&lt;CR&gt;lyiwo&lt;/&lt;C-r&gt;\"&gt;&lt;Esc&gt;O\n</code></pre>\n\n<p><strong>Sample usage</strong></p>\n\n<p>Type:</p>\n\n<pre><code>&lt;div class=\"foo\"&gt;[Tab]\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>&lt;div class=\"foo\"&gt;\n |\n&lt;div&gt;\n</code></pre>\n\n<p>where <code>|</code> indicates cursor position</p>\n\n<p>And as an example of adding the closing tag inline instead of block style:</p>\n\n<pre><code>inoremap &gt;&lt;Tab&gt; &gt;&lt;Esc&gt;?&lt;[a-z]&lt;CR&gt;lyiwh/[^%]&gt;&lt;CR&gt;la&lt;/&lt;C-r&gt;\"&gt;&lt;Esc&gt;F&lt;i\n</code></pre>\n\n<p><strong>Sample usage</strong></p>\n\n<p>Type:</p>\n\n<pre><code>&lt;div class=\"foo\"&gt;[Tab]\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>&lt;div class=\"foo\"&gt;|&lt;div&gt;\n</code></pre>\n\n<p>where <code>|</code> indicates cursor position</p>\n\n<p>It's true that both of the above examples rely on <code>&gt;[Tab]</code> to signal a closing tag (meaning you would have to choose <strong>either</strong> inline or block style). Personally, I use the block-style with <code>&gt;[Tab]</code> and the inline-style with <code>&gt;&gt;</code>.</p>\n" }, { "answer_id": 42428601, "author": "Sheharyar", "author_id": 1533054, "author_profile": "https://Stackoverflow.com/users/1533054", "pm_score": 4, "selected": false, "text": "<h1>Check out <a href=\"https://github.com/alvan/vim-closetag\" rel=\"noreferrer\"><code>vim-closetag</code></a></h1>\n\n<p>It's a really simple script (also available as a <code>vundle</code> plugin) that closes (X)HTML tags for you. From it's <code>README</code>:</p>\n\n<blockquote>\n <p>If this is the current content:</p>\n\n<pre><code>&lt;table|\n</code></pre>\n \n <p>Now you press <kbd>></kbd>, the content will be:</p>\n\n<pre><code>&lt;table&gt;|&lt;/table&gt;\n</code></pre>\n \n <p>And now if you press <kbd>></kbd> again, the content will be:</p>\n\n<pre><code>&lt;table&gt;\n |\n&lt;/table&gt;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p><em>Note: <code>|</code> is the cursor here</em></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10098/" ]
It's been a while since I've had to do any HTML-like code in `Vim`, but recently I came across this again. Say I'm writing some simple `HTML`: ``` <html><head><title>This is a title</title></head></html> ``` How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one. Of course I can use `Ctrl``P` to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.
Check this out.. closetag.vim ``` Functions and mappings to close open HTML/XML tags ``` <https://www.vim.org/scripts/script.php?script_id=13> I use something similar.
130,740
<p>I have the following program:</p> <pre><code>~/test&gt; cat test.cc int main() { int i = 3; int j = __sync_add_and_fetch(&amp;i, 1); return 0; } </code></pre> <p>I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine:</p> <pre><code>~/test&gt; uname --all Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux </code></pre> <p>When I compile the program in 64-bit mode, it compiles and links fine:</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ test.cc ~/test&gt; </code></pre> <p>When I compile it in 32-bit mode, I get the following error:</p> <pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc /tmp/ccEVHGkB.o(.text+0x27): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test&gt; </code></pre> <p>Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries.</p> <p>My 2 questions are:</p> <ol> <li><p>Why do I get a link error when I compile in 32-bit mode?</p></li> <li><p>Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?</p></li> </ol>
[ { "answer_id": 130754, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 5, "selected": true, "text": "<p>From the <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html#Atomic-Builtins\" rel=\"noreferrer\">GCC page on Atomic Builtins</a>:</p>\n\n<blockquote>\n <p>Not all operations are supported by\n all target processors. If a particular\n operation cannot be implemented on the\n target processor, a warning will be\n generated and a call an external\n function will be generated. The\n external function will carry the same\n name as the builtin, with an\n additional suffix `_n' where n is the\n size of the data type.</p>\n</blockquote>\n\n<p>Judging from your compiler output, which refers to <code>__sync_add_and_fetch_4</code>, this is what's happening. For some reason, GCC is not generating the external function properly.</p>\n\n<p>This is likely why you're only getting an error in 32-bit mode - when compiling for 64-bit mode, it compiles for your processor more closely. When compiling for 32-bit, it may well be using a generic arch (i386, for example) which does not natively support those features. Try specifying a specific architecture for your chip family (Xeon, Core 2, etc.) via -mcpu and see if that works.</p>\n\n<p>If not, you'll have to figure out why GCC isn't including the appropriate function that it should be generating.</p>\n" }, { "answer_id": 130813, "author": "Bruno Rijsman", "author_id": 21435, "author_profile": "https://Stackoverflow.com/users/21435", "pm_score": 5, "selected": false, "text": "<p>The answer from Dan Udey was close, close enough in fact to allow me to find the real solution.</p>\n\n<p>According to the man page \"-mcpu\" is a deprecated synonym for \"-mtune\" and just means \"optimize for a particular CPU (but still run on older CPUs, albeit less optimal)\". I tried this, and it did not solve the issue.</p>\n\n<p>However, \"-march=\" means \"generate code for a particular CPU (and don't run on older CPUs)\". When I tried this it solved the problem: specifying a CPU of i486 or better got rid of the link error.</p>\n\n<pre><code>~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc\n/tmp/ccYnYLj6.o(.text+0x27): In function `main':\n: undefined reference to `__sync_add_and_fetch_4'\ncollect2: ld returned 1 exit status\n\n~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i386 test.cc\n/tmp/ccOr3ww8.o(.text+0x22): In function `main':\n: undefined reference to `__sync_add_and_fetch_4'\ncollect2: ld returned 1 exit status\n\n~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i486 test.cc\n\n~/test&gt; /share/tools/gcc-4.2.2/bin/g++ -m32 -march=pentium test.cc\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21435/" ]
I have the following program: ``` ~/test> cat test.cc int main() { int i = 3; int j = __sync_add_and_fetch(&i, 1); return 0; } ``` I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine: ``` ~/test> uname --all Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux ``` When I compile the program in 64-bit mode, it compiles and links fine: ``` ~/test> /share/tools/gcc-4.2.2/bin/g++ test.cc ~/test> ``` When I compile it in 32-bit mode, I get the following error: ``` ~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc /tmp/ccEVHGkB.o(.text+0x27): In function `main': : undefined reference to `__sync_add_and_fetch_4' collect2: ld returned 1 exit status ~/test> ``` Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries. My 2 questions are: 1. Why do I get a link error when I compile in 32-bit mode? 2. Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?
From the [GCC page on Atomic Builtins](http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html#Atomic-Builtins): > > Not all operations are supported by > all target processors. If a particular > operation cannot be implemented on the > target processor, a warning will be > generated and a call an external > function will be generated. The > external function will carry the same > name as the builtin, with an > additional suffix `\_n' where n is the > size of the data type. > > > Judging from your compiler output, which refers to `__sync_add_and_fetch_4`, this is what's happening. For some reason, GCC is not generating the external function properly. This is likely why you're only getting an error in 32-bit mode - when compiling for 64-bit mode, it compiles for your processor more closely. When compiling for 32-bit, it may well be using a generic arch (i386, for example) which does not natively support those features. Try specifying a specific architecture for your chip family (Xeon, Core 2, etc.) via -mcpu and see if that works. If not, you'll have to figure out why GCC isn't including the appropriate function that it should be generating.
130,748
<p>I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.</p> <p>The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.</p> <p>This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?</p>
[ { "answer_id": 130805, "author": "Lloyd Cotten", "author_id": 21807, "author_profile": "https://Stackoverflow.com/users/21807", "pm_score": 3, "selected": true, "text": "<p>Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control.</p>\n\n<pre><code>private void OnRadioButtonCheckedChanged(object sender, EventArgs e)\n{\n Control1.Visible = RadioButton1.Checked;\n Control2.Visible = RadioButton2.Checked;\n}\n</code></pre>\n" }, { "answer_id": 170638, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 2, "selected": false, "text": "<p>Well you could also use databinding... seems a bit more elegant to me. Suppose you have two radiobuttons \"rbA\" and \"rbB\" and two textboxes \"txtA\" and \"txtB\". And you want to have txtA visible only when rbA is checked and txtB visible only when rbB is checked. You could do it like so :</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{\n txtA.DataBindings.Add(\"Visible\", rbA, \"Checked\");\n txtB.DataBindings.Add(\"Visible\", rbB, \"Checked\");\n}\n</code></pre>\n\n<p>However... I observed that using UserControls instead of TextBoxes breaks the functionality and I should go read on the net why..</p>\n\n<p>LATER EDIT : </p>\n\n<p>The databinding works two-ways! : If you programatically set (from somewhere else) the visibility of the txtA to false the rbA will become unchecked. That's the beauty of Databinding.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user. The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value. This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?
Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control. ``` private void OnRadioButtonCheckedChanged(object sender, EventArgs e) { Control1.Visible = RadioButton1.Checked; Control2.Visible = RadioButton2.Checked; } ```
130,763
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
[ { "answer_id": 131092, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 5, "selected": false, "text": "<p>It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that <em>need</em> those privileges. There are two ways to do this:</p>\n\n<ol>\n<li>Write a manifest file that tells Windows the application might require some privileges</li>\n<li>Run the application with elevated privileges from inside another program</li>\n</ol>\n\n<p>This <a href=\"http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx\" rel=\"noreferrer\">two</a> <a href=\"http://msdn.microsoft.com/en-gb/magazine/cc163486.aspx\" rel=\"noreferrer\">articles</a> explain in much more detail how this works.</p>\n\n<p>What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:</p>\n\n<p>When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.</p>\n\n<p>As you describe your program as a \"script\", I suppose that's enough for your needs.</p>\n\n<p>Cheers.</p>\n" }, { "answer_id": 138970, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "<p>If your script always requires an Administrator's privileges then: </p>\n\n<pre><code>runas /user:Administrator \"python your_script.py\"\n</code></pre>\n" }, { "answer_id": 3787689, "author": "TinyGrasshopper", "author_id": 444763, "author_profile": "https://Stackoverflow.com/users/444763", "pm_score": 2, "selected": false, "text": "<p>This may not completely answer your question but you could also try using the Elevate Command Powertoy in order to run the script with elevated UAC privileges.</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx\" rel=\"nofollow\">http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx</a></p>\n\n<p>I think if you use it it would look like 'elevate python yourscript.py'</p>\n" }, { "answer_id": 11746382, "author": "Jorenko", "author_id": 7161, "author_profile": "https://Stackoverflow.com/users/7161", "pm_score": 6, "selected": false, "text": "<p>It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:</p>\n\n<pre><code>import os\nimport sys\nimport win32com.shell.shell as shell\nASADMIN = 'asadmin'\n\nif sys.argv[-1] != ASADMIN:\n script = os.path.abspath(sys.argv[0])\n params = ' '.join([script] + sys.argv[1:] + [ASADMIN])\n shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)\n sys.exit(0)\n</code></pre>\n" }, { "answer_id": 22821704, "author": "officialhopsof", "author_id": 2088050, "author_profile": "https://Stackoverflow.com/users/2088050", "pm_score": 2, "selected": false, "text": "<p>You can make a shortcut somewhere and as the target use:\npython yourscript.py\nthen under properties and advanced select run as administrator. </p>\n\n<p>When the user executes the shortcut it will ask them to elevate the application.</p>\n" }, { "answer_id": 32230199, "author": "KenV99", "author_id": 3697388, "author_profile": "https://Stackoverflow.com/users/3697388", "pm_score": 3, "selected": false, "text": "<p>Recognizing this question was asked years ago, I think a more elegant solution is offered on <a href=\"https://github.com/frmdstryr/pywinutils\" rel=\"nofollow noreferrer\">github</a> by frmdstryr using his module pywinutils: </p>\n\n<p>Excerpt:</p>\n\n<pre><code>import pythoncom\nfrom win32com.shell import shell,shellcon\n\ndef copy(src,dst,flags=shellcon.FOF_NOCONFIRMATION):\n \"\"\" Copy files using the built in Windows File copy dialog\n\n Requires absolute paths. Does NOT create root destination folder if it doesn't exist.\n Overwrites and is recursive by default \n @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx for flags available\n \"\"\"\n # @see IFileOperation\n pfo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation,None,pythoncom.CLSCTX_ALL,shell.IID_IFileOperation)\n\n # Respond with Yes to All for any dialog\n # @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx\n pfo.SetOperationFlags(flags)\n\n # Set the destionation folder\n dst = shell.SHCreateItemFromParsingName(dst,None,shell.IID_IShellItem)\n\n if type(src) not in (tuple,list):\n src = (src,)\n\n for f in src:\n item = shell.SHCreateItemFromParsingName(f,None,shell.IID_IShellItem)\n pfo.CopyItem(item,dst) # Schedule an operation to be performed\n\n # @see http://msdn.microsoft.com/en-us/library/bb775780(v=vs.85).aspx\n success = pfo.PerformOperations()\n\n # @see sdn.microsoft.com/en-us/library/bb775769(v=vs.85).aspx\n aborted = pfo.GetAnyOperationsAborted()\n return success is None and not aborted \n</code></pre>\n\n<p>This utilizes the COM interface and automatically indicates that admin privileges are needed with the familiar dialog prompt that you would see if you were copying into a directory where admin privileges are required and also provides the typical file progress dialog during the copy operation.</p>\n" }, { "answer_id": 34216774, "author": "Berwyn", "author_id": 1232094, "author_profile": "https://Stackoverflow.com/users/1232094", "pm_score": 2, "selected": false, "text": "<p>A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):</p>\n\n<pre><code>def spawn_as_administrator():\n \"\"\" Spawn ourself with administrator rights and wait for new process to exit\n Make the new process use the same console as the old one.\n Raise Exception() if we could not get a handle for the new re-run the process\n Raise pywintypes.error() if we could not re-spawn\n Return the exit code of the new process,\n or return None if already running the second admin process. \"\"\"\n #pylint: disable=no-name-in-module,import-error\n import win32event, win32api, win32process\n import win32com.shell.shell as shell\n if '--admin' in sys.argv:\n return None\n script = os.path.abspath(sys.argv[0])\n params = ' '.join([script] + sys.argv[1:] + ['--admin'])\n SEE_MASK_NO_CONSOLE = 0x00008000\n SEE_MASK_NOCLOSE_PROCESS = 0x00000040\n process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)\n hProcess = process['hProcess']\n if not hProcess:\n raise Exception(\"Could not identify administrator process to install drivers\")\n # It is necessary to wait for the elevated process or else\n # stdin lines are shared between 2 processes: they get one line each\n INFINITE = -1\n win32event.WaitForSingleObject(hProcess, INFINITE)\n exitcode = win32process.GetExitCodeProcess(hProcess)\n win32api.CloseHandle(hProcess)\n return exitcode\n</code></pre>\n" }, { "answer_id": 41930586, "author": "Martín De la Fuente", "author_id": 6535374, "author_profile": "https://Stackoverflow.com/users/6535374", "pm_score": 8, "selected": true, "text": "<p>As of 2017, an easy method to achieve this is the following:</p>\n\n<pre><code>import ctypes, sys\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n return False\n\nif is_admin():\n # Code of your program here\nelse:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", sys.executable, \" \".join(sys.argv), None, 1)\n</code></pre>\n\n<p>If you are using Python 2.x, then you should replace the last line for:</p>\n\n<pre><code>ctypes.windll.shell32.ShellExecuteW(None, u\"runas\", unicode(sys.executable), unicode(\" \".join(sys.argv)), None, 1)\n</code></pre>\n\n<p>Also note that if you converted you python script into an executable file (using tools like <code>py2exe</code>, <code>cx_freeze</code>, <code>pyinstaller</code>) then you should use <code>sys.argv[1:]</code> instead of <code>sys.argv</code> in the fourth parameter.</p>\n\n<p>Some of the advantages here are:</p>\n\n<ul>\n<li>No external libraries required. It only uses <code>ctypes</code> and <code>sys</code> from standard library.</li>\n<li>Works on both Python 2 and Python 3.</li>\n<li>There is no need to modify the file resources nor creating a manifest file.</li>\n<li>If you don't add code below if/else statement, the code won't ever be executed twice.</li>\n<li>You can get the return value of the API call in the last line and take an action if it fails (code &lt;= 32). Check possible return values <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea?redirectedfrom=MSDN#return-value\" rel=\"noreferrer\">here</a>.</li>\n<li>You can change the display method of the spawned process modifying the sixth parameter.</li>\n</ul>\n\n<p>Documentation for the underlying ShellExecute call is <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx?f=255&amp;MSPPError=-2147217396\" rel=\"noreferrer\">here</a>. </p>\n" }, { "answer_id": 42787518, "author": "Noctis Skytower", "author_id": 216356, "author_profile": "https://Stackoverflow.com/users/216356", "pm_score": 3, "selected": false, "text": "<p>The following example builds on <strong>MARTIN DE LA FUENTE SAAVEDRA's</strong> excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, <code>sys.argv[0]</code> should probably be replaced with a function call: <code>subprocess.list2cmdline(sys.argv)</code>.</p>\n\n<pre><code>#! /usr/bin/env python3\nimport ctypes\nimport enum\nimport subprocess\nimport sys\n\n# Reference:\n# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx\n\n\n# noinspection SpellCheckingInspection\nclass SW(enum.IntEnum):\n HIDE = 0\n MAXIMIZE = 3\n MINIMIZE = 6\n RESTORE = 9\n SHOW = 5\n SHOWDEFAULT = 10\n SHOWMAXIMIZED = 3\n SHOWMINIMIZED = 2\n SHOWMINNOACTIVE = 7\n SHOWNA = 8\n SHOWNOACTIVATE = 4\n SHOWNORMAL = 1\n\n\nclass ERROR(enum.IntEnum):\n ZERO = 0\n FILE_NOT_FOUND = 2\n PATH_NOT_FOUND = 3\n BAD_FORMAT = 11\n ACCESS_DENIED = 5\n ASSOC_INCOMPLETE = 27\n DDE_BUSY = 30\n DDE_FAIL = 29\n DDE_TIMEOUT = 28\n DLL_NOT_FOUND = 32\n NO_ASSOC = 31\n OOM = 8\n SHARE = 26\n\n\ndef bootstrap():\n if ctypes.windll.shell32.IsUserAnAdmin():\n main()\n else:\n # noinspection SpellCheckingInspection\n hinstance = ctypes.windll.shell32.ShellExecuteW(\n None,\n 'runas',\n sys.executable,\n subprocess.list2cmdline(sys.argv),\n None,\n SW.SHOWNORMAL\n )\n if hinstance &lt;= 32:\n raise RuntimeError(ERROR(hinstance))\n\n\ndef main():\n # Your Code Here\n print(input('Echo: '))\n\n\nif __name__ == '__main__':\n bootstrap()\n</code></pre>\n" }, { "answer_id": 49759083, "author": "Orsiris de Jong", "author_id": 2635443, "author_profile": "https://Stackoverflow.com/users/2635443", "pm_score": 2, "selected": false, "text": "<p>This is mostly an upgrade to Jorenko's answer, that allows to use parameters with spaces in Windows, but should also work fairly well on Linux :)\nAlso, will work with cx_freeze or py2exe since we don't use <code>__file__</code> but <code>sys.argv[0]</code> as executable</p>\n<p>[EDIT]\nDisclaimer: The code in this post is outdated.\n<strong>I have published the elevation code as a python package.</strong>\nInstall with <code>pip install command_runner</code></p>\n<p>Usage:</p>\n\n<pre><code>from command_runner.elevate import elevate\n\ndef main():\n &quot;&quot;&quot;My main function that should be elevated&quot;&quot;&quot;\n print(&quot;Who's the administrator, now ?&quot;)\n\nif __name__ == '__main__':\n elevate(main)\n</code></pre>\n<p>[/EDIT]</p>\n<pre><code>import sys,ctypes,platform\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n raise False\n\nif __name__ == '__main__':\n\n if platform.system() == &quot;Windows&quot;:\n if is_admin():\n main(sys.argv[1:])\n else:\n # Re-run the program with admin rights, don't use __file__ since py2exe won't know about it\n # Use sys.argv[0] as script path and sys.argv[1:] as arguments, join them as lpstr, quoting each parameter or spaces will divide parameters\n lpParameters = &quot;&quot;\n # Litteraly quote all parameters which get unquoted when passed to python\n for i, item in enumerate(sys.argv[0:]):\n lpParameters += '&quot;' + item + '&quot; '\n try:\n ctypes.windll.shell32.ShellExecuteW(None, &quot;runas&quot;, sys.executable, lpParameters , None, 1)\n except:\n sys.exit(1)\n else:\n main(sys.argv[1:])\n</code></pre>\n" }, { "answer_id": 58513700, "author": "Irving Moy", "author_id": 4505578, "author_profile": "https://Stackoverflow.com/users/4505578", "pm_score": 4, "selected": false, "text": "<p>Just adding this answer in case others are directed here by Google Search as I was.\nI used the <code>elevate</code> module in my Python script and the script executed with Administrator Privileges in Windows 10.</p>\n\n<p><a href=\"https://pypi.org/project/elevate/\" rel=\"noreferrer\">https://pypi.org/project/elevate/</a></p>\n" }, { "answer_id": 72732324, "author": "BaiJiFeiLong", "author_id": 5254103, "author_profile": "https://Stackoverflow.com/users/5254103", "pm_score": 1, "selected": false, "text": "<p>For one-liners, put the code to where you need UAC.</p>\n<h2>Request UAC, if failed, keep running:</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import ctypes, sys\n\nctypes.windll.shell32.IsUserAnAdmin() or ctypes.windll.shell32.ShellExecuteW(\n None, &quot;runas&quot;, sys.executable, &quot; &quot;.join(sys.argv), None, 1) &gt; 32 and exit()\n\n\n</code></pre>\n<h2>Request UAC, if failed, exit:</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import ctypes, sys\n\nctypes.windll.shell32.IsUserAnAdmin() or (ctypes.windll.shell32.ShellExecuteW(\n None, &quot;runas&quot;, sys.executable, &quot; &quot;.join(sys.argv), None, 1) &gt; 32, exit())\n</code></pre>\n<h2>Function style:</h2>\n<pre class=\"lang-py prettyprint-override\"><code># Created by [email protected] at 2022/6/24\nimport ctypes\nimport sys\n\n\ndef request_uac_or_skip():\n ctypes.windll.shell32.IsUserAnAdmin() or ctypes.windll.shell32.ShellExecuteW(\n None, &quot;runas&quot;, sys.executable, &quot; &quot;.join(sys.argv), None, 1) &gt; 32 and sys.exit()\n\n\ndef request_uac_or_exit():\n ctypes.windll.shell32.IsUserAnAdmin() or (ctypes.windll.shell32.ShellExecuteW(\n None, &quot;runas&quot;, sys.executable, &quot; &quot;.join(sys.argv), None, 1) &gt; 32, sys.exit())\n\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
I want my Python script to copy files on Vista. When I run it from a normal `cmd.exe` window, no errors are generated, yet the files are NOT copied. If I run `cmd.exe` "as administator" and then run my script, it works fine. This makes sense since User Account Control (UAC) normally prevents many file system actions. Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?") If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?
As of 2017, an easy method to achieve this is the following: ``` import ctypes, sys def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): # Code of your program here else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1) ``` If you are using Python 2.x, then you should replace the last line for: ``` ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1) ``` Also note that if you converted you python script into an executable file (using tools like `py2exe`, `cx_freeze`, `pyinstaller`) then you should use `sys.argv[1:]` instead of `sys.argv` in the fourth parameter. Some of the advantages here are: * No external libraries required. It only uses `ctypes` and `sys` from standard library. * Works on both Python 2 and Python 3. * There is no need to modify the file resources nor creating a manifest file. * If you don't add code below if/else statement, the code won't ever be executed twice. * You can get the return value of the API call in the last line and take an action if it fails (code <= 32). Check possible return values [here](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea?redirectedfrom=MSDN#return-value). * You can change the display method of the spawned process modifying the sixth parameter. Documentation for the underlying ShellExecute call is [here](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396).
130,775
<p>As far as variable naming conventions go, should iterators be named <code>i</code> or something more semantic like <code>count</code>? If you don't use <code>i</code>, why not? If you feel that <code>i</code> is acceptable, are there cases of iteration where it shouldn't be used?</p>
[ { "answer_id": 130782, "author": "Matthew Rapati", "author_id": 15000, "author_profile": "https://Stackoverflow.com/users/15000", "pm_score": 0, "selected": false, "text": "<p>It helps if you name it something that describes what it is looping through. But I usually just use i.</p>\n" }, { "answer_id": 130783, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 2, "selected": false, "text": "<p>i is definitely acceptable. Not sure what kind of justification I need to make -- but I do use it all of the time, and other very respected programmers do as well.</p>\n\n<p>Social validation, I guess :)</p>\n" }, { "answer_id": 130786, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<p>Yes, in fact it's preferred since any programmer reading your code will understand that it's simply an iterator.</p>\n" }, { "answer_id": 130793, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 0, "selected": false, "text": "<p>As long as you are either using i to count loops, or part of an index that goes from 0 (or 1 depending on PL) to n, then I would say i is fine.</p>\n\n<p>Otherwise its probably easy to name i something meaningful it its more than just an index.</p>\n" }, { "answer_id": 130799, "author": "Captain Segfault", "author_id": 18408, "author_profile": "https://Stackoverflow.com/users/18408", "pm_score": 1, "selected": false, "text": "<p>If the \"something more semantic\" is \"iterator\" then there is no reason not to use i; it is a well understood idiom.</p>\n" }, { "answer_id": 130802, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 4, "selected": false, "text": "<p>\"i\" <em>means</em> \"loop counter\" to a programmer. There's nothing wrong with it.</p>\n" }, { "answer_id": 130806, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>I tend to use i, j, k for very localized loops (only exist for a short period in terms of number of source lines). For variables that exist over a larger source area, I tend to use more detailed names so I can see what they're for without searching back in the code.</p>\n\n<p>By the way, I think that the naming convention for these came from the early Fortran language where I was the first integer variable (A - H were floats)?</p>\n" }, { "answer_id": 130807, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 3, "selected": false, "text": "<p>Here's another example of something that's perfectly okay:</p>\n\n<pre><code>foreach (Product p in ProductList)\n{\n // Do something with p\n}\n</code></pre>\n" }, { "answer_id": 130809, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 0, "selected": false, "text": "<p>I should point out that i and j are also mathematical notation for matrix indices. And usually, you're looping over an array. So it makes sense.</p>\n" }, { "answer_id": 130810, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 6, "selected": true, "text": "<p>Depends on the context I suppose. If you where looping through a set of Objects in some \ncollection then it should be fairly obvious from the context what you are doing.</p>\n\n<pre><code>for(int i = 0; i &lt; 10; i++)\n{\n // i is well known here to be the index\n objectCollection[i].SomeProperty = someValue;\n}\n</code></pre>\n\n<p>However if it is not immediately clear from the context what it is you are doing, or if you are making modifications to the index you should use a variable name that is more indicative of the usage.</p>\n\n<pre><code>for(int currentRow = 0; currentRow &lt; numRows; currentRow++)\n{\n for(int currentCol = 0; currentCol &lt; numCols; currentCol++)\n {\n someTable[currentRow][currentCol] = someValue;\n }\n} \n</code></pre>\n" }, { "answer_id": 130811, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 0, "selected": false, "text": "<p>As long as you're using it temporarily inside a simple loop and it's obvious what you're doing, sure. That said, is there no other short word you can use instead?</p>\n\n<p><code>i</code> is widely known as a loop iterator, so you're actually more likely to confuse maintenance programmers if you use it outside of a loop, but if you use something more descriptive (like <code>filecounter</code>), it makes code nicer.</p>\n" }, { "answer_id": 130812, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 2, "selected": false, "text": "<p><code>i</code> is acceptable, for certain. However, I learned a tremendous amount one semester from a C++ teacher I had who refused code that did not have a descriptive name for every single variable. The simple act of naming everything descriptively forced me to think harder about my code, and I wrote better programs after that course, not from learning C++, but from learning to name everything. <em>Code Complete</em> has some good words on this same topic.</p>\n" }, { "answer_id": 130823, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 2, "selected": false, "text": "<p>What is the value of using i instead of a more specific variable name? To save 1 second or 10 seconds or maybe, maybe, even 30 seconds of thinking and typing?</p>\n\n<p>What is the cost of using i? Maybe nothing. Maybe the code is so simple that using i is fine. But maybe, maybe, using i will force developers who come to this code in the future to have to think for a moment \"what does i mean here?\" They will have to think: \"is it an index, a count, an offset, a flag?\" They will have to think: \"is this change safe, is it correct, will I be off by 1?\"</p>\n\n<p>Using i saves time and intellectual effort when writing code but may end up costing more intellectual effort in the future, or perhaps even result in the inadvertent introduction of defects due to misunderstanding the code.</p>\n\n<p>Generally speaking, most software development is maintenance and extension, so the amount of time spent reading your code will vastly exceed the amount of time spent writing it.</p>\n\n<p>It's very easy to develop the habit of using meaningful names everywhere, and once you have that habit it takes only a few seconds more to write code with meaningful names, but then you have code which is easier to read, easier to understand, and more obviously correct.</p>\n" }, { "answer_id": 130830, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>I use i for short loops.</p>\n\n<p>The reason it's OK is that I find it utterly implausible that someone could see a declaration of iterator type, with initializer, and then three lines later claim that it's not clear what the variable represents. They're just pretending, because they've decided that \"meaningful variable names\" must mean \"long variable names\".</p>\n\n<p>The reason I actually do it, is that I find that using something unrelated to the specific task at hand, and that I would only ever use in a small scope, saves me worrying that I might use a name that's misleading, or ambiguous, or will some day be useful for something else in the larger scope. The reason it's \"i\" rather than \"q\" or \"count\" is just convention borrowed from mathematics.</p>\n\n<p>I don't use i if:</p>\n\n<ul>\n<li>The loop body is not small, or</li>\n<li>the iterator does anything other than advance (or retreat) from the start of a range to the finish of the loop:</li>\n</ul>\n\n<p>i doesn't necessarily have to go in increments of 1 so long as the increment is consistent and clear, and of course might stop before the end of the iterand, but if it ever changes direction, or is unmodified by an iteration of the loop (including the devilish use of iterator.insertAfter() in a forward loop), I try to remember to use something different. This signals \"this is not just a trivial loop variable, hence this may not be a trivial loop\".</p>\n" }, { "answer_id": 130833, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 0, "selected": false, "text": "<p>It depends.\nIf you're iterating over some particular set of data then I think it makes more sense to use a descriptive name. (eg. <code>filecounter</code> as Dan suggested).</p>\n\n<p>However, if you're performing an arbitrary loop then <code>i</code> is acceptable. As one work mate described it to me - <code>i</code> is a convention that means \"this variable is only ever modified by the <code>for</code> loop construct. If that's not true, don't use <code>i</code>\"</p>\n" }, { "answer_id": 130838, "author": "DaveF", "author_id": 17579, "author_profile": "https://Stackoverflow.com/users/17579", "pm_score": 0, "selected": false, "text": "<p>The use of i, j, k for INTEGER loop counters goes back to the early days of FORTRAN.<br>\nPersonally I don't have a problem with them so long as they are INTEGER counts.<br>\nBut then I grew up on FORTRAN!</p>\n" }, { "answer_id": 131045, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p><strong>i</strong> is fine, but something like this is not:</p>\n\n<pre><code>for (int i = 0; i &lt; 10; i++)\n{\n for (int j = 0; j &lt; 10; j++)\n {\n string s = datarow[i][j].ToString(); // or worse\n }\n}\n</code></pre>\n\n<p>Very common for programmers to inadvertently swap the i and the j in the code, especially if they have bad eyesight or their Windows theme is \"hotdog\". This is always a \"code smell\" for me - it's kind of rare when this doesn't get screwed up.</p>\n" }, { "answer_id": 131087, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 2, "selected": false, "text": "<p>i is so common that it is acceptable, even for people that love descriptive variable names.</p>\n\n<p>What is absolutely unacceptable (and a sin in my book) is using i,j, or k in any other context than as an integer index in a loop.... e.g.</p>\n\n<pre><code>foreach(Input i in inputs)\n{\n Process(i);\n\n}\n</code></pre>\n" }, { "answer_id": 132611, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>i think i is completely acceptable in for-loop situations. i have always found this to be pretty standard and never really run into interpretation issues when i is used in this instance. foreach-loops get a little trickier and i think really depends on your situation. i rarely if ever use i in foreach, only in for loops, as i find i to be too un-descriptive in these cases. for foreach i try to use an abbreviation of the object type being looped. e.g:</p>\n\n<pre><code>foreach(DataRow dr in datatable.Rows)\n{\n //do stuff to/with datarow dr here\n}\n</code></pre>\n\n<p>anyways, just my $0.02.</p>\n" }, { "answer_id": 134450, "author": "just mike", "author_id": 12293, "author_profile": "https://Stackoverflow.com/users/12293", "pm_score": 0, "selected": false, "text": "<p>my feeling is that the <em>concept</em> of using a single letter is fine for \"simple\" loops, however, i learned to use double-letters a long time ago and it has worked out great.</p>\n\n<p>i asked a <a href=\"https://stackoverflow.com/questions/101070\">similar question</a> last week and the following is part of <a href=\"https://stackoverflow.com/questions/101070#101071\">my own answer</a>:<pre><code>// recommended style &#9679; // \"typical\" single-letter style\n &#9679;\nfor (ii=0; ii&lt;10; ++ii) { &#9679; for (i=0; i&lt;10; ++i) {\n for (jj=0; jj&lt;10; ++jj) { &#9679; for (j=0; j&lt;10; ++j) {\n mm[ii][jj] = ii * jj; &#9679; m[i][j] = i * j;\n } &#9679; }\n} &#9679; }</code></pre>\nin case the benefit isn't immediately obvious: searching through code for any single letter will find many things that <em>aren't</em> what you're looking for. the letter <code>i</code> occurs quite often in code where it isn't the variable you're looking for.</p>\n\n<p>i've been doing it this way for at least 10 years.</p>\n\n<p>note that plenty of people commented that either/both of the above are \"ugly\"...</p>\n" }, { "answer_id": 4089959, "author": "JohnFx", "author_id": 30018, "author_profile": "https://Stackoverflow.com/users/30018", "pm_score": -1, "selected": false, "text": "<p>I am going to go against the grain and say no. </p>\n\n<p>For the crowd that says \"i is understood as an iterator\", that may be true, but to me that is the equivalent of comments like 'Assign the value 5 to variable Y. Variable names like comment should explain the why/what not the how.</p>\n\n<p>To use an example from a previous answer:</p>\n\n<pre><code>for(int i = 0; i &lt; 10; i++)\n{\n // i is well known here to be the index\n objectCollection[i].SomeProperty = someValue;\n}\n</code></pre>\n\n<p>Is it that much harder to just use a meaningful name like so?</p>\n\n<pre><code>for(int objectCollectionIndex = 0; objectCollectionIndex &lt; 10; objectCollectionIndex ++)\n{\n objectCollection[objectCollectionIndex].SomeProperty = someValue;\n}\n</code></pre>\n\n<p>Granted the (borrowed) variable name objectCollection is pretty badly named too.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
As far as variable naming conventions go, should iterators be named `i` or something more semantic like `count`? If you don't use `i`, why not? If you feel that `i` is acceptable, are there cases of iteration where it shouldn't be used?
Depends on the context I suppose. If you where looping through a set of Objects in some collection then it should be fairly obvious from the context what you are doing. ``` for(int i = 0; i < 10; i++) { // i is well known here to be the index objectCollection[i].SomeProperty = someValue; } ``` However if it is not immediately clear from the context what it is you are doing, or if you are making modifications to the index you should use a variable name that is more indicative of the usage. ``` for(int currentRow = 0; currentRow < numRows; currentRow++) { for(int currentCol = 0; currentCol < numCols; currentCol++) { someTable[currentRow][currentCol] = someValue; } } ```
130,789
<p>I heard that decision tables in relational database have been researched a lot in academia. I also know that business rules engines use decision tables and that many BPMS use them as well. I was wondering if people today use decision tables within their relational databases?</p>
[ { "answer_id": 130910, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": -1, "selected": false, "text": "<p>I would look into using an Object database rather than a traditional RDBMS (Relational Database Management System). Object databases are designed to be fast at handling hierarchical relationships between objects, whereas in an RDBMS, you have to represent these relationships across multiple table rows, or even tables so your queries (tree traversals) will be slow.</p>\n" }, { "answer_id": 132483, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": true, "text": "<p>A decision table is a cluster of conditions and actions. A condition can be simple enough that you can represent it with a simple \"match a column against this value\" string. Or a condition could be hellishly complex. An action, similarly, could be as simple as \"move this value to a column\". Or the action could involve multiple parts or steps or -- well -- anything.</p>\n\n<p>A CASE function in a SELECT or WHERE clause <em>is</em> a decision table. This is the first example of decision table \"in\" a relational database. </p>\n\n<p>You can have a \"transformation\" table with columns that have old-value and replacement-value. You can then write a small piece of code like the following.</p>\n\n<pre><code>def decision_table( aRow ):\n result= connection.execute( \"SELECT replacement_value FROM transformation WHERE old_value = ?\", aRow['somecolumn'] )\n replacement= result.fetchone()\n aRow['anotherColumn']= result['replacement_value']\n</code></pre>\n\n<p>Each row of the decision table has a \"match this old_value\" and \"move this replacement_value\" kind of definition.</p>\n\n<p>The \"condition\" parts of a decision table have to be evaluated somewhere. Your application is where this will happen. You will fetch the condition values from the database. You'll use those values in some function(s) to see if the rule is true.</p>\n\n<p>The \"action\" parts of a decision table have to be executed somewhere; again, your application does stuff. You'll fetch action values from the database. You'll use those values to insert, update or delete other values.</p>\n\n<p>Decision tables are used all the time; they've always been around in relational databases. Each table requires a highly customized data model. It also requires a unique condition function and action procedure.</p>\n\n<p>It doesn't generalize well. If you want, you could store XML in the database and invoke some rules engine to interpret and execute the BPEL rules. In this case, the rules engine does the condition and action processing.</p>\n\n<p>If you want, you could store Python (or Tcl or something else) in the database. Seriously. You'd write the conditions and actions in Python. You'd fetch it from the database and run the Python code fragment.</p>\n\n<p>Lots of choices. None of the \"academic\". Indeed, the basic condition - action stuff is done all the time.</p>\n" }, { "answer_id": 291403, "author": "Guge", "author_id": 37771, "author_profile": "https://Stackoverflow.com/users/37771", "pm_score": 1, "selected": false, "text": "<p>Wheter or not to put decision tables in a database depends on a number of other questions.</p>\n\n<p>Will your conditions be calculated inside the RDBMS or elsewhere? If the data used for evaluating these conditions, and a suitable method for evaluating them inside the RDBMS can be devised, it is probably a good idea. Maybe your actions also happens inside your database, which would make it even more attractive.</p>\n\n<p>Your conditions, and even execution of your actions might be on the outside of the RDBMS, but you could still keep the connections between combinations of conditions and actions on the inside. Probably because most of you other data is there, and all you have is a web server sitting on top of it.</p>\n\n<p>I can think of two ways to model this, depending on how many conditions you have (and wheter they are binary), and what the capacity for columns per table is.</p>\n\n<p>Let's say you have 6 conditions that are binary, this means you have 2^6 = 64 possible combinations. Then you could have one column for every combination, and one row for every action.</p>\n\n<p>Or you could have 16 conditions which means you would have almost an incalculable number of combinations (actually 65536). Which is a ridiculous number of columns. Better then to have a column for each condition and a column for each action and 65536 rows of what to do in each possible situation. Each row would represent a situation and what to do in that situation. The only datatype you use would be bool. You could also package these bools into bitmasked integers.</p>\n\n<p>Actually, bigger decision tables are better avoided. Divide and rule, and use more tables is a much better way. Usually a subject matter expert will get tired if asked to give opinions on too high a number of conditions.</p>\n\n<p>The strength of the decision table is really in the modelling stage where the developer and the subject matter expert can find out if every possible situation is mapped, and no blind spots can exist.</p>\n" }, { "answer_id": 1015783, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think they will contribute to the already too much declined state of what used to be \"in-person\" communications- enough hide behind the screen as it is..... come out of the closet, get out - got the picture.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19272/" ]
I heard that decision tables in relational database have been researched a lot in academia. I also know that business rules engines use decision tables and that many BPMS use them as well. I was wondering if people today use decision tables within their relational databases?
A decision table is a cluster of conditions and actions. A condition can be simple enough that you can represent it with a simple "match a column against this value" string. Or a condition could be hellishly complex. An action, similarly, could be as simple as "move this value to a column". Or the action could involve multiple parts or steps or -- well -- anything. A CASE function in a SELECT or WHERE clause *is* a decision table. This is the first example of decision table "in" a relational database. You can have a "transformation" table with columns that have old-value and replacement-value. You can then write a small piece of code like the following. ``` def decision_table( aRow ): result= connection.execute( "SELECT replacement_value FROM transformation WHERE old_value = ?", aRow['somecolumn'] ) replacement= result.fetchone() aRow['anotherColumn']= result['replacement_value'] ``` Each row of the decision table has a "match this old\_value" and "move this replacement\_value" kind of definition. The "condition" parts of a decision table have to be evaluated somewhere. Your application is where this will happen. You will fetch the condition values from the database. You'll use those values in some function(s) to see if the rule is true. The "action" parts of a decision table have to be executed somewhere; again, your application does stuff. You'll fetch action values from the database. You'll use those values to insert, update or delete other values. Decision tables are used all the time; they've always been around in relational databases. Each table requires a highly customized data model. It also requires a unique condition function and action procedure. It doesn't generalize well. If you want, you could store XML in the database and invoke some rules engine to interpret and execute the BPEL rules. In this case, the rules engine does the condition and action processing. If you want, you could store Python (or Tcl or something else) in the database. Seriously. You'd write the conditions and actions in Python. You'd fetch it from the database and run the Python code fragment. Lots of choices. None of the "academic". Indeed, the basic condition - action stuff is done all the time.
130,790
<p>I have some C# code in an ASP.Net application that does this:</p> <p>Bitmap bmp = new Bitmap(1184, 1900);</p> <p>And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space. Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.</p> <p>Anyone have any solutions?</p>
[ { "answer_id": 130891, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>You not only need enough memory, it needs to be contiguous. Over time memory becomes fragmented and it becomes harder to find big blocks. There aren't a lot of good solutions to this, aside from building up images from smaller bitmaps.</p>\n\n<p>new Bitmap(x, y) pretty much just needs to allocate memory -- assuming that your program isn't corrupted in some way (is there any unsafe code that could corrupt the heap), then I would start with this allocation failing. Needing a contiguous block is how a seemingly small allocation could fail. Fragmentation of the heap is something that is usually solved with a custom allocator -- I don't think this is a good idea in IIS (or possible). </p>\n\n<p>To see what error you get on out of memory, try just allocation a gigantic Bitmap as a test -- see what error it throws.</p>\n\n<p>One strategy I've seen is to pre-allocate some large blocks of memory (in your case Bitmaps) and treat them as a pool (get and return them to the pool). If you only need them for a short period of time, you might be able to get away with just keeping a few in memory and sharing them.</p>\n" }, { "answer_id": 146992, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I just got a reply from microsoft support. Apparently if you look here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.drawing.aspx</a></p>\n\n<p>You can see it says \"Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions.\"\nSo they're basically washing their hands of the issue.\nIt appears that they're admitting that this section of the .Net framework is unreliable. I'm a bit disappointed.</p>\n\n<p>Next up - can anyone recommend a similar library to open a gif file, superimpose some text, and save it again?</p>\n" }, { "answer_id": 170935, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 2, "selected": false, "text": "<p>Everything I've seen to date in my context is related to memory leaks / handle leaks. I recommend you get a fresh pair of eyes to investigate your code. </p>\n\n<p>What actually happens is that the image is disposed at a random point in the future, even if you've created it on the previous line of code. This may be because of a memory/handle leak (cleaning some out of my code appears to improve but not completely resolve this problem). </p>\n\n<p>Because this error happens after the application has been in use for a while, sometimes using lots of memory, sometimes not, I feel the garbage collector doesn't obey the rules because of some special tweaks related to services and that is why Microsoft washes their hands of this problem. </p>\n\n<p><a href=\"http://blog.lavablast.com/post/2007/11/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx\" rel=\"nofollow noreferrer\">http://blog.lavablast.com/post/2007/11/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx</a></p>\n" }, { "answer_id": 170946, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "<p>Stop using GDI+ and start using the WPF Imaging classes (.NET 3.0). These are a major cleanup of the GDI+ classes and tuned for performance. Additionally, it sets up a \"bitmap chain\" that allows you to easily perform multiple actions on the bitmap in an efficient manner.</p>\n\n<p>Find more by reading about <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx\" rel=\"nofollow noreferrer\">BitmapSource</a></p>\n\n<p>Here's an example of starting with a blank bitmap just waiting to receive some pixels:</p>\n\n<pre><code>using System.Windows.Media.Imaging;\nclass Program {\n public static void Main(string[] args) {\n var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null);\n }\n}\n</code></pre>\n" }, { "answer_id": 181126, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>For anyone who's interested, the solution i'm going to use is the Mono.Cairo libraries from the mono C# distribution instead of using system.drawing. If i simply drag the mono.cairo.dll, libcairo-2.dll, libpng13.dll and zlib1.dll files from the windows version of mono into the same folder as my executable, then i can develop in windows using visual studio 2005 and it all works nicely.</p>\n\n<p>Update - i've done the above, and stress tested the application and it all seems to run smoothly now, and uses up to 200mb less ram to boot. Very happy.</p>\n" }, { "answer_id": 20326125, "author": "Tony Edgecombe", "author_id": 57094, "author_profile": "https://Stackoverflow.com/users/57094", "pm_score": 0, "selected": false, "text": "<p>Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service</p>\n\n<p>For a supported alternative, see <a href=\"http://en.wikipedia.org/wiki/Windows_Imaging_Component\" rel=\"nofollow\">Windows Imaging Components</a> (<a href=\"http://msdn.microsoft.com/en-us/library/ee719654.aspx\" rel=\"nofollow\">msdn</a>), a native library which ironically System.Drawing is based on.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have some C# code in an ASP.Net application that does this: Bitmap bmp = new Bitmap(1184, 1900); And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space. Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free. Anyone have any solutions?
Stop using GDI+ and start using the WPF Imaging classes (.NET 3.0). These are a major cleanup of the GDI+ classes and tuned for performance. Additionally, it sets up a "bitmap chain" that allows you to easily perform multiple actions on the bitmap in an efficient manner. Find more by reading about [BitmapSource](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx) Here's an example of starting with a blank bitmap just waiting to receive some pixels: ``` using System.Windows.Media.Imaging; class Program { public static void Main(string[] args) { var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null); } } ```
130,794
<p>There have been several questions already posted with specific questions about <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a>, such as when to use it and what frameworks are there for it. However,</p> <p><strong>What is dependency injection and when/why should or shouldn't it be used?</strong></p>
[ { "answer_id": 130862, "author": "wds", "author_id": 10098, "author_profile": "https://Stackoverflow.com/users/10098", "pm_score": 12, "selected": true, "text": "<p><strong>Dependency Injection</strong> is passing dependency to other <strong>objects</strong> or <strong>framework</strong>( dependency injector).</p>\n\n<p>Dependency injection makes testing easier. The injection can be done through <strong>constructor</strong>. </p>\n\n<p><code>SomeClass()</code> has its constructor as following:</p>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code>public SomeClass() {\n myObject = Factory.getObject();\n}\n</code></pre>\n\n<p><strong>Problem</strong>:\nIf <code>myObject</code> involves complex tasks such as disk access or network access, it is <strong>hard</strong> to do unit test on <code>SomeClass()</code>. Programmers have to mock <code>myObject</code> and might <strong>intercept</strong> the factory call.</p>\n\n<p><strong>Alternative solution</strong>: </p>\n\n<ul>\n<li>Passing <code>myObject</code> in as an argument to the constructor</li>\n</ul>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code>public SomeClass (MyClass myObject) {\n this.myObject = myObject;\n}\n</code></pre>\n\n<p><code>myObject</code> can be passed directly which makes testing easier. </p>\n\n<ul>\n<li>One common alternative is defining a <strong>do-nothing constructor</strong>. Dependency injection can be done through setters. (h/t @MikeVella). </li>\n<li><a href=\"http://martinfowler.com/articles/injection.html#InterfaceInjection\" rel=\"noreferrer\">Martin Fowler</a> documents a third alternative (h/t @MarcDix), where <strong>classes explicitly implement an interface</strong> for the dependencies programmers wish injected.</li>\n</ul>\n\n<p>It is harder to isolate components in unit testing without dependency injection. </p>\n\n<p>In 2013, when I wrote this answer, this was a major theme on the <a href=\"http://googletesting.blogspot.com/\" rel=\"noreferrer\">Google Testing Blog</a>. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.</p>\n" }, { "answer_id": 131766, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 8, "selected": false, "text": "<p>Dependency Injection is a practice where objects are designed in a manner where they receive instances of the objects from other pieces of code, instead of constructing them internally. This means that any object implementing the interface which is required by the object can be substituted in without changing the code, which simplifies testing, and improves decoupling.</p>\n\n<p>For example, consider these clases:</p>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code>public class PersonService {\n public void addManager( Person employee, Person newManager ) { ... }\n public void removeManager( Person employee, Person oldManager ) { ... }\n public Group getGroupByManager( Person manager ) { ... }\n}\n\npublic class GroupMembershipService() {\n public void addPersonToGroup( Person person, Group group ) { ... }\n public void removePersonFromGroup( Person person, Group group ) { ... }\n} \n</code></pre>\n\n<p>In this example, the implementation of <code>PersonService::addManager</code> and <code>PersonService::removeManager</code> would need an instance of the <code>GroupMembershipService</code> in order to do its work. Without Dependency Injection, the traditional way of doing this would be to instantiate a new <code>GroupMembershipService</code> in the constructor of <code>PersonService</code> and use that instance attribute in both functions. However, if the constructor of <code>GroupMembershipService</code> has multiple things it requires, or worse yet, there are some initialization \"setters\" that need to be called on the <code>GroupMembershipService</code>, the code grows rather quickly, and the <code>PersonService</code> now depends not only on the <code>GroupMembershipService</code> but also everything else that <code>GroupMembershipService</code> depends on. Furthermore, the linkage to <code>GroupMembershipService</code> is hardcoded into the <code>PersonService</code> which means that you can't \"dummy up\" a <code>GroupMembershipService</code> for testing purposes, or to use a strategy pattern in different parts of your application. </p>\n\n<p>With Dependency Injection, instead of instantiating the <code>GroupMembershipService</code> within your <code>PersonService</code>, you'd either pass it in to the <code>PersonService</code> constructor, or else add a Property (getter and setter) to set a local instance of it. This means that your <code>PersonService</code> no longer has to worry about how to create a <code>GroupMembershipService</code>, it just accepts the ones it's given, and works with them. This also means that anything which is a subclass of <code>GroupMembershipService</code>, or implements the <code>GroupMembershipService</code> interface can be \"injected\" into the <code>PersonService</code>, and the <code>PersonService</code> doesn't need to know about the change.</p>\n" }, { "answer_id": 140655, "author": "Thiago Arrais", "author_id": 17801, "author_profile": "https://Stackoverflow.com/users/17801", "pm_score": 11, "selected": false, "text": "<p>The best definition I've found so far is <a href=\"http://jamesshore.com/Blog/Dependency-Injection-Demystified.html\" rel=\"noreferrer\">one by James Shore</a>: </p>\n\n<blockquote>\n <p>\"Dependency Injection\" is a 25-dollar\n term for a 5-cent concept. [...]\n Dependency injection means giving an\n object its instance variables. [...].</p>\n</blockquote>\n\n<p>There is <a href=\"http://martinfowler.com/articles/injection.html\" rel=\"noreferrer\">an article by Martin Fowler</a> that may prove useful, too.</p>\n\n<p>Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.</p>\n\n<p>Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g. Spring) to do that, but they certainly aren't required. You don't need those frameworks to have dependency injection. Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.</p>\n" }, { "answer_id": 4618417, "author": "zby", "author_id": 356679, "author_profile": "https://Stackoverflow.com/users/356679", "pm_score": 8, "selected": false, "text": "<p>The accepted answer is a good one - but I would like to add to this that DI is very much like the classic avoiding of hardcoded constants in the code. </p>\n\n<p>When you use some constant like a database name you'd quickly move it from the inside of the code to some config file and pass a variable containing that value to the place where it is needed. The reason to do that is that these constants usually change more frequently than the rest of the code. For example if you'd like to test the code in a test database. </p>\n\n<p>DI is analogous to this in the world of Object Oriented programming. The values there instead of constant literals are whole objects - but the reason to move the code creating them out from the class code is similar - the objects change more frequently then the code that uses them. One important case where such a change is needed is tests.</p>\n" }, { "answer_id": 6085922, "author": "gtiwari333", "author_id": 607637, "author_profile": "https://Stackoverflow.com/users/607637", "pm_score": 10, "selected": false, "text": "<p><em>I found this funny example in terms of <a href=\"https://en.wikipedia.org/wiki/Loose_coupling\" rel=\"noreferrer\">loose coupling</a>:</em></p>\n<p>Source: <em><a href=\"http://ganeshtiwaridotcomdotnp.blogspot.com/2011/05/understanding-dependency-injection-and.html\" rel=\"noreferrer\">Understanding dependency injection</a></em></p>\n<p>Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.</p>\n<p>For example, consider a <code>Car</code> object.</p>\n<p>A <code>Car</code> depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the <code>Car</code> object.</p>\n<p><strong>Without Dependency Injection (DI):</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>class Car{\n private Wheel wh = new NepaliRubberWheel();\n private Battery bt = new ExcideBattery();\n\n //The rest\n}\n</code></pre>\n<p>Here, the <code>Car</code> object <em>is responsible for creating the dependent objects.</em></p>\n<p>What if we want to change the type of its dependent object - say <code>Wheel</code> - after the initial <code>NepaliRubberWheel()</code> punctures?\nWe need to recreate the Car object with its new dependency say <code>ChineseRubberWheel()</code>, but only the <code>Car</code> manufacturer can do that.</p>\n<p><em><strong>Then what does the <code>Dependency Injection</code> do for us...?</strong></em></p>\n<p>When using dependency injection, objects are given their dependencies <em>at run time rather than compile time (car manufacturing time)</em>.\nSo that we can now change the <code>Wheel</code> whenever we want. Here, the <code>dependency</code> (<code>wheel</code>) can be injected into <code>Car</code> at run time.</p>\n<p><strong>After using dependency injection:</strong></p>\n<p>Here, we are <strong>injecting</strong> the <strong>dependencies</strong> (Wheel and Battery) at runtime. Hence the term : <em>Dependency Injection.</em> We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed.</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Car{\n private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime\n private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime\n Car(Wheel wh,Battery bt) {\n this.wh = wh;\n this.bt = bt;\n }\n //Or we can have setters\n void setWheel(Wheel wh) {\n this.wh = wh;\n }\n}\n</code></pre>\n<p><strong>The advantages are:</strong></p>\n<ul>\n<li>decoupling the creation of object (in other word, separate usage from the creation of object)</li>\n<li>ability to replace dependencies (eg: Wheel, Battery) without changing the class that uses it(Car)</li>\n<li>promotes &quot;Code to interface not to implementation&quot; principle</li>\n<li>ability to create and use mock dependency during test (if we want to use a Mock of Wheel during test instead of a real instance.. we can create Mock Wheel object and let DI framework inject to Car)</li>\n</ul>\n" }, { "answer_id": 13005079, "author": "Olivier Liechti", "author_id": 1341338, "author_profile": "https://Stackoverflow.com/users/1341338", "pm_score": 7, "selected": false, "text": "<p>Let's imagine that you want to go fishing:</p>\n\n<ul>\n<li><p>Without dependency injection, you need to take care of everything yourself. You need to find a boat, to buy a fishing rod, to look for bait, etc. It's possible, of course, but it puts a lot of responsibility on you. In software terms, it means that you have to perform a lookup for all these things.</p></li>\n<li><p>With dependency injection, someone else takes care of all the preparation and makes the required equipment available to you. You will receive (\"be injected\") the boat, the fishing rod and the bait - all ready to use.</p></li>\n</ul>\n" }, { "answer_id": 16328631, "author": "JaneGoodall", "author_id": 2167210, "author_profile": "https://Stackoverflow.com/users/2167210", "pm_score": 6, "selected": false, "text": "<p>Doesn't \"dependency injection\" just mean using parameterized constructors and public setters?</p>\n\n<p><a href=\"http://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html\" rel=\"noreferrer\">James Shore's article shows the following examples for comparison</a>.</p>\n\n<blockquote>\n <p>Constructor without dependency injection:</p>\n \n \n\n<pre class=\"lang-csh prettyprint-override\"><code>public class Example { \n private DatabaseThingie myDatabase; \n\n public Example() { \n myDatabase = new DatabaseThingie(); \n } \n\n public void doStuff() { \n ... \n myDatabase.getData(); \n ... \n } \n} \n</code></pre>\n \n <p>Constructor with dependency injection:</p>\n \n \n\n<pre class=\"lang-csh prettyprint-override\"><code>public class Example { \n private DatabaseThingie myDatabase; \n\n public Example(DatabaseThingie useThisDatabaseInstead) { \n myDatabase = useThisDatabaseInstead; \n }\n\n public void doStuff() { \n ... \n myDatabase.getData(); \n ... \n } \n}\n</code></pre>\n</blockquote>\n" }, { "answer_id": 16628165, "author": "TastyCode", "author_id": 949827, "author_profile": "https://Stackoverflow.com/users/949827", "pm_score": 3, "selected": false, "text": "<p>From the Book, '<a href=\"https://rads.stackoverflow.com/amzn/click/com/1617290068\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Well-Grounded Java Developer: Vital techniques of Java 7 and polyglot programming</a></p>\n\n<blockquote>\n <p>DI is a particular form of IoC, whereby the process of finding your dependencies is\n outside the direct control of your currently executing code.</p>\n</blockquote>\n" }, { "answer_id": 18964312, "author": "uvsmtid", "author_id": 441652, "author_profile": "https://Stackoverflow.com/users/441652", "pm_score": 5, "selected": false, "text": "<p>The whole point of Dependency Injection (DI) is to keep application source code <strong>clean</strong> and <strong>stable</strong>:</p>\n\n<ul>\n<li><strong>clean</strong> of dependency initialization code</li>\n<li><strong>stable</strong> regardless of dependency used</li>\n</ul>\n\n<p>Practically, every design pattern separates concerns to make future changes affect minimum files.</p>\n\n<p>The specific domain of DI is delegation of dependency configuration and initialization.</p>\n\n<h2>Example: DI with shell script</h2>\n\n<p>If you occasionally work outside of Java, recall how <code>source</code> is often used in many scripting languages (Shell, Tcl, etc., or even <code>import</code> in Python misused for this purpose).</p>\n\n<p>Consider simple <code>dependent.sh</code> script:</p>\n\n<pre><code>#!/bin/sh\n# Dependent\ntouch \"one.txt\" \"two.txt\"\narchive_files \"one.txt\" \"two.txt\"\n</code></pre>\n\n<p>The script is dependent: it won't execute successfully on its own (<code>archive_files</code> is not defined).</p>\n\n<p>You define <code>archive_files</code> in <code>archive_files_zip.sh</code> implementation script (using <code>zip</code> in this case):</p>\n\n<pre><code>#!/bin/sh\n# Dependency\nfunction archive_files {\n zip files.zip \"$@\"\n}\n</code></pre>\n\n<p>Instead of <code>source</code>-ing implementation script directly in the dependent one, you use an <code>injector.sh</code> \"container\" which wraps both \"components\":</p>\n\n<pre><code>#!/bin/sh \n# Injector\nsource ./archive_files_zip.sh\nsource ./dependent.sh\n</code></pre>\n\n<p>The <code>archive_files</code> <em>dependency</em> has just been <em>injected</em> into <em>dependent</em> script.</p>\n\n<p>You could have injected dependency which implements <code>archive_files</code> using <code>tar</code> or <code>xz</code>.</p>\n\n<h2>Example: removing DI</h2>\n\n<p>If <code>dependent.sh</code> script used dependencies directly, the approach would be called <em>dependency lookup</em> (which is opposite to <em>dependency injection</em>):</p>\n\n<pre><code>#!/bin/sh\n# Dependent\n\n# dependency look-up\nsource ./archive_files_zip.sh\n\ntouch \"one.txt\" \"two.txt\"\narchive_files \"one.txt\" \"two.txt\"\n</code></pre>\n\n<p>Now the problem is that dependent \"component\" has to perform initialization itself.</p>\n\n<p>The \"component\"'s source code is neither <strong>clean</strong> nor <strong>stable</strong> because every changes in initialization of dependencies requires new release for \"components\"'s source code file as well.</p>\n\n<h2>Last words</h2>\n\n<p>DI is not as largely emphasized and popularized as in Java frameworks.</p>\n\n<p>But it's a generic approach to split concerns of:</p>\n\n<ul>\n<li>application <strong>development</strong> (<strong>single</strong> source code release lifecycle)</li>\n<li>application <strong>deployment</strong> (<strong>multiple</strong> target environments with independent lifecycles)</li>\n</ul>\n\n<p>Using configuration only with <em>dependency lookup</em> does not help as number of configuration parameters may change per dependency (e.g. new authentication type) as well as number of supported types of dependencies (e.g. new database type).</p>\n" }, { "answer_id": 19580829, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I think since everyone has written for DI, let me ask a few questions..</p>\n\n<ol>\n<li>When you have a configuration of DI where all the actual implementations(not interfaces) that are going to be injected into a class (for e.g services to a controller) why is that not some sort of hard-coding? </li>\n<li>What if I want to change the object at runtime? For example, my config already says when I instantiate MyController, inject for FileLogger as ILogger. But I might want to inject DatabaseLogger. </li>\n<li>Every time I want to change what objects my AClass needs, I need to now look into two places - The class itself and the configuration file. How does that make life easier?</li>\n<li>If Aproperty of AClass is not injected, is it harder to mock it out? </li>\n<li>Going back to the first question. If using new object() is bad, how come we inject the implementation and not the interface? I think a lot of you are saying we're in fact injecting the interface but the configuration makes you specify the implementation of that interface ..not at runtime .. it is hardcoded during compile time.</li>\n</ol>\n\n<p>This is based on the answer @Adam N posted.</p>\n\n<p>Why does PersonService no longer have to worry about GroupMembershipService? You just mentioned GroupMembership has multiple things(objects/properties) it depends on. If GMService was required in PService, you'd have it as a property. You can mock that out regardless of whether you injected it or not. The only time I'd like it to be injected is if GMService had more specific child classes, which you wouldn't know until runtime. Then you'd want to inject the subclass. Or if you wanted to use that as either singleton or prototype. To be honest, the configuration file has everything hardcoded as far as what subclass for a type (interface) it is going to inject during compile time. </p>\n\n<p><strong>EDIT</strong> </p>\n\n<p><a href=\"https://dzone.com/articles/dependency-injection-makes\" rel=\"nofollow noreferrer\">A nice comment by Jose Maria Arranz on DI</a></p>\n\n<p><em>DI increases cohesion by removing any need to determine the direction of dependency and write any glue code.</em></p>\n\n<p>False. The direction of dependencies is in XML form or as annotations, your dependencies are written as XML code and annotations. XML and annotations ARE source code.</p>\n\n<p><em>DI reduces coupling by making all of your components modular (i.e. replaceable) and have well-defined interfaces to each other.</em></p>\n\n<p>False. You do not need a DI framework to build a modular code based on interfaces.</p>\n\n<p>About replaceable: with a very simple .properties archive and Class.forName you can define which classes can change. If ANY class of your code can be changed, Java is not for you, use an scripting language. By the way: annotations cannot be changed without recompiling.</p>\n\n<p>In my opinion there is one only reason for DI frameworks: boiler plate reduction. With a well done factory system you can do the same, more controlled and more predictable as your preferred DI framework, DI frameworks promise code reduction (XML and annotations are source code too). The problem is this boiler plate reduction is just real in very very simple cases (one instance-per class and similar), sometimes in the real world picking the appropriated service object is not as easy as mapping a class to a singleton object.</p>\n" }, { "answer_id": 19921438, "author": "Waqas Ahmed", "author_id": 1212046, "author_profile": "https://Stackoverflow.com/users/1212046", "pm_score": 2, "selected": false, "text": "<p>In simple words dependency injection (DI) is the way to remove dependencies or tight coupling between different object. Dependency Injection gives a cohesive behavior to each object. </p>\n\n<p>DI is the implementation of IOC principal of Spring which says \"Don't call us we will call you\". Using dependency injection programmer doesn't need to create object using the new keyword. </p>\n\n<p>Objects are once loaded in Spring container and then we reuse them whenever we need them by fetching those objects from Spring container using getBean(String beanName) method.</p>\n" }, { "answer_id": 20970795, "author": "Piyush Deshpande", "author_id": 2394846, "author_profile": "https://Stackoverflow.com/users/2394846", "pm_score": 4, "selected": false, "text": "<p>It means that objects should only have as many dependencies as is needed to do their job and the dependencies should be few. Furthermore, an object’s dependencies should be on interfaces and not on “concrete” objects, when possible. (A concrete object is any object created with the keyword new.) Loose coupling promotes greater reusability, easier maintainability, and allows you to easily provide “mock” objects in place of expensive services.</p>\n\n<p>The “Dependency Injection” (DI) is also known as “Inversion of Control” (IoC), can be used as a technique for encouraging this loose coupling.</p>\n\n<p>There are two primary approaches to implementing DI:</p>\n\n<ol>\n<li>Constructor injection </li>\n<li>Setter injection</li>\n</ol>\n\n<h2>Constructor injection</h2>\n\n<p>It’s the technique of passing objects dependencies to its constructor.</p>\n\n<p>Note that the constructor accepts an interface and not concrete object. Also, note that an exception is thrown if the orderDao parameter is null. This emphasizes the importance of receiving a valid dependency. Constructor Injection is, in my opinion, the preferred mechanism for giving an object its dependencies. It is clear to the developer while invoking the object which dependencies need to be given to the “Person” object for proper execution.</p>\n\n<h2>Setter Injection</h2>\n\n<p>But consider the following example… Suppose you have a class with ten methods that have no dependencies, but you’re adding a new method that does have a dependency on IDAO. You could change the constructor to use Constructor Injection, but this may force you to changes to all constructor calls all over the place. Alternatively, you could just add a new constructor that takes the dependency, but then how does a developer easily know when to use one constructor over the other. Finally, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? “Setter Injection” is another DI technique that can be used in situations such as this.</p>\n\n<p>Setter Injection does not force dependencies to be passed to the constructor. Instead, the dependencies are set onto public properties exposed by the object in need. As implied previously, the primary motivators for doing this include:</p>\n\n<ol>\n<li>Supporting dependency injection without having to modify the constructor of a legacy class.</li>\n<li>Allowing expensive resources or services to be created as late as possible and only when needed.</li>\n</ol>\n\n<p>Here is the example of how the above code would look like:</p>\n\n<pre><code>public class Person {\n public Person() {}\n\n public IDAO Address {\n set { addressdao = value; }\n get {\n if (addressdao == null)\n throw new MemberAccessException(\"addressdao\" +\n \" has not been initialized\");\n return addressdao;\n }\n }\n\n public Address GetAddress() {\n // ... code that uses the addressdao object\n // to fetch address details from the datasource ...\n }\n\n // Should not be called directly;\n // use the public property instead\n private IDAO addressdao;\n</code></pre>\n" }, { "answer_id": 22798058, "author": "Volksman", "author_id": 257364, "author_profile": "https://Stackoverflow.com/users/257364", "pm_score": 3, "selected": false, "text": "<p>Dependency injection is one possible solution to what could generally be termed the \"Dependency Obfuscation\" requirement. Dependency Obfuscation is a method of taking the 'obvious' nature out of the process of providing a dependency to a class that requires it and therefore obfuscating, in some way, the provision of said dependency to said class. This is not necessarily a bad thing. In fact, by obfuscating the manner by which a dependency is provided to a class then something outside the class is responsible for creating the dependency which means, in various scenarios, a different implementation of the dependency can be supplied to the class without making any changes to the class. This is great for switching between production and testing modes (eg., using a 'mock' service dependency).</p>\n\n<p>Unfortunately the bad part is that some people have assumed you need a specialized framework to do dependency obfuscation and that you are somehow a 'lesser' programmer if you choose not to use a particular framework to do it. Another, extremely disturbing myth, believed by many, is that dependency injection is the only way of achieving dependency obfuscation. This is demonstrably and historically and obviously 100% wrong but you will have trouble convincing some people that there are alternatives to dependency injection for your dependency obfuscation requirements.</p>\n\n<p>Programmers have understood the dependency obfuscation requirement for years and many alternative solutions have evolved both before and after dependency injection was conceived. There are Factory patterns but there are also many options using ThreadLocal where no injection to a particular instance is needed - the dependency is effectively injected into the thread which has the benefit of making the object available (via convenience static getter methods) to <em>any</em> class that requires it without having to add annotations to the classes that require it and set up intricate XML 'glue' to make it happen. When your dependencies are required for persistence (JPA/JDO or whatever) it allows you to achieve 'tranaparent persistence' much easier and with domain model and business model classes made up purely of POJOs (i.e. no framework specific/locked in annotations).</p>\n" }, { "answer_id": 23907306, "author": "mohit sarsar", "author_id": 3205359, "author_profile": "https://Stackoverflow.com/users/3205359", "pm_score": 2, "selected": false, "text": "<p>Dependency injection is the heart of the concept related with Spring Framework.While creating the framework of any project spring may perform a vital role,and here dependency injection come in pitcher.</p>\n\n<p>Actually,Suppose in java you created two different classes as class A and class B, and whatever the function are available in class B you want to use in class A, So at that time dependency injection can be used.\nwhere you can crate object of one class in other,in the same way you can inject an entire class in another class to make it accessible.\nby this way dependency can be overcome.</p>\n\n<p>DEPENDENCY INJECTION IS SIMPLY GLUING TWO CLASSES AND AT THE SAME TIME KEEPING THEM SEPARATE.</p>\n" }, { "answer_id": 26889535, "author": "Alex", "author_id": 1187785, "author_profile": "https://Stackoverflow.com/users/1187785", "pm_score": 3, "selected": false, "text": "<p>I know there are already many answers, but I found this very helpful: <a href=\"http://tutorials.jenkov.com/dependency-injection/index.html\" rel=\"nofollow noreferrer\">http://tutorials.jenkov.com/dependency-injection/index.html</a> </p>\n\n<h3>No Dependency:</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MyDao {\n\n protected DataSource dataSource = new DataSourceImpl(\n \"driver\", \"url\", \"user\", \"password\");\n\n //data access methods...\n public Person readPerson(int primaryKey) {...} \n}\n</code></pre>\n\n<h3>Dependency:</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MyDao {\n\n protected DataSource dataSource = null;\n\n public MyDao(String driver, String url, String user, String password) {\n this.dataSource = new DataSourceImpl(driver, url, user, password);\n }\n\n //data access methods...\n public Person readPerson(int primaryKey) {...}\n}\n</code></pre>\n\n<p>Notice how the <code>DataSourceImpl</code> instantiation is moved into a constructor. The constructor takes four parameters which are the four values needed by the <code>DataSourceImpl</code>. Though the <code>MyDao</code> class still depends on these four values, it no longer satisfies these dependencies itself. They are provided by whatever class creating a <code>MyDao</code> instance.</p>\n" }, { "answer_id": 29929112, "author": "StuartLC", "author_id": 314291, "author_profile": "https://Stackoverflow.com/users/314291", "pm_score": 5, "selected": false, "text": "<p><strong>What is Dependency Injection (DI)?</strong></p>\n\n<p>As others have said, <em>Dependency Injection(DI)</em> removes the responsibility of direct creation, and management of the lifespan, of other object instances upon which our class of interest (consumer class) is dependent (in the <a href=\"https://en.wikipedia.org/wiki/Class_diagram#Dependency\" rel=\"noreferrer\">UML sense</a>). These instances are instead passed to our consumer class, typically as constructor parameters or via property setters (the management of the dependency object instancing and passing to the consumer class is usually performed by an <em>Inversion of Control (IoC)</em> container, but that's another topic).</p>\n\n<p><strong>DI, DIP and SOLID</strong></p>\n\n<p>Specifically, in the paradigm of Robert C Martin's <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"noreferrer\">SOLID principles of Object Oriented Design</a>, <code>DI</code> is one of the possible implementations of the <a href=\"http://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"noreferrer\">Dependency Inversion Principle (DIP)</a>. The <a href=\"https://stackoverflow.com/q/27978841/314291\">DIP is the <code>D</code> of the <code>SOLID</code> mantra</a> - other DIP implementations include the Service Locator, and Plugin patterns.</p>\n\n<p>The objective of the DIP is to decouple tight, concrete dependencies between classes, and instead, to loosen the coupling by means of an abstraction, which can be achieved via an <code>interface</code>, <code>abstract class</code> or <code>pure virtual class</code>, depending on the language and approach used.</p>\n\n<p>Without the DIP, our code (I've called this 'consuming class') is directly coupled to a concrete dependency and is also often burdened with the responsibility of knowing how to obtain, and manage, an instance of this dependency, i.e. conceptually:</p>\n\n<pre><code>\"I need to create/use a Foo and invoke method `GetBar()`\"\n</code></pre>\n\n<p>Whereas after application of the DIP, the requirement is loosened, and the concern of obtaining and managing the lifespan of the <code>Foo</code> dependency has been removed:</p>\n\n<pre><code>\"I need to invoke something which offers `GetBar()`\"\n</code></pre>\n\n<p><strong>Why use DIP (and DI)?</strong></p>\n\n<p>Decoupling dependencies between classes in this way allows for <em>easy substitution</em> of these dependency classes with other implementations which also fulfil the prerequisites of the abstraction (e.g. the dependency can be switched with another implementation of the same interface). Moreover, as others have mentioned, possibly <em>the</em> most common reason to decouple classes via the DIP is to allow a consuming class to be tested in isolation, as these same dependencies can now be stubbed and/or mocked.</p>\n\n<p>One consequence of DI is that the lifespan management of dependency object instances is no longer controlled by a consuming class, as the dependency object is now passed into the consuming class (via constructor or setter injection).</p>\n\n<p>This can be viewed in different ways:</p>\n\n<ul>\n<li>If lifespan control of dependencies by the consuming class needs to be retained, control can be re-established by injecting an (abstract) factory for creating the dependency class instances, into the consumer class. The consumer will be able to obtain instances via a <code>Create</code> on the factory as needed, and dispose of these instances once complete.</li>\n<li>Or, lifespan control of dependency instances can be relinquished to an IoC container (more about this below).</li>\n</ul>\n\n<p><strong>When to use DI?</strong></p>\n\n<ul>\n<li>Where there likely will be a need to substitute a dependency for an equivalent implementation, </li>\n<li>Any time where you will need to unit test the methods of a class in isolation of its dependencies, </li>\n<li>Where uncertainty of the lifespan of a dependency may warrant experimentation (e.g. Hey, <code>MyDepClass</code> is thread safe - what if we make it a singleton and inject the same instance into all consumers?)</li>\n</ul>\n\n<p><strong>Example</strong></p>\n\n<p>Here's a simple C# implementation. Given the below Consuming class:</p>\n\n<pre><code>public class MyLogger\n{\n public void LogRecord(string somethingToLog)\n {\n Console.WriteLine(\"{0:HH:mm:ss} - {1}\", DateTime.Now, somethingToLog);\n }\n}\n</code></pre>\n\n<p>Although seemingly innocuous, it has two <code>static</code> dependencies on two other classes, <code>System.DateTime</code> and <code>System.Console</code>, which not only limit the logging output options (logging to console will be worthless if no one is watching), but worse, it is difficult to automatically test given the dependency on a non-deterministic system clock.</p>\n\n<p>We can however apply <code>DIP</code> to this class, by abstracting out the the concern of timestamping as a dependency, and coupling <code>MyLogger</code> only to a simple interface:</p>\n\n<pre><code>public interface IClock\n{\n DateTime Now { get; }\n}\n</code></pre>\n\n<p>We can also loosen the dependency on <code>Console</code> to an abstraction, such as a <code>TextWriter</code>. Dependency Injection is typically implemented as either <code>constructor</code> injection (passing an abstraction to a dependency as a parameter to the constructor of a consuming class) or <code>Setter Injection</code> (passing the dependency via a <code>setXyz()</code> setter or a .Net Property with <code>{set;}</code> defined). Constructor Injection is preferred, as this guarantees the class will be in a correct state after construction, and allows the internal dependency fields to be marked as <code>readonly</code> (C#) or <code>final</code> (Java). So using constructor injection on the above example, this leaves us with:</p>\n\n<pre><code>public class MyLogger : ILogger // Others will depend on our logger.\n{\n private readonly TextWriter _output;\n private readonly IClock _clock;\n\n // Dependencies are injected through the constructor\n public MyLogger(TextWriter stream, IClock clock)\n {\n _output = stream;\n _clock = clock;\n }\n\n public void LogRecord(string somethingToLog)\n {\n // We can now use our dependencies through the abstraction \n // and without knowledge of the lifespans of the dependencies\n _output.Write(\"{0:yyyy-MM-dd HH:mm:ss} - {1}\", _clock.Now, somethingToLog);\n }\n}\n</code></pre>\n\n<p>(A concrete <code>Clock</code> needs to be provided, which of course could revert to <code>DateTime.Now</code>, and the two dependencies need to be provided by an IoC container via constructor injection)</p>\n\n<p>An automated Unit Test can be built, which definitively proves that our logger is working correctly, as we now have control over the dependencies - the time, and we can spy on the written output:</p>\n\n<pre><code>[Test]\npublic void LoggingMustRecordAllInformationAndStampTheTime()\n{\n // Arrange\n var mockClock = new Mock&lt;IClock&gt;();\n mockClock.Setup(c =&gt; c.Now).Returns(new DateTime(2015, 4, 11, 12, 31, 45));\n var fakeConsole = new StringWriter();\n\n // Act\n new MyLogger(fakeConsole, mockClock.Object)\n .LogRecord(\"Foo\");\n\n // Assert\n Assert.AreEqual(\"2015-04-11 12:31:45 - Foo\", fakeConsole.ToString());\n}\n</code></pre>\n\n<p><strong>Next Steps</strong></p>\n\n<p>Dependency injection is invariably associated with an <a href=\"http://martinfowler.com/articles/injection.html\" rel=\"noreferrer\">Inversion of Control container(IoC)</a>, to inject (provide) the concrete dependency instances, and to manage lifespan instances. During the configuration / bootstrapping process, <code>IoC</code> containers allow the following to be defined:</p>\n\n<ul>\n<li>mapping between each abstraction and the configured concrete implementation (e.g. <em>\"any time a consumer requests an <code>IBar</code>, return a <code>ConcreteBar</code> instance\"</em>)</li>\n<li>policies can be set up for the lifespan management of each dependency, e.g. to create a new object for each consumer instance, to share a singleton dependency instance across all consumers, to share the same dependency instance only across the same thread, etc.</li>\n<li>In .Net, IoC containers are aware of protocols such as <code>IDisposable</code> and will take on the responsibility of <code>Disposing</code> dependencies in line with the configured lifespan management.</li>\n</ul>\n\n<p>Typically, once IoC containers have been configured / bootstrapped, they operate seamlessly in the background allowing the coder to focus on the code at hand rather than worrying about dependencies.</p>\n\n<blockquote>\n <p>The key to DI-friendly code is to avoid static coupling of classes, and not to use new() for the creation of Dependencies</p>\n</blockquote>\n\n<p>As per above example, decoupling of dependencies does require some design effort, and for the developer, there is a paradigm shift needed to break the habit of <code>new</code>ing dependencies directly, and instead trusting the container to manage dependencies. </p>\n\n<p>But the benefits are many, especially in the ability to thoroughly test your class of interest.</p>\n\n<p><strong>Note</strong> : The creation / mapping / projection (via <code>new ..()</code>) of POCO / POJO / Serialization DTOs / Entity Graphs / Anonymous JSON projections et al - i.e. \"Data only\" classes or records - used or returned from methods are <em>not</em> regarded as Dependencies (in the UML sense) and not subject to DI. Using <code>new</code> to project these is just fine.</p>\n" }, { "answer_id": 30603464, "author": "Phil Goetz", "author_id": 1122081, "author_profile": "https://Stackoverflow.com/users/1122081", "pm_score": 3, "selected": false, "text": "<p>The popular answers are unhelpful, because they define dependency injection in a way that isn't useful. Let's agree that by \"dependency\" we mean some pre-existing other object that our object X needs. But we don't say we're doing \"dependency injection\" when we say</p>\n\n<pre><code>$foo = Foo-&gt;new($bar);\n</code></pre>\n\n<p>We just call that passing parameters into the constructor. We've been doing that regularly ever since constructors were invented.</p>\n\n<p>\"Dependency injection\" is considered a type of \"inversion of control\", which means that some logic is taken out of the caller. That isn't the case when the caller passes in parameters, so if that were DI, DI would not imply inversion of control.</p>\n\n<p>DI means there is an intermediate level between the caller and the constructor which manages dependencies. A Makefile is a simple example of dependency injection. The \"caller\" is the person typing \"make bar\" on the command line, and the \"constructor\" is the compiler. The Makefile specifies that bar depends on foo, and it does a</p>\n\n<pre><code>gcc -c foo.cpp; gcc -c bar.cpp\n</code></pre>\n\n<p>before doing a</p>\n\n<pre><code>gcc foo.o bar.o -o bar\n</code></pre>\n\n<p>The person typing \"make bar\" doesn't need to know that bar depends on foo. The dependency was injected between \"make bar\" and gcc.</p>\n\n<p>The main purpose of the intermediate level is not just to pass in the dependencies to the constructor, but to list all the dependencies in <em>just one place</em>, and to hide them from the coder (not to make the coder provide them).</p>\n\n<p>Usually the intermediate level provides factories for the constructed objects, which must provide a role that each requested object type must satisfy. That's because by having an intermediate level that hides the details of construction, you've already incurred the abstraction penalty imposed by factories, so you might as well use factories.</p>\n" }, { "answer_id": 32268340, "author": "BERGUIGA Mohamed Amine", "author_id": 2299789, "author_profile": "https://Stackoverflow.com/users/2299789", "pm_score": 2, "selected": false, "text": "<p>from Book <strong>Apress.Spring.Persistence.with.Hibernate.Oct.2010</strong><br/></p>\n\n<blockquote>\n <p>The purpose of dependency injection is to decouple the work of\n resolving external software components from your application business\n logic.Without dependency injection, the details of how a component\n accesses required services can get muddled in with the component’s\n code. This not only increases the potential for errors, adds code\n bloat, and magnifies maintenance complexities; it couples components\n together more closely, making it difficult to modify dependencies when\n refactoring or testing.</p>\n</blockquote>\n" }, { "answer_id": 32679456, "author": "hariprasad", "author_id": 3632455, "author_profile": "https://Stackoverflow.com/users/3632455", "pm_score": 2, "selected": false, "text": "<p>Dependency Injection (DI) is one from Design Patterns, which uses the basic feature of OOP - the relationship in one object with another object. While inheritance inherits one object to do more complex and specific another object, relationship or association simply creates a pointer to another object from one object using attribute. The power of DI is in combination with other features of OOP as are interfaces and hiding code.\nSuppose, we have a customer (subscriber) in the library, which can borrow only one book for simplicity.</p>\n\n<p>Interface of book:</p>\n\n<pre><code>package com.deepam.hidden;\n\npublic interface BookInterface {\n\npublic BookInterface setHeight(int height);\npublic BookInterface setPages(int pages); \npublic int getHeight();\npublic int getPages(); \n\npublic String toString();\n}\n</code></pre>\n\n<p>Next we can have many kind of books; one of type is fiction:</p>\n\n<pre><code>package com.deepam.hidden;\n\npublic class FictionBook implements BookInterface {\nint height = 0; // height in cm\nint pages = 0; // number of pages\n\n/** constructor */\npublic FictionBook() {\n // TODO Auto-generated constructor stub\n}\n\n@Override\npublic FictionBook setHeight(int height) {\n this.height = height;\n return this;\n}\n\n@Override\npublic FictionBook setPages(int pages) {\n this.pages = pages;\n return this; \n}\n\n@Override\npublic int getHeight() {\n // TODO Auto-generated method stub\n return height;\n}\n\n@Override\npublic int getPages() {\n // TODO Auto-generated method stub\n return pages;\n}\n\n@Override\npublic String toString(){\n return (\"height: \" + height + \", \" + \"pages: \" + pages);\n}\n}\n</code></pre>\n\n<p>Now subscriber can have association to the book:</p>\n\n<pre><code>package com.deepam.hidden;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class Subscriber {\nBookInterface book;\n\n/** constructor*/\npublic Subscriber() {\n // TODO Auto-generated constructor stub\n}\n\n// injection I\npublic void setBook(BookInterface book) {\n this.book = book;\n}\n\n// injection II\npublic BookInterface setBook(String bookName) {\n try {\n Class&lt;?&gt; cl = Class.forName(bookName);\n Constructor&lt;?&gt; constructor = cl.getConstructor(); // use it for parameters in constructor\n BookInterface book = (BookInterface) constructor.newInstance();\n //book = (BookInterface) Class.forName(bookName).newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n } catch (SecurityException e) {\n e.printStackTrace();\n } catch (IllegalArgumentException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n return book;\n}\n\npublic BookInterface getBook() {\n return book;\n}\n\npublic static void main(String[] args) {\n\n}\n\n}\n</code></pre>\n\n<p>All the three classes can be hidden for it's own implementation. Now we can use this code for DI:</p>\n\n<pre><code>package com.deepam.implement;\n\nimport com.deepam.hidden.Subscriber;\nimport com.deepam.hidden.FictionBook;\n\npublic class CallHiddenImplBook {\n\npublic CallHiddenImplBook() {\n // TODO Auto-generated constructor stub\n}\n\npublic void doIt() {\n Subscriber ab = new Subscriber();\n\n // injection I\n FictionBook bookI = new FictionBook();\n bookI.setHeight(30); // cm\n bookI.setPages(250);\n ab.setBook(bookI); // inject\n System.out.println(\"injection I \" + ab.getBook().toString());\n\n // injection II\n FictionBook bookII = ((FictionBook) ab.setBook(\"com.deepam.hidden.FictionBook\")).setHeight(5).setPages(108); // inject and set\n System.out.println(\"injection II \" + ab.getBook().toString()); \n}\n\npublic static void main(String[] args) {\n CallHiddenImplBook kh = new CallHiddenImplBook();\n kh.doIt();\n}\n}\n</code></pre>\n\n<p>There are many different ways how to use dependency injection. It is possible to combine it with Singleton, etc., but still in basic it is only association realized by creating attribute of object type inside another object.\nThe usefulness is only and only in feature, that code, which we should write again and again is always prepared and done for us forward. This is why DI so closely binded with Inversion of Control (IoC) which means, that our program passes control another running module, which does injections of beans to our code. (Each object, which can be injected can be signed or considered as a Bean.) For example in Spring it is done by creating and initialization <em>ApplicationContext</em> container, which does this work for us. We simply in our code create the Context and invoke initialization the beans. In that moment injection has been done automatically.</p>\n" }, { "answer_id": 34081752, "author": "Harleen", "author_id": 5527914, "author_profile": "https://Stackoverflow.com/users/5527914", "pm_score": 4, "selected": false, "text": "<h2>What is dependency Injection?</h2>\n\n<p>Dependency Injection(DI) means to decouple the objects which are dependent on each other. Say object A is dependent on Object B so the idea is to decouple these object from each other. We don’t need to hard code the object using new keyword rather sharing dependencies to objects at runtime in spite of compile time.\nIf we talk about </p>\n\n<h2>How Dependency Injection works in Spring:</h2>\n\n<p>We don’t need to hard code the object using new keyword rather define the bean dependency in the configuration file. The spring container will be responsible for hooking up all.</p>\n\n<h2>Inversion of Control (IOC)</h2>\n\n<p>IOC is a general concept and it can be expressed in many different ways and Dependency Injection is one concrete example of IOC.</p>\n\n<h2>Two types of Dependency Injection:</h2>\n\n<ol>\n<li>Constructor Injection</li>\n<li>Setter Injection</li>\n</ol>\n\n<h2>1. Constructor-based dependency injection:</h2>\n\n<p>Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.</p>\n\n<pre><code>public class Triangle {\n\nprivate String type;\n\npublic String getType(){\n return type;\n }\n\npublic Triangle(String type){ //constructor injection\n this.type=type;\n }\n}\n&lt;bean id=triangle\" class =\"com.test.dependencyInjection.Triangle\"&gt;\n &lt;constructor-arg value=\"20\"/&gt;\n &lt;/bean&gt;\n</code></pre>\n\n<h2>2. Setter-based dependency injection:</h2>\n\n<p>Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.</p>\n\n<pre><code>public class Triangle{\n\n private String type;\n\n public String getType(){\n return type;\n }\n public void setType(String type){ //setter injection\n this.type = type;\n }\n }\n\n&lt;!-- setter injection --&gt;\n &lt;bean id=\"triangle\" class=\"com.test.dependencyInjection.Triangle\"&gt;\n &lt;property name=\"type\" value=\"equivialteral\"/&gt;\n</code></pre>\n\n<p>NOTE:\nIt is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the if we use annotation based than @Required annotation on a setter can be used to make setters as a required dependencies.</p>\n" }, { "answer_id": 34206179, "author": "Nikos M.", "author_id": 3591273, "author_profile": "https://Stackoverflow.com/users/3591273", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://en.wikipedia.org/wiki/Dependency_injection\">Dependency Injection</a> means a way (actually <strong>any-way</strong>) for one part of code (e.g a class) to have access to dependencies (other parts of code, e.g other classes, it depends upon) in a modular way without them being hardcoded (so they can change or be overriden freely, or even be loaded at another time, as needed)</p>\n\n<p><em>(and ps , yes it has become an overly-hyped 25$ name for a rather simple, concept)</em>, my <code>.25</code> cents</p>\n" }, { "answer_id": 36431786, "author": "Anwar Husain", "author_id": 1921855, "author_profile": "https://Stackoverflow.com/users/1921855", "pm_score": 4, "selected": false, "text": "<p>The best analogy I can think of is the surgeon and his assistant(s) in an operation theater, where the surgeon is the main person and his assistant who provides the various surgical components when he needs it so that the surgeon can concentrate on the one thing he does best (surgery). Without the assistant the surgeon has to get the components himself every time he needs one.</p>\n\n<p>DI for short, is a technique to remove a common additional responsibility (burden) on components to fetch the dependent components, by providing them to it.</p>\n\n<p>DI brings you closer to the Single Responsibility (SR) principle, like the <code>surgeon who can concentrate on surgery</code>.</p>\n\n<p>When to use DI : I would recommend using DI in almost all production projects ( small/big), particularly in ever changing business environments :)</p>\n\n<p>Why : Because you want your code to be easily testable, mockable etc so that you can quickly test your changes and push it to the market. Besides why would you not when you there are lots of awesome free tools/frameworks to support you in your journey to a codebase where you have more control.</p>\n" }, { "answer_id": 37049915, "author": "Peyman Mohamadpour", "author_id": 5104596, "author_profile": "https://Stackoverflow.com/users/5104596", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://php-di.org/doc/understanding-di.html\">This</a> is the most simple explanation about <strong>Dependency Injection</strong> and <strong>Dependency Injection Container</strong> I have ever seen:</p>\n\n<h1>Without Dependency Injection</h1>\n\n<ul>\n<li>Application needs Foo (e.g. a controller), so:</li>\n<li>Application creates Foo</li>\n<li>Application calls Foo\n\n<ul>\n<li>Foo needs Bar (e.g. a service), so:</li>\n<li>Foo creates Bar</li>\n<li>Foo calls Bar\n\n<ul>\n<li>Bar needs Bim (a service, a repository,\n…), so:</li>\n<li>Bar creates Bim</li>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<h1>With Dependency Injection</h1>\n\n<ul>\n<li>Application needs Foo, which needs Bar, which needs Bim, so:</li>\n<li>Application creates Bim</li>\n<li>Application creates Bar and gives it Bim</li>\n<li>Application creates Foo and gives it Bar</li>\n<li>Application calls Foo\n\n<ul>\n<li>Foo calls Bar\n\n<ul>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<h1>Using a Dependency Injection Container</h1>\n\n<ul>\n<li>Application needs Foo so:</li>\n<li>Application gets Foo from the Container, so:\n\n<ul>\n<li>Container creates Bim</li>\n<li>Container creates Bar and gives it Bim</li>\n<li>Container creates Foo and gives it Bar</li>\n</ul></li>\n<li>Application calls Foo\n\n<ul>\n<li>Foo calls Bar\n\n<ul>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong>Dependency Injection</strong> and <strong>dependency Injection Containers</strong> are different things:</p>\n\n<ul>\n<li>Dependency Injection is a method for writing better code</li>\n<li>a DI Container is a tool to help injecting dependencies</li>\n</ul>\n\n<p>You don't need a container to do dependency injection. However a container can help you.</p>\n" }, { "answer_id": 37624871, "author": "kusnaditjung tjung", "author_id": 1316199, "author_profile": "https://Stackoverflow.com/users/1316199", "pm_score": 2, "selected": false, "text": "<p>Dependency Injection (DI) is part of Dependency Inversion Principle (DIP) practice, which is also called Inversion of Control (IoC). Basically you need to do DIP because you want to make your code more modular and unit testable, instead of just one monolithic system. So you start identifying parts of the code that can be separated from the class and abstracted away. Now the implementation of the abstraction need to be injected from outside of the class. Normally this can be done via constructor. So you create a constructor that accepts the abstraction as a parameter, and this is called dependency injection (via constructor). For more explanation about DIP, DI, and IoC container you can read <a href=\"http://kusnaditjung.blogspot.co.uk/2016/05/dependency-inversion-principle-dip.html\" rel=\"nofollow\">Here</a></p>\n" }, { "answer_id": 40312799, "author": "wakqasahmed", "author_id": 2314594, "author_profile": "https://Stackoverflow.com/users/2314594", "pm_score": 6, "selected": false, "text": "<p>To make Dependency Injection concept simple to understand. Let's take an example of switch button to toggle(on/off) a bulb.</p>\n\n<h2>Without Dependency Injection</h2>\n\n<p>Switch needs to know beforehand which bulb I am connected to (hard-coded dependency). So,</p>\n\n<p>Switch -> PermanentBulb <em>//switch is directly connected to permanent bulb, testing not possible easily</em></p>\n\n<p><a href=\"https://i.stack.imgur.com/cIt97.jpg\"><img src=\"https://i.stack.imgur.com/cIt97.jpg\" alt=\"\"></a></p>\n\n<pre><code>Switch(){\nPermanentBulb = new Bulb();\nPermanentBulb.Toggle();\n}\n</code></pre>\n\n<h2>With Dependency Injection</h2>\n\n<p>Switch only knows I need to turn on/off whichever Bulb is passed to me. So,</p>\n\n<p>Switch -> Bulb1 OR Bulb2 OR NightBulb (injected dependency)</p>\n\n<p><a href=\"https://i.stack.imgur.com/NrXaF.jpg\"><img src=\"https://i.stack.imgur.com/NrXaF.jpg\" alt=\"\"></a></p>\n\n<pre><code>Switch(AnyBulb){ //pass it whichever bulb you like\nAnyBulb.Toggle();\n}\n</code></pre>\n\n<p>Modifying <a href=\"http://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html\">James</a> Example for Switch and Bulb:</p>\n\n<pre><code>public class SwitchTest { \n TestToggleBulb() { \n MockBulb mockbulb = new MockBulb(); \n\n // MockBulb is a subclass of Bulb, so we can \n // \"inject\" it here: \n Switch switch = new Switch(mockBulb); \n\n switch.ToggleBulb(); \n mockBulb.AssertToggleWasCalled(); \n } \n}\n\npublic class Switch { \n private Bulb myBulb; \n\n public Switch() { \n myBulb = new Bulb(); \n } \n\n public Switch(Bulb useThisBulbInstead) { \n myBulb = useThisBulbInstead; \n } \n\n public void ToggleBulb() { \n ... \n myBulb.Toggle(); \n ... \n } \n}`\n</code></pre>\n" }, { "answer_id": 40665840, "author": "Ciro Corvino", "author_id": 3762855, "author_profile": "https://Stackoverflow.com/users/3762855", "pm_score": 1, "selected": false, "text": "<p><strong>Dependency Injection</strong> is a type of implementation of the \"<strong>Inversion of Control</strong>\" principle on which is based Frameworks building.</p>\n\n<p><strong>Frameworks</strong> as stated in \"Design Pattern\" of GoF are classes that implement the main control flow logic raising the developer to do that, in this way Frameworks realize the inversion of control principle.</p>\n\n<p>A way to implement as a technique, and not as class hierarchy, this IoC principle it is just Dependency Injection.</p>\n\n<p><strong>DI</strong> consists mainly into delegate the mapping of classes instances and type reference to that instances, to an external \"entity\": an object, static class, component, framework, etc... </p>\n\n<p>Classes instances are the \"<strong><em>dependencies</em></strong>\", the external binding of the calling component with the class instance through the reference it is the \"<strong><em>injection</em></strong>\".</p>\n\n<p>Obviously you can implement this technique in many way as you want from OOP point of view, see for example <em>constructor injection</em>, <em>setter injection</em>, <em>interface injection</em>.</p>\n\n<p>Delegating a third party to carry out the task of match a ref to an object it is very useful when you want to completely separate a component that needs some services from the same services implementation. </p>\n\n<p>In this way, when designing components, you can focus exclusively on their architecture and their specific logic, trusting on interfaces for collaborating with other objects without worry about any type of implementation changes of objects/services used, also if the same object you are using will be totally replaced (obviously respecting the interface).</p>\n" }, { "answer_id": 43043715, "author": "Hisham Javed", "author_id": 1942984, "author_profile": "https://Stackoverflow.com/users/1942984", "pm_score": 0, "selected": false, "text": "<p>Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). <strong>When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system.</strong> In other words, dependencies are injected into objects.</p>\n\n<p>For further details please see <a href=\"http://www.javaworld.com/article/2071914/excellent-explanation-of-dependency-injection--inversion-of-control-.html\" rel=\"nofollow noreferrer\">enter link description here</a></p>\n" }, { "answer_id": 44945310, "author": "user2771704", "author_id": 2771704, "author_profile": "https://Stackoverflow.com/users/2771704", "pm_score": 8, "selected": false, "text": "<p>Let's try simple example with <strong>Car</strong> and <strong>Engine</strong> classes, any car need an engine to go anywhere, at least for now. So below how code will look without dependency injection.</p>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code>public class Car\n{\n public Car()\n {\n GasEngine engine = new GasEngine();\n engine.Start();\n }\n}\n\npublic class GasEngine\n{\n public void Start()\n {\n Console.WriteLine(\"I use gas as my fuel!\");\n }\n}\n</code></pre>\n\n<p>And to instantiate the Car class we will use next code:</p>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code>Car car = new Car();\n</code></pre>\n\n<p>The issue with this code that we tightly coupled to GasEngine and if we decide to change it to ElectricityEngine then we will need to rewrite Car class. And the bigger the application the more issues and headache we will have to add and use new type of engine. </p>\n\n<p>In other words with this approach is that our high level Car class is dependent on the lower level GasEngine class which violate Dependency Inversion Principle(DIP) from SOLID. DIP suggests that we should depend on abstractions, not concrete classes. So to satisfy this we introduce IEngine interface and rewrite code like below:</p>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code> public interface IEngine\n {\n void Start();\n }\n\n public class GasEngine : IEngine\n {\n public void Start()\n {\n Console.WriteLine(\"I use gas as my fuel!\");\n }\n }\n\n public class ElectricityEngine : IEngine\n {\n public void Start()\n {\n Console.WriteLine(\"I am electrocar\");\n }\n }\n\n public class Car\n {\n private readonly IEngine _engine;\n public Car(IEngine engine)\n {\n _engine = engine;\n }\n\n public void Run()\n {\n _engine.Start();\n }\n }\n</code></pre>\n\n<p>Now our Car class is dependent on only the IEngine interface, not a specific implementation of engine. \nNow, the only trick is how do we create an instance of the Car and give it an actual concrete Engine class like GasEngine or ElectricityEngine. That's where <strong>Dependency Injection</strong> comes in. </p>\n\n\n\n<pre class=\"lang-csh prettyprint-override\"><code> Car gasCar = new Car(new GasEngine());\n gasCar.Run();\n Car electroCar = new Car(new ElectricityEngine());\n electroCar.Run();\n</code></pre>\n\n<p>Here we basically inject(pass) our dependency(Engine instance) to Car constructor. So now our classes have loose coupling between objects and their dependencies, and we can easily add new types of engines without changing the Car class.</p>\n\n<p>The main benefit of the <strong>Dependency Injection</strong> that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually <strong>interfaces</strong>) which are provided to them when the class is constructed.</p>\n\n<blockquote>\n <p>So in the end <strong>Dependency injection</strong> is just a technique for\n achieving loose coupling between objects and their dependencies.\n Rather than directly instantiating dependencies that class needs in\n order to perform its actions, dependencies are provided to the class\n (most often) via constructor injection.</p>\n</blockquote>\n\n<p>Also when we have many dependencies it is very good practice to use Inversion of Control(IoC) containers which we can tell which interfaces should be mapped to which concrete implementations for all our dependencies and we can have it resolve those dependencies for us when it constructs our object. For example, we could specify in the mapping for the IoC container that the <strong>IEngine</strong> dependency should be mapped to the <strong>GasEngine</strong> class and when we ask the IoC container for an instance of our <strong>Car</strong> class, it will automatically construct our <strong>Car</strong> class with a <strong>GasEngine</strong> dependency passed in. </p>\n\n<p><strong>UPDATE:</strong> Watched course about EF Core from Julie Lerman recently and also liked her short definition about DI.</p>\n\n<blockquote>\n <p>Dependency injection is a pattern to allow your application to inject\n objects on the fly to classes that need them, without forcing those\n classes to be responsible for those objects. It allows your code to be\n more loosely coupled, and Entity Framework Core plugs in to this same\n system of services.</p>\n</blockquote>\n" }, { "answer_id": 47090662, "author": "SAMUEL", "author_id": 2761513, "author_profile": "https://Stackoverflow.com/users/2761513", "pm_score": 5, "selected": false, "text": "<p><strong>All the above answers are good, my aim is to explain the concept in a simple way so that anyone without a programming knowledge can also understand concept</strong></p>\n<p>Dependency injection is one of the design pattern that help us to create complex systems in a simpler manner.</p>\n<p>We can see a wide variety of application of this pattern in our day to day life.\nSome of the examples are Tape recorder, VCD, CD Drive etc.</p>\n<p><a href=\"https://i.stack.imgur.com/Ubcrh.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Ubcrh.jpg\" alt=\"Reel-to-reel portable tape recorder, mid-20th century.\" /></a></p>\n<p>The above image is an image of Reel-to-reel portable tape recorder, mid-20th century. <a href=\"https://www.britannica.com/technology/tape-recorder\" rel=\"noreferrer\">Source</a>.</p>\n<p>The primary intention of a tape recorder machine is to record or playback sound.</p>\n<p>While designing a system it require a reel to record or playback sound or music. There are two possibilities for designing this system</p>\n<ol>\n<li>we can place the reel inside the machine</li>\n<li>we can provide a hook for the reel where it can be placed.</li>\n</ol>\n<p>If we use the first one we need to open the machine to change the reel.\nif we opt for the second one, that is placing a hook for reel, we are getting an added benefit of playing any music by changing the reel. and also reducing the function only to playing whatever in the reel.</p>\n<p>Like wise dependency injection is the process of externalizing the dependencies to focus only on the specific functionality of the component so that independent components can be coupled together to form a complex system.</p>\n<p>The main benefits we achieved by using dependency injection.</p>\n<ul>\n<li>High cohesion and loose coupling.</li>\n<li>Externalizing dependency and looking only on responsibility.</li>\n<li>Making things as components and to combine to form a large systems with high capabilities.</li>\n<li>It helps to develop high quality components since they are independently developed they are properly tested.</li>\n<li>It helps to replace the component with another if one fails.</li>\n</ul>\n<p>Now a days these concept forms the basis of well known frameworks in programming world.\nThe Spring Angular etc are the well-known software frameworks built on the top of this concept</p>\n<p>Dependency injection is a pattern used to create instances of objects that other objects rely upon without knowing at compile time which class will be used to provide that functionality or simply the way of injecting properties to an object is called dependency injection.</p>\n<p><strong>Example for Dependency injection</strong></p>\n<p>Previously we are writing code like this</p>\n<pre><code>Public MyClass{\n DependentClass dependentObject\n /*\n At somewhere in our code we need to instantiate \n the object with new operator inorder to use it or perform some method.\n */ \n dependentObject= new DependentClass();\n dependentObject.someMethod();\n}\n</code></pre>\n<p>With Dependency injection, the dependency injector will take off the instantiation for us</p>\n<pre><code>Public MyClass{\n /* Dependency injector will instantiate object*/\n DependentClass dependentObject\n\n /*\n At somewhere in our code we perform some method. \n The process of instantiation will be handled by the dependency injector\n */ \n \n dependentObject.someMethod();\n}\n</code></pre>\n<p>You can also read</p>\n<p><a href=\"https://stackoverflow.com/questions/26884881/difference-between-inversion-of-control-dependency-injection/41519414#41519414\">Difference between Inversion of Control &amp; Dependency Injection</a></p>\n" }, { "answer_id": 49269907, "author": "Linh", "author_id": 5381331, "author_profile": "https://Stackoverflow.com/users/5381331", "pm_score": 4, "selected": false, "text": "<p>Example, we have 2 class <code>Client</code> and <code>Service</code>. <code>Client</code> will use <code>Service</code></p>\n\n<pre><code>public class Service {\n public void doSomeThingInService() {\n // ...\n }\n}\n</code></pre>\n\n<h2>Without Dependency Injection</h2>\n\n<p><strong>Way 1)</strong> </p>\n\n<pre><code>public class Client {\n public void doSomeThingInClient() {\n Service service = new Service();\n service.doSomeThingInService();\n }\n}\n</code></pre>\n\n<p><strong>Way 2)</strong></p>\n\n<pre><code>public class Client {\n Service service = new Service();\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n</code></pre>\n\n<p><strong>Way 3)</strong> </p>\n\n<pre><code>public class Client {\n Service service;\n public Client() {\n service = new Service();\n }\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n</code></pre>\n\n<p><strong>1) 2) 3) Using</strong></p>\n\n<pre><code>Client client = new Client();\nclient.doSomeThingInService();\n</code></pre>\n\n<p><strong>Advantages</strong></p>\n\n<ul>\n<li>Simple</li>\n</ul>\n\n<p><strong>Disadvantages</strong></p>\n\n<ul>\n<li>Hard for test <code>Client</code> class</li>\n<li>When we change <code>Service</code> constructor, we need to change code in all place create <code>Service</code> object</li>\n</ul>\n\n<h2>Use Dependency Injection</h2>\n\n<p><strong>Way 1)</strong> Constructor injection</p>\n\n<pre><code>public class Client {\n Service service;\n\n Client(Service service) {\n this.service = service;\n }\n\n // Example Client has 2 dependency \n // Client(Service service, IDatabas database) {\n // this.service = service;\n // this.database = database;\n // }\n\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n</code></pre>\n\n<p><em>Using</em> </p>\n\n<pre><code>Client client = new Client(new Service());\n// Client client = new Client(new Service(), new SqliteDatabase());\nclient.doSomeThingInClient();\n</code></pre>\n\n<p><strong>Way 2)</strong> Setter injection</p>\n\n<pre><code>public class Client {\n Service service;\n\n public void setService(Service service) {\n this.service = service;\n }\n\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n</code></pre>\n\n<p><em>Using</em> </p>\n\n<pre><code>Client client = new Client();\nclient.setService(new Service());\nclient.doSomeThingInClient();\n</code></pre>\n\n<p><strong>Way 3)</strong> Interface injection</p>\n\n<p>Check <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Dependency_injection</a></p>\n\n<p>=== </p>\n\n<p>Now, this code is already follow <code>Dependency Injection</code> and it is easier for test <code>Client</code> class.<br>\nHowever, we still use <code>new Service()</code> many time and it is not good when change <code>Service</code> constructor. To prevent it, we can use DI injector like<br>\n1) Simple manual <code>Injector</code></p>\n\n<pre><code>public class Injector {\n public static Service provideService(){\n return new Service();\n }\n\n public static IDatabase provideDatatBase(){\n return new SqliteDatabase();\n }\n public static ObjectA provideObjectA(){\n return new ObjectA(provideService(...));\n }\n}\n</code></pre>\n\n<p><strong>Using</strong></p>\n\n<pre><code>Service service = Injector.provideService();\n</code></pre>\n\n<p>2) Use library: For Android <a href=\"https://github.com/google/dagger\" rel=\"noreferrer\">dagger2</a></p>\n\n<p><strong>Advantages</strong></p>\n\n<ul>\n<li>Make test easier</li>\n<li>When you change the <code>Service</code>, you only need to change it in Injector class</li>\n<li>If you use use <code>Constructor Injection</code>, when you look at constructor of <code>Client</code>, you will see how many dependency of <code>Client</code> class</li>\n</ul>\n\n<p><strong>Disadvantages</strong> </p>\n\n<ul>\n<li>If you use use <code>Constructor Injection</code>, the <code>Service</code> object is created when <code>Client</code> created, sometime we use function in <code>Client</code> class without use <code>Service</code> so created <code>Service</code> is wasted</li>\n</ul>\n\n<h3>Dependency Injection definition</h3>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Dependency_injection</a></p>\n\n<blockquote>\n <p>A dependency is an object that can be used (<code>Service</code>)<br>\n An injection is the passing of a dependency (<code>Service</code>) to a dependent object (<code>Client</code>) that would use it</p>\n</blockquote>\n" }, { "answer_id": 51126085, "author": "H S W", "author_id": 8584904, "author_profile": "https://Stackoverflow.com/users/8584904", "pm_score": 2, "selected": false, "text": "<p>From Christoffer Noring, Pablo Deeleman's book “Learning Angular - Second Edition”:</p>\n\n<p>\"As our <strong>applications</strong> grow and evolves, each one of our <strong>code entities</strong> will internally require <strong>instances of other objects</strong>, which are better known as <strong>dependencies</strong> in the world of software engineering. The <strong>action</strong> of passing such <strong>dependencies</strong> to the dependent client is known as <strong>injection</strong>, and it also entails the participation of another code entity, named the <strong>injector</strong>. The <strong>injector</strong> will take responsibility for <strong>instantiating</strong> and <strong>bootstrapping</strong> the required <strong>dependencies</strong> so they are ready for use from the very moment they are successfully injected in the client. This is very important since the client knows nothing about how to <strong>instantiate</strong> its own <strong>dependencies</strong> and is only aware of the <strong>interface</strong> they implement in order to use them.\"</p>\n\n<p>From: Anton Moiseev. book “Angular Development with Typescript, Second Edition.”:</p>\n\n<p>“In short, <strong>DI</strong> helps you write code in a <strong>loosely coupled</strong> way and makes your <strong>code</strong> more <strong>testable</strong> and <strong>reusable</strong>.”</p>\n" }, { "answer_id": 52440903, "author": "adamw", "author_id": 362531, "author_profile": "https://Stackoverflow.com/users/362531", "pm_score": 2, "selected": false, "text": "<p>I would propose a slightly different, short and precise definition of what Dependency Injection is, focusing on the primary goal, not on the technical means (following along from <a href=\"https://blog.softwaremill.com/what-is-dependency-injection-8c9e7805502f\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<blockquote>\n <p>Dependency Injection is the process of creating the static, stateless\n graph of service objects, where each service is parametrised by its\n dependencies.</p>\n</blockquote>\n\n<p>The objects that we create in our applications (regardless if we use Java, C# or other object-oriented language) usually fall into one of two categories: stateless, static and global “service objects” (modules), and stateful, dynamic and local “data objects”.</p>\n\n<p>The module graph - the graph of service objects - is typically created on application startup. This can be done using a container, such as Spring, but can also be done manually, by passing parameters to object constructors. Both ways have their pros and cons, but a framework definitely isn’t necessary to use DI in your application.</p>\n\n<p>One requirement is that the services must be parametrised by their dependencies. What this means exactly depends on the language and approach taken in a given system. Usually, this takes the form of constructor parameters, but using setters is also an option. This also means that the dependencies of a service are hidden (when invoking a service method) from the users of the service.</p>\n\n<p>When to use? I would say whenever the application is large enough that encapsulating logic into separate modules, with a dependency graph between the modules gives a gain in readability and explorability of the code.</p>\n" }, { "answer_id": 52531239, "author": "DevTheJo", "author_id": 5338073, "author_profile": "https://Stackoverflow.com/users/5338073", "pm_score": 1, "selected": false, "text": "<p>Dependency Injection is the practice to make decoupled component agnostic from some of their dependencies, this follow the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> guideline that say</p>\n\n<blockquote>\n <p>Dependency inversion principle: one should \"depend upon abstractions,\n not concretions.</p>\n</blockquote>\n\n<p>The better implementation of Dependency Injection is the Composition Root design pattern, as it's allow your components to be decoupled from the dependency injection container.</p>\n\n<p>I recommand this great article on Composition Root \n<a href=\"http://blog.ploeh.dk/2011/07/28/CompositionRoot/\" rel=\"nofollow noreferrer\">http://blog.ploeh.dk/2011/07/28/CompositionRoot/</a>\nwritten by Mark Seemann</p>\n\n<p>here is essential points from this article:</p>\n\n<blockquote>\n <p>A Composition Root is a (preferably) unique location in an application\n where modules are composed together.</p>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n <p>Only applications should have Composition Roots. Libraries and\n frameworks shouldn't.</p>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n <p>A DI Container should only be referenced from the Composition Root.\n All other modules should have no reference to the container.</p>\n</blockquote>\n\n<p>The documentation of Di-Ninja, a dependency injection framework, is a very good example to demonstrate how works the principles of Composition Root and Dependency Injection.\n<a href=\"https://github.com/di-ninja/di-ninja\" rel=\"nofollow noreferrer\">https://github.com/di-ninja/di-ninja</a>\nAs I know, is the only one DiC in javascript that implement the Composition-Root design pattern.</p>\n" }, { "answer_id": 54050455, "author": "Shadi Alnamrouti", "author_id": 3380497, "author_profile": "https://Stackoverflow.com/users/3380497", "pm_score": 0, "selected": false, "text": "<p>DI is how real objects actually interact with each other without one object being responsible for the existence of another object. Objects should be treated in equality. They are all objects. No one should act like a creator. This is how you do justice to your objects.</p>\n\n<p><strong>Simple example</strong>: </p>\n\n<p>if you need a physician, you simply go and find (an existing) one. You will not be thinking of creating a physician from scratch to help you. He already exists and he may serve you or other objects. He has the right to exist whether you (a single object) needs him or not because his purpose is to serve one or more objects. Who decided his existence is Almighty God, not natural selection. Therefore, one advantage of DI is to avoid creating useless redundant objects living without a purpose during the lifetime of your universe (i.e. application).</p>\n" }, { "answer_id": 57834999, "author": "Nithin Prasad", "author_id": 7230799, "author_profile": "https://Stackoverflow.com/users/7230799", "pm_score": 3, "selected": false, "text": "<p>Dependency Injection for 5 year olds.</p>\n\n<p>When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might be even looking for something we don't even have or which has expired.</p>\n\n<p>What you should be doing is stating a need, \"I need something to drink with lunch,\" and then we will make sure you have something when you sit down to eat.</p>\n" }, { "answer_id": 59837213, "author": "王玉略", "author_id": 8409280, "author_profile": "https://Stackoverflow.com/users/8409280", "pm_score": 1, "selected": false, "text": "<p>we can achieve a Dependency injection to know it:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>class Injector {\n constructor() {\n this.dependencies = {};\n this.register = (key, value) =&gt; {\n this.dependencies[key] = value;\n };\n }\n resolve(...args) {\n let func = null;\n let deps = null;\n let scope = null;\n const self = this;\n if (typeof args[0] === 'string') {\n func = args[1];\n deps = args[0].replace(/ /g, '').split(',');\n scope = args[2] || {};\n } else {\n func = args[0];\n deps = func.toString().match(/^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m)[1].replace(/ /g, '').split(',');\n scope = args[1] || {};\n }\n return (...args) =&gt; {\n func.apply(scope || {}, deps.map(dep =&gt; self.dependencies[dep] &amp;&amp; dep != '' ? self.dependencies[dep] : args.shift()));\n }\n }\n}\n\ninjector = new Injector();\n\ninjector.register('module1', () =&gt; { console.log('hello') });\ninjector.register('module2', () =&gt; { console.log('world') });\n\nvar doSomething1 = injector.resolve(function (module1, module2, other) {\n module1();\n module2();\n console.log(other);\n});\ndoSomething1(\"Other\");\n\nconsole.log('--------')\n\nvar doSomething2 = injector.resolve('module1,module2,', function (a, b, c) {\n a();\n b();\n console.log(c);\n});\ndoSomething2(\"Other\");\n</code></pre>\n\n<p>above is a implementation by javascript</p>\n" }, { "answer_id": 59928466, "author": "Gk Mohammad Emon", "author_id": 7200133, "author_profile": "https://Stackoverflow.com/users/7200133", "pm_score": 7, "selected": false, "text": "<p>Before going to the technical description first visualize it with a real-life example because you will find a lot of technical stuff to learn dependency injection but the majority of the people can't get the core concept of it.</p>\n<p>In the first picture, assume that you have a <strong>car factory</strong> with a lot of units. A car is actually built in the <strong>assembly unit</strong> but it needs <strong>engine</strong>, <strong>seats</strong> as well as <strong>wheels</strong>. So an <strong>assembly unit</strong> is dependent on these all units and they are the <strong>dependencies</strong> of the factory.</p>\n<p>You can feel that now it is too complicated to maintain all of the tasks in this factory because along with the main task (assembling a car in the Assembly unit) you have to also focus on <strong>other units</strong>. It is now very costly to maintain and the factory building is huge so it takes your extra bucks for rent.</p>\n<p>Now, look at the second picture. If you find some provider companies that will provide you with the <strong>wheel</strong>, <strong>seat</strong>, and <strong>engine</strong> for cheaper than your self-production cost then now you don't need to make them in your factory. You can rent a smaller building now just for your <strong>assembly unit</strong> which will lessen your maintenance task and reduce your extra rental cost. Now you can also focus only on your main task (Car assembly).</p>\n<p>Now we can say that all the <strong>dependencies</strong> for assembling a car are <strong>injected</strong> on the factory from the <strong>providers</strong>. It is an example of a real-life <em><strong>Dependency Injection (DI)</strong></em>.</p>\n<p>Now in the technical word, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.</p>\n<p><a href=\"https://www.freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/\" rel=\"noreferrer\">This</a> will help you now to learn DI with a technical explanation. <a href=\"http://tutorials.jenkov.com/dependency-injection/when-to-use-dependency-injection.html\" rel=\"noreferrer\">This</a> will show when to use DI and when you should <a href=\"https://softwareengineering.stackexchange.com/questions/135971/when-is-it-not-appropriate-to-use-the-dependency-injection-pattern\">not</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/E7OWM.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/E7OWM.png\" alt=\"All in one car factory\" /></a>.</p>\n<p><a href=\"https://i.stack.imgur.com/auqDX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/auqDX.png\" alt=\"Simple car factory\" /></a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354/" ]
There have been several questions already posted with specific questions about [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection), such as when to use it and what frameworks are there for it. However, **What is dependency injection and when/why should or shouldn't it be used?**
**Dependency Injection** is passing dependency to other **objects** or **framework**( dependency injector). Dependency injection makes testing easier. The injection can be done through **constructor**. `SomeClass()` has its constructor as following: ```csh public SomeClass() { myObject = Factory.getObject(); } ``` **Problem**: If `myObject` involves complex tasks such as disk access or network access, it is **hard** to do unit test on `SomeClass()`. Programmers have to mock `myObject` and might **intercept** the factory call. **Alternative solution**: * Passing `myObject` in as an argument to the constructor ```csh public SomeClass (MyClass myObject) { this.myObject = myObject; } ``` `myObject` can be passed directly which makes testing easier. * One common alternative is defining a **do-nothing constructor**. Dependency injection can be done through setters. (h/t @MikeVella). * [Martin Fowler](http://martinfowler.com/articles/injection.html#InterfaceInjection) documents a third alternative (h/t @MarcDix), where **classes explicitly implement an interface** for the dependencies programmers wish injected. It is harder to isolate components in unit testing without dependency injection. In 2013, when I wrote this answer, this was a major theme on the [Google Testing Blog](http://googletesting.blogspot.com/). It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.
130,801
<p>I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.</p> <p><em>Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?</em></p>
[ { "answer_id": 131256, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 3, "selected": false, "text": "<p>You seem to be asking 2 questions in the first paragraph.</p>\n\n<p>The first is about adding tests to the GNU autotools toolchain - but those tests, if I'm understanding you correctly, are for both validating that the environment necessary to build your application exists (dependent libraries and tools) as well as adapt the build to the environment (platform specific differences).</p>\n\n<p>The second is about unit testing your C++ application and where to invoke those tests, you've proposed doing so from the autotools tool chain, presumably from the configure script. Doing that isn't conventional though - putting a 'test' target in your Makefile is a more conventional way of executing your test suite. The typical steps for building and installing an application with autotools (at least from a user's perspective, not from your, the developer, perspective) is to run the configure script, then run make, then optionally run make test and finally make install.</p>\n\n<p>For the second issue, not wanting cppunit to be a dependency, why not just distribute it with your c++ application? Can you just put it right in what ever archive format you're using (be it tar.gz, tar.bz2 or .zip) along with your source code. I've used cppunit in the past and was happy with it, having used JUnit and other xUnit style frameworks.</p>\n" }, { "answer_id": 174142, "author": "jonner", "author_id": 78437, "author_profile": "https://Stackoverflow.com/users/78437", "pm_score": 6, "selected": true, "text": "<p>To make test run when you issue <code>make check</code>, you need to add them to the <code>TESTS</code> variable</p>\n\n<p>Assuming you've already built the executable that runs the unit tests, you just add the name of the executable to the TESTS variable like this:</p>\n\n<pre><code>TESTS=my-test-executable\n</code></pre>\n\n<p>It should then be automatically run when you <code>make check</code>, and if the executable returns a non-zero value, it will report that as a test failure. If you have multiple unit test executables, just list them all in the <code>TESTS</code> variable:</p>\n\n<pre><code>TESTS=my-first-test my-second-test my-third-test\n</code></pre>\n\n<p>and they will all get run.</p>\n" }, { "answer_id": 20277301, "author": "Dongho Yoo", "author_id": 1309262, "author_profile": "https://Stackoverflow.com/users/1309262", "pm_score": 4, "selected": false, "text": "<p>I'm using <a href=\"https://libcheck.github.io/check/\" rel=\"noreferrer\">Check 0.9.10</a></p>\n\n<pre><code> configure.ac\n Makefile.am\n src/Makefile.am\n src/foo.c\n tests/check_foo.c\n tests/Makefile.am\n</code></pre>\n\n<ol>\n<li><p><code>./configure.ac</code></p>\n\n<p>PKG_CHECK_MODULES([CHECK], [check >= 0.9.10])</p></li>\n<li><p><code>./tests/Makefile.am</code> for test codes</p>\n\n<pre><code>TESTS = check_foo\ncheck_PROGRAMS = check_foo\ncheck_foo_SOURCES = check_foo.c $(top_builddir)/src/foo.h\ncheck_foo_CFLAGS = @CHECK_CFLAGS@\n</code></pre></li>\n<li><p>and write test code, <code>./tests/check_foo.c</code></p>\n\n<pre><code>START_TEST (test_foo)\n{\n ck_assert( foo() == 0 );\n ck_assert_int_eq( foo(), 0);\n}\nEND_TEST\n\n/// And there are some tcase_xxx codes to run this test\n</code></pre></li>\n</ol>\n\n<p>Using check you can use timeout and raise signal. it is very helpful.</p>\n" }, { "answer_id": 46856458, "author": "wedesoft", "author_id": 382784, "author_profile": "https://Stackoverflow.com/users/382784", "pm_score": 1, "selected": false, "text": "<p>You can use Automake's <code>TESTS</code> to run programs generated with <code>check_PROGRAMS</code> but this will assume that you are using a log driver and a compiler for the output. It is probably easier to still use <code>check_PROGRAMS</code> but to invoke the test suite using a local rule in the Makefile:</p>\n\n<pre><code>check_PROGRAMS=testsuite\n\ntestsuite_SOURCES=...\ntestsuite_CFLAGS=...\ntestsuite_LDADD=...\n\ncheck-local:\n ./testsuite\n</code></pre>\n" }, { "answer_id": 60347950, "author": "Lloyd Rochester", "author_id": 5005311, "author_profile": "https://Stackoverflow.com/users/5005311", "pm_score": 2, "selected": false, "text": "<p>Here is a method without dependencies:</p>\n\n<pre><code>#src/Makefile.am\ncheck_PROGRAMS = test1 test2\ntest1_SOURCES = test/test1.c code_needed_to_test1.h code_needed_to_test1.c\ntest2_SOURCES = test/test2.c code_needed_to_test2.h code_needed_to_test2.c\nTESTS = $(check_PROGRAMS)\n</code></pre>\n\n<p>The <code>make check</code> will naturally work and show formatted and summarized output:</p>\n\n<pre><code>$ make check\n...\nPASS: test1\nPASS: test2\n============================================================================\nTestsuite summary for foo 1.0\n============================================================================\n# TOTAL: 2\n# PASS: 2\n# SKIP: 0\n# XFAIL: 0\n# FAIL: 0\n# XPASS: 0\n# ERROR: 0\n============================================================================\n</code></pre>\n\n<ol>\n<li>When you do a <code>make dist</code> nothing from <code>src/test/*</code> will be\nin the tarball. Test code is not in the dist, only source will be. </li>\n<li>When you do a <code>make distcheck</code> it will run <code>make check</code> and run your tests.</li>\n</ol>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well. *Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?*
To make test run when you issue `make check`, you need to add them to the `TESTS` variable Assuming you've already built the executable that runs the unit tests, you just add the name of the executable to the TESTS variable like this: ``` TESTS=my-test-executable ``` It should then be automatically run when you `make check`, and if the executable returns a non-zero value, it will report that as a test failure. If you have multiple unit test executables, just list them all in the `TESTS` variable: ``` TESTS=my-first-test my-second-test my-third-test ``` and they will all get run.
130,829
<p>I have 3 points in a 3D space of which I know the exact locations. Suppose they are: <code>(x0,y0,z0)</code>, <code>(x1,y1,z1)</code> and <code>(x2,y2,z2)</code>.</p> <p>Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example <code>(x0,y0,z0)</code> will be <code>(x0',y0')</code>, and <code>(x1,y1,z1)</code> will be <code>(x1',y1')</code> and <code>(x2,y2,z2)</code> will be <code>(x2',y2')</code> from the camera's point of view.</p> <p>What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.</p>
[ { "answer_id": 130909, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 5, "selected": true, "text": "<p>This gives you two sets, each of three equations in 3 variables:</p>\n\n<pre><code>a*x0+b*y0+c*z0 = x0'\na*x1+b*y1+c*z1 = x1'\na*x2+b*y2+c*z2 = x2'\n\nd*x0+e*y0+f*z0 = y0'\nd*x1+e*y1+f*z1 = y1'\nd*x2+e*y2+f*z2 = y2'\n</code></pre>\n\n<p>Just use whatever method of solving simultaneous equations is easiest in your situation (it isn't even hard to solve these \"by hand\"). Then your transformation matrix is just ((a,b,c)(d,e,f)).</p>\n\n<p>...</p>\n\n<p>Actually, that is over-simplified and assumes a camera pointed at the origin of your 3D coordinate system and no perspective.</p>\n\n<p>For perspective, the transformation matrix works more like:</p>\n\n<pre><code> ( a, b, c, d ) ( xt )\n( x, y, z, 1 ) ( e, f, g, h ) = ( yt )\n ( i, j, k, l ) ( zt )\n\n( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md &lt; zt;\n</code></pre>\n\n<p>but the 4x3 matrix is more constrained than 12 degrees of freedom since we should have</p>\n\n<pre><code>a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1\na*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1\n</code></pre>\n\n<p>So you should probably have 4 points to get 8 equations to cover the 6 variables for camera position and angle and 1 more for scaling of the 2-D view points since we'll be able to eliminate the \"center\" coordinates (xc,yc).</p>\n\n<p>So if you have 4 points and transform your 2-D view points to be relative to the center of your display, then you can get 14 simultaneous equations in 13 variables and solve.</p>\n\n<p>Unfortunately, six of the equations are not linear equations. Fortunately, all of the variables in those equations are restricted to the values between -1 and 1 so it is still probably feasible to solve the equations.</p>\n" }, { "answer_id": 130914, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 0, "selected": false, "text": "<p>I don't think there is enough information to find a definitive solution. Without knowing your camera location and without knowing your view plane, there is an infinite number of matrices that can solve this problem.</p>\n" }, { "answer_id": 130927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Your camera has (at least) 7 degrees of freedom - 3 for position, 3 for orientation and 1 for FOV. I'm sure someone will correct me if I'm wrong, but it doesn't seem like 3 points are enough for a full solution.</p>\n\n<p>For a generalised solution to this problem, look up 'View Correlation' in Graphics Gems II.</p>\n" }, { "answer_id": 4990615, "author": "Lex van der Sluijs", "author_id": 615953, "author_profile": "https://Stackoverflow.com/users/615953", "pm_score": 2, "selected": false, "text": "<p>What you are looking for is called a Pose Estimation algorithm. Have a look at the POSIT implementation in OpenCV: <a href=\"http://opencv.willowgarage.com/documentation/c/calib3d_camera_calibration_and_3d_reconstruction.html#posit\" rel=\"nofollow\">http://opencv.willowgarage.com/documentation/c/calib3d_camera_calibration_and_3d_reconstruction.html#posit</a></p>\n\n<p>You will need four or more points, and they may not lie in the same plane.</p>\n\n<p>A tutorial for this implementation is here:\n<a href=\"http://opencv.willowgarage.com/wiki/Posit\" rel=\"nofollow\">http://opencv.willowgarage.com/wiki/Posit</a></p>\n\n<p>Do take care though: in the tutorial a square viewport is used, so all view-coordinates are in the -1,-1 to 1,1 range. This leads one to assume that these should be in the camera coordinate system (before aspect-ratio correction). This is not the case, so if you use a viewport with e.g. a 4:3 aspect ratio then your input coordinates should be in the -1.3333,-1 to 1.3333,1 range.</p>\n\n<p>By the way, if your points <em>must</em> lie in the same plane, then you can also look at the CameraCalibration algorithm from OpenCV, but this is more involved to set up and requires more points as input. However it will also yield you the distortion information and intrinsic parameters of your camera.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have 3 points in a 3D space of which I know the exact locations. Suppose they are: `(x0,y0,z0)`, `(x1,y1,z1)` and `(x2,y2,z2)`. Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example `(x0,y0,z0)` will be `(x0',y0')`, and `(x1,y1,z1)` will be `(x1',y1')` and `(x2,y2,z2)` will be `(x2',y2')` from the camera's point of view. What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.
This gives you two sets, each of three equations in 3 variables: ``` a*x0+b*y0+c*z0 = x0' a*x1+b*y1+c*z1 = x1' a*x2+b*y2+c*z2 = x2' d*x0+e*y0+f*z0 = y0' d*x1+e*y1+f*z1 = y1' d*x2+e*y2+f*z2 = y2' ``` Just use whatever method of solving simultaneous equations is easiest in your situation (it isn't even hard to solve these "by hand"). Then your transformation matrix is just ((a,b,c)(d,e,f)). ... Actually, that is over-simplified and assumes a camera pointed at the origin of your 3D coordinate system and no perspective. For perspective, the transformation matrix works more like: ``` ( a, b, c, d ) ( xt ) ( x, y, z, 1 ) ( e, f, g, h ) = ( yt ) ( i, j, k, l ) ( zt ) ( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md < zt; ``` but the 4x3 matrix is more constrained than 12 degrees of freedom since we should have ``` a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1 a*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1 ``` So you should probably have 4 points to get 8 equations to cover the 6 variables for camera position and angle and 1 more for scaling of the 2-D view points since we'll be able to eliminate the "center" coordinates (xc,yc). So if you have 4 points and transform your 2-D view points to be relative to the center of your display, then you can get 14 simultaneous equations in 13 variables and solve. Unfortunately, six of the equations are not linear equations. Fortunately, all of the variables in those equations are restricted to the values between -1 and 1 so it is still probably feasible to solve the equations.
130,837
<p>I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:</p> <ol> <li>No directories. JUST the file name.</li> <li>File name needs to be all lowercase.</li> <li>Whitespaces need to be replaced with underscores.</li> </ol> <p>Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).</p>
[ { "answer_id": 130845, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 2, "selected": false, "text": "<p>If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at <a href=\"http://regexlib.com/\" rel=\"nofollow noreferrer\">http://regexlib.com/</a>.\nEdit to say: <a href=\"http://regexlib.com/REDetails.aspx?regexp_id=1934\" rel=\"nofollow noreferrer\">Here's one that might work for you</a>:</p>\n<pre><code>([0-9a-z_-]+[\\.][0-9a-z_-]{1,3})$\n</code></pre>\n" }, { "answer_id": 139301, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "<p>If you're taking a string path from the user (eg. by reading the .value of a file upload field), you can't actually be sure what the path separator character is. It might be a backslash (Windows), forward slash (Linux, OS X, BSD etc.) or something else entirely on old or obscure OSs. Splitting the path on either forward or backslash will cover the common cases, but it's a good idea to include the ability for the user to override the filename in case we guessed wrong.</p>\n\n<p>As for 'invalid characters' these too depend on the operating system. Probably the easiest path is to replace all non-alphanumerics with a placeholder such as an underscore.</p>\n\n<p>Here's what I use:</p>\n\n<pre><code>var parts= path.split('\\\\');\nparts= parts[parts.length-1].split('/');\nvar filename= parts[parts.length-1].toLowerCase();\nfilename= filename.replace(new RegExp('[^a-z0-9]+', 'g'), '_');\nif (filename=='') filename= '_'\n</code></pre>\n" }, { "answer_id": 147271, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 2, "selected": true, "text": "<p>And a simple combination of RegExp and other javascript is what I would recommend:</p>\n\n<pre><code>var a = \"c:\\\\some\\\\path\\\\to\\\\a\\\\file\\\\with Whitespace.TXT\";\na = a.replace(/^.*[\\\\\\/]([^\\\\\\/]*)$/i,\"$1\");\na = a.replace(/\\s/g,\"_\");\na = a.toLowerCase();\nalert(a);\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string: 1. No directories. JUST the file name. 2. File name needs to be all lowercase. 3. Whitespaces need to be replaced with underscores. Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).
And a simple combination of RegExp and other javascript is what I would recommend: ``` var a = "c:\\some\\path\\to\\a\\file\\with Whitespace.TXT"; a = a.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1"); a = a.replace(/\s/g,"_"); a = a.toLowerCase(); alert(a); ```
130,843
<p>Using Prototype 1.6's "new Element(...)" I am trying to create a &lt;table&gt; element with both a &lt;thead&gt; and &lt;tbody&gt; but nothing happens in IE6.</p> <pre><code>var tableProto = new Element('table').update('&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Situation Task&lt;/th&gt;&lt;th&gt;Action&lt;/th&gt;&lt;th&gt;Result&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;b&lt;/td&gt;&lt;td&gt;c&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;'); </code></pre> <p>I'm then trying to inject copies of it like this:</p> <pre><code>$$('div.question').each(function(o) { Element.insert(o, { after:$(tableProto.cloneNode(true)) }); }); </code></pre> <p>My current workaround is to create a &lt;div&gt; instead of a &lt;table&gt; element, and then "update" it with all of the table HTML.</p> <p>How does one successfully do this?</p>
[ { "answer_id": 130884, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>If prototypes' .update() method internally tries to set the .innerHTML it will fail in IE. In IE, <strong>the .innerHTML of a table element is readonly</strong>.</p>\n\n<p>Source:</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/12/bug-210-no-innerhtml-support-on-tables.html\" rel=\"nofollow noreferrer\">http://webbugtrack.blogspot.com/2007/12/bug-210-no-innerhtml-support-on-tables.html</a></p>\n" }, { "answer_id": 131460, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "<p>As it turns out, there's nothing wrong with the example code I provided in the question--it works in IE6 just fine. The issue I was facing is that I was also specifying a class for the &lt;table&gt; element in the constructor incorrectly, but omitted that from my example.</p>\n\n<p>The \"real\" code was as follows, and is incorrect:</p>\n\n<pre><code>var tableProto = new Element('table', { class:'hide-on-screen'} ).update('&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Situation Task&lt;/th&gt;&lt;th&gt;Action&lt;/th&gt;&lt;th&gt;Result&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;b&lt;/td&gt;&lt;td&gt;c&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;');\n</code></pre>\n\n<p>This works correctly in Firefox, but fails in IE6 because it is <strong>wrong</strong>.</p>\n\n<p>The correct way to add attributes to an element via this constructor is to provides strings, not just attribute names. The following code works in both browsers:</p>\n\n<pre><code>var tableProto = new Element('table', { 'class':'hide-on-screen'} ).update('&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Situation Task&lt;/th&gt;&lt;th&gt;Action&lt;/th&gt;&lt;th&gt;Result&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;b&lt;/td&gt;&lt;td&gt;c&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;');\n</code></pre>\n\n<p>There is an error due to \"class\" being a reserved word in JavaScript. Doh!</p>\n\n<p>Let this be a lesson to those who don't supply their <strong>actual</strong> code!</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
Using Prototype 1.6's "new Element(...)" I am trying to create a <table> element with both a <thead> and <tbody> but nothing happens in IE6. ``` var tableProto = new Element('table').update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>'); ``` I'm then trying to inject copies of it like this: ``` $$('div.question').each(function(o) { Element.insert(o, { after:$(tableProto.cloneNode(true)) }); }); ``` My current workaround is to create a <div> instead of a <table> element, and then "update" it with all of the table HTML. How does one successfully do this?
As it turns out, there's nothing wrong with the example code I provided in the question--it works in IE6 just fine. The issue I was facing is that I was also specifying a class for the <table> element in the constructor incorrectly, but omitted that from my example. The "real" code was as follows, and is incorrect: ``` var tableProto = new Element('table', { class:'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>'); ``` This works correctly in Firefox, but fails in IE6 because it is **wrong**. The correct way to add attributes to an element via this constructor is to provides strings, not just attribute names. The following code works in both browsers: ``` var tableProto = new Element('table', { 'class':'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>'); ``` There is an error due to "class" being a reserved word in JavaScript. Doh! Let this be a lesson to those who don't supply their **actual** code!
130,877
<p>What function will let us know whether a date in VBA is in DST or not?</p>
[ { "answer_id": 130879, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 4, "selected": true, "text": "<p><b>For non-current dates (DST 2007+):</b></p>\n\n<p>First, you need a function to find the number of specific weekdays in a month:</p>\n\n<pre><code>Public Function NDow(Y As Integer, M As Integer, _\n N As Integer, DOW As Integer) As Date \n\n' Returns Date of Nth Day of the Week in Month \n\nNDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _\n (DOW + 1) Mod 8)) + ((N - 1) * 7)) \n\nEnd Function \n</code></pre>\n\n<p>Then, you can check for the DST day versus the following function calls:</p>\n\n<p>Fall: NDow(Year(newdate), 11, 1, 1)<br>\n Spring: NDow(Year(newdate), 3, 2, 1) </p>\n\n<p><b>For the current date:</b></p>\n\n<p>Call the Windows API function GetTimeZoneInformation,\nand it will return an enum (integer) with the status.</p>\n\n<p>I got the code for this from Chip Pearson's great Excel site.</p>\n\n<p><a href=\"http://www.cpearson.com/excel/MainPage.aspx\" rel=\"nofollow noreferrer\">Pearson's site</a></p>\n" }, { "answer_id": 34357342, "author": "Pieter Heemeryck", "author_id": 2568944, "author_profile": "https://Stackoverflow.com/users/2568944", "pm_score": 2, "selected": false, "text": "<p>For anyone wondering how to account for daylight saving time in Europe (central europe time), I modified the script from <a href=\"http://www.cpearson.com/excel/DaylightSavings.htm\" rel=\"nofollow noreferrer\">Chip Pearson</a>. The last sunday of March (2 AM to 3 AM) and October (3 AM to 2 AM) are the days when the hour switching occurs.</p>\n\n<p>Following code is the click event of a button in Excel:</p>\n\n<pre><code>Dim dates As String\ndates = \"A1:A20\"\n\nFor Each c In Worksheets(\"Sheet1\").Range(dates).Cells\n If (IsDateWithinDST(c.Value)) Then\n c.Value = DateAdd(\"h\", 1, c.Value)\n End If\nNext\n</code></pre>\n\n<p>The module containing the necessary methods are to be found <a href=\"https://github.com/pheemery2/EuropeanDST\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Summer_Time_in_Europe\" rel=\"nofollow noreferrer\">More info on DST in Europe.</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
What function will let us know whether a date in VBA is in DST or not?
**For non-current dates (DST 2007+):** First, you need a function to find the number of specific weekdays in a month: ``` Public Function NDow(Y As Integer, M As Integer, _ N As Integer, DOW As Integer) As Date ' Returns Date of Nth Day of the Week in Month NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _ (DOW + 1) Mod 8)) + ((N - 1) * 7)) End Function ``` Then, you can check for the DST day versus the following function calls: Fall: NDow(Year(newdate), 11, 1, 1) Spring: NDow(Year(newdate), 3, 2, 1) **For the current date:** Call the Windows API function GetTimeZoneInformation, and it will return an enum (integer) with the status. I got the code for this from Chip Pearson's great Excel site. [Pearson's site](http://www.cpearson.com/excel/MainPage.aspx)
130,878
<p>What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex.</p> <h2>Code with Global</h2> <pre><code>$conn = new PDO(...); function getSomething() { global $conn; . . . } </code></pre> <h2>Code with Singleton</h2> <pre><code>class DB_Instance { private static $db; public static function getDBO() { if (!self::$db) self::$db = new PDO(...); return self::$db; } } function getSomething() { $conn = DB_Instance::getDBO(); . . . } </code></pre> <p>If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.</p>
[ { "answer_id": 130889, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>It is quite simple. Never use global OR Singleton.</p>\n" }, { "answer_id": 130900, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 2, "selected": false, "text": "<p>If you're not going to use a persistent connection, and there are cases for not doing that, I find a singleton to be conceptually more palatable than a global in OO design.</p>\n\n<p>In a true OO architecture, a singleton is more effective than creating a new instance the object each time.</p>\n" }, { "answer_id": 130905, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 4, "selected": false, "text": "<p>I'm not sure I can answer your specific question, but wanted to suggest that global / singleton connection objects may not be the best idea if this if for a web-based system. DBMSs are generally designed to manage large numbers of unique connections in an efficient manner. If you are using a global connection object, then you are doing a couple of things:</p>\n\n<ol>\n<li><p>Forcing you pages to do all database\nconnections sequentially and killing\nany attempts at asyncronous page\nloads. </p></li>\n<li><p>Potentially holding open locks on\ndatabase elements longer than\nnecessary, slowing down overall\ndatabase performance.</p></li>\n<li><p>Maxing out the total number of\nsimultaneous connections your\ndatabase can support and blocking\nnew users from accessing the\nresources.</p></li>\n</ol>\n\n<p>I am sure there are other potential consequences as well. Remember, this method will attempt to sustain a database connection for every user accessing the site. If you only have one or two users, not a problem. If this is a public website and you want traffic then scalability will become an issue.</p>\n\n<p><strong>[EDIT]</strong></p>\n\n<p>In larger scaled situations, creating new connections everytime you hit the datase can be bad. However, the answer is not to create a global connection and reuse it for everything. The answer is connection pooling. </p>\n\n<p>With connection pooling, a number of distinct connections are maintained. When a connection is required by the application the first available connection from the pool is retrieved and then returned to the pool once its job is done. If a connection is requested and none are available one of two things will happen: a) if the maximum number of allowed connection is not reached, a new connection is opened, or b) the application is forced to wait for a connection to become available.</p>\n\n<p><strong>Note:</strong> In .Net languages, connection pooling is handled by the ADO.Net objects by default (the connection string sets all the required information). </p>\n\n<p>Thanks to Crad for commenting on this.</p>\n" }, { "answer_id": 130906, "author": "Dprado", "author_id": 21943, "author_profile": "https://Stackoverflow.com/users/21943", "pm_score": 2, "selected": false, "text": "<p>On the given example, I see no reason to use singletons. As a rule of thumb if my only concern is to allow a single instance of an object, if the language allows it, I prefer to use globals</p>\n" }, { "answer_id": 130931, "author": "RWendi", "author_id": 15152, "author_profile": "https://Stackoverflow.com/users/15152", "pm_score": 1, "selected": false, "text": "<p>In general I would use a singleton for a database connection... You don't want to create a new connection everytime you need to interact to the database... This might hurt perfomance and bandwidth of your network... Why create a new one, when there's one available... Just my 2 cents...</p>\n\n<p>RWendi</p>\n" }, { "answer_id": 131208, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 2, "selected": false, "text": "<p>Both patterns achieve the same net effect, providing one single access point for your database calls. </p>\n\n<p>In terms of specific implementation, the singleton has a small advantage of not initiating a database connection until at least one of your other methods requests it. In practice in most applications I've written, this doesn't make much of a difference, but it's a potential advantage if you have some pages/execution paths which don't make any database calls at all, since those pages won't ever request a connection to the database.</p>\n\n<p>One other minor difference is that the global implementation may trample over other variable names in the application unintentionally. It's unlikely that you'll ever accidentally declare another global $db reference, though it's possible that you could overwrite it accidentally ( say, you write if($db = null) when you meant to write if($db == null). The singleton object prevents that.</p>\n" }, { "answer_id": 219599, "author": "Jon Raphaelson", "author_id": 27546, "author_profile": "https://Stackoverflow.com/users/27546", "pm_score": 8, "selected": true, "text": "<p>I know this is old, but Dr8k's answer was <em>almost</em> there.</p>\n\n<p>When you are considering writing a piece of code, assume it's going to change. That doesn't mean that you're assuming the kinds of changes it will have hoisted upon it at some point in the future, but rather that some form of change will be made.</p>\n\n<p>Make it a goal mitigate the pain of making changes in the future: a global is dangerous because it's hard to manage in a single spot. What if I want to make that database connection context aware in the future? What if I want it to close and reopen itself every 5th time it was used. What if I decide that in the interest of scaling my app I want to use a pool of 10 connections? Or a configurable number of connections?</p>\n\n<p>A <strong>singleton factory</strong> gives you that flexibility. I set it up with very little extra complexity and gain more than just access to the same connection; I gain the ability to change how that connection is passed to me later on in a simple manner.</p>\n\n<p>Note that I say <em>singleton factory</em> as opposed to simply <em>singleton</em>. There's precious little difference between a singleton and a global, true. And because of that, there's no reason to have a singleton connection: why would you spend the time setting that up when you could create a regular global instead?</p>\n\n<p>What a factory gets you is a why to get connections, and a separate spot to decide what connections (or connection) you're going to get.</p>\n\n<h2>Example</h2>\n\n<pre><code>class ConnectionFactory\n{\n private static $factory;\n private $db;\n\n public static function getFactory()\n {\n if (!self::$factory)\n self::$factory = new ConnectionFactory(...);\n return self::$factory;\n }\n\n public function getConnection() {\n if (!$this-&gt;db)\n $this-&gt;db = new PDO(...);\n return $this-&gt;db;\n }\n}\n\nfunction getSomething()\n{\n $conn = ConnectionFactory::getFactory()-&gt;getConnection();\n .\n .\n .\n}\n</code></pre>\n\n<p>Then, in 6 months when your app is super famous and getting dugg and slashdotted and you decide you need more than a single connection, all you have to do is implement some pooling in the getConnection() method. Or if you decide that you want a wrapper that implements SQL logging, you can pass a PDO subclass. Or if you decide you want a new connection on every invocation, you can do do that. It's flexible, instead of rigid.</p>\n\n<p>16 lines of code, including braces, which will save you hours and hours and hours of refactoring to something eerily similar down the line.</p>\n\n<p>Note that I don't consider this \"Feature Creep\" because I'm not doing any feature implementation in the first go round. It's border line \"Future Creep\", but at some point, the idea that \"coding for tomorrow today\" is <em>always</em> a bad thing doesn't jive for me.</p>\n" }, { "answer_id": 8482925, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The singleton method was created to make sure there was only one instance of any class. But, because people use it as a way to shortcut globalizing, it becomes known as lazy and/or bad programming.</p>\n\n<p>Therefore, I would ignore global and Singleton since both are not really OOP. </p>\n\n<p>What you were looking for is <strong>dependency injection</strong>. </p>\n\n<p>You can check on easy to read PHP based information related to dependency injection (with examples) at <a href=\"http://components.symfony-project.org/dependency-injection/trunk/book/01-Dependency-Injection\" rel=\"noreferrer\">http://components.symfony-project.org/dependency-injection/trunk/book/01-Dependency-Injection</a></p>\n" }, { "answer_id": 50555311, "author": "Lenin Zapata", "author_id": 3557834, "author_profile": "https://Stackoverflow.com/users/3557834", "pm_score": 0, "selected": false, "text": "<p>As advice both <strong>singleton</strong> and <strong>global</strong> are valid and can be joined within the same <em>system, project, plugin, product, etc</em> ...\nIn my case, I make digital products for web (plugin). </p>\n\n<p>I use only <strong>singleton</strong> in the main class and I use it by principle. I almost do not use it because I know that the main class will not instantiate it again</p>\n\n<pre><code>&lt;?php // file0.php\n\nfinal class Main_Class\n{\n private static $instance;\n private $time;\n\n private final function __construct()\n {\n $this-&gt;time = 0;\n }\n public final static function getInstance() : self\n {\n if (self::$instance instanceof self) {\n return self::$instance;\n }\n\n return self::$instance = new self();\n }\n public final function __clone()\n {\n throw new LogicException(\"Cloning timer is prohibited\");\n }\n public final function __sleep()\n {\n throw new LogicException(\"Serializing timer is prohibited\");\n }\n public final function __wakeup()\n {\n throw new LogicException(\"UnSerializing timer is prohibited\");\n }\n}\n</code></pre>\n\n<p><strong>Global</strong> use for almost all the secondary classes, example:</p>\n\n<pre><code>&lt;?php // file1.php\nglobal $YUZO;\n$YUZO = new YUZO; // YUZO is name class\n</code></pre>\n\n<p>while at runtime I can use <strong>Global</strong> to call their methods and attributes in the same instance because I do not need another instance of my main product class.</p>\n\n<pre><code>&lt;?php // file2.php\nglobal $YUZO;\n$YUZO-&gt;method1()-&gt;run();\n$YUZO-&gt;method2( 'parameter' )-&gt;html()-&gt;print();\n</code></pre>\n\n<p>I get with the global is to use the same instance to be able to make the product work because I do not need a factory for instances of the same class, usually the instance factory is for large systems or for very rare purposes.</p>\n\n<p><code>In conclusion:</code>, you must if you already understand well that is the anti-pattern <strong>Singleton</strong> and understand the <strong>Global</strong>, you can use one of the 2 options or mix them but if I recommend not to abuse since there are many programmers who are very exception and faithful to the programming OOP, use it for main and secondary classes that you use a lot within the execution time. (It saves you a lot of CPU). </p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]
What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex. Code with Global ---------------- ``` $conn = new PDO(...); function getSomething() { global $conn; . . . } ``` Code with Singleton ------------------- ``` class DB_Instance { private static $db; public static function getDBO() { if (!self::$db) self::$db = new PDO(...); return self::$db; } } function getSomething() { $conn = DB_Instance::getDBO(); . . . } ``` If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.
I know this is old, but Dr8k's answer was *almost* there. When you are considering writing a piece of code, assume it's going to change. That doesn't mean that you're assuming the kinds of changes it will have hoisted upon it at some point in the future, but rather that some form of change will be made. Make it a goal mitigate the pain of making changes in the future: a global is dangerous because it's hard to manage in a single spot. What if I want to make that database connection context aware in the future? What if I want it to close and reopen itself every 5th time it was used. What if I decide that in the interest of scaling my app I want to use a pool of 10 connections? Or a configurable number of connections? A **singleton factory** gives you that flexibility. I set it up with very little extra complexity and gain more than just access to the same connection; I gain the ability to change how that connection is passed to me later on in a simple manner. Note that I say *singleton factory* as opposed to simply *singleton*. There's precious little difference between a singleton and a global, true. And because of that, there's no reason to have a singleton connection: why would you spend the time setting that up when you could create a regular global instead? What a factory gets you is a why to get connections, and a separate spot to decide what connections (or connection) you're going to get. Example ------- ``` class ConnectionFactory { private static $factory; private $db; public static function getFactory() { if (!self::$factory) self::$factory = new ConnectionFactory(...); return self::$factory; } public function getConnection() { if (!$this->db) $this->db = new PDO(...); return $this->db; } } function getSomething() { $conn = ConnectionFactory::getFactory()->getConnection(); . . . } ``` Then, in 6 months when your app is super famous and getting dugg and slashdotted and you decide you need more than a single connection, all you have to do is implement some pooling in the getConnection() method. Or if you decide that you want a wrapper that implements SQL logging, you can pass a PDO subclass. Or if you decide you want a new connection on every invocation, you can do do that. It's flexible, instead of rigid. 16 lines of code, including braces, which will save you hours and hours and hours of refactoring to something eerily similar down the line. Note that I don't consider this "Feature Creep" because I'm not doing any feature implementation in the first go round. It's border line "Future Creep", but at some point, the idea that "coding for tomorrow today" is *always* a bad thing doesn't jive for me.
130,894
<p>I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but:</p> <ul> <li>It is an older version (lacking features I need)</li> <li>I need slightly different compile options than the default.</li> </ul> <p>What is the easiest way of doing it? I am concerned about a couple of things</p> <ul> <li>How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.)</li> <li>How I can I prevent the update system installing the older version in the repo on an update?</li> <li>How I can prevent the system installing a newer version (when its out), overwriting my custom package?</li> </ul>
[ { "answer_id": 130908, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "<p>I believe <a href=\"http://www.debian.org/doc/maint-guide/\" rel=\"nofollow noreferrer\">this</a> is the Debian package 'bible'.</p>\n<p>Well, it's the Debian new maintainer's guide, so a lot of it won't be applicable, but they do cover what goes where.</p>\n" }, { "answer_id": 130985, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://tldp.org/HOWTO/html_single/Debian-Binary-Package-Building-HOWTO/\" rel=\"nofollow noreferrer\">Here</a> is a tutorial for building a Debian package.</p>\n\n<p>Basically, you need to:</p>\n\n<ol>\n<li>Set up your folder structure</li>\n<li>Create a <strong>control</strong> file</li>\n<li>Optionally create <strong>postinst</strong> or <strong>prerm</strong> scripts</li>\n<li>Run dpkg-deb</li>\n</ol>\n\n<p>I usually do all of this in my Makefile so I can just type <strong>make</strong> to spit out the binary and package it in one go.</p>\n" }, { "answer_id": 131090, "author": "Daniel Bungert", "author_id": 21093, "author_profile": "https://Stackoverflow.com/users/21093", "pm_score": 5, "selected": false, "text": "<p>First, the title question:\n Assuming the debian directory is already there, be in the source directory (the directory containing the debian directory) and invoke dpkg-buildpackage. I like to run it with these options:</p>\n\n<pre><code>dpkg-buildpackage -us -uc -nc\n</code></pre>\n\n<p>which mean don't sign the result and don't clean.</p>\n\n<blockquote>\n <p>How can I check if I have listed all the dependencies correctly?</p>\n</blockquote>\n\n<p>Getting the dependencies is a black art. The \"official\" way is to check build depends is if the package builds with only the base system, the \"build-essential\" packages, and the build dependencies you have specified. Don't know a general answer for regular Dependencies, just wade in :)</p>\n\n<blockquote>\n <p>How I can I prevent the update system installing the older version in the repo on an update?\n How I can prevent the system installing a newer version (when its out), overwriting my custom package?</p>\n</blockquote>\n\n<p>My knowledge might be out of date on this one, but to address both:\nUse dpkg --set-selections. Assuming nullidentd was the package you wanted to stay put, run as root</p>\n\n<pre><code>echo 'nullidentd hold' | dpkg --set-selections\n</code></pre>\n\n<p>Alternately, since you are building from source, you can use an <a href=\"http://www.us.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version\" rel=\"noreferrer\">epoch</a> to set the version number artificially high and never be bothered again. To use an epoch, add a new entry to the debian/changelog file, and put a 99: in front of the version number. Given my nullidentd example, the first line of your updated changelog would read:</p>\n\n<pre><code>nullidentd (99:1.0-4) unstable; urgency=low\n</code></pre>\n\n<p><a href=\"http://www.debian.org/doc/maint-guide/\" rel=\"noreferrer\">Bernard's link</a> is good, especially if you have to create the debian directory yourself - also helpful are the <a href=\"http://www.us.debian.org/doc/developers-reference/\" rel=\"noreferrer\">developers reference</a> and the <a href=\"http://www.us.debian.org/devel/\" rel=\"noreferrer\">general resource page</a>. <a href=\"http://tldp.org/HOWTO/html_single/Debian-Binary-Package-Building-HOWTO/\" rel=\"noreferrer\">Adam's link</a> also looks good but I'm not familiar with it.</p>\n" }, { "answer_id": 133844, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 3, "selected": false, "text": "<p>For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from <a href=\"http://packages.debian.org\" rel=\"noreferrer\">packages.debian.org</a>, or can get it along with the .dsc and the original source archive by using \"apt-get source\".</p>\n\n<p>Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing</p>\n\n<pre><code>zcat ~/downloaded.diff.gz | patch -p1\nchmod +x debian/rules\n</code></pre>\n\n<p>Then make the changes you wanted to compile options, and build the package by doing</p>\n\n<pre><code>dpkg-buildpackage -rfakeroot -us -uc\n</code></pre>\n" }, { "answer_id": 308961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>you can use the special package \"checkinstall\" for all packages which are not even in debian/ubuntu yet.</p>\n\n<p>You can use \"uupdate\" (<code>apt-get install devscripts</code>) to build a package from source with existing debian sources:</p>\n\n<p>Example for libdrm2:</p>\n\n<pre><code>apt-get build-dep libdrm2\napt-get source libdrm2\ncd libdrm-2.3.1\nuupdate ~/Downloads/libdrm-2.4.1.tar.gz\ncd ../libdrm-2.4.1\ndpkg-buildpackage -us -uc -nc\n</code></pre>\n" }, { "answer_id": 1197968, "author": "zowers", "author_id": 142561, "author_profile": "https://Stackoverflow.com/users/142561", "pm_score": 2, "selected": false, "text": "<ul>\n<li>put \"debian\" directory from original package to your source directory</li>\n<li>use \"<a href=\"http://manpages.ubuntu.com/manpages/lucid/man1/dch.1.html\" rel=\"nofollow noreferrer\">dch</a>\" to update version of package</li>\n<li>use \"debuild\" to build the package</li>\n</ul>\n" }, { "answer_id": 5207713, "author": "LRMAAX", "author_id": 646503, "author_profile": "https://Stackoverflow.com/users/646503", "pm_score": 2, "selected": false, "text": "<p>If you're using Ubuntu, check out the pkgcreator project:\n<a href=\"http://code.google.com/p/pkgcreator\" rel=\"nofollow\">http://code.google.com/p/pkgcreator</a></p>\n" }, { "answer_id": 7996582, "author": "thiton", "author_id": 847601, "author_profile": "https://Stackoverflow.com/users/847601", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>How can I check if I have listed all the dependencies correctly?</p>\n</blockquote>\n\n<p>The <code>pbuilder</code> is an excellent tool for checking both build dependencies and dependencies by setting up a clean base system within a chroot environment. By compiling the package within pbuilder, you can easily check the build dependencies, and by testing it within a pbuilder environment, you can check the dependencies.</p>\n" }, { "answer_id": 9620733, "author": "Allard Hoeve", "author_id": 1178372, "author_profile": "https://Stackoverflow.com/users/1178372", "pm_score": 1, "selected": false, "text": "<p>If you want a quick and dirty way of installing the build dependencies, use:</p>\n\n<pre><code>apt-get build-dep\n</code></pre>\n\n<p>This installs the dependencies. You need sources lines in your sources.list for this:</p>\n\n<pre><code>deb-src http://ftp.nl.debian.org/debian/ squeeze-updates main contrib non-free\n</code></pre>\n\n<p>If you are backporting packages from testing to stable, please be advised that the dependencies might have changed. The command apt-get build-deb installs dependencies for the source packages in your current repository.</p>\n\n<p>But of course, dpkg-buildpackage -us -uc will show you any uninstalled dependencies.</p>\n\n<p>If you want to compile more often, use cowbuilder.</p>\n\n<pre><code>apt-get install cowbuilder\n</code></pre>\n\n<p>Then create a build-area:</p>\n\n<p>sudo DIST=squeeze ARCH=amd64 cowbuilder --create</p>\n\n<p>Then compile a source package:</p>\n\n<pre><code>apt-get source cowsay\n\n# do your magic editing\ndpkg-source -b cowsay-3.03+dfsg1 # build the new source packages\ncowbuilder --build cowsay_3.03+dfsg1-2.dsc # build the packages from source\n</code></pre>\n\n<p>Watch where cowbuilder puts the resulting package.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 12485164, "author": "Dariusz Cieslak", "author_id": 1681483, "author_profile": "https://Stackoverflow.com/users/1681483", "pm_score": 3, "selected": false, "text": "<p>Sample <strong>Ubuntu-based build</strong> for ccache:</p>\n\n<pre><code>sudo apt-get update\nsudo apt-get build-dep ccache\napt-get -b source ccache\nsudo dpkg -i ccache*.deb\n</code></pre>\n\n<p>More details: <a href=\"http://blog.aplikacja.info/2011/11/building-packages-from-sources-in-debianubuntu/\">http://blog.aplikacja.info/2011/11/building-packages-from-sources-in-debianubuntu/</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but: * It is an older version (lacking features I need) * I need slightly different compile options than the default. What is the easiest way of doing it? I am concerned about a couple of things * How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.) * How I can I prevent the update system installing the older version in the repo on an update? * How I can prevent the system installing a newer version (when its out), overwriting my custom package?
you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet. You can use "uupdate" (`apt-get install devscripts`) to build a package from source with existing debian sources: Example for libdrm2: ``` apt-get build-dep libdrm2 apt-get source libdrm2 cd libdrm-2.3.1 uupdate ~/Downloads/libdrm-2.4.1.tar.gz cd ../libdrm-2.4.1 dpkg-buildpackage -us -uc -nc ```
130,898
<p>How can I perform list comprehensions in C#?</p>
[ { "answer_id": 130915, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": -1, "selected": false, "text": "<p>While this isn't a tutorial, here's some code that illustrates the concept:</p>\n\n<pre><code>public List&lt;string&gt; ValidUsers(List&lt;User&gt; users) {\n List&lt;string&gt; names = new List&lt;string&gt;();\n foreach(User user in users) {\n if(user.Valid) {\n names.Add(user.Name);\n }\n }\n return names;\n}\n</code></pre>\n" }, { "answer_id": 130919, "author": "brock.holum", "author_id": 15860, "author_profile": "https://Stackoverflow.com/users/15860", "pm_score": 2, "selected": false, "text": "<p>You can use LINQ to make expressions that are similar to list comprehensions. Here's a site explaining it a little:</p>\n\n<p><a href=\"http://artyprog.blogspot.com/2008/07/list-comprehension-in-c-with-linq.html\" rel=\"noreferrer\">List Comprehension in C# with LINQ</a></p>\n\n<p><a href=\"http://artyprog.blogspot.com/2008/07/list-comprehension-in-c-with-linq-part.html\" rel=\"noreferrer\">List Comprehension in C# with LINQ - Part 2</a></p>\n" }, { "answer_id": 130945, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": "<p>@Ian P</p>\n\n<pre><code> return (from user in users\n where user.Valid\n select user.Name).ToArray();\n</code></pre>\n" }, { "answer_id": 684218, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 6, "selected": false, "text": "<p>Found this when I was looking up how to do list comprehensions in C#...</p>\n\n<p>When someone says list comprehensions I immediately think about Python. The below code generates a list that looks like this:</p>\n\n<pre><code>[0,2,4,6,8,10,12,14,16,18]\n</code></pre>\n\n<p>The Python way is like this:</p>\n\n<pre><code>list = [2*number for number in range(0,10)]\n</code></pre>\n\n<p>In C#:</p>\n\n<pre><code>var list2 = from number in Enumerable.Range(0, 10) select 2*number;\n</code></pre>\n\n<p>Both methods are lazily evaluated.</p>\n" }, { "answer_id": 954090, "author": "λ Jonas Gorauskas", "author_id": 11507, "author_profile": "https://Stackoverflow.com/users/11507", "pm_score": 6, "selected": false, "text": "<p>A List Comprehension is a type of set notation in which the programmer can describe the properties that the members of a set must meet. It is usually used to create a set based on other, already existing, set or sets by applying some type of combination, transform or reduction function to the existing set(s).</p>\n\n<p>Consider the following problem: You have a sequence of 10 numbers from 0 to 9 and you need to extract all the even numbers from that sequence. In a language such a C# version 1.1, you were pretty much confined to the following code to solve this problem:</p>\n\n<pre><code>ArrayList evens = new ArrayList();\nArrayList numbers = Range(10);\nint size = numbers.Count;\nint i = 0;\n\nwhile (i &lt; size) \n{\n if (i % 2 == 0) \n {\n evens.Add(i);\n }\n i++;\n}\n</code></pre>\n\n<p>The code above does not show the implementation of the Range function, which is available in the full code listing below. With the advent of C# 3.0 and the .NET Framework 3.5, a List Comprehension notation based on Linq is now available to C# programmers. The above C# 1.1 code can be ported to C# 3.0 like so:</p>\n\n<pre><code>IEnumerable&lt;int&gt; numbers = Enumerable.Range(0, 10);\nvar evens = from num in numbers where num % 2 == 0 select num;\n</code></pre>\n\n<p>And technically speaking, the C# 3.0 code above could be written as a one-liner by moving the call to <em>Enumarable.Range</em> to the Linq expression that generates the <em>evens</em> sequence. In the C# List Comprehension I am reducing the set <em>numbers</em> by applying a function (the modulo 2) to that sequence. This produces the <em>evens</em> sequence in a much more concise manner and avoid the use of loop syntax. Now, you may ask yourself: Is this purely syntax sugar? I don't know, but I will definitelly investigate, and maybe even ask the question myself here. I suspect that this is not just syntax sugar and that there are some true optimizations that can be done by utilizing the underlying monads.</p>\n\n<p>The full code listing is available <a href=\"http://thestandardoutput.com/2009/06/list-comprehensions-in-c/\" rel=\"noreferrer\">here</a>.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21944/" ]
How can I perform list comprehensions in C#?
Found this when I was looking up how to do list comprehensions in C#... When someone says list comprehensions I immediately think about Python. The below code generates a list that looks like this: ``` [0,2,4,6,8,10,12,14,16,18] ``` The Python way is like this: ``` list = [2*number for number in range(0,10)] ``` In C#: ``` var list2 = from number in Enumerable.Range(0, 10) select 2*number; ``` Both methods are lazily evaluated.
130,913
<p>Is it at the state where it is actually useful and can do more than rename classes?</p>
[ { "answer_id": 130926, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 6, "selected": true, "text": "<p>CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings</p>\n\n<pre><code>* Declare Method\n* Extract Baseclass\n* Extract Constant\n* Extract Method\n* Extract Subclass\n* Hide Method\n* Implement Method\n* Move Field / Method\n* Replace Number\n* Separate Class\n* Generate Getters and Setters\n</code></pre>\n\n<p>There is a CDT refactoring <a href=\"http://r2.ifs.hsr.ch/cdtrefactoring\" rel=\"noreferrer\">wiki</a></p>\n" }, { "answer_id": 149101, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yeah and most of them don't work actually if the code is too complicated. Things like move a method, rename, etc have problems sometimes.</p>\n" }, { "answer_id": 837063, "author": "Mike Kucera", "author_id": 102367, "author_profile": "https://Stackoverflow.com/users/102367", "pm_score": 0, "selected": false, "text": "<p>C++ is a very hard language to provide refactoring support for. This is because the langauge is very complex and hard to parse but its mostly because of the preprocessor.</p>\n\n<p>The preprocessor is the main reason why C/C++ IDEs lag behind other languages.</p>\n" }, { "answer_id": 886817, "author": "none", "author_id": 78244, "author_profile": "https://Stackoverflow.com/users/78244", "pm_score": 2, "selected": false, "text": "<p>There have been numerous efforts to provide refactoring tools for C++, most of them failed pretty early, because the creation of such tools requires the full ability to process C++ source code, i.e. you need a working and full c++ compiler in the first place to implement even the most basic forms of automated source to source transformations.</p>\n\n<p>Fortunately, with the introduction of <a href=\"http://gcc.gnu.org/wiki/plugins\" rel=\"nofollow noreferrer\">plugins into gcc</a>, it it's finally becoming foreseeable that related efforts may actually be able to leverage an existing C++ compiler for this purpose, instead of having to resort to their own implementations of a C++ compiler.</p>\n\n<p>For a more in depth discussion, you may want to check out <a href=\"http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?action=browse&amp;id=BoostSpiritCXXParser&amp;revision=48\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>For the time being, the most promising candidate to provide widely automated C++ refactoring support, is certainly the Mozilla <a href=\"https://wiki.mozilla.org/pork\" rel=\"nofollow noreferrer\">pork</a> project, along with its related companion project <a href=\"https://developer.mozilla.org/En/Dehydra\" rel=\"nofollow noreferrer\">Dehydra</a>.</p>\n" }, { "answer_id": 4408040, "author": "none", "author_id": 537742, "author_profile": "https://Stackoverflow.com/users/537742", "pm_score": 1, "selected": false, "text": "<p>Some C++ refactorings which are supported by for example by Ref++ do not need to fully understand C++ syntax. For example pull up method, push down method etc are quite straightforward. For some reason this kind of refactorings are not implemented to CDT refactorings.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13760/" ]
Is it at the state where it is actually useful and can do more than rename classes?
CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings ``` * Declare Method * Extract Baseclass * Extract Constant * Extract Method * Extract Subclass * Hide Method * Implement Method * Move Field / Method * Replace Number * Separate Class * Generate Getters and Setters ``` There is a CDT refactoring [wiki](http://r2.ifs.hsr.ch/cdtrefactoring)
130,916
<p>I need to keep as much as I can of large file in the operating system block cache even though it's bigger than I can fit in ram, and I'm continously reading another very very large file. ATM I'll remove large chunk of large important file from system cache when I stream read form another file.</p>
[ { "answer_id": 130955, "author": "William Hutchen", "author_id": 21944, "author_profile": "https://Stackoverflow.com/users/21944", "pm_score": 1, "selected": false, "text": "<p>Some operating systems have ramdisks that you can use to set aside a segment of ram for storage and then mounting it as a file system.</p>\n\n<p>What I don't understand, though, is why you want to keep the operating system from caching the file. Your full question doesn't really make sense to me.</p>\n" }, { "answer_id": 130983, "author": "Sufian", "author_id": 9241, "author_profile": "https://Stackoverflow.com/users/9241", "pm_score": 2, "selected": false, "text": "<p>Within linux, you can mount a filesystem as the type <em>tmpfs</em>, which uses available swap memory as backing if needed. You should be able to create a filesystem greater than your memory size and it will prioritize the contents of that filesystem in the system cache.</p>\n\n<pre><code>mount -t tmpfs none /mnt/point\n</code></pre>\n\n<p>See: <a href=\"http://lxr.linux.no/linux/Documentation/filesystems/tmpfs.txt\" rel=\"nofollow noreferrer\">http://lxr.linux.no/linux/Documentation/filesystems/tmpfs.txt</a></p>\n\n<p>You may also benefit from the files <code>swapiness</code> and <code>drop_cache</code> within <code>/proc/sys/vm</code></p>\n" }, { "answer_id": 132582, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 0, "selected": false, "text": "<p>Buy more ram (it's relatively cheap!) or let the OS do its thing. I think you'll find that circumventing the OS is going to be more trouble than it's worth. The OS will cache as much of the file as needed, until yours or any other applications needs memory. </p>\n\n<p>I guess you could minimize the number of processes, but it's probably quicker to buy more memory.</p>\n" }, { "answer_id": 154029, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 0, "selected": false, "text": "<p>mlock() and mlockall() respectively lock part or all of the calling process’s virtual address space into RAM, preventing that memory from being paged to the swap area.</p>\n\n<p>(copied from the MLOCK(2) Linux man page)</p>\n" }, { "answer_id": 154047, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 2, "selected": false, "text": "<p>If you're using Windows, consider opening the file you're scanning through with the flag</p>\n\n<pre><code>FILE_FLAG_SEQUENTIAL_SCAN\n</code></pre>\n\n<p>You could also use</p>\n\n<pre><code>FILE_FLAG_NO_BUFFERING\n</code></pre>\n\n<p>for that file, but it imposes some restrictions on your read size and buffer alignment.</p>\n" }, { "answer_id": 154076, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 3, "selected": true, "text": "<p>In a POSIX system like Linux or Solaris, try using posix_fadvise.</p>\n\n<p>On the streaming file, do something like this:</p>\n\n<pre><code>posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);\nwhile( bytes &gt; 0 ) {\n bytes = pread(fd, buffer, 64 * 1024, current_pos);\n current_pos += 64 * 1024;\n posix_fadvise(fd, 0, current_pos, POSIX_FADV_DONTNEED);\n}\n</code></pre>\n\n<p>And you can apply POSIX_FADV_WILLNEED to your other file, which should raise its memory priority.</p>\n\n<p>Now, I know that Windows Vista and Server 2008 can also do nifty tricks with memory priorities. Probably older versions like XP can do more basic tricks as well. But I don't know the functions off the top of my head and don't have time to look them up.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15307/" ]
I need to keep as much as I can of large file in the operating system block cache even though it's bigger than I can fit in ram, and I'm continously reading another very very large file. ATM I'll remove large chunk of large important file from system cache when I stream read form another file.
In a POSIX system like Linux or Solaris, try using posix\_fadvise. On the streaming file, do something like this: ``` posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); while( bytes > 0 ) { bytes = pread(fd, buffer, 64 * 1024, current_pos); current_pos += 64 * 1024; posix_fadvise(fd, 0, current_pos, POSIX_FADV_DONTNEED); } ``` And you can apply POSIX\_FADV\_WILLNEED to your other file, which should raise its memory priority. Now, I know that Windows Vista and Server 2008 can also do nifty tricks with memory priorities. Probably older versions like XP can do more basic tricks as well. But I don't know the functions off the top of my head and don't have time to look them up.
130,941
<p>In a VB.Net Windows Service I'm currently pooling units of work with: </p> <pre><code>ThreadPool.QueueUserWorkItem(operation, nextQueueID) </code></pre> <p>In each unit of work (or thread I'll use for ease of understanding), it will make a couple MSSQL operations like so: </p> <pre><code> Using sqlcmd As New SqlCommand("", New SqlConnection(ConnString)) With sqlcmd .CommandType = CommandType.Text .CommandText = "UPDATE [some table]" .Parameters.Add("@ID", SqlDbType.Int).Value = msgID .Connection.Open() .ExecuteNonQuery() .Connection.Close() 'Found connections not closed quick enough' End With End Using </code></pre> <p>When running a <code>netstat -a -o</code> on the server I'm seeing about 50 connections to SQL server sitting on <code>IDLE</code> or <code>ESTABLISHED</code>, this seems excessive to me especially since we have much larger Web Applications that get by with 5-10 connections. </p> <p>The connection string is global to the application (doesn't change), and has <code>Pooling=true</code> defined as well. </p> <p>Now will each of these threads have their own <code>ConnectionPool</code>, or is there one <code>ConnectionPool</code> for the entire .EXE process?</p>
[ { "answer_id": 130963, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": true, "text": "<p>From the MS Docs -</p>\n\n<p>\"Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity\"</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx</a></p>\n\n<p>Are you experiencing errors such as -</p>\n\n<p><em>Exception Details: System.InvalidOperationException: Timeout expired. The timeout\nperiod elapsed prior to obtaining a connection from the pool. This may have occurred\nbecause all pooled connections were in use and max pool size was reached.</em></p>\n\n<p>Also how many work items are being queued in the service?</p>\n" }, { "answer_id": 131207, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>If the number of open connections offends you, take control in the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx\" rel=\"nofollow noreferrer\">connection string</a></p>\n\n<p>Notice: MinPoolSize and MaxPoolSize.</p>\n" }, { "answer_id": 131787, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>One big problem with your code is that you aren't closing your connection if ExecuteNonQuery throws an exception. Disposing the SqlCommand is not enough, you need to also dispose the SqlConnection when an exception is thrown, something like:</p>\n\n<pre><code>Using SqlConnection connection = New SqlConnection(ConnString)\n Using sqlcmd As New SqlCommand(\"\", connection) \n With sqlcmd \n ... etc\n End With \n End Using\nEnd Using\n</code></pre>\n" }, { "answer_id": 429861, "author": "Marcus Erickson", "author_id": 38373, "author_profile": "https://Stackoverflow.com/users/38373", "pm_score": 1, "selected": false, "text": "<p>Although I generally like the using statement, I find that sometimes in the .NET libraries the actual CLOSE of a handle isnt done until garbage collection. So being old school and religious about such things, I add an explicit close at the end of my using statement. This is pseduo code since I generally code in C# rather then VB.NET but it should give you the idea.</p>\n\n<pre><code>Using SqlConnection connection = New SqlConnection(ConnString)\n\n TRY\n Using sqlcmd As New SqlCommand(\"\", connection)\n With sqlcmd\n ... etc\n End With\n End Using\n FINALLY\n connection.Close()\n\nEnd Using\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/952/" ]
In a VB.Net Windows Service I'm currently pooling units of work with: ``` ThreadPool.QueueUserWorkItem(operation, nextQueueID) ``` In each unit of work (or thread I'll use for ease of understanding), it will make a couple MSSQL operations like so: ``` Using sqlcmd As New SqlCommand("", New SqlConnection(ConnString)) With sqlcmd .CommandType = CommandType.Text .CommandText = "UPDATE [some table]" .Parameters.Add("@ID", SqlDbType.Int).Value = msgID .Connection.Open() .ExecuteNonQuery() .Connection.Close() 'Found connections not closed quick enough' End With End Using ``` When running a `netstat -a -o` on the server I'm seeing about 50 connections to SQL server sitting on `IDLE` or `ESTABLISHED`, this seems excessive to me especially since we have much larger Web Applications that get by with 5-10 connections. The connection string is global to the application (doesn't change), and has `Pooling=true` defined as well. Now will each of these threads have their own `ConnectionPool`, or is there one `ConnectionPool` for the entire .EXE process?
From the MS Docs - "Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity" <http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx> Are you experiencing errors such as - *Exception Details: System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.* Also how many work items are being queued in the service?
130,948
<p>I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:</p> <pre><code>file = File.open("path-to-file.tar.gz") contents = "" file.each {|line| contents &lt;&lt; line } </code></pre> <p>I thought that would be enough to convert it to a string, but then when I try to write it back out like this...</p> <pre><code>newFile = File.open("test.tar.gz", "w") newFile.write(contents) </code></pre> <p>It isn't the same file. Doing <code>ls -l</code> shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?</p>
[ { "answer_id": 130984, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.</p>\n\n<p>You do something like:</p>\n\n<pre><code>require 'base64'\n\nfile_contents = Base64.encode64(tar_file_data)\n</code></pre>\n\n<p>Have look at the Base64 <a href=\"http://www.ruby-doc.org/stdlib/libdoc/base64/rdoc/index.html\" rel=\"noreferrer\">Rubydocs</a> to get a better idea.</p>\n" }, { "answer_id": 130987, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 4, "selected": false, "text": "<p>on os x these are the same for me... could this maybe be extra \"\\r\" in windows?</p>\n\n<p>in any case you may be better of with:</p>\n\n<pre><code>contents = File.read(\"e.tgz\")\nnewFile = File.open(\"ee.tgz\", \"w\")\nnewFile.write(contents)\n</code></pre>\n" }, { "answer_id": 131001, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 10, "selected": true, "text": "<p>First, you should open the file as a binary file. Then you can read the entire file in, in one command.</p>\n\n<pre><code>file = File.open(\"path-to-file.tar.gz\", \"rb\")\ncontents = file.read\n</code></pre>\n\n<p>That will get you the entire file in a string.</p>\n\n<p>After that, you probably want to <code>file.close</code>. If you don’t do that, <code>file</code> won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.</p>\n" }, { "answer_id": 131096, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 7, "selected": false, "text": "<p>To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.</p>\n\n<pre><code>contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }\n</code></pre>\n" }, { "answer_id": 271300, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>If you need binary mode, you'll need to do it the hard way:</p>\n\n<pre><code>s = File.open(filename, 'rb') { |f| f.read }\n</code></pre>\n\n<p>If not, shorter and sweeter is:</p>\n\n<pre><code>s = IO.read(filename)\n</code></pre>\n" }, { "answer_id": 4565144, "author": "Alex", "author_id": 197359, "author_profile": "https://Stackoverflow.com/users/197359", "pm_score": 4, "selected": false, "text": "<p>how about some open/close safety.</p>\n\n<pre><code>string = File.open('file.txt', 'rb') { |file| file.read }\n</code></pre>\n" }, { "answer_id": 27103819, "author": "Boris", "author_id": 4092408, "author_profile": "https://Stackoverflow.com/users/4092408", "pm_score": -1, "selected": false, "text": "<p>If you can encode the tar file by Base64 (and storing it in a plain text file) you can use </p>\n\n<pre><code>File.open(\"my_tar.txt\").each {|line| puts line}\n</code></pre>\n\n<p><strong>or</strong> </p>\n\n<pre><code>File.new(\"name_file.txt\", \"r\").each {|line| puts line}\n</code></pre>\n\n<p>to print each (text) line in the cmd.</p>\n" }, { "answer_id": 30799222, "author": "bardzo", "author_id": 4354686, "author_profile": "https://Stackoverflow.com/users/4354686", "pm_score": 4, "selected": false, "text": "<p>Ruby have binary reading</p>\n\n<pre><code>data = IO.binread(path/filaname)\n</code></pre>\n\n<p>or if less than Ruby 1.9.2</p>\n\n<pre><code>data = IO.read(path/file)\n</code></pre>\n" }, { "answer_id": 67305904, "author": "David Moles", "author_id": 27358, "author_profile": "https://Stackoverflow.com/users/27358", "pm_score": 1, "selected": false, "text": "<p>Ruby 1.9+ has <a href=\"https://ruby-doc.org/core-1.9.2/IO.html#method-c-binread\" rel=\"nofollow noreferrer\"><code>IO.binread</code></a> (see <a href=\"https://stackoverflow.com/a/30799222/27358\">@bardzo's answer</a>) and also supports passing the encoding as an option to <code>IO.read</code>:</p>\n<ul>\n<li><p><a href=\"https://ruby-doc.org/core-1.9.2/IO.html#method-c-read\" rel=\"nofollow noreferrer\">Ruby 1.9</a></p>\n<pre class=\"lang-rb prettyprint-override\"><code>data = File.read(name, {:encoding =&gt; 'BINARY'})\n</code></pre>\n</li>\n<li><p><a href=\"https://ruby-doc.org/core-2.0.0/IO.html#method-c-read\" rel=\"nofollow noreferrer\">Ruby 2+</a></p>\n<pre class=\"lang-rb prettyprint-override\"><code>data = File.read(name, encoding: 'BINARY')\n</code></pre>\n</li>\n</ul>\n<p>(Note in both cases that <code>'BINARY'</code> is an <a href=\"https://ruby-doc.org/core-1.9.2/Encoding.html#method-c-aliases\" rel=\"nofollow noreferrer\">alias</a> for <code>'ASCII-8BIT'</code>.)</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/130948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this: ``` file = File.open("path-to-file.tar.gz") contents = "" file.each {|line| contents << line } ``` I thought that would be enough to convert it to a string, but then when I try to write it back out like this... ``` newFile = File.open("test.tar.gz", "w") newFile.write(contents) ``` It isn't the same file. Doing `ls -l` shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?
First, you should open the file as a binary file. Then you can read the entire file in, in one command. ``` file = File.open("path-to-file.tar.gz", "rb") contents = file.read ``` That will get you the entire file in a string. After that, you probably want to `file.close`. If you don’t do that, `file` won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.
131,014
<p>I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering <code>COL1</code> and <code>COL2</code> only. </p> <p>So let's say I have something like this:</p> <pre><code> COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j aa 112 blah_m ab 111 blah_s bb 112 blah_d bb 112 blah_d cc 112 blah_w cc 113 blah_p </code></pre> <p>I need a SQL query that returns this:</p> <pre><code> COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j bb 112 blah_d bb 112 blah_d </code></pre>
[ { "answer_id": 131018, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "<p>Join on yourself like this:</p>\n\n<pre><code>SELECT a.col3, b.col3, a.col1, a.col2 \nFROM tablename a, tablename b\nWHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3\n</code></pre>\n\n<p>If you're using postgresql, you can use the oid to make it return less duplicated results, like this:</p>\n\n<pre><code>SELECT a.col3, b.col3, a.col1, a.col2 \nFROM tablename a, tablename b\nWHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3\n AND a.oid &lt; b.oid\n</code></pre>\n" }, { "answer_id": 131022, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<p>Don't have a database handy to test this, but I think it should work...</p>\n\n<pre><code>select\n *\nfrom\n theTable\nwhere\n col1 in\n (\n select\n col1\n from\n theTable\n group by\n col1||col2\n having\n count(col1||col2) &gt; 1\n )\n</code></pre>\n" }, { "answer_id": 131026, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>My naive attempt would be</p>\n\n<pre><code>select a.*, b.* from table a, table b where a.col1 = b.col1 and a.col2 = b.col2 and a.col3 != b.col3;\n</code></pre>\n\n<p>but that would return all the rows twice. I'm not sure how you'd restrict it to just returning them once. Maybe if there was a primary key, you could add \"and a.pkey &lt; b.pkey\".</p>\n\n<p>Like I said, that's not elegant and there is probably a better way to to do this.</p>\n" }, { "answer_id": 131031, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 3, "selected": false, "text": "<p>With the data you have listed, your query is not possible. The data on rows 5 &amp; 6 is not distinct within itself.</p>\n\n<p>Assuming that your table is named 'quux', if you start with something like this:</p>\n\n<pre><code>SELECT a.COL1, a.COL2, a.COL3 \nFROM quux a, quux b\nWHERE a.COL1 = b.COL1 AND a.COL2 = b.COL2 AND a.COL3 &lt;&gt; b.COL3\nORDER BY a.COL1, a.COL2\n</code></pre>\n\n<p>You'll end up with this answer:</p>\n\n<pre><code> COL1 COL2 COL3\n ---------------------\n aa 111 blah_x\n aa 111 blah_j\n</code></pre>\n\n<p>That's because rows 5 &amp; 6 have the same values for COL3. Any query that returns both rows 5 &amp; 6 will also return duplicates of ALL of the rows in this dataset.</p>\n\n<p>On the other hand, if you have a primary key (ID), then you can use this query instead:</p>\n\n<pre><code>SELECT a.COL1, a.COL2, a.COL3\nFROM quux a, quux b\nWHERE a.COL1 = b.COL1 AND a.COL2 = b.COL2 AND a.ID &lt;&gt; b.ID\nORDER BY a.COL1, a.COL2\n</code></pre>\n\n<p><em>[Edited to simplify the WHERE clause]</em></p>\n\n<p>And you'll get the results you want:</p>\n\n<pre><code>COL1 COL2 COL3\n---------------------\naa 111 blah_x\naa 111 blah_j\nbb 112 blah_d\nbb 112 blah_d\n</code></pre>\n\n<p>I just tested this on SQL Server 2000, but you should see the same results on any modern SQL database.</p>\n\n<p><strong><a href=\"https://stackoverflow.com/users/369/blorgbeard\">blorgbeard</a> proved me <a href=\"https://stackoverflow.com/questions/131014/whats-the-sql-query-to-list-all-rows-that-have-2-column-sub-rows-as-duplicates#131036\">wrong</a> -- good for him!</strong></p>\n" }, { "answer_id": 131036, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": true, "text": "<p>Does this work for you?</p>\n\n<pre><code>select t.* from table t\nleft join ( select col1, col2, count(*) as count from table group by col1, col2 ) c on t.col1=c.col1 and t.col2=c.col2\nwhere c.count &gt; 1\n</code></pre>\n" }, { "answer_id": 131043, "author": "Jonathan Schuster", "author_id": 21957, "author_profile": "https://Stackoverflow.com/users/21957", "pm_score": 2, "selected": false, "text": "<p>Something like this should work:</p>\n\n<pre><code>SELECT a.COL1, a.COL2, a.COL3\nFROM YourTable a\nJOIN YourTable b ON b.COL1 = a.COL1 AND b.COL2 = a.COL2 AND b.COL3 &lt;&gt; a.COL3\n</code></pre>\n\n<p>In general, the JOIN clause should include every column that you're considering to be part of a \"duplicate\" (COL1 and COL2 in this case), and at least one column (or as many as it takes) to eliminate a row joining to itself (COL3, in this case).</p>\n" }, { "answer_id": 131057, "author": "IK.", "author_id": 21283, "author_profile": "https://Stackoverflow.com/users/21283", "pm_score": 2, "selected": false, "text": "<p>This is pretty similar to the self-join, except it will not have the duplicates.</p>\n\n<pre><code>select COL1,COL2,COL3\nfrom theTable a\nwhere exists (select 'x'\n from theTable b\n where a.col1=b.col1\n and a.col2=b.col2\n and a.col3&lt;&gt;b.col3)\norder by col1,col2,col3\n</code></pre>\n" }, { "answer_id": 131204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>select COL1,COL2,COL3</p>\n\n<p>from table </p>\n\n<p>group by COL1,COL2,COL3</p>\n\n<p>having count(*)>1 </p>\n" }, { "answer_id": 131332, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "<p>Forget joins -- use an analytic function:</p>\n\n<pre><code>select col1, col2, col3\nfrom\n(\nselect col1, col2, col3, count(*) over (partition by col1, col2) rows_per_col1_col2\nfrom table\n)\nwhere rows_per_col1_col2 &gt; 1\n</code></pre>\n" }, { "answer_id": 156268, "author": "Kyle Dyer", "author_id": 24011, "author_profile": "https://Stackoverflow.com/users/24011", "pm_score": 1, "selected": false, "text": "<p>Here is how you find duplicates. Tested in oracle 10g with your data.</p>\n\n<p>select * from tst\nwhere (col1, col2) in \n(select col1, col2 from tst group by col1, col2 having count(*) > 1)</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering `COL1` and `COL2` only. So let's say I have something like this: ``` COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j aa 112 blah_m ab 111 blah_s bb 112 blah_d bb 112 blah_d cc 112 blah_w cc 113 blah_p ``` I need a SQL query that returns this: ``` COL1 COL2 COL3 --------------------- aa 111 blah_x aa 111 blah_j bb 112 blah_d bb 112 blah_d ```
Does this work for you? ``` select t.* from table t left join ( select col1, col2, count(*) as count from table group by col1, col2 ) c on t.col1=c.col1 and t.col2=c.col2 where c.count > 1 ```
131,021
<p>I have a backroundrb scheduled task that takes quite a long time to run. However it seems that the process is ending after only 2.5 minutes.</p> <p>My background.yml file:</p> <pre><code>:schedules: :named_worker: :task_name: :trigger_args: 0 0 12 * * * * :data: input_data </code></pre> <p>I have zero activity on the server when the process is running. (Meaning I am the only one on the server watching the log files do their thing until the process suddenly stops.)</p> <p>Any ideas?</p>
[ { "answer_id": 131779, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 3, "selected": true, "text": "<p>There's not much information here that allows us to get to the bottom of the problem.\nBecause backgroundrb operates in the background, it can be quite hard to monitor/debug.</p>\n\n<p>Here are some ideas I use:</p>\n\n<ol>\n<li>Write a unit test to test the worker code itself and make sure there are no problems there</li>\n<li>Put \"puts\" statements at multiple points in the code so you can at least see some responses while the worker is running.</li>\n<li>Wrap the entire worker in a begin..rescue..end block so that you can catch any errors that might be occurring and cutting the process short.</li>\n</ol>\n" }, { "answer_id": 136530, "author": "salt.racer", "author_id": 757, "author_profile": "https://Stackoverflow.com/users/757", "pm_score": 0, "selected": false, "text": "<p>Thanks Andrew. Those debugging tips helped. Especially the begin..rescue..end block. </p>\n\n<p>It was still a pain to debug though. In the end it wasn't BackgroundRB cutting short after 2.5 minutes. There was a network connection being made that wasn't being closed properly. Once that was found and closed, everything works great.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
I have a backroundrb scheduled task that takes quite a long time to run. However it seems that the process is ending after only 2.5 minutes. My background.yml file: ``` :schedules: :named_worker: :task_name: :trigger_args: 0 0 12 * * * * :data: input_data ``` I have zero activity on the server when the process is running. (Meaning I am the only one on the server watching the log files do their thing until the process suddenly stops.) Any ideas?
There's not much information here that allows us to get to the bottom of the problem. Because backgroundrb operates in the background, it can be quite hard to monitor/debug. Here are some ideas I use: 1. Write a unit test to test the worker code itself and make sure there are no problems there 2. Put "puts" statements at multiple points in the code so you can at least see some responses while the worker is running. 3. Wrap the entire worker in a begin..rescue..end block so that you can catch any errors that might be occurring and cutting the process short.
131,040
<p>I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label:</p> <pre> <code> &lt;mx:Canvas> &lt;mx:Script> [Bindable] public var color:uint; &lt;/mx:Script> &lt;mx:Label text="foobar" color="{color}" /> &lt;/mx:Canvas> </code> </pre> <p>and then add the component in another mxml file, something along the lines of:</p> <pre> <code> &lt;foo:foo_label color="red" /> </code> </pre> <p>When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do</p> <pre><code>&lt;mx:Label text="foobar" color="red"></code></pre> <p>without any problems, and the color property is still type uint. </p> <p>My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special?</p> <p>Thanks.</p>
[ { "answer_id": 132076, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 4, "selected": true, "text": "<p>Color is not a property, it is a style. You need to define the style like this:</p>\n\n<pre><code>[Style(name=\"labelColor\", type=\"uint\", format=\"Color\" )]\n</code></pre>\n\n<p>(enclose it in tag if you define it directly in MXML). You then need to add some ActionScript to handle this style and apply it to whichever control you need, please refer to <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html\" rel=\"noreferrer\">http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html</a> for more information.</p>\n" }, { "answer_id": 7631250, "author": "theaibo", "author_id": 825825, "author_profile": "https://Stackoverflow.com/users/825825", "pm_score": 2, "selected": false, "text": "<p>Here you are 2 of my utils functions:</p>\n\n<pre><code> public static function convertUintToString( color:uint ):String { \n return color.toString(16); \n } \n\n public static function convertStringToUint(value:String, mask:String):uint { \n var colorString:String = \"0x\" + value; \n var colorUint:uint = mx.core.Singleton.getInstance(\"mx.styles::IStyleManager2\").getColorName( colorString ); \n\n return colorUint; \n } \n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo\_label: ``` <mx:Canvas> <mx:Script> [Bindable] public var color:uint; </mx:Script> <mx:Label text="foobar" color="{color}" /> </mx:Canvas> ``` and then add the component in another mxml file, something along the lines of: ``` <foo:foo_label color="red" /> ``` When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do ``` <mx:Label text="foobar" color="red"> ``` without any problems, and the color property is still type uint. My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special? Thanks.
Color is not a property, it is a style. You need to define the style like this: ``` [Style(name="labelColor", type="uint", format="Color" )] ``` (enclose it in tag if you define it directly in MXML). You then need to add some ActionScript to handle this style and apply it to whichever control you need, please refer to <http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html> for more information.
131,049
<p>I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips &amp; tricks from somebody's blog. How do I make the copied content appear in a box with border?</p> <p>For example, the box at the end of this blog post looks pretty nice:<br> <a href="http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/" rel="noreferrer">http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/</a></p> <p>I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?</p>
[ { "answer_id": 131330, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 2, "selected": false, "text": "<p>Mediawiki supports the div tag. Combine the div tag with some styles:</p>\n\n<pre><code>&lt;div style=\"background-color: cyan; border-style: dashed;\"&gt;\nA bunch of text that will wrap.\n&lt;/div&gt;\n</code></pre>\n\n<p>You can play around with whatever css attributes you want, but that should get you started.</p>\n" }, { "answer_id": 131757, "author": "Oddmund", "author_id": 4417, "author_profile": "https://Stackoverflow.com/users/4417", "pm_score": 5, "selected": false, "text": "<pre><code>&lt;blockquote style=\"background-color: lightgrey; border: solid thin grey;\"&gt;\nDet er jeg som kjenner hemmeligheten din. Ikke et pip, gutten min.\n&lt;/blockquote&gt;\n</code></pre>\n\n<p>The blockquotes are better than divs because they \"explain\" that the text is actually a blockqoute, and not \"just-some-text\". Also a blockquote will most likely be properly indented, and actually look like a blockqoute.</p>\n" }, { "answer_id": 131886, "author": "SamS", "author_id": 14068, "author_profile": "https://Stackoverflow.com/users/14068", "pm_score": 5, "selected": false, "text": "<p>I made a template in my wiki called Template:quote, which contains the following content:</p>\n\n<pre><code>&lt;div style=\"background-color: #ddf5eb; border-style: dotted;\"&gt;\n{{{1}}}\n&lt;/div&gt;\n</code></pre>\n\n<p>Then I can use the template in a page, e.g., </p>\n\n<blockquote>\n <p>{{quote|a little test}}</p>\n</blockquote>\n\n<p>Works pretty well - Thanks!</p>\n" }, { "answer_id": 12389988, "author": "scubasteve", "author_id": 478810, "author_profile": "https://Stackoverflow.com/users/478810", "pm_score": 4, "selected": false, "text": "<p>To combine the two mostly valid answers, you should use a <a href=\"http://www.mediawiki.org/wiki/Help%3aTemplates\">MediaWiki template</a> that itself utilizes a <a href=\"http://www.htmlquick.com/reference/tags/blockquote.html\">blockquote</a>.</p>\n\n<p>The content of the template:</p>\n\n<pre><code>&lt;blockquote style=\"color: lightgrey; border: solid thin gray;\"&gt;\n {{{1}}}\n&lt;/blockquote&gt;\n</code></pre>\n\n<p>Usage on your WIKI page (assuming you named the template \"quote\"):</p>\n\n<pre><code>{{ quote | The text you want to quote }}\n</code></pre>\n" }, { "answer_id": 21567312, "author": "Genteel", "author_id": 3273356, "author_profile": "https://Stackoverflow.com/users/3273356", "pm_score": 0, "selected": false, "text": "<p>Set a width in the pre tag, and it will wrap.</p>\n\n<pre><code>&lt;pre width=\"80%\"&gt;\n</code></pre>\n" }, { "answer_id": 30355475, "author": "Jeff Albrecht", "author_id": 884630, "author_profile": "https://Stackoverflow.com/users/884630", "pm_score": 2, "selected": false, "text": "<p>I used the code from @steve k Changing light-grey to black and adding padding between the border and text. I found the light-grey nearly invisible and the text was directly adjacent to the border.</p>\n\n<pre><code>&lt;blockquote style=\"\n color: black;\n border: solid thin gray;\n padding-top: 10px;\n padding-right: 10px;\n padding-bottom: 10px;\n padding-left: 10px;\n \"&gt;\n{{{1}}}\n&lt;/blockquote&gt;\n</code></pre>\n" }, { "answer_id": 43711388, "author": "Johnny Baloney", "author_id": 779449, "author_profile": "https://Stackoverflow.com/users/779449", "pm_score": 1, "selected": false, "text": "<p>You can use <code>index.php?title=MediaWiki:Common.css</code> page for this purpose and set a CSS style for the <code>&lt;blockquote/&gt;</code> element there:</p>\n\n<pre><code>blockquote {\n background-color: #ddf5eb; \n border-style: dotted;\n}\n</code></pre>\n\n<p>In a similar fashion you can style <code>&lt;pre/&gt;</code> which is useful for code snippets etc. so that it wraps content:</p>\n\n<pre><code>pre {\n white-space: pre-wrap;\n white-space: -moz-pre-wrap; \n white-space: -pre-wrap; \n white-space: -o-pre-wrap; \n word-wrap: break-word;\n}\n</code></pre>\n\n<p>For longer code snippets you may want to use <code>&lt;syntaxhighlight/&gt;</code> (or <code>&lt;source/&gt;</code>) element that comes with <a href=\"https://www.mediawiki.org/wiki/Extension:SyntaxHighlight\" rel=\"nofollow noreferrer\">SyntaxHighlight extension</a>. You can <a href=\"https://www.mediawiki.org/wiki/Extension:SyntaxHighlight#style\" rel=\"nofollow noreferrer\"><code>style</code></a> it too.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068/" ]
I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips & tricks from somebody's blog. How do I make the copied content appear in a box with border? For example, the box at the end of this blog post looks pretty nice: <http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/> I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?
``` <blockquote style="background-color: lightgrey; border: solid thin grey;"> Det er jeg som kjenner hemmeligheten din. Ikke et pip, gutten min. </blockquote> ``` The blockquotes are better than divs because they "explain" that the text is actually a blockqoute, and not "just-some-text". Also a blockquote will most likely be properly indented, and actually look like a blockqoute.
131,050
<p>Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.</p> <p>I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.</p> <p>The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?</p>
[ { "answer_id": 131294, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 0, "selected": false, "text": "<p>The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor if the constructor is being called a second time. For Example:</p>\n\n<pre><code>public class Foo {\n private static var instance : Foo;\n\n public Foo() {\n if( instance != null ) { \n throw new Exception (\"Singleton constructor called\");\n }\n instance = this;\n }\n\n public static getInstance() : Foo {\n if( instance == null ) {\n instance = new Foo();\n }\n return instance;\n }\n\n} \n</code></pre>\n" }, { "answer_id": 131340, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 0, "selected": false, "text": "<p>You can get a private class like so:</p>\n\n<pre><code>package some.pack\n{\n public class Foo\n {\n public Foo(f : CheckFoo)\n {\n if (f == null) throw new Exception(...);\n }\n }\n\n static private inst : Foo;\n static public getInstance() : Foo\n {\n if (inst == null)\n inst = new Foo(new CheckFoo());\n return inst;\n }\n}\n\nclass CheckFoo\n{\n}\n</code></pre>\n" }, { "answer_id": 132003, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": false, "text": "<p>I've been using this for some time, which I believe I originally got from wikipedia of all places.</p>\n\n<pre><code>package {\n public final class Singleton {\n private static var instance:Singleton = new Singleton();\n\n public function Singleton() {\n if( Singleton.instance ) {\n throw new Error( \"Singleton and can only be accessed through Singleton.getInstance()\" ); \n }\n }\n\n public static function getInstance():Singleton { \n return Singleton.instance;\n }\n }\n}\n</code></pre>\n\n<p><a href=\"http://life.neophi.com/danielr/2006/10/singleton_pattern_in_as3.html\" rel=\"noreferrer\">Here's an interesting summary</a> of the problem, which leads to a similar solution. </p>\n" }, { "answer_id": 132846, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 5, "selected": true, "text": "<p>A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book \"Advanced ActionScrpt3 with Design Patterns\" too).</p>\n\n<pre><code>package {\n public class Singleton {\n\n private static var _instance:Singleton;\n\n public function Singleton(enforcer:SingletonEnforcer) {\n if( !enforcer) \n {\n throw new Error( \"Singleton and can only be accessed through Singleton.getInstance()\" ); \n }\n }\n\n public static function get instance():Singleton\n {\n if(!Singleton._instance)\n {\n Singleton._instance = new Singleton(new SingletonEnforcer());\n }\n\n return Singleton._instance;\n }\n}\n\n}\nclass SingletonEnforcer{}\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it. I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace. The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?
A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too). ``` package { public class Singleton { private static var _instance:Singleton; public function Singleton(enforcer:SingletonEnforcer) { if( !enforcer) { throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" ); } } public static function get instance():Singleton { if(!Singleton._instance) { Singleton._instance = new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer{} ```
131,053
<p>I have been getting an error in <strong>VB .Net</strong> </p> <blockquote> <p>object reference not set to an instance of object.</p> </blockquote> <p>Can you tell me what are the causes of this error ?</p>
[ { "answer_id": 131055, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": "<p>The object has not been initialized before use.</p>\n\n<p>At the top of your code file type:</p>\n\n<pre><code>Option Strict On\nOption Explicit On\n</code></pre>\n" }, { "answer_id": 131098, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>In general, under the .NET runtime, such a thing happens whenever a variable that's unassigned or assigned the value <code>Nothing</code> (in VB.Net, <code>null</code> in C#) is dereferenced.</p>\n\n<p><code>Option Strict On</code> and <code>Option Explicit On</code> will help detect instances where this may occur, but it's possible to get a null/Nothing from another function call:</p>\n\n<pre><code>Dim someString As String = someFunctionReturningString();\nIf ( someString Is Nothing ) Then\n Sysm.Console.WriteLine(someString.Length); // will throw the NullReferenceException\nEnd If\n</code></pre>\n\n<p>and the <a href=\"http://msdn.microsoft.com/en-us/library/system.nullreferenceexception.aspx#Mtps_DropDownFilterText\" rel=\"nofollow noreferrer\">NullReferenceException</a> is the source of the \"object reference not set to an instance of an object\".</p>\n" }, { "answer_id": 131160, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 1, "selected": false, "text": "<p>You can put a logging mechanism in your application so you can isolate the cause of the error. An Exception object has the StackTrace property which is a string that describes the contents of the call stack, with the most recent method call appearing first. By looking at it, you'll have more details on what might be causing the exception.</p>\n" }, { "answer_id": 131175, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": true, "text": "<p>sef,\nIf the problem is with Database return results, I presume it is in this scenario:</p>\n\n<pre><code> dsData = getSQLData(conn,sql, blah,blah....)\n dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here\n</code></pre>\n\n<p>To fix that:</p>\n\n<pre><code> dsData = getSQLData(conn,sql, blah,blah....)\n If dsData.Tables.Count = 0 Then Exit Sub\n dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here\n</code></pre>\n\n<p><strong>edit</strong>: added code formatting tags ...</p>\n" }, { "answer_id": 131177, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 2, "selected": false, "text": "<p>And if you think it's occuring when no data is returned from a database query then maybe you should test the result before doing an operation on it? </p>\n\n<pre><code>Dim result As String = SqlCommand.ExecuteScalar() 'just for scope'\nIf result Is Nothing OrElse IsDBNull(result) Then\n 'no result!'\nEnd If\n</code></pre>\n" }, { "answer_id": 131190, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 1, "selected": false, "text": "<p>When working with databases, you can get this error when you try to get a value form a field or row which doesn't exist. i.e. if you're using datasets and you use:</p>\n\n<pre><code>Dim objDt as DataTable = objDs.Tables(\"tablename\")\n</code></pre>\n\n<p>you get the object \"reference not set to an instance of object\" if tablename doesn't exists in the Dataset. The same for rows or fields in the datasets.</p>\n" }, { "answer_id": 6680958, "author": "Andrew Neely", "author_id": 825386, "author_profile": "https://Stackoverflow.com/users/825386", "pm_score": 3, "selected": false, "text": "<p>Let's deconstruct the error message.</p>\n\n<p>\"object reference\" means a variable you used in your code which referenced an object. The object variable could have been declared by you the or it you might just be using a variable declared inside another object.</p>\n\n<p>\"instance of object\" Means that the object is blank (or in VB speak, \"<strong>Nothing</strong>\"). When you are dealing with object variables, you have to create an <strong>instance</strong> of that object before referencing it. </p>\n\n<p>\"not set to an \" means that you tried to access an object, but there was nothing inside of it for the computer to access.</p>\n\n<p>If you create a variable like </p>\n\n<pre><code>Dim aPerson as PersonClass\n</code></pre>\n\n<p>All you have done was tell the compiler that aPerson will represent a person, but not <strong><em>what</em></strong> person. </p>\n\n<p>You can create a blank copy of the object by using the \"New\" keyword. For example</p>\n\n<pre><code>Dim aPerson as New PersonClass\n</code></pre>\n\n<p>If you want to be able to test to see if the object is \"nothing\" by</p>\n\n<pre><code>If aPerson Is Nothing Then\n aPerson = New PersonClass\nEnd If\n</code></pre>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 49980059, "author": "Menuka Ishan", "author_id": 2940265, "author_profile": "https://Stackoverflow.com/users/2940265", "pm_score": 0, "selected": false, "text": "<p>Well, Error is explaining itself. Since You haven't provided any code sample, we can only say somewhere in your code, you are using a Null object for some task. I got same Error for below code sample.</p>\n\n<pre><code>Dim cmd As IDbCommand\ncmd.Parameters.Clear()\n</code></pre>\n\n<p>As You can see I am going to Clear a Null Object. For that, I'm getting Error </p>\n\n<blockquote>\n <p>\"object reference not set to an instance of an object\"</p>\n</blockquote>\n\n<p>Check your code for such code in your code. Since you haven't given code example we can't highlight the code :)</p>\n" }, { "answer_id": 61949298, "author": "Yassine CHABLI", "author_id": 7764014, "author_profile": "https://Stackoverflow.com/users/7764014", "pm_score": 0, "selected": false, "text": "<p>In case you have a class property , and multiple constructors, you must initialize the property in all constructors.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
I have been getting an error in **VB .Net** > > object reference not set to an instance of object. > > > Can you tell me what are the causes of this error ?
sef, If the problem is with Database return results, I presume it is in this scenario: ``` dsData = getSQLData(conn,sql, blah,blah....) dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here ``` To fix that: ``` dsData = getSQLData(conn,sql, blah,blah....) If dsData.Tables.Count = 0 Then Exit Sub dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here ``` **edit**: added code formatting tags ...
131,056
<p>Not sure how to ask a followup on SO, but this is in reference to an earlier question: <a href="https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list">Fetch one row per account id from list</a></p> <p>The query I'm working with is:</p> <pre><code>SELECT * FROM scores s1 WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score &lt; s2.score) ORDER BY score DESC </code></pre> <p>This selects the top scores, and limits results to one row per accountid; their top score.</p> <p>The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75.</p> <p>Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id?</p> <p>Thanks again!</p>
[ { "answer_id": 131060, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 0, "selected": false, "text": "<p>If you are selecting a subset of columns then you can use the DISTINCT keyword to filter results.</p>\n\n<pre><code>SELECT DISTINCT UserID, score\nFROM scores s1\nWHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score &lt; s2.score)\nORDER BY score DESC\n</code></pre>\n" }, { "answer_id": 131063, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 0, "selected": false, "text": "<p>Does your database support distinct? As in select distinct x from y?</p>\n" }, { "answer_id": 131066, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<pre><code>select accountid, max(score) from scores group by accountid;\n</code></pre>\n" }, { "answer_id": 131322, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "<p>If your RDBMS supports them, then an analytic function would be a good approach particularly if you need all the columns of the row.</p>\n\n<pre><code>select ...\nfrom (\n select accountid,\n score,\n ...\n row_number() over \n (partition by accountid\n order by score desc) score_rank\n from scores)\nwhere score_rank = 1;\n</code></pre>\n\n<p>The row returned is indeterminate in the case you describe, but you can easily modify the analytic function, for example by ordering on (score desc, test_date desc) to get the more recent of two matching high scores.</p>\n\n<p>Other analytic functions based on rank will achieve a similar purpose.</p>\n\n<p>If you don't mind duplicates then the following would probably me more efficient than your current method:</p>\n\n<pre><code>select ...\nfrom (\n select accountid,\n score,\n ...\n max(score) over (partition by accountid) max_score\n from scores)\nwhere score = max_score;\n</code></pre>\n" }, { "answer_id": 131877, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>If you're only interested in the accountid and the score, then you can use the simple GROUP BY query given by Paul above.</p>\n\n<pre><code>SELECT accountid, MAX(score) \nFROM scores \nGROUP BY accountid;\n</code></pre>\n\n<p>If you need other attributes from the scores table, then you can get other attributes from the row with a query like the following:</p>\n\n<pre><code>SELECT s1.*\nFROM scores AS s1\n LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid \n AND s1.score &lt; s2.score)\nWHERE s2.accountid IS NULL;\n</code></pre>\n\n<p>But this still gives multiple rows, in your example where a given accountid has two scores matching its maximum value. To further reduce the result set to a single row, for example the row with the latest gamedate, try this:</p>\n\n<pre><code>SELECT s1.*\nFROM scores AS s1\n LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid \n AND s1.score &lt; s2.score)\n LEFT OUTER JOIN scores AS s3 ON (s1.accountid = s3.accountid \n AND s1.score = s3.score AND s1.gamedate &lt; s3.gamedate) \nWHERE s2.accountid IS NULL\n AND s3.accountid IS NULL;\n</code></pre>\n" }, { "answer_id": 132828, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>This solutions works in MS SQL, giving you the whole row.</p>\n\n<pre><code>SELECT *\nFROM scores\nWHERE scoreid in\n(\n SELECT max(scoreid)\n FROM scores as s2\n JOIN\n (\n SELECT max(score) as maxscore, accountid\n FROM scores s1\n GROUP BY accountid\n ) sub ON s2.score = sub.maxscore AND s2.accountid = s1.accountid\n GROUP BY s2.score, s2.accountid\n)\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
Not sure how to ask a followup on SO, but this is in reference to an earlier question: [Fetch one row per account id from list](https://stackoverflow.com/questions/94930/fetch-one-row-per-account-id-from-list) The query I'm working with is: ``` SELECT * FROM scores s1 WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score) ORDER BY score DESC ``` This selects the top scores, and limits results to one row per accountid; their top score. The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75. Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id? Thanks again!
If you're only interested in the accountid and the score, then you can use the simple GROUP BY query given by Paul above. ``` SELECT accountid, MAX(score) FROM scores GROUP BY accountid; ``` If you need other attributes from the scores table, then you can get other attributes from the row with a query like the following: ``` SELECT s1.* FROM scores AS s1 LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid AND s1.score < s2.score) WHERE s2.accountid IS NULL; ``` But this still gives multiple rows, in your example where a given accountid has two scores matching its maximum value. To further reduce the result set to a single row, for example the row with the latest gamedate, try this: ``` SELECT s1.* FROM scores AS s1 LEFT OUTER JOIN scores AS s2 ON (s1.accountid = s2.accountid AND s1.score < s2.score) LEFT OUTER JOIN scores AS s3 ON (s1.accountid = s3.accountid AND s1.score = s3.score AND s1.gamedate < s3.gamedate) WHERE s2.accountid IS NULL AND s3.accountid IS NULL; ```
131,062
<p>I've read numerous posts about people having problems with <code>viewWillAppear</code> when you do not create your view hierarchy <em>just</em> right. My problem is I can't figure out what that means.</p> <p>If I create a <code>RootViewController</code> and call <code>addSubView</code> on that controller, I would expect the added view(s) to be wired up for <code>viewWillAppear</code> events. </p> <p>Does anyone have an example of a complex programmatic view hierarchy that successfully receives <code>viewWillAppear</code> events at every level?</p> <p>Apple's Docs state:</p> <blockquote> <p>Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed.</p> </blockquote> <p>The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view?</p> <p>I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.</p>
[ { "answer_id": 135418, "author": "Josh Gagnon", "author_id": 7944, "author_profile": "https://Stackoverflow.com/users/7944", "pm_score": 3, "selected": false, "text": "<p>I've been using a navigation controller. When I want to either descend to another level of data or show my custom view I use the following:</p>\n\n<pre><code>[self.navigationController pushViewController:&lt;view&gt; animated:&lt;BOOL&gt;];\n</code></pre>\n\n<p>When I do this, I do get the <code>viewWillAppear</code> function to fire. I suppose this qualifies as \"indirect\" because I'm not calling the actual <code>addSubView</code> method myself. I don't know if this is 100% applicable to your application since I can't tell if you're using a navigation controller, but maybe it will provide a clue.</p>\n" }, { "answer_id": 144935, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 5, "selected": false, "text": "<p>I've run into this same problem. Just send a <code>viewWillAppear</code> message to your view controller before you add it as a subview. (There is one BOOL parameter which tells the view controller if it's being animated to appear or not.)</p>\n\n<pre><code>[myViewController viewWillAppear:NO];\n</code></pre>\n\n<p>Look at RootViewController.m in the Metronome example. </p>\n\n<p>(I actually found Apple's example projects great. There's a LOT more than HelloWorld ;)</p>\n" }, { "answer_id": 179151, "author": "Martin Gordon", "author_id": 2481, "author_profile": "https://Stackoverflow.com/users/2481", "pm_score": 1, "selected": false, "text": "<p>I'm not 100% sure on this, but I think that adding a view to the view hierarchy directly means calling <code>-addSubview:</code> on the view controller's view (e.g., <code>[viewController.view addSubview:anotherViewController.view]</code>) instead of pushing a new view controller onto the navigation controller's stack.</p>\n" }, { "answer_id": 211091, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": false, "text": "<p>If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked.</p>\n\n<p>You need to use the navigation controller delegate methods instead:</p>\n\n<pre><code>navigationController:willShowViewController:animated:\nnavigationController:didShowViewController:animated:\n</code></pre>\n" }, { "answer_id": 905527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think that adding a subview doesn't necessarily mean that the view will appear, so there is not an automatic call to the class's method that it will</p>\n" }, { "answer_id": 2057427, "author": "Antoine", "author_id": 249885, "author_profile": "https://Stackoverflow.com/users/249885", "pm_score": 3, "selected": false, "text": "<p>I just had the same issue. In my application I have 2 navigation controllers and pushing the same view controller in each of them worked in one case and not in the other. I mean that when pushing the exact same view controller in the first <code>UINavigationController</code>, <code>viewWillAppear</code> was called but not when pushed in the second navigation controller.</p>\n\n<p>Then I came across this post <a href=\"http://discussions.apple.com/thread.jspa?threadID=1529769&amp;tstart=0\" rel=\"noreferrer\">UINavigationController should call viewWillAppear/viewWillDisappear methods </a></p>\n\n<p>And realized that my second navigation controller did redefine <code>viewWillAppear</code>. Screening the code showed that I was not calling </p>\n\n<pre><code>[super viewWillAppear:animated];\n</code></pre>\n\n<p>I added it and it worked !</p>\n\n<p>The documentation says:</p>\n\n<blockquote>\n <p>If you override this method, you must call super at some point in your implementation.</p>\n</blockquote>\n" }, { "answer_id": 3046801, "author": "Bogatyr", "author_id": 188252, "author_profile": "https://Stackoverflow.com/users/188252", "pm_score": 1, "selected": false, "text": "<p>I think what they mean \"directly\" is by hooking things up just the same way as the xcode \"Navigation Application\" template does, which sets the UINavigationController as the sole subview of the application's UIWindow.</p>\n\n<p>Using that template is the only way I've been able to get the Will/Did/Appear/Disappear methods called on the object ViewControllers upon push/pops of those controllers in the UINavigationController. None of the other solutions in the answers here worked for me, including implementing them in the RootController and passing them through to the (child) NavigationController. Those functions (will/did/appear/disappear) were only called in my RootController upon showing/hiding the top-level VCs, my \"login\" and navigationVCs, not the sub-VCs in the navigation controller, so I had no opportunity to \"pass them through\" to the Nav VC.</p>\n\n<p>I ended up using the UINavigationController's delegate functionality to look for the particular transitions that required follow-up functionality in my app, and that works, but it requires a bit more work in order to get both the disappear and appear functionality \"simulated\".</p>\n\n<p>Also it's a matter of principle to get it to work after banging my head against this problem for hours today. Any working code snippets using a custom RootController and a child navigation VC would be much appreciated.</p>\n" }, { "answer_id": 4229031, "author": "Andrew", "author_id": 513938, "author_profile": "https://Stackoverflow.com/users/513938", "pm_score": 1, "selected": false, "text": "<p>In case this helps anyone. I had a similar problem where my <code>ViewWillAppear</code> is not firing on a <code>UITableViewController</code>. After a lot of playing around, I realized that the problem was that the <code>UINavigationController</code> that is controlling my <code>UITableView</code> is not on the root view. Once I fix that, it is now working like a champ.</p>\n" }, { "answer_id": 4241990, "author": "AndrewS", "author_id": 173964, "author_profile": "https://Stackoverflow.com/users/173964", "pm_score": 2, "selected": false, "text": "<p>Views are added \"directly\" by calling <code>[view addSubview:subview]</code>.\nViews are added \"indirectly\" by methods such as tab bars or nav bars that swap subviews.</p>\n\n<p>Any time you call <code>[view addSubview:subviewController.view]</code>, you should then call <code>[subviewController viewWillAppear:NO]</code> (or YES as your case may be).</p>\n\n<p>I had this problem when I implemented my own custom root-view management system for a subscreen in a game. Manually adding the call to viewWillAppear cured my problem.</p>\n" }, { "answer_id": 4256538, "author": "Gaurav", "author_id": 437149, "author_profile": "https://Stackoverflow.com/users/437149", "pm_score": 1, "selected": false, "text": "<pre><code>[self.navigationController setDelegate:self];\n</code></pre>\n\n<p>Set the delegate to the root view controller.</p>\n" }, { "answer_id": 4355780, "author": "hol", "author_id": 382009, "author_profile": "https://Stackoverflow.com/users/382009", "pm_score": 2, "selected": false, "text": "<p>As no answer is accepted and people (like I did) land here I give my variation. Though I am not sure that was the original problem. When the navigation controller is added as a subview to a another view you must call the viewWillAppear/Dissappear etc. methods yourself like this:</p>\n\n<pre><code>- (void) viewWillAppear:(BOOL)animated\n{\n [super viewWillAppear:animated];\n\n [subNavCntlr viewWillAppear:animated];\n}\n\n- (void) viewWillDisappear:(BOOL)animated\n{\n [super viewWillDisappear:animated];\n\n [subNavCntlr viewWillDisappear:animated];\n}\n</code></pre>\n\n<p>Just to make the example complete. This code appears in my ViewController where I created and added the the navigation controller into a view that I placed on the view. </p>\n\n<pre><code>- (void)viewDidLoad {\n\n // This is the root View Controller\n rootTable *rootTableController = [[rootTable alloc]\n initWithStyle:UITableViewStyleGrouped];\n\n subNavCntlr = [[UINavigationController alloc] \n initWithRootViewController:rootTableController];\n\n [rootTableController release];\n\n subNavCntlr.view.frame = subNavContainer.bounds;\n\n [subNavContainer addSubview:subNavCntlr.view];\n\n [super viewDidLoad];\n}\n</code></pre>\n\n<p>the .h looks like this</p>\n\n<pre><code>@interface navTestViewController : UIViewController &lt;UINavigationControllerDelegate&gt; {\n IBOutlet UIView *subNavContainer;\n UINavigationController *subNavCntlr;\n}\n\n@end\n</code></pre>\n\n<p>In the nib file I have the view and below this view I have a label a image and the container (another view) where i put the controller in. Here is how it looks. I had to scramble some things as this was work for a client.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CZ2Vw.png\" alt=\"alt text\"></p>\n" }, { "answer_id": 4508301, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 4, "selected": false, "text": "<p>I finally found a solution for this THAT WORKS!</p>\n\n<p><a href=\"http://www.idev101.com/code/User_Interface/UINavigationController/viewWillAppear.html\" rel=\"noreferrer\">UINavigationControllerDelegate</a></p>\n\n<p>I think the gist of it is to set your nav control's delegate to the viewcontroller it is in, and implement <code>UINavigationControllerDelegate</code> and it's two methods. Brilliant! I'm so excited i finally found a solution!</p>\n" }, { "answer_id": 6833875, "author": "Sam", "author_id": 135700, "author_profile": "https://Stackoverflow.com/users/135700", "pm_score": 2, "selected": false, "text": "<p>Firstly, the tab bar should be at the root level, ie, added to the window, as stated in the Apple documentation. This is key for correct behavior.</p>\n\n<p>Secondly, you <em>can</em> use <code>UITabBarDelegate</code> / <code>UINavigationBarDelegate</code> to forward the notifications on manually, but I found that to get the whole hierarchy of view calls to work correctly, all I had to do was manually call </p>\n\n<pre><code>[tabBarController viewWillAppear:NO];\n[tabBarController viewDidAppear:NO];\n</code></pre>\n\n<p>and</p>\n\n<pre><code>[navBarController viewWillAppear:NO];\n[navBarController viewDidAppear:NO];\n</code></pre>\n\n<p>.. just ONCE before setting up the view controllers on the respective controller (right after allocation). From then on, it correctly called these methods on its child view controllers.</p>\n\n<p>My hierarchy is like this:</p>\n\n<pre><code>window\n UITabBarController (subclass of)\n UIViewController (subclass of) // &lt;-- manually calls [navController viewWill/DidAppear\n UINavigationController (subclass of)\n UIViewController (subclass of) // &lt;-- still receives viewWill/Did..etc all the way down from a tab switch at the top of the chain without needing to use ANY delegate methods\n</code></pre>\n\n<p>Just calling the mentioned methods on the tab/nav controller the first time ensured that ALL the events were forwarded correctly. It stopped me needing to call them manually from the <code>UINavigationBarDelegate</code> / <code>UITabBarControllerDelegate</code> methods.</p>\n\n<p>Sidenote:\nCuriously, when it didn't work, the private method </p>\n\n<pre><code>- (void)transitionFromViewController:(UIViewController*)aFromViewController toViewController:(UIViewController*)aToViewController \n</code></pre>\n\n<p>.. which you can see from the callstack on a working implementation, usually calls the <code>viewWill/Did..</code> methods but didn't until I performed the above (even though it was called).</p>\n\n<p>I think it is VERY important that the <code>UITabBarController</code> is at window level though and the documents seem to back this up.</p>\n\n<p>Hope that was clear(ish), happy to answer further questions.</p>\n" }, { "answer_id": 7454285, "author": "Nigel Flack", "author_id": 797706, "author_profile": "https://Stackoverflow.com/users/797706", "pm_score": -1, "selected": false, "text": "<p>You should only have 1 UIViewController active at any time. Any subviews you want to manipulate should be exactly that - subVIEWS - i.e. UIView.</p>\n\n<p>I use a simlple technique for managing my view hierarchy and have yet to run into a problem since I started doing things this way. There are 2 key points:</p>\n\n<ul>\n<li>a single UIViewController should be used to manage \"a screen's worth\"\nof your app</li>\n<li>use UINavigationController for changing views</li>\n</ul>\n\n<p>What do I mean by \"a screen's worth\"? It's a bit vague on purpose, but generally it's a feature or section of your app. If you've got a few screens with the same background image but different overlays/popups etc., that should be 1 view controller and several child views. You should never find yourself working with 2 view controllers. Note you can still instantiate a UIView in one view controller and add it as a subview of another view controller if you want certain areas of the screen to be shown in multiple view controllers.</p>\n\n<p>As for UINavigationController - this is your best friend! Turn off the navigation bar and specify NO for animated, and you have an excellent way of switching screens on demand. You can push and pop view controllers if they're in a hierarchy, or you can prepare an array of view controllers (including an array containing a single VC) and set it to be the view stack using setViewControllers. This gives you total freedom to change VC's, while gaining all the advantages of working within Apple's expected model and getting all events etc. fired properly.</p>\n\n<p>Here's what I do every time when I start an app:</p>\n\n<ul>\n<li>start from a window-based app</li>\n<li>add a UINavigationController as the window's rootViewController</li>\n<li>add whatever I want my first UIViewController to be as the rootViewController of the nav\ncontroller</li>\n</ul>\n\n<p>(note starting from window-based is just a personal preference - I like to construct things myself so I know exactly how they are built. It should work fine with view-based template)</p>\n\n<p>All events fire correctly and basically life is good. You can then spend all your time writing the important bits of your app and not messing about trying to manually hack view hierarchies into shape.</p>\n" }, { "answer_id": 8157562, "author": "Sean", "author_id": 934741, "author_profile": "https://Stackoverflow.com/users/934741", "pm_score": -1, "selected": false, "text": "<p>I'm not sure this is the same problem that I solved.<br/>\nIn some occasions, method doesn't executed with normal way such as \"[self methodOne]\".</p>\n\n<p>Try</p>\n\n<pre><code>- (void)viewWillAppear:(BOOL)animated\n{\n [self performSelector:@selector(methodOne) \n withObject:nil afterDelay:0];\n}\n</code></pre>\n" }, { "answer_id": 11152273, "author": "Arash Zeinoddini", "author_id": 1391007, "author_profile": "https://Stackoverflow.com/users/1391007", "pm_score": 2, "selected": false, "text": "<p>I use this code for push and pop view controllers:</p>\n\n<p>push: </p>\n\n<pre><code>[self.navigationController pushViewController:detaiViewController animated:YES];\n[detailNewsViewController viewWillAppear:YES];\n</code></pre>\n\n<p>pop:</p>\n\n<pre><code>[[self.navigationController popViewControllerAnimated:YES] viewWillAppear:YES];\n</code></pre>\n\n<p>.. and it works fine for me.</p>\n" }, { "answer_id": 18935985, "author": "Finn Gaida", "author_id": 1642174, "author_profile": "https://Stackoverflow.com/users/1642174", "pm_score": 1, "selected": false, "text": "<p>I just had this problem myself and it took me 3 full hours (2 of which googling) to fix it.</p>\n\n<p>What turned out to help was to simply <strong>delete the app from the device/simulator, clean and then run again</strong>.</p>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 20402075, "author": "gdm", "author_id": 778508, "author_profile": "https://Stackoverflow.com/users/778508", "pm_score": 2, "selected": false, "text": "<p>A very common mistake is as follows.\nYou have one view, <code>UIView* a</code>, and another one, <code>UIView* b</code>.\nYou add b to a as a subview.\nIf you try to call viewWillAppear in b, it will never be fired, because it is a subview of a</p>\n" }, { "answer_id": 31682471, "author": "Hari Kunwar", "author_id": 3892773, "author_profile": "https://Stackoverflow.com/users/3892773", "pm_score": 2, "selected": false, "text": "<p>Correct way to do this is using UIViewController containment api. </p>\n\n<pre><code>- (void)viewDidLoad {\n [super viewDidLoad];\n // Do any additional setup after loading the view.\n UIViewController *viewController = ...;\n [self addChildViewController:viewController];\n [self.view addSubview:viewController.view];\n [viewController didMoveToParentViewController:self];\n}\n</code></pre>\n" }, { "answer_id": 52944364, "author": "ober", "author_id": 1668686, "author_profile": "https://Stackoverflow.com/users/1668686", "pm_score": 1, "selected": false, "text": "<p>In my case problem was with custom transition animation.\nWhen set <code>modalPresentationStyle = .custom</code> <code>viewWillAppear</code> not called</p>\n\n<p>in custom transition animation class need call methods:\n<code>beginAppearanceTransition</code> and <code>endAppearanceTransition</code></p>\n" }, { "answer_id": 53863204, "author": "Vadim Motorine", "author_id": 6918530, "author_profile": "https://Stackoverflow.com/users/6918530", "pm_score": 1, "selected": false, "text": "<p>For Swift. First create the protocol to call what you wanted to call in viewWillAppear</p>\n\n<pre><code>protocol MyViewWillAppearProtocol{func myViewWillAppear()}\n</code></pre>\n\n<p>Second, create the class</p>\n\n<pre><code>class ForceUpdateOnViewAppear: NSObject, UINavigationControllerDelegate {\nfunc navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool){\n if let updatedCntllr: MyViewWillAppearProtocol = viewController as? MyViewWillAppearProtocol{\n updatedCntllr.myViewWillAppear()\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Third, make the instance of ForceUpdateOnViewAppear to be the member of the appropriate class that have the access to the Navigation Controller and exists as long as Navigation controller exists. It may be for example the root view controller of the navigation controller or the class that creates or present it. Then assign the instance of ForceUpdateOnViewAppear to the Navigation Controller delegate property as early as possible. </p>\n" }, { "answer_id": 54428324, "author": "coldembrace", "author_id": 7110268, "author_profile": "https://Stackoverflow.com/users/7110268", "pm_score": 0, "selected": false, "text": "<p>In my case that was just a weird bug on the ios 12.1 emulator. Disappeared after launching on real device.</p>\n" }, { "answer_id": 54804900, "author": "GregJaskiewicz", "author_id": 846262, "author_profile": "https://Stackoverflow.com/users/846262", "pm_score": 0, "selected": false, "text": "<p>I have created a class that solves this problem. \nJust set it as a delegate of your navigation controller, and implement simple one or two methods in your view controller - that will get called when the view is about to be shown or has been shown via NavigationController</p>\n\n<p><a href=\"https://gist.github.com/greggjaskiewicz/70f4a37cf6abc51423c9ecbb0033d6c7\" rel=\"nofollow noreferrer\">Here's the GIST showing the code</a></p>\n" }, { "answer_id": 54805338, "author": "Abu Ul Hassan", "author_id": 7229378, "author_profile": "https://Stackoverflow.com/users/7229378", "pm_score": 0, "selected": false, "text": "<p>ViewWillAppear is an override method of UIViewController class so adding a subView will not call viewWillAppear, but when you present, push , pop, show , setFront Or popToRootViewController from a viewController then viewWillAppear for presented viewController will get called.</p>\n" }, { "answer_id": 56599649, "author": "BilalReffas", "author_id": 4142753, "author_profile": "https://Stackoverflow.com/users/4142753", "pm_score": 4, "selected": false, "text": "<p>Thanks iOS 13. </p>\n\n<blockquote>\n <p><code>ViewWillDisappear</code>, <code>ViewDidDisappear</code>, <code>ViewWillAppear</code> and\n <code>ViewDidAppear</code> won't get called on a presenting view controller on\n iOS 13 which uses a new modal presentation that doesn't cover the\n whole screen.</p>\n</blockquote>\n\n<p>Credits are going to <a href=\"https://twitter.com/arekholko/status/1137756105050918912\" rel=\"noreferrer\">Arek Holko</a>. He really saved my day.</p>\n\n<p><a href=\"https://i.stack.imgur.com/I1mH3.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/I1mH3.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 58416153, "author": "dollardime", "author_id": 972024, "author_profile": "https://Stackoverflow.com/users/972024", "pm_score": 2, "selected": false, "text": "<p>iOS 13 bit my app in the butt here. If you've noticed behavior change as of iOS 13 just set the following before you push it:</p>\n\n<pre><code>yourVC.modalPresentationStyle = UIModalPresentationFullScreen;\n</code></pre>\n\n<p>You may also need to set it in your .storyboard in the Attributes inspector (set Presentation to Full Screen).</p>\n\n<p>This will make your app behave as it did in prior versions of iOS.</p>\n" }, { "answer_id": 61223070, "author": "user2385491", "author_id": 2385491, "author_profile": "https://Stackoverflow.com/users/2385491", "pm_score": 0, "selected": false, "text": "<p>My issue was that viewWillAppear was not called when unwinding from a segue. The answer was to put a call to viewWillAppear(true) in the unwind segue in the View Controller that you segueing back to</p>\n\n<p>@IBAction func unwind(for unwindSegue: UIStoryboardSegue, ViewController subsequentVC: Any) {</p>\n\n<pre><code> viewWillAppear(true)\n}\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21964/" ]
I've read numerous posts about people having problems with `viewWillAppear` when you do not create your view hierarchy *just* right. My problem is I can't figure out what that means. If I create a `RootViewController` and call `addSubView` on that controller, I would expect the added view(s) to be wired up for `viewWillAppear` events. Does anyone have an example of a complex programmatic view hierarchy that successfully receives `viewWillAppear` events at every level? Apple's Docs state: > > Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed. > > > The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view? I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.
If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked. You need to use the navigation controller delegate methods instead: ``` navigationController:willShowViewController:animated: navigationController:didShowViewController:animated: ```
131,116
<p>I'm wondering if updating statistics has helped you before and how did you know to update them?</p>
[ { "answer_id": 131168, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": true, "text": "<pre><code>exec sp_updatestats\n</code></pre>\n\n<p>Yes, updating statistics can be very helpful if you find that your queries are not performing as well as they should. This is evidenced by inspecting the query plan and noticing when, for example, table scans or index scans are being performed instead of index seeks. All of this assumes that you have set up your indexes correctly.</p>\n\n<p>There is also the <a href=\"http://doc.ddart.net/mssql/sql70/ua-uz_4.htm\" rel=\"nofollow noreferrer\">UPDATE STATISTICS</a> command, but I've personally never used that.</p>\n" }, { "answer_id": 131169, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>It's common to add your statistics update to a maintenance plan (as in an Enterprise Manager-defined Maintenance plan). That way it happens on a schedule - daily, weekly, whatever.</p>\n\n<p>SQL Server 2000 uses statistics to make good decisions about query execution so they definitely help.</p>\n\n<p>It's a good idea to rebuild your indexes at the same time (DBCC DBREINDEX and DBCC INDEXDEFRAG).</p>\n" }, { "answer_id": 131982, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 1, "selected": false, "text": "<p>Updating statistics becomes necessary after the following events:<br>\n- Records are inserted into your table<br>\n- Records are deleted from your table<br>\n- Records are updated in your table </p>\n\n<p>If you have a large database with millions of records that gets lots of writes per day you probably should be determining an off-peak time to schedule index updates. </p>\n\n<p>Also, you need to consider your type of traffic. If you have a lot (millions) of records in tables with many foreign key dependencies and you have a larger proportion of writes to reads you might want to consider turning off automatic statistics recomputation (NOTE: this feature will be removed in a future version of SQL Server, but for SQL Server 2000 you should be OK). This tells the engine to not recompute statistics on every INSERT, DELETE, or UPDATE and makes those actions much more performant.</p>\n\n<p>Indexes are no laughing matter. They are the heart and soul of a performant database. </p>\n" }, { "answer_id": 132006, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>If you rebuild indexes, then the statistics for those indexes are automatically rebuilt.\nIf your timeframes allow, then running UPDATE STATISTICS of part of a maintenance plan is a good idea, as frequently as nightly (if your indexes are being rebuilt less frequently than that).</p>\n\n<p>SQL Server: To determine if out of date statistics are the cause of a query performing poorly, turn on 'Query->Display Estimated Execution plan' (CTRL-L) in Management Studio and run the query. Open another window, paste in the same query and turn on 'Query->Display ActualExecution plan' (CTRL-M) in Management Studio and re-run the query. If the execution plans are different then statistics are most likely out of date.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
I'm wondering if updating statistics has helped you before and how did you know to update them?
``` exec sp_updatestats ``` Yes, updating statistics can be very helpful if you find that your queries are not performing as well as they should. This is evidenced by inspecting the query plan and noticing when, for example, table scans or index scans are being performed instead of index seeks. All of this assumes that you have set up your indexes correctly. There is also the [UPDATE STATISTICS](http://doc.ddart.net/mssql/sql70/ua-uz_4.htm) command, but I've personally never used that.
131,121
<p>If I have a Range object--for example, let's say it refers to cell <code>A1</code> on a worksheet called <code>Book1</code>. So I know that calling <code>Address()</code> will get me a simple local reference: <code>$A$1</code>. I know it can also be called as <code>Address(External:=True)</code> to get a reference including the workbook name and worksheet name: <code>[Book1]Sheet1!$A$1</code>.</p> <p>What I want is to get an address including the sheet name, but not the book name. I really don't want to call <code>Address(External:=True)</code> and try to strip out the workbook name myself with string functions. Is there any call I can make on the range to get <code>Sheet1!$A$1</code>?</p>
[ { "answer_id": 131155, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 7, "selected": true, "text": "<p>Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:</p>\n\n<pre><code>Dim cell As Range\nDim cellAddress As String\nSet cell = ThisWorkbook.Worksheets(1).Cells(1, 1)\ncellAddress = cell.Parent.Name &amp; \"!\" &amp; cell.Address(External:=False)\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Modify last line to :</p>\n\n<pre><code>cellAddress = \"'\" &amp; cell.Parent.Name &amp; \"'!\" &amp; cell.Address(External:=False) \n</code></pre>\n\n<p>if you want it to work even if there are spaces or other funny characters in the sheet name.</p>\n" }, { "answer_id": 131185, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 2, "selected": false, "text": "<p>Ben is right. I also can't think of any way to do this. I'd suggest either the method Ben recommends, or the following to strip the Workbook name off.</p>\n\n<pre><code>Dim cell As Range\nDim address As String\nSet cell = Worksheets(1).Cells.Range(\"A1\")\naddress = cell.address(External:=True)\naddress = Right(address, Len(address) - InStr(1, address, \"]\"))\n</code></pre>\n" }, { "answer_id": 688610, "author": "TimS", "author_id": 83470, "author_profile": "https://Stackoverflow.com/users/83470", "pm_score": -1, "selected": false, "text": "<p>[edit on 2009-04-21]</p>\n\n<p><i>&nbsp;&nbsp;&nbsp;&nbsp;As Micah pointed out, this only works when you have named that<br> \n&nbsp;&nbsp;&nbsp;&nbsp;particular range (hence .Name anyone?) Yeah, oops!</i></p>\n\n<p>[/edit]</p>\n\n<p>A little late to the party, I know, but in case anyone else catches this in a google search (as I just did), you could also try the following: </p>\n\n<pre><code>Dim cell as Range\nDim address as String\nSet cell = Sheet1.Range(\"A1\")\naddress = cell.Name\n</code></pre>\n\n<p>This should return the full address, something like \"=Sheet1!$A$1\". </p>\n\n<p>Assuming you don't want the equal sign, you can strip it off with a Replace function: </p>\n\n<pre><code>address = Replace(address, \"=\", \"\")\n</code></pre>\n" }, { "answer_id": 1089769, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Why not just return the worksheet name with\n<strong>address = cell.Worksheet.Name</strong>\nthen you can concatenate the address back on like this\n<strong>address = cell.Worksheet.Name &amp; \"!\" &amp; cell.Address</strong></p>\n" }, { "answer_id": 1266074, "author": "raph82", "author_id": 113885, "author_profile": "https://Stackoverflow.com/users/113885", "pm_score": 2, "selected": false, "text": "<p>The <code>Address()</code> worksheet function does exactly that. As it's not available through <code>Application.WorksheetFunction</code>, I came up with a solution using the <code>Evaluate()</code> method.</p>\n\n<p>This solution let Excel deals with spaces and other funny characters in the sheet name, which is a nice advantage over the previous answers.</p>\n\n<p>Example:</p>\n\n<pre><code>Evaluate(\"ADDRESS(\" &amp; rng.Row &amp; \",\" &amp; rng.Column &amp; \",1,1,\"\"\" &amp; _\n rng.Worksheet.Name &amp; \"\"\")\")\n</code></pre>\n\n<p>returns exactly \"Sheet1!$A$1\", with a <code>Range</code> object named <code>rng</code> referring the A1 cell in the Sheet1 worksheet.</p>\n\n<p>This solution returns only the address of the first cell of a range, not the address of the whole range (\"Sheet1!$A$1\" vs \"Sheet1!$A$1:$B$2\"). So I use it in a custom function:</p>\n\n<pre><code>Public Function AddressEx(rng As Range) As String\n\n Dim strTmp As String\n\n strTmp = Evaluate(\"ADDRESS(\" &amp; rng.Row &amp; \",\" &amp; _\n rng.Column &amp; \",1,1,\"\"\" &amp; rng.Worksheet.Name &amp; \"\"\")\")\n\n If (rng.Count &gt; 1) Then\n\n strTmp = strTmp &amp; \":\" &amp; rng.Cells(rng.Count) _\n .Address(RowAbsolute:=True, ColumnAbsolute:=True)\n\n End If\n\n AddressEx = strTmp\n\nEnd Function\n</code></pre>\n\n<p>The full documentation of the Address() worksheet function is available on the Office website: <a href=\"https://support.office.com/en-us/article/ADDRESS-function-D0C26C0D-3991-446B-8DE4-AB46431D4F89\" rel=\"nofollow noreferrer\">https://support.office.com/en-us/article/ADDRESS-function-D0C26C0D-3991-446B-8DE4-AB46431D4F89</a></p>\n" }, { "answer_id": 5432001, "author": "rinku", "author_id": 676637, "author_profile": "https://Stackoverflow.com/users/676637", "pm_score": -1, "selected": false, "text": "<pre><code>Dim rg As Range\nSet rg = Range(\"A1:E10\")\nDim i As Integer\nFor i = 1 To rg.Rows.Count\n\n For j = 1 To rg.Columns.Count\n rg.Cells(i, j).Value = rg.Cells(i, j).Address(False, False)\n\n Next\nNext\n</code></pre>\n" }, { "answer_id": 17954921, "author": "Luciano Evaristo Guerche", "author_id": 2635415, "author_profile": "https://Stackoverflow.com/users/2635415", "pm_score": 4, "selected": false, "text": "<pre><code>Split(cell.address(External:=True), \"]\")(1)\n</code></pre>\n" }, { "answer_id": 24112118, "author": "Jeff", "author_id": 3720789, "author_profile": "https://Stackoverflow.com/users/3720789", "pm_score": 0, "selected": false, "text": "<p>I found the following worked for me in a user defined function I created. I concatenated the cell range reference and worksheet name as a string and then used in an Evaluate statement (I was using Evaluate on Sumproduct).</p>\n\n<p>For example: </p>\n\n<pre><code>Function SumRange(RangeName as range) \n\nDim strCellRef, strSheetName, strRngName As String\n\nstrCellRef = RangeName.Address \nstrSheetName = RangeName.Worksheet.Name &amp; \"!\" \nstrRngName = strSheetName &amp; strCellRef \n</code></pre>\n\n<p>Then refer to strRngName in the rest of your code. </p>\n" }, { "answer_id": 28025767, "author": "HarveyFrench", "author_id": 4413676, "author_profile": "https://Stackoverflow.com/users/4413676", "pm_score": 0, "selected": false, "text": "<p>You may need to write code that handles a range with multiple areas, which this does:</p>\n\n<pre><code>Public Function GetAddressWithSheetname(Range As Range, Optional blnBuildAddressForNamedRangeValue As Boolean = False) As String\n\n Const Seperator As String = \",\"\n\n Dim WorksheetName As String\n Dim TheAddress As String\n Dim Areas As Areas\n Dim Area As Range\n\n WorksheetName = \"'\" &amp; Range.Worksheet.Name &amp; \"'\"\n\n For Each Area In Range.Areas\n' ='Sheet 1'!$H$8:$H$15,'Sheet 1'!$C$12:$J$12\n TheAddress = TheAddress &amp; WorksheetName &amp; \"!\" &amp; Area.Address(External:=False) &amp; Seperator\n\n Next Area\n\n GetAddressWithSheetname = Left(TheAddress, Len(TheAddress) - Len(Seperator))\n\n If blnBuildAddressForNamedRangeValue Then\n GetAddressWithSheetname = \"=\" &amp; GetAddressWithSheetname\n End If\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 38344905, "author": "ArnonK", "author_id": 6583035, "author_profile": "https://Stackoverflow.com/users/6583035", "pm_score": 0, "selected": false, "text": "<pre><code>rngYourRange.Address(,,,TRUE)\n</code></pre>\n\n<p>Shows External Address, Full Address</p>\n" }, { "answer_id": 41627956, "author": "Harry S", "author_id": 4476460, "author_profile": "https://Stackoverflow.com/users/4476460", "pm_score": -1, "selected": false, "text": "<p>For confused old me a range</p>\n\n<p>.Address(False, False, , True) </p>\n\n<p>seems to give in format TheSheet!B4:K9</p>\n\n<p>If it does not why the criteria .. avoid Str functons</p>\n\n<p>will probably only take less a millisecond and use 153 already used electrons</p>\n\n<p>about 0.3 Microsec</p>\n\n<p>RaAdd=mid(RaAdd,instr(raadd,\"]\") +1)</p>\n\n<p>or</p>\n\n<p>'about 1.7 microsec</p>\n\n<p>RaAdd= split(radd,\"]\")(1)</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6209/" ]
If I have a Range object--for example, let's say it refers to cell `A1` on a worksheet called `Book1`. So I know that calling `Address()` will get me a simple local reference: `$A$1`. I know it can also be called as `Address(External:=True)` to get a reference including the workbook name and worksheet name: `[Book1]Sheet1!$A$1`. What I want is to get an address including the sheet name, but not the book name. I really don't want to call `Address(External:=True)` and try to strip out the workbook name myself with string functions. Is there any call I can make on the range to get `Sheet1!$A$1`?
Only way I can think of is to concatenate the worksheet name with the cell reference, as follows: ``` Dim cell As Range Dim cellAddress As String Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1) cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False) ``` EDIT: Modify last line to : ``` cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False) ``` if you want it to work even if there are spaces or other funny characters in the sheet name.
131,128
<p>Short version: I'm wondering if it's possible, and how best, to utilise CPU specific instructions within a DLL?</p> <p>Slightly longer version: When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors.</p> <p>Does this mean that they are strictly built for the lowest common denominator (ie. the minimum platform supported by the OS)? Or is there some technique that is used to export a single interface within the DLL but utilise CPU specific code behind the scenes to get optimal performance? And if so, how is it done?</p>
[ { "answer_id": 131199, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "<p>The DLL is expected to work on every computer WIN32 runs on, so you are stuck to the i386 instruction set in general. There is no official method of exposing functionality/code for specific instruction sets. You have to do it by hand and transparently.</p>\n\n<p>The technique used basically is as follows:\n - determine CPU features like MMX, SSE in runtime\n - if they are present, use them, if not, have fallback code ready</p>\n\n<p>Because you cannot let your compiler optimise for anything else than i386, you will have to write the code using the specific instruction sets in inline assembler. I don't know if there are higher-language toolkits for this. Determining the CPU features is straight forward, but could also need to be done in assembler.</p>\n" }, { "answer_id": 131203, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": true, "text": "<p>I don't know of any <em>standard</em> technique but if I had to make such a thing, I would write some code in the DllMain() function to detect the CPU type and populate a jump table with function pointers to CPU-optimized versions of each function.</p>\n\n<p>There would also need to be a lowest common denominator function for when the CPU type is unknown.</p>\n\n<p>You can find current CPU info in the registry here:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\n</code></pre>\n" }, { "answer_id": 131251, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>An easy way to get the SSE/SSE2 optimizations is to just use the <code>/arch</code> argument for MSVC. I wouldn't worry about fallback--there is no reason to support anything below that unless you have a very niche application.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/7t5yh4fd.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/7t5yh4fd.aspx</a></p>\n\n<p>I believe gcc/g++ have equivalent flags.</p>\n" }, { "answer_id": 131491, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 1, "selected": false, "text": "<p>DLLs you download from Microsoft are targeted for the generic x86 architecture for the simple reason that it has to work across all the multitude of machines out there. </p>\n\n<p>Until the Visual Studio 6.0 time frame (I do not know if it has changed) Microsoft used to optimize its DLLs for size rather than speed. This is because the reduction in the overall size of the DLL gave a higher performance boost than any other optimization that the compiler could generate. This is because speed ups from micro optimization would be decidedly low compared to speed ups from not having the CPU wait for the memory. True improvements in speed come from reducing I/O or from improving the base algorithm. </p>\n\n<p>Only a few critical loops that run at the heart of the program could benefit from micro optimizations simply because of the huge number of times they are invoked. Only about 5-10% of your code might fall in this category. You could rest assured that such critical loops would already be optimized in assembler by the Microsoft software engineers to some level and not leave much behind for the compiler to find. (I know it's expecting too much but I hope they do this)</p>\n\n<p>As you can see, there would be only drawbacks from the increased DLL code that includes additional versions of code that are tuned for different architectures when most of this code is rarely used / are never part of the critical code that consumes most of your CPU cycles.</p>\n" }, { "answer_id": 132613, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>Intel's ICC can compile code twice, for different architectures. That way, you can have your cake and eat it. (OK, you get two cakes - your DLL will be bigger). And even MSVC2005 can do it for very specific cases (E.g. memcpy() can use SSE4)</p>\n\n<p>There are many ways to switch between different versions. A DLL is loaded, because the loading process needs functions from it. Function names are converted into addresses. One solution is to let this lookup depend on not just function name, but also processor features. Another method uses the fact that the name to address function uses a table of pointers in an interim step; you can switch out the entire table. Or you could even have a branch inside critical functions; so foo() calls foo__sse4 when that's faster.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11694/" ]
Short version: I'm wondering if it's possible, and how best, to utilise CPU specific instructions within a DLL? Slightly longer version: When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors. Does this mean that they are strictly built for the lowest common denominator (ie. the minimum platform supported by the OS)? Or is there some technique that is used to export a single interface within the DLL but utilise CPU specific code behind the scenes to get optimal performance? And if so, how is it done?
I don't know of any *standard* technique but if I had to make such a thing, I would write some code in the DllMain() function to detect the CPU type and populate a jump table with function pointers to CPU-optimized versions of each function. There would also need to be a lowest common denominator function for when the CPU type is unknown. You can find current CPU info in the registry here: ``` HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor ```
131,164
<p>I have a number of code value tables that contain a code and a description with a Long id.</p> <p>I now want to create an entry for an Account Type that references a number of codes, so I have something like this:</p> <pre><code>insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) ( select account_type_standard_seq.nextval, ts.tax_status_id, r.recipient_id from tax_status ts, recipient r where ts.tax_status_code = ? and r.recipient_code = ?) </code></pre> <p>This retrieves the appropriate values from the tax_status and recipient tables if a match is found for their respective codes. Unfortunately, recipient_code is nullable, and therefore the ? substitution value could be null. Of course, the implicit join doesn't return a row, so a row doesn't get inserted into my table.</p> <p>I've tried using NVL on the ? and on the r.recipient_id. </p> <p>I've tried to force an outer join on the r.recipient_code = ? by adding (+), but it's not an explicit join, so Oracle still didn't add another row.</p> <p>Anyone know of a way of doing this?</p> <p>I can obviously modify the statement so that I do the lookup of the recipient_id externally, and have a ? instead of r.recipient_id, and don't select from the recipient table at all, but I'd prefer to do all this in 1 SQL statement.</p>
[ { "answer_id": 131183, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 6, "selected": true, "text": "<p>Outter joins don't work \"as expected\" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless.</p>\n\n<p>A work-around</p>\n\n<pre><code>INSERT INTO account_type_standard \n (account_type_Standard_id, tax_status_id, recipient_id) \nVALUES( \n (SELECT account_type_standard_seq.nextval FROM DUAL),\n (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?), \n (SELECT recipient_id FROM recipient WHERE recipient_code = ?)\n)\n</code></pre>\n\n<p>[Edit]\nIf you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases.</p>\n\n<p>[Edit] Per comment, </p>\n\n<pre><code> (SELECT account_type_standard_seq.nextval FROM DUAL),\n</code></pre>\n\n<p>can be just</p>\n\n<pre><code> account_type_standard_seq.nextval,\n</code></pre>\n" }, { "answer_id": 131554, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>It was not clear to me in the question if ts.tax_status_code is a primary or alternate key or not. Same thing with recipient_code. This would be useful to know.</p>\n\n<p>You can deal with the possibility of your bind variable being null using an OR as follows. You would bind the same thing to the first two bind variables.</p>\n\n<p>If you are concerned about performance, you would be better to check if the values you intend to bind are null or not and then issue different SQL statement to avoid the OR.</p>\n\n<pre><code>insert into account_type_standard \n(account_type_Standard_id, tax_status_id, recipient_id)\n(\nselect \n account_type_standard_seq.nextval,\n ts.tax_status_id, \n r.recipient_id\nfrom tax_status ts, recipient r\nwhere (ts.tax_status_code = ? OR (ts.tax_status_code IS NULL and ? IS NULL))\nand (r.recipient_code = ? OR (r.recipient_code IS NULL and ? IS NULL))\n</code></pre>\n" }, { "answer_id": 132705, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)\nselect account_type_standard_seq.nextval,\n ts.tax_status_id, \n ( select r.recipient_id\n from recipient r\n where r.recipient_code = ?\n )\nfrom tax_status ts\nwhere ts.tax_status_code = ?\n</code></pre>\n" }, { "answer_id": 138674, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "<p>A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:</p>\n\n<pre><code>INSERT INTO account_type_standard \n (account_type_Standard_id, tax_status_id, recipient_id) \nVALUES( \n account_type_standard_seq.nextval,\n (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),\n (SELECT recipient_id FROM recipient WHERE recipient_code = ?)\n)\n</code></pre>\n" }, { "answer_id": 2872150, "author": "Arjun", "author_id": 345895, "author_profile": "https://Stackoverflow.com/users/345895", "pm_score": -1, "selected": false, "text": "<pre><code>insert into received_messages(id, content, status)\n values (RECEIVED_MESSAGES_SEQ.NEXT_VAL, empty_blob(), '');\n</code></pre>\n" }, { "answer_id": 13601299, "author": "paparao", "author_id": 1859208, "author_profile": "https://Stackoverflow.com/users/1859208", "pm_score": 1, "selected": false, "text": "<pre><code>insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)\nselect account_type_standard_seq.nextval,\n ts.tax_status_id, \n ( select r.recipient_id\n from recipient r\n where r.recipient_code = ?\n )\nfrom tax_status ts\nwhere ts.tax_status_code = ?\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5382/" ]
I have a number of code value tables that contain a code and a description with a Long id. I now want to create an entry for an Account Type that references a number of codes, so I have something like this: ``` insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) ( select account_type_standard_seq.nextval, ts.tax_status_id, r.recipient_id from tax_status ts, recipient r where ts.tax_status_code = ? and r.recipient_code = ?) ``` This retrieves the appropriate values from the tax\_status and recipient tables if a match is found for their respective codes. Unfortunately, recipient\_code is nullable, and therefore the ? substitution value could be null. Of course, the implicit join doesn't return a row, so a row doesn't get inserted into my table. I've tried using NVL on the ? and on the r.recipient\_id. I've tried to force an outer join on the r.recipient\_code = ? by adding (+), but it's not an explicit join, so Oracle still didn't add another row. Anyone know of a way of doing this? I can obviously modify the statement so that I do the lookup of the recipient\_id externally, and have a ? instead of r.recipient\_id, and don't select from the recipient table at all, but I'd prefer to do all this in 1 SQL statement.
Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless. A work-around ``` INSERT INTO account_type_standard (account_type_Standard_id, tax_status_id, recipient_id) VALUES( (SELECT account_type_standard_seq.nextval FROM DUAL), (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?), (SELECT recipient_id FROM recipient WHERE recipient_code = ?) ) ``` [Edit] If you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases. [Edit] Per comment, ``` (SELECT account_type_standard_seq.nextval FROM DUAL), ``` can be just ``` account_type_standard_seq.nextval, ```
131,179
<p>Trying to install the RMagick gem is failing with an error about being unable to find ImageMagick libraries, even though I'm sure they are installed.</p> <p>The pertinent output from gem install rmagick is:</p> <pre><code>checking for InitializeMagick() in -lMagick... no checking for InitializeMagick() in -lMagickCore... no checking for InitializeMagick() in -lMagick++... no Can't install RMagick 2.6.0. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information. *** extconf.rb failed *** </code></pre> <p>And looking in mkmf.log reveals:</p> <pre><code>have_library: checking for InitializeMagick() in -lMagick... -------------------- no "/usr/local/bin/gcc -o conftest -I. -I/usr/local/lib/ruby/1.8/i386-solaris2.10 -I. -I/usr/local/include/ImageMagick -I/usr/local/include/ImageMagick conftest.c -L. - L/usr/local/lib -Wl,-R/usr/local/lib -L/usr/local/lib -L/usr/local/lib -R/usr/local/lib -lfreetype -lz -L/usr/local/lib -L/usr/local/lib -lMagickCore -lruby-static - lMagick -ldl -lcrypt -lm -lc" ld: fatal: library -lMagick: not found ld: fatal: File processing errors. No output written to conftest </code></pre> <p>This is on Solaris 10 x86 with ImageMagick version 6.4.3 and RMagick version 2.6.0</p> <p>If I need to add something to LDFLAGS, its not clear to me what that would be. I installed ImageMagick from source and it should be in the usual places. ie,</p> <pre><code># ls -l /usr/local/lib/ | grep -i magick drwxr-xr-x 5 root root 512 Sep 24 23:09 ImageMagick-6.4.3/ -rw-r--r-- 1 root root 10808764 Sep 25 02:09 libMagickCore.a -rwxr-xr-x 1 root root 1440 Sep 25 02:09 libMagickCore.la* -rw-r--r-- 1 root root 2327072 Sep 25 02:09 libMagickWand.a -rwxr-xr-x 1 root root 1472 Sep 25 02:09 libMagickWand.la* </code></pre> <p>ImageMagick-6.4.3/ contains nothing interesting and I can't find any other files that I might be able to point gem install at.</p> <p>Any advice would be much appreciated!! googling hasn't been too helpful.</p> <p>thanks -</p>
[ { "answer_id": 131194, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>The linker cannot find libMagick in the standard places. Maybe you installed ImageMagick in a non standard place you have to specify via LDFLAGS?</p>\n" }, { "answer_id": 149490, "author": "rory", "author_id": 8063, "author_profile": "https://Stackoverflow.com/users/8063", "pm_score": 3, "selected": true, "text": "<p>problem solved.</p>\n\n<p>RMagick was unable to find ImageMagick because I neglected to build the shared objects (there were no .so files installed as you can see from the \"ls\" in the original question). The solution was to add <code>--with-shared</code> to my configure options.</p>\n\n<p>This however caused other problems. Most notably, <code>make</code> failing with \"undefined symbol\" messages for libiconv. This was solved by setting CFLAGS to point to libiconv:</p>\n\n<pre><code>export CFLAGS=\"-liconv\"\n</code></pre>\n\n<p>Ultimately, my successful configure command was:</p>\n\n<pre><code>./configure --disable-static --with-modules --without-perl --with-quantum-depth=8 --with-bzlib=no --with-libiconv\n</code></pre>\n\n<p>and after that, <code>make</code>, <code>make install</code>, and <code>gem install rmagick</code> all worked smoothly.</p>\n\n<p>thanks,</p>\n\n<p>R</p>\n" }, { "answer_id": 6662397, "author": "Sam Critchley", "author_id": 645042, "author_profile": "https://Stackoverflow.com/users/645042", "pm_score": 1, "selected": false, "text": "<p>I ran into this problem on OpenSuSE 11.4 - after installing a whole load of packages it turned out that libtool was the missing element....</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8063/" ]
Trying to install the RMagick gem is failing with an error about being unable to find ImageMagick libraries, even though I'm sure they are installed. The pertinent output from gem install rmagick is: ``` checking for InitializeMagick() in -lMagick... no checking for InitializeMagick() in -lMagickCore... no checking for InitializeMagick() in -lMagick++... no Can't install RMagick 2.6.0. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information. *** extconf.rb failed *** ``` And looking in mkmf.log reveals: ``` have_library: checking for InitializeMagick() in -lMagick... -------------------- no "/usr/local/bin/gcc -o conftest -I. -I/usr/local/lib/ruby/1.8/i386-solaris2.10 -I. -I/usr/local/include/ImageMagick -I/usr/local/include/ImageMagick conftest.c -L. - L/usr/local/lib -Wl,-R/usr/local/lib -L/usr/local/lib -L/usr/local/lib -R/usr/local/lib -lfreetype -lz -L/usr/local/lib -L/usr/local/lib -lMagickCore -lruby-static - lMagick -ldl -lcrypt -lm -lc" ld: fatal: library -lMagick: not found ld: fatal: File processing errors. No output written to conftest ``` This is on Solaris 10 x86 with ImageMagick version 6.4.3 and RMagick version 2.6.0 If I need to add something to LDFLAGS, its not clear to me what that would be. I installed ImageMagick from source and it should be in the usual places. ie, ``` # ls -l /usr/local/lib/ | grep -i magick drwxr-xr-x 5 root root 512 Sep 24 23:09 ImageMagick-6.4.3/ -rw-r--r-- 1 root root 10808764 Sep 25 02:09 libMagickCore.a -rwxr-xr-x 1 root root 1440 Sep 25 02:09 libMagickCore.la* -rw-r--r-- 1 root root 2327072 Sep 25 02:09 libMagickWand.a -rwxr-xr-x 1 root root 1472 Sep 25 02:09 libMagickWand.la* ``` ImageMagick-6.4.3/ contains nothing interesting and I can't find any other files that I might be able to point gem install at. Any advice would be much appreciated!! googling hasn't been too helpful. thanks -
problem solved. RMagick was unable to find ImageMagick because I neglected to build the shared objects (there were no .so files installed as you can see from the "ls" in the original question). The solution was to add `--with-shared` to my configure options. This however caused other problems. Most notably, `make` failing with "undefined symbol" messages for libiconv. This was solved by setting CFLAGS to point to libiconv: ``` export CFLAGS="-liconv" ``` Ultimately, my successful configure command was: ``` ./configure --disable-static --with-modules --without-perl --with-quantum-depth=8 --with-bzlib=no --with-libiconv ``` and after that, `make`, `make install`, and `gem install rmagick` all worked smoothly. thanks, R
131,217
<p>In one of our application im getting an exception that i can not seem to find or trap. </p> <pre><code>... Application.CreateForm(TFrmMain, FrmMain); outputdebugstring(pansichar('Application Run')); //this is printed Application.Run; outputdebugstring(pansichar('Application Run After')); //this is printed end. &lt;--- The Exception seems to be here </code></pre> <p>The Event log shows</p> <pre><code>&gt; ODS: Application Run &gt; //Various Application Messages &gt; ODS: Application Run After &gt; First Change Exception at $xxxxxxxx. ...etc </code></pre> <p>All i can think of is it is the finalization code of one of the units.</p> <p>(Delphi 7)</p>
[ { "answer_id": 131233, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": true, "text": "<p>Try installing <a href=\"http://www.madshi.net/\" rel=\"noreferrer\">MadExcept</a> - it should catch the exception and give you a stack-trace.</p>\n\n<p>It helped me when I had a similar issue.</p>\n" }, { "answer_id": 131280, "author": "Zartog", "author_id": 9467, "author_profile": "https://Stackoverflow.com/users/9467", "pm_score": 2, "selected": false, "text": "<p>Here's two things you can try:</p>\n\n<p>1) Quick and easy is to to hit 'F7' on the final 'end.'. This will step you into the other finalization blocks.</p>\n\n<p>2) Try overriding the Application.OnException Event.</p>\n" }, { "answer_id": 131342, "author": "Malcolm Groves", "author_id": 21463, "author_profile": "https://Stackoverflow.com/users/21463", "pm_score": 2, "selected": false, "text": "<p>The SysUtils unit actually sets up the default ErrorProc and ExceptProc procedures in its initialization section, and undoes them in its finalization section, so often in this situation it's worth ensuring that SysUtils is the very first unit in the uses clause in your dpr, so then it will be the last one finalised. Might be enough to get you some meaningful data about what is going wrong.</p>\n" }, { "answer_id": 131631, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 2, "selected": false, "text": "<p>Finalization exceptions are tricky. Even if you put <em>SysUtls</em> first in your project file, your application object may already be gone, which means your global exception handler is gone too. <em>MadExcept</em> may work for this though.</p>\n\n<p>Another solution is to put a <strong>Try</strong> / <strong>Except</strong> block in each of your unit <strong>finalization</strong> sections, and then handle the exceptions there. </p>\n\n<p>What is your objective? Do you want to suppress the exception or debug it? Debugging it can be done by stepping through them with <strong>F7</strong> as Zartog suggested. If you discover which unit has the exception in <strong>finalization</strong> then you might try placing it in a different order in the uses clause it is called from. </p>\n\n<p>Good luck!</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11016/" ]
In one of our application im getting an exception that i can not seem to find or trap. ``` ... Application.CreateForm(TFrmMain, FrmMain); outputdebugstring(pansichar('Application Run')); //this is printed Application.Run; outputdebugstring(pansichar('Application Run After')); //this is printed end. <--- The Exception seems to be here ``` The Event log shows ``` > ODS: Application Run > //Various Application Messages > ODS: Application Run After > First Change Exception at $xxxxxxxx. ...etc ``` All i can think of is it is the finalization code of one of the units. (Delphi 7)
Try installing [MadExcept](http://www.madshi.net/) - it should catch the exception and give you a stack-trace. It helped me when I had a similar issue.
131,238
<p>In Sharepoint designer's workflow editor I wish to retrieve the username/name of the work flow initiator (i.e. who kicked it off or triggered the workflow) - this is relatively easy to do using 3rd party products such as Nintex Workflow 2007 (where I would use something like {Common:Initiator}) - but I can't seem to find any way out of the box to do this using share point designer and MOSS 2007.</p> <p><strong>Update</strong></p> <p>It does not look like this rather obvious feature is supported OOTB, so I ended up writing a custom activity (as suggested by one of the answers). I have listed the activities code here for reference though I suspect there are probably a few instances of this floating around out there on blogs as it's a pretty trivial solution:</p> <pre><code>public partial class LookupInitiatorInfo : Activity { public static DependencyProperty __ActivationPropertiesProperty = DependencyProperty.Register("__ActivationProperties", typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties), typeof(LookupInitiatorInfo)); public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof (WorkflowContext), typeof (LookupInitiatorInfo)); public static DependencyProperty PropertyValueVariableProperty = DependencyProperty.Register("PropertyValueVariable", typeof (string), typeof(LookupInitiatorInfo)); public static DependencyProperty UserPropertyProperty = DependencyProperty.Register("UserProperty", typeof (string), typeof (LookupInitiatorInfo)); public LookupInitiatorInfo() { InitializeComponent(); } [Description("ActivationProperties")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties { get { return ((Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)(base.GetValue(__ActivationPropertiesProperty))); } set { base.SetValue(__ActivationPropertiesProperty, value); } } [Description("Context")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public WorkflowContext __Context { get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); } set { base.SetValue(__ContextProperty, value); } } [Description("UserProperty")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string UserProperty { get { return ((string) (base.GetValue(UserPropertyProperty))); } set { base.SetValue(UserPropertyProperty, value); } } [Description("PropertyValueVariable")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string PropertyValueVariable { get { return ((string) (base.GetValue(PropertyValueVariableProperty))); } set { base.SetValue(PropertyValueVariableProperty, value); } } protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // value values for the UserProperty (in most cases you // would use LoginName or Name) //Sid //ID //LoginName //Name //IsDomainGroup //Email //RawSid //Notes try { string err = string.Empty; if (__ActivationProperties == null) { err = "__ActivationProperties was null"; } else { SPUser user = __ActivationProperties.OriginatorUser; if (user != null &amp;&amp; UserProperty != null) { PropertyInfo property = typeof (SPUser).GetProperty(UserProperty); if (property != null) { object value = property.GetValue(user, null); PropertyValueVariable = (value != null) ? value.ToString() : ""; } else { err = string.Format("no property found with the name \"{0}\"", UserProperty); } } else { err = "__ActivationProperties.OriginatorUser was null"; } } if (!string.IsNullOrEmpty(err)) Common.LogExceptionToWorkflowHistory(new ArgumentOutOfRangeException(err), executionContext, WorkflowInstanceId); } catch (Exception e) { Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId); } return ActivityExecutionStatus.Closed; } } </code></pre> <p>And then wire it up with the following .action xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;WorkflowInfo Language="en-us"&gt; &lt;Actions&gt; &lt;Action Name="Lookup initiator user property" ClassName="XXX.ActivityLibrary.LookupInitiatorInfo" Assembly="XXX.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX" AppliesTo="all" Category="WormaldWorkflow Custom Actions"&gt; &lt;RuleDesigner Sentence="Lookup initating users property named %1 and store in %2"&gt; &lt;FieldBind Field="UserProperty" DesignerType="TextArea" Id="1" Text="LoginName" /&gt; &lt;FieldBind Field="PropertyValueVariable" DesignerType="ParameterNames" Text="variable" Id="2"/&gt; &lt;/RuleDesigner&gt; &lt;Parameters&gt; &lt;Parameter Name="__Context" Type="Microsoft.Sharepoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In"/&gt; &lt;Parameter Name="__ActivationProperties" Type="Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint" Direction="In"/&gt; &lt;Parameter Name="UserProperty" Type="System.String, mscorlib" Direction="In" /&gt; &lt;Parameter Name="PropertyValueVariable" Type="System.String, mscorlib" Direction="Out" /&gt; &lt;/Parameters&gt; &lt;/Action&gt; &lt;/Actions&gt; &lt;/WorkflowInfo&gt; </code></pre>
[ { "answer_id": 131999, "author": "Bryan Friedman", "author_id": 16985, "author_profile": "https://Stackoverflow.com/users/16985", "pm_score": 3, "selected": true, "text": "<p>I don't think this is possible to do in SharePoint Designer out of the box. You could probably write a custom action to get the originator, but I don't believe it is exposed through the SPD workflow interface at all. </p>\n\n<p>The best you could probably do is get the user who created or modified the item in the list, but this wouldn't handle cases where the workflow was manually run.</p>\n" }, { "answer_id": 1760129, "author": "Behnam", "author_id": 148264, "author_profile": "https://Stackoverflow.com/users/148264", "pm_score": 1, "selected": false, "text": "<p>I can think about a simple but not very sophisticated solution for this one by using just SPD. Just in workflow steps create a test item in a secondary list (probably a task list which stores the workflowId and itemId properties for refrence back) and then do a lookup in your workflow on that list to see who is the creator of that item, that value would be the current workflow initiator.</p>\n" }, { "answer_id": 4876994, "author": "Bkwdesign", "author_id": 114543, "author_profile": "https://Stackoverflow.com/users/114543", "pm_score": 3, "selected": false, "text": "<p>For those that google into this article and are now using SharePoint 2010, the workflow initiator variable is now supported OOTB in SharePoint Designer.</p>\n\n<p>The datasource would be \"Workflow Context\" and the field is, of course, \"Initiator\" and you can choose to return it as the \"Display Name\", \"Email\", \"Login Name\" or the \"User ID Number\"</p>\n" }, { "answer_id": 7404681, "author": "germandb", "author_id": 202866, "author_profile": "https://Stackoverflow.com/users/202866", "pm_score": 0, "selected": false, "text": "<p>The custom activity solution only work if you are working with moss, if you only have wss 3.0 you can put one step more in your workflow and set a custom comment field with any information, this make the last modified person to change and become the same as the workflow initiator, then you can use the ModifiedBy field to make any decision that you need.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4843/" ]
In Sharepoint designer's workflow editor I wish to retrieve the username/name of the work flow initiator (i.e. who kicked it off or triggered the workflow) - this is relatively easy to do using 3rd party products such as Nintex Workflow 2007 (where I would use something like {Common:Initiator}) - but I can't seem to find any way out of the box to do this using share point designer and MOSS 2007. **Update** It does not look like this rather obvious feature is supported OOTB, so I ended up writing a custom activity (as suggested by one of the answers). I have listed the activities code here for reference though I suspect there are probably a few instances of this floating around out there on blogs as it's a pretty trivial solution: ``` public partial class LookupInitiatorInfo : Activity { public static DependencyProperty __ActivationPropertiesProperty = DependencyProperty.Register("__ActivationProperties", typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties), typeof(LookupInitiatorInfo)); public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof (WorkflowContext), typeof (LookupInitiatorInfo)); public static DependencyProperty PropertyValueVariableProperty = DependencyProperty.Register("PropertyValueVariable", typeof (string), typeof(LookupInitiatorInfo)); public static DependencyProperty UserPropertyProperty = DependencyProperty.Register("UserProperty", typeof (string), typeof (LookupInitiatorInfo)); public LookupInitiatorInfo() { InitializeComponent(); } [Description("ActivationProperties")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties { get { return ((Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)(base.GetValue(__ActivationPropertiesProperty))); } set { base.SetValue(__ActivationPropertiesProperty, value); } } [Description("Context")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public WorkflowContext __Context { get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); } set { base.SetValue(__ContextProperty, value); } } [Description("UserProperty")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string UserProperty { get { return ((string) (base.GetValue(UserPropertyProperty))); } set { base.SetValue(UserPropertyProperty, value); } } [Description("PropertyValueVariable")] [ValidationOption(ValidationOption.Required)] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public string PropertyValueVariable { get { return ((string) (base.GetValue(PropertyValueVariableProperty))); } set { base.SetValue(PropertyValueVariableProperty, value); } } protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // value values for the UserProperty (in most cases you // would use LoginName or Name) //Sid //ID //LoginName //Name //IsDomainGroup //Email //RawSid //Notes try { string err = string.Empty; if (__ActivationProperties == null) { err = "__ActivationProperties was null"; } else { SPUser user = __ActivationProperties.OriginatorUser; if (user != null && UserProperty != null) { PropertyInfo property = typeof (SPUser).GetProperty(UserProperty); if (property != null) { object value = property.GetValue(user, null); PropertyValueVariable = (value != null) ? value.ToString() : ""; } else { err = string.Format("no property found with the name \"{0}\"", UserProperty); } } else { err = "__ActivationProperties.OriginatorUser was null"; } } if (!string.IsNullOrEmpty(err)) Common.LogExceptionToWorkflowHistory(new ArgumentOutOfRangeException(err), executionContext, WorkflowInstanceId); } catch (Exception e) { Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId); } return ActivityExecutionStatus.Closed; } } ``` And then wire it up with the following .action xml file: ``` <?xml version="1.0" encoding="utf-8"?> <WorkflowInfo Language="en-us"> <Actions> <Action Name="Lookup initiator user property" ClassName="XXX.ActivityLibrary.LookupInitiatorInfo" Assembly="XXX.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX" AppliesTo="all" Category="WormaldWorkflow Custom Actions"> <RuleDesigner Sentence="Lookup initating users property named %1 and store in %2"> <FieldBind Field="UserProperty" DesignerType="TextArea" Id="1" Text="LoginName" /> <FieldBind Field="PropertyValueVariable" DesignerType="ParameterNames" Text="variable" Id="2"/> </RuleDesigner> <Parameters> <Parameter Name="__Context" Type="Microsoft.Sharepoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In"/> <Parameter Name="__ActivationProperties" Type="Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint" Direction="In"/> <Parameter Name="UserProperty" Type="System.String, mscorlib" Direction="In" /> <Parameter Name="PropertyValueVariable" Type="System.String, mscorlib" Direction="Out" /> </Parameters> </Action> </Actions> </WorkflowInfo> ```
I don't think this is possible to do in SharePoint Designer out of the box. You could probably write a custom action to get the originator, but I don't believe it is exposed through the SPD workflow interface at all. The best you could probably do is get the user who created or modified the item in the list, but this wouldn't handle cases where the workflow was manually run.
131,241
<p>Take the following two lines of code:</p> <pre><code>for (int i = 0; i &lt; some_vector.size(); i++) { //do stuff } </code></pre> <p>And this:</p> <pre><code>for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); some_iterator++) { //do stuff } </code></pre> <p>I'm told that the second way is preferred. Why exactly is this?</p>
[ { "answer_id": 131253, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 6, "selected": false, "text": "<p>because you are not tying your code to the particular implementation of the some_vector list. if you use array indices, it has to be some form of array; if you use iterators you can use that code on any list implementation.</p>\n" }, { "answer_id": 131254, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "<p>I don't think it makes much difference for a vector. I prefer to use an index myself as I consider it to be more readable and you can do random access like jumping forward 6 items or jumping backwards if needs be.</p>\n\n<p>I also like to make a reference to the item inside the loop like this so there are not a lot of square brackets around the place:</p>\n\n<pre><code>for(size_t i = 0; i &lt; myvector.size(); i++)\n{\n MyClass &amp;item = myvector[i];\n\n // Do stuff to \"item\".\n}\n</code></pre>\n\n<p>Using an iterator can be good if you think you might need to replace the vector with a list at some point in the future and it also looks more stylish to the STL freaks but I can't think of any other reason.</p>\n" }, { "answer_id": 131259, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 4, "selected": false, "text": "<p>Because it is more object-oriented. if you are iterating with an index you are assuming:</p>\n\n<p>a) that those objects are ordered<br>\nb) that those objects can be obtained by an index<br>\nc) that the index increment will hit every item<br>\nd) that that index starts at zero</p>\n\n<p>With an iterator, you are saying \"give me everything so I can work with it\" without knowing what the underlying implementation is. (In Java, there are collections that cannot be accessed through an index)</p>\n\n<p>Also, with an iterator, no need to worry about going out of bounds of the array.</p>\n" }, { "answer_id": 131267, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 5, "selected": false, "text": "<p>Imagine some_vector is implemented with a linked-list. Then requesting an item in the i-th place requires i operations to be done to traverse the list of nodes. Now, if you use iterator, generally speaking, it will make its best effort to be as efficient as possible (in the case of a linked list, it will maintain a pointer to the current node and advance it in each iteration, requiring just a single operation).</p>\n\n<p>So it provides two things:</p>\n\n<ul>\n<li>Abstraction of use: you just want to iterate some elements, you don't care about how to do it</li>\n<li>Performance</li>\n</ul>\n" }, { "answer_id": 131271, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 9, "selected": true, "text": "<p>The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in</p>\n\n<pre><code>T elem = some_vector[i];\n</code></pre>\n\n<p>then you're making the assumption that the container has <code>operator[](std::size_t)</code> defined. Again, this is true for vector but not for other containers.</p>\n\n<p>The use of iterators bring you closer to <strong>container independence</strong>. You're not making assumptions about random-access ability or fast <code>size()</code> operation, only that the container has iterator capabilities.</p>\n\n<p>You could enhance your code further by using standard algorithms. Depending on what it is you're trying to achieve, you may elect to use <code>std::for_each()</code>, <code>std::transform()</code> and so on. By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. Your code is likely to be more efficient (given the right algorithm is chosen), correct and reusable.</p>\n" }, { "answer_id": 131304, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "<p>Aside from all of the other excellent answers... <code>int</code> may not be large enough for your vector. Instead, if you want to use indexing, use the <code>size_type</code> for your container:</p>\n\n<pre><code>for (std::vector&lt;Foo&gt;::size_type i = 0; i &lt; myvector.size(); ++i)\n{\n Foo&amp; this_foo = myvector[i];\n // Do stuff with this_foo\n}\n</code></pre>\n" }, { "answer_id": 131305, "author": "Colen", "author_id": 13500, "author_profile": "https://Stackoverflow.com/users/13500", "pm_score": 2, "selected": false, "text": "<p>The second form represents what you're doing more accurately. In your example, you don't care about the value of i, really - all you want is the next element in the iterator.</p>\n" }, { "answer_id": 131319, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 5, "selected": false, "text": "<p>You might want to use an iterator if you are going to add/remove items to the vector while you are iterating over it.</p>\n\n<pre><code>some_iterator = some_vector.begin(); \nwhile (some_iterator != some_vector.end())\n{\n if (/* some condition */)\n {\n some_iterator = some_vector.erase(some_iterator);\n // some_iterator now positioned at the element after the deleted element\n }\n else\n {\n if (/* some other condition */)\n {\n some_iterator = some_vector.insert(some_iterator, some_new_value);\n // some_iterator now positioned at new element\n }\n ++some_iterator;\n }\n}\n</code></pre>\n\n<p>If you were using indices you would have to shuffle items up/down in the array to handle the insertions and deletions.</p>\n" }, { "answer_id": 131324, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "<p>Another nice thing about iterators is that they better allow you to express (and enforce) your const-preference. This example ensures that you will not be altering the vector in the midst of your loop:</p>\n\n<pre><code>\nfor(std::vector&lt;Foo&gt;::const_iterator pos=foos.begin(); pos != foos.end(); ++pos)\n{\n // Foo & foo = *pos; // this won't compile\n const Foo & foo = *pos; // this will compile\n}\n</code></pre>\n" }, { "answer_id": 131351, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": false, "text": "<p>It's part of the modern C++ indoctrination process. Iterators are the only way to iterate most containers, so you use it even with vectors just to get yourself into the proper mindset. Seriously, that's the only reason I do it - I don't think I've ever replaced a vector with a different kind of container.\n<hr>\nWow, this is still getting downvoted after three weeks. I guess it doesn't pay to be a little tongue-in-cheek.</p>\n\n<p>I think the array index is more readable. It matches the syntax used in other languages, and the syntax used for old-fashioned C arrays. It's also less verbose. Efficiency should be a wash if your compiler is any good, and there are hardly any cases where it matters anyway.</p>\n\n<p>Even so, I still find myself using iterators frequently with vectors. I believe the iterator is an important concept, so I promote it whenever I can.</p>\n" }, { "answer_id": 131469, "author": "Sergey Stolyarov", "author_id": 15958, "author_profile": "https://Stackoverflow.com/users/15958", "pm_score": 2, "selected": false, "text": "<p>During iteration you don't need to know number of item to be processed. You just need the item and iterators do such things very good.</p>\n" }, { "answer_id": 131534, "author": "Chad", "author_id": 17382, "author_profile": "https://Stackoverflow.com/users/17382", "pm_score": 5, "selected": false, "text": "<p>I'm going to be the devils advocate here, and not recommend iterators. The main reason why, is all the source code I've worked on from Desktop application development to game development have i nor have i needed to use iterators. All the time they have not been required and secondly the hidden assumptions and code mess and debugging nightmares you get with iterators make them a prime example not to use it in any applications that require speed. </p>\n\n<p>Even from a maintence stand point they're a mess. Its not because of them but because of all the aliasing that happen behind the scene. How do i know that you haven't implemented your own virtual vector or array list that does something completely different to the standards. Do i know what type is currently now during runtime? Did you overload a operator I didn't have time to check all your source code. Hell do i even know what version of the STL your using?</p>\n\n<p>The next problem you got with iterators is leaky abstraction, though there are numerous web sites that discuss this in detail with them.</p>\n\n<p>Sorry, I have not and still have not seen any point in iterators. If they abstract the list or vector away from you, when in fact you should know already what vector or list your dealing with if you don't then your just going to be setting yourself up for some great debugging sessions in the future.</p>\n" }, { "answer_id": 131541, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 0, "selected": false, "text": "<p>Even better than \"telling the CPU what to do\" (imperative) is \"telling the libraries what you want\" (functional).</p>\n\n<p>So instead of using loops you should learn the algorithms present in stl.</p>\n" }, { "answer_id": 131725, "author": "Krirk", "author_id": 17521, "author_profile": "https://Stackoverflow.com/users/17521", "pm_score": 0, "selected": false, "text": "<p>I always use array index because many application of mine require something like \"display thumbnail image\". So I wrote something like this:</p>\n\n<pre><code>some_vector[0].left=0;\nsome_vector[0].top =0;&lt;br&gt;\n\nfor (int i = 1; i &lt; some_vector.size(); i++)\n{\n\n some_vector[i].left = some_vector[i-1].width + some_vector[i-1].left;\n if(i % 6 ==0)\n {\n some_vector[i].top = some_vector[i].top.height + some_vector[i].top;\n some_vector[i].left = 0;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 132125, "author": "user22044", "author_id": 22044, "author_profile": "https://Stackoverflow.com/users/22044", "pm_score": 1, "selected": false, "text": "<p>Several good points already. I have a few additional comments:</p>\n\n<ol>\n<li><p>Assuming we are talking about the C++ standard library, \"vector\" implies a random access container that has the guarantees of C-array (random access, contiguos memory layout etc). If you had said 'some_container', many of the above answers would have been more accurate (container independence etc).</p></li>\n<li><p>To eliminate any dependencies on compiler optimization, you could move some_vector.size() out of the loop in the indexed code, like so:</p>\n\n<pre>const size_t numElems = some_vector.size();\nfor (size_t i = 0; i </li>\n<li><p>Always pre-increment iterators and treat post-increments as exceptional cases.</p></li>\n</ol>\n\nfor (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); ++some_iterator){ //do stuff }</pre>\n\n<p>So assuming and indexable <code>std::vector&lt;&gt;</code> like container, there is no good reason to prefer one over other, sequentially going through the container. If you have to refer to older or newer elemnent indexes frequently, then the indexed version is more appropropriate.</p>\n\n<p>In general, using the iterators is preferred because algorithms make use of them and behavior can be controlled (and implicitly documented) by changing the type of the iterator. Array locations can be used in place of iterators, but the syntactical difference will stick out.</p>\n" }, { "answer_id": 132672, "author": "all2one", "author_id": 6773, "author_profile": "https://Stackoverflow.com/users/6773", "pm_score": 0, "selected": false, "text": "<p>For container independence</p>\n" }, { "answer_id": 133367, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 3, "selected": false, "text": "<p>STL iterators are mostly there so that the STL algorithms like sort can be container independent. </p>\n\n<p>If you just want to loop over all the entries in a vector just use the index loop style. </p>\n\n<p>It is less typing and easier to parse for most humans. It would be nice if C++ had a simple foreach loop without going overboard with template magic.</p>\n\n<pre><code>for( size_t i = 0; i &lt; some_vector.size(); ++i )\n{\n T&amp; rT = some_vector[i];\n // now do something with rT\n}\n'\n</code></pre>\n" }, { "answer_id": 138933, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 4, "selected": false, "text": "<p>I probably should point out you can also call</p>\n\n<p><code>std::for_each(some_vector.begin(), some_vector.end(), &amp;do_stuff);</code></p>\n" }, { "answer_id": 144357, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 4, "selected": false, "text": "<h2>Separation of Concerns</h2>\n\n<p>It's very nice to separate the iteration code from the 'core' concern of the loop. It's almost a design decision.</p>\n\n<p>Indeed, iterating by index ties you to the implementation of the container. Asking the container for a begin and end iterator, enables the loop code for use with other container types.</p>\n\n<p>Also, in the <code>std::for_each</code> way, you <a href=\"http://www.pragmaticprogrammer.com/articles/tell-dont-ask\" rel=\"nofollow noreferrer\">TELL the collection what to do, instead of ASKing</a> it something about its internals</p>\n\n<p>The 0x standard is going to introduce closures, which will make this approach much more easy to use - have a look at the expressive power of e.g. Ruby's <code>[1..6].each { |i| print i; }</code>...</p>\n\n<h2>Performance</h2>\n\n<p>But maybe a much overseen issue is that, using the <code>for_each</code> approach yields an opportunity to have the iteration parallelized - the <a href=\"http://www.threadingbuildingblocks.org/\" rel=\"nofollow noreferrer\">intel threading blocks</a> can distribute the code block over the number of processors in the system!</p>\n\n<p>Note: after discovering the <code>algorithms</code> library, and especially <code>foreach</code>, I went through two or three months of writing ridiculously small 'helper' operator structs which will drive your fellow developers crazy. After this time, I went back to a pragmatic approach - small loop bodies deserve no <code>foreach</code> no more :)</p>\n\n<p>A must read reference on iterators is the book <a href=\"http://blog.extendedstl.com/\" rel=\"nofollow noreferrer\">\"Extended STL\"</a>.</p>\n\n<p>The GoF have a tiny little paragraph in the end of the Iterator pattern, which talks about this brand of iteration; it's called an 'internal iterator'. Have a look <a href=\"http://gafter.blogspot.com/2007/07/internal-versus-external-iterators.html\" rel=\"nofollow noreferrer\">here</a>, too.</p>\n" }, { "answer_id": 373053, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>After having learned a little more on the subject of this answer, I realize it was a bit of an oversimplification. The difference between this loop:</p>\n\n<pre><code>for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();\n some_iterator++)\n{\n //do stuff\n}\n</code></pre>\n\n<p>And this loop:</p>\n\n<pre><code>for (int i = 0; i &lt; some_vector.size(); i++)\n{\n //do stuff\n}\n</code></pre>\n\n<p>Is fairly minimal. In fact, the syntax of doing loops this way seems to be growing on me:</p>\n\n<pre><code>while (it != end){\n //do stuff\n ++it;\n}\n</code></pre>\n\n<p>Iterators do unlock some fairly powerful declarative features, and when combined with the STL algorithms library you can do some pretty cool things that are outside the scope of array index administrivia.</p>\n" }, { "answer_id": 838279, "author": "Marc Eaddy", "author_id": 25029, "author_profile": "https://Stackoverflow.com/users/25029", "pm_score": 2, "selected": false, "text": "<p>Indexing requires an extra <code>mul</code> operation. For example, for <code>vector&lt;int&gt; v</code>, the compiler converts <code>v[i]</code> into <code>&amp;v + sizeof(int) * i</code>.</p>\n" }, { "answer_id": 1118103, "author": "AareP", "author_id": 11741, "author_profile": "https://Stackoverflow.com/users/11741", "pm_score": 1, "selected": false, "text": "<p>I don't use iterators for the same reason I dislike foreach-statements. When having multiple inner-loops it's hard enough to keep track of global/member variables without having to remember all the local values and iterator-names as well. What I find useful is to use two sets of indices for different occasions:</p>\n\n<pre><code>for(int i=0;i&lt;anims.size();i++)\n for(int j=0;j&lt;bones.size();j++)\n {\n int animIndex = i;\n int boneIndex = j;\n\n\n // in relatively short code I use indices i and j\n ... animation_matrices[i][j] ...\n\n // in long and complicated code I use indices animIndex and boneIndex\n ... animation_matrices[animIndex][boneIndex] ...\n\n\n }\n</code></pre>\n\n<p>I don't even want to abbreviate things like \"animation_matrices[i]\" to some random \"anim_matrix\"-named-iterator for example, because then you can't see clearly from which array this value is originated.</p>\n" }, { "answer_id": 11292392, "author": "Messiah", "author_id": 1495868, "author_profile": "https://Stackoverflow.com/users/1495868", "pm_score": 0, "selected": false, "text": "<p>Both the implementations are correct, but I would prefer the 'for' loop. As we have decided to use a Vector and not any other container, using indexes would be the best option. Using iterators with Vectors would lose the very benefit of having the objects in continuous memory blocks which help ease in their access.</p>\n" }, { "answer_id": 33719931, "author": "Engineer", "author_id": 279738, "author_profile": "https://Stackoverflow.com/users/279738", "pm_score": 1, "selected": false, "text": "<ul>\n<li>If you like being close to the metal / don't trust their implementation details, <strong>don't use</strong> iterators.</li>\n<li>If you regularly switch out one collection type for another during development, <strong>use</strong> iterators.</li>\n<li>If you find it difficult to remember how to iterate different sorts of collections (maybe you have several types from several different external sources in use), <strong>use</strong> iterators to unify the means by which you walk over elements. This applies to say switching a linked list with an array list.</li>\n</ul>\n\n<p>Really, that's all there is to it. It's not as if you're going to gain more brevity either way on average, and if brevity really is your goal, you can always fall back on macros.</p>\n" }, { "answer_id": 46161362, "author": "danpla", "author_id": 7225714, "author_profile": "https://Stackoverflow.com/users/7225714", "pm_score": 2, "selected": false, "text": "<p>No one mentioned yet that one advantage of indices is that they are not become invalid when you append to a contiguous container like <code>std::vector</code>, so you can add items to the container during iteration.</p>\n\n<p>This is also possible with iterators, but you must call <code>reserve()</code>, and therefore need to know how many items you'll append.</p>\n" }, { "answer_id": 59079263, "author": "Marcus Harrison", "author_id": 3292006, "author_profile": "https://Stackoverflow.com/users/3292006", "pm_score": 0, "selected": false, "text": "<p>I felt that none of the answers here explain why I like iterators as a general concept over indexing into containers. Note that most of my experience using iterators doesn't actually come from C++ but from higher-level programming languages like Python.</p>\n\n<p>The iterator interface imposes fewer requirements on consumers of your function, which allows consumers to do more with it.</p>\n\n<p>If all you need is to be able to forward-iterate, the developer isn't limited to using indexable containers - they can use any class implementing <code>operator++(T&amp;)</code>, <code>operator*(T)</code> and <code>operator!=(const &amp;T, const &amp;T)</code>.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\ntemplate &lt;class InputIterator&gt;\nvoid printAll(InputIterator&amp; begin, InputIterator&amp; end)\n{\n for (auto current = begin; current != end; ++current) {\n std::cout &lt;&lt; *current &lt;&lt; \"\\n\";\n }\n}\n\n// elsewhere...\n\nprintAll(myVector.begin(), myVector.end());\n</code></pre>\n\n<p>Your algorithm works for the case you need it - iterating over a vector - but it can also be useful for applications you don't necessarily anticipate:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;random&gt;\n\nclass RandomIterator\n{\nprivate:\n std::mt19937 random;\n std::uint_fast32_t current;\n std::uint_fast32_t floor;\n std::uint_fast32_t ceil;\n\npublic:\n RandomIterator(\n std::uint_fast32_t floor = 0,\n std::uint_fast32_t ceil = UINT_FAST32_MAX,\n std::uint_fast32_t seed = std::mt19937::default_seed\n ) :\n floor(floor),\n ceil(ceil)\n {\n random.seed(seed);\n ++(*this);\n }\n\n RandomIterator&amp; operator++()\n {\n current = floor + (random() % (ceil - floor));\n }\n\n std::uint_fast32_t operator*() const\n {\n return current;\n }\n\n bool operator!=(const RandomIterator &amp;that) const\n {\n return current != that.current;\n }\n};\n\nint main()\n{\n // roll a 1d6 until we get a 6 and print the results\n RandomIterator firstRandom(1, 7, std::random_device()());\n RandomIterator secondRandom(6, 7);\n printAll(firstRandom, secondRandom);\n\n return 0;\n}\n</code></pre>\n\n<p>Attempting to implement a square-brackets operator which does something similar to this iterator would be contrived, while the iterator implementation is relatively simple. The square-brackets operator also makes implications about the capabilities of your class - that you can index to any arbitrary point - which may be difficult or inefficient to implement.</p>\n\n<p>Iterators also lend themselves to <a href=\"https://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">decoration</a>. People can write iterators which take an iterator in their constructor and extend its functionality:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template&lt;class InputIterator, typename T&gt;\nclass FilterIterator\n{\nprivate:\n InputIterator internalIterator;\n\npublic:\n FilterIterator(const InputIterator &amp;iterator):\n internalIterator(iterator)\n {\n }\n\n virtual bool condition(T) = 0;\n\n FilterIterator&lt;InputIterator, T&gt;&amp; operator++()\n {\n do {\n ++(internalIterator);\n } while (!condition(*internalIterator));\n\n return *this;\n }\n\n T operator*()\n {\n // Needed for the first result\n if (!condition(*internalIterator))\n ++(*this);\n return *internalIterator;\n }\n\n virtual bool operator!=(const FilterIterator&amp; that) const\n {\n return internalIterator != that.internalIterator;\n }\n};\n\ntemplate &lt;class InputIterator&gt;\nclass EvenIterator : public FilterIterator&lt;InputIterator, std::uint_fast32_t&gt;\n{\npublic:\n EvenIterator(const InputIterator &amp;internalIterator) :\n FilterIterator&lt;InputIterator, std::uint_fast32_t&gt;(internalIterator)\n {\n }\n\n bool condition(std::uint_fast32_t n)\n {\n return !(n % 2);\n }\n};\n\n\nint main()\n{\n // Rolls a d20 until a 20 is rolled and discards odd rolls\n EvenIterator&lt;RandomIterator&gt; firstRandom(RandomIterator(1, 21, std::random_device()()));\n EvenIterator&lt;RandomIterator&gt; secondRandom(RandomIterator(20, 21));\n printAll(firstRandom, secondRandom);\n\n return 0;\n}\n</code></pre>\n\n<p>While these toys might seem mundane, it's not difficult to imagine using iterators and iterator decorators to do powerful things with a simple interface - decorating a forward-only iterator of database results with an iterator which constructs a model object from a single result, for example. These patterns enable memory-efficient iteration of infinite sets and, with a filter like the one I wrote above, potentially lazy evaluation of results.</p>\n\n<p>Part of the power of C++ templates is your iterator interface, when applied to the likes of fixed-length C arrays, <a href=\"https://en.cppreference.com/w/cpp/iterator/end\" rel=\"nofollow noreferrer\">decays to simple and efficient pointer arithmetic</a>, making it a truly zero-cost abstraction.</p>\n" }, { "answer_id": 60338688, "author": "honk", "author_id": 2675154, "author_profile": "https://Stackoverflow.com/users/2675154", "pm_score": 2, "selected": false, "text": "<p>If you have access to <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow noreferrer\">C++11</a> features, then you can also use a <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based <code>for</code> loop</a> for iterating over your vector (or any other container) as follows:</p>\n\n<pre><code>for (auto &amp;item : some_vector)\n{\n //do stuff\n}\n</code></pre>\n\n<p>The benefit of this loop is that you can access elements of the vector directly via the <code>item</code> variable, without running the risk of messing up an index or making a making a mistake when dereferencing an iterator. In addition, the placeholder <a href=\"https://en.cppreference.com/w/cpp/language/auto\" rel=\"nofollow noreferrer\"><code>auto</code></a> prevents you from having to repeat the type of the container elements,\nwhich brings you even closer to a container-independent solution.</p>\n\n<p>Notes:</p>\n\n<ul>\n<li>If you need the the element index in your loop and the <code>operator[]</code> exists for your container (and is fast enough for you), then better go for your first way.</li>\n<li>A range-based <code>for</code> loop cannot be used to add/delete elements into/from a container. If you want to do that, then better stick to the <a href=\"https://stackoverflow.com/a/131319/2675154\">solution</a> given by Brian Matthews.</li>\n<li>If you don't want to change the elements in your container, then you should use the keyword <code>const</code> as follows: <code>for (auto const &amp;item : some_vector) { ... }</code>.</li>\n</ul>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Take the following two lines of code: ``` for (int i = 0; i < some_vector.size(); i++) { //do stuff } ``` And this: ``` for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); some_iterator++) { //do stuff } ``` I'm told that the second way is preferred. Why exactly is this?
The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in ``` T elem = some_vector[i]; ``` then you're making the assumption that the container has `operator[](std::size_t)` defined. Again, this is true for vector but not for other containers. The use of iterators bring you closer to **container independence**. You're not making assumptions about random-access ability or fast `size()` operation, only that the container has iterator capabilities. You could enhance your code further by using standard algorithms. Depending on what it is you're trying to achieve, you may elect to use `std::for_each()`, `std::transform()` and so on. By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. Your code is likely to be more efficient (given the right algorithm is chosen), correct and reusable.
131,303
<p>How do you measure the memory usage of an application or process in Linux?</p> <p>From the blog article of <em><a href="http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html" rel="noreferrer">Understanding memory usage on Linux</a></em>, <code>ps</code> is not an accurate tool to use for this intent.</p> <blockquote> <p><strong>Why <code>ps</code> is &quot;wrong&quot;</strong></p> <p>Depending on how you look at it, <code>ps</code> is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up <strong>if it were the only process running</strong>. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by <code>ps</code> are almost definitely <em>wrong</em>.</p> </blockquote> <p><sub>(Note: This question is covered <a href="https://stackoverflow.com/q/63166/15161">here</a> in great detail.)</sub></p>
[ { "answer_id": 131346, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 10, "selected": true, "text": "<p>With <code>ps</code> or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but:</p>\n<ul>\n<li><p>does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it</p>\n</li>\n<li><p>can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries</p>\n</li>\n</ul>\n<p>If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, <a href=\"https://en.wikipedia.org/wiki/Valgrind\" rel=\"noreferrer\">Valgrind</a> can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif':</p>\n<blockquote>\n</blockquote>\n<p>Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal.</p>\n<p>As explained in the <a href=\"http://valgrind.org/docs/manual/ms-manual.html\" rel=\"noreferrer\">Valgrind documentation</a>, you need to run the program through Valgrind:</p>\n<pre><code>valgrind --tool=massif &lt;executable&gt; &lt;arguments&gt;\n</code></pre>\n<p>Massif writes a dump of memory usage snapshots (e.g. <code>massif.out.12345</code>). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is <a href=\"https://github.com/KDE/massif-visualizer\" rel=\"noreferrer\">massif-visualizer</a>. But I found <code>ms_print</code>, a simple text-based tool shipped with Valgrind, to be of great help already.</p>\n<p>To find memory leaks, use the (default) <code>memcheck</code> tool of valgrind.</p>\n" }, { "answer_id": 131399, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 8, "selected": false, "text": "<p>It is hard to tell for sure, but here are two &quot;close&quot; things that can help.</p>\n<pre><code>$ ps aux\n</code></pre>\n<p>will give you Virtual Size (VSZ)</p>\n<p>You can also get detailed statistics from the <em>/proc</em> file-system by going to <code>/proc/$pid/status</code>.</p>\n<p>The most important is the VmSize, which should be close to what <code>ps aux</code> gives.</p>\n<pre>\n/proc/19420$ cat status\nName: firefox\nState: S (sleeping)\nTgid: 19420\nPid: 19420\nPPid: 1\nTracerPid: 0\nUid: 1000 1000 1000 1000\nGid: 1000 1000 1000 1000\nFDSize: 256\nGroups: 4 6 20 24 25 29 30 44 46 107 109 115 124 1000\nVmPeak: 222956 kB\nVmSize: 212520 kB\nVmLck: 0 kB\nVmHWM: 127912 kB\nVmRSS: 118768 kB\nVmData: 170180 kB\nVmStk: 228 kB\nVmExe: 28 kB\nVmLib: 35424 kB\nVmPTE: 184 kB\nThreads: 8\nSigQ: 0/16382\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: 0000000000000000\nSigIgn: 0000000020001000\nSigCgt: 000000018000442f\nCapInh: 0000000000000000\nCapPrm: 0000000000000000\nCapEff: 0000000000000000\nCpus_allowed: 03\nMems_allowed: 1\nvoluntary_ctxt_switches: 63422\nnonvoluntary_ctxt_switches: 7171\n\n</pre>\n" }, { "answer_id": 131462, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 3, "selected": false, "text": "<p>Get <a href=\"https://en.wikipedia.org/wiki/Valgrind\" rel=\"nofollow noreferrer\">Valgrind</a>. Give it your program to run, and it'll tell you plenty about its memory usage.</p>\n<p>This would apply only for the case of a program that runs for some time and stops. I don't know if Valgrind can get its hands on an already-running process or shouldn't-stop processes such as daemons.</p>\n" }, { "answer_id": 133444, "author": "Bash", "author_id": 16051, "author_profile": "https://Stackoverflow.com/users/16051", "pm_score": 7, "selected": false, "text": "<p>There isn't any easy way to calculate this. But some people have tried to get some good answers:</p>\n<ul>\n<li><a href=\"http://www.pixelbeat.org/scripts/ps_mem.py\" rel=\"noreferrer\">ps_mem.py</a></li>\n<li><a href=\"https://raw.github.com/pixelb/ps_mem/master/ps_mem.py\" rel=\"noreferrer\">ps_mem.py at GitHub</a></li>\n</ul>\n" }, { "answer_id": 133520, "author": "Dan", "author_id": 8251, "author_profile": "https://Stackoverflow.com/users/8251", "pm_score": 2, "selected": false, "text": "<p>Another vote for <a href=\"https://en.wikipedia.org/wiki/Valgrind\" rel=\"nofollow noreferrer\">Valgrind</a> here, but I would like to add that you can use a tool like <a href=\"http://alleyoop.sourceforge.net/\" rel=\"nofollow noreferrer\">Alleyoop</a> to help you interpret the results generated by Valgrind.</p>\n<p>I use the two tools all the time and always have lean, non-leaky code to proudly show for it ;)</p>\n" }, { "answer_id": 147348, "author": "Dprado", "author_id": 21943, "author_profile": "https://Stackoverflow.com/users/21943", "pm_score": 5, "selected": false, "text": "<p>There isn't a single answer for this because you can't pin point precisely the amount of memory a process uses. Most processes under Linux use shared libraries.</p>\n<p>For instance, let's say you want to calculate memory usage for the 'ls' process. Do you count only the memory used by the executable 'ls' (if you could isolate it)? How about libc? Or all these other libraries that are required to run 'ls'?</p>\n<pre><code>linux-gate.so.1 =&gt; (0x00ccb000)\nlibrt.so.1 =&gt; /lib/librt.so.1 (0x06bc7000)\nlibacl.so.1 =&gt; /lib/libacl.so.1 (0x00230000)\nlibselinux.so.1 =&gt; /lib/libselinux.so.1 (0x00162000)\nlibc.so.6 =&gt; /lib/libc.so.6 (0x00b40000)\nlibpthread.so.0 =&gt; /lib/libpthread.so.0 (0x00cb4000)\n/lib/ld-linux.so.2 (0x00b1d000)\nlibattr.so.1 =&gt; /lib/libattr.so.1 (0x00229000)\nlibdl.so.2 =&gt; /lib/libdl.so.2 (0x00cae000)\nlibsepol.so.1 =&gt; /lib/libsepol.so.1 (0x0011a000)\n</code></pre>\n<p>You could argue that they are shared by other processes, but 'ls' can't be run on the system without them being loaded.</p>\n<p>Also, if you need to know how much memory a process needs in order to do capacity planning, you have to calculate how much each additional copy of the process uses. I think <em>/proc/PID/status</em> might give you enough information of the memory usage <em>at</em> a single time. On the other hand, <a href=\"https://en.wikipedia.org/wiki/Valgrind\" rel=\"nofollow noreferrer\">Valgrind</a> will give you a better profile of the memory usage throughout the lifetime of the program.</p>\n" }, { "answer_id": 1237930, "author": "Paul Biggar", "author_id": 104021, "author_profile": "https://Stackoverflow.com/users/104021", "pm_score": 7, "selected": false, "text": "<p>In recent versions of Linux, use the <em>smaps</em> subsystem. For example, for a process with a PID of 1234:</p>\n<pre><code>cat /proc/1234/smaps\n</code></pre>\n<p>It will tell you exactly how much memory it is using at that time. More importantly, it will divide the memory into private and shared, so you can tell how much memory your <em>instance</em> of the program is using, without including memory shared between multiple instances of the program.</p>\n" }, { "answer_id": 1238159, "author": "juanjux", "author_id": 150404, "author_profile": "https://Stackoverflow.com/users/150404", "pm_score": 2, "selected": false, "text": "<p>If you want something quicker than profiling with Valgrind and your kernel is older and you can't use smaps, a ps with the options to show the resident set of the process (with <code>ps -o rss,command</code>) can give you a quick and reasonable <code>_aproximation_</code> of the real amount of non-swapped memory being used.</p>\n" }, { "answer_id": 1491573, "author": "phoku", "author_id": 157410, "author_profile": "https://Stackoverflow.com/users/157410", "pm_score": 5, "selected": false, "text": "<p>This is an excellent summary of the tools and problems: <a href=\"http://web.archive.org/web/20110614010958/http://ktown.kde.org/%7Eseli/memory/analysis.html\" rel=\"noreferrer\">archive.org link</a></p>\n<p>I'll quote it, so that more devs will actually read it.</p>\n<blockquote>\n<p>If you want to analyse memory usage of the whole system or to thoroughly analyse memory usage of one application (not just its heap usage), use <strong>exmap</strong>. For whole system analysis, find processes with the highest effective usage, they take the most memory in practice, find processes with the highest writable usage, they create the most data (and therefore possibly leak or are very ineffective in their data usage). Select such application and analyse its mappings in the second listview. See exmap section for more details. Also use <strong>xrestop</strong> to check high usage of X resources, especially if the process of the X server takes a lot of memory. See xrestop section for details.</p>\n<p>If you want to detect leaks, use <strong>valgrind</strong> or possibly <strong>kmtrace</strong>.</p>\n<p>If you want to analyse heap (malloc etc.) usage of an application, either run it in <strong>memprof</strong> or with <strong>kmtrace</strong>, profile the application and search the function call tree for biggest allocations. See their sections for more details.</p>\n</blockquote>\n" }, { "answer_id": 1999717, "author": "holmes", "author_id": 239054, "author_profile": "https://Stackoverflow.com/users/239054", "pm_score": 4, "selected": false, "text": "<p><strong>Valgrind</strong> can show detailed information, but it <strong>slows down</strong> the target application significantly, and most of the time it changes the behavior of the application.</p>\n<p><strong>Exmap</strong> was something I didn't know yet, but it seems that you need a <strong>kernel module</strong> to get the information, which can be an obstacle.</p>\n<p>I assume what everyone wants to know with respect to &quot;memory usage&quot; is the following...\nIn Linux, the amount of physical memory a single process might use can be roughly divided into following categories.</p>\n<ul>\n<li><p><strong>M.a anonymous mapped memory</strong></p>\n</li>\n<li><p>.p private</p>\n<ul>\n<li>.d dirty == malloc/mmapped heap and stack allocated and written memory</li>\n<li>.c clean == malloc/mmapped heap and stack memory once allocated, written, then freed, but not reclaimed yet</li>\n</ul>\n</li>\n<li><p>.s shared</p>\n<ul>\n<li>.d dirty == <strong>malloc/mmaped heap could get copy-on-write and shared among processes</strong> (edited)</li>\n<li>.c clean == <strong>malloc/mmaped heap could get copy-on-write and shared among processes</strong> (edited)</li>\n</ul>\n</li>\n<li><p><strong>M.n named mapped memory</strong></p>\n</li>\n<li><p>.p private</p>\n<ul>\n<li>.d dirty == file mmapped written memory private</li>\n<li>.c clean == mapped program/library text private mapped</li>\n</ul>\n</li>\n<li><p>.s shared</p>\n<ul>\n<li>.d dirty == file mmapped written memory shared</li>\n<li>.c clean == mapped library text shared mapped</li>\n</ul>\n</li>\n</ul>\n<p>Utility included in Android called <strong>showmap</strong> is quite useful</p>\n<pre><code>virtual shared shared private private\nsize RSS PSS clean dirty clean dirty object\n-------- -------- -------- -------- -------- -------- -------- ------------------------------\n 4 0 0 0 0 0 0 0:00 0 [vsyscall]\n 4 4 0 4 0 0 0 [vdso]\n 88 28 28 0 0 4 24 [stack]\n 12 12 12 0 0 0 12 7909 /lib/ld-2.11.1.so\n 12 4 4 0 0 0 4 89529 /usr/lib/locale/en_US.utf8/LC_IDENTIFICATION\n 28 0 0 0 0 0 0 86661 /usr/lib/gconv/gconv-modules.cache\n 4 0 0 0 0 0 0 87660 /usr/lib/locale/en_US.utf8/LC_MEASUREMENT\n 4 0 0 0 0 0 0 89528 /usr/lib/locale/en_US.utf8/LC_TELEPHONE\n 4 0 0 0 0 0 0 89527 /usr/lib/locale/en_US.utf8/LC_ADDRESS\n 4 0 0 0 0 0 0 87717 /usr/lib/locale/en_US.utf8/LC_NAME\n 4 0 0 0 0 0 0 87873 /usr/lib/locale/en_US.utf8/LC_PAPER\n 4 0 0 0 0 0 0 13879 /usr/lib/locale/en_US.utf8/LC_MESSAGES/SYS_LC_MESSAGES\n 4 0 0 0 0 0 0 89526 /usr/lib/locale/en_US.utf8/LC_MONETARY\n 4 0 0 0 0 0 0 89525 /usr/lib/locale/en_US.utf8/LC_TIME\n 4 0 0 0 0 0 0 11378 /usr/lib/locale/en_US.utf8/LC_NUMERIC\n 1156 8 8 0 0 4 4 11372 /usr/lib/locale/en_US.utf8/LC_COLLATE\n 252 0 0 0 0 0 0 11321 /usr/lib/locale/en_US.utf8/LC_CTYPE\n 128 52 1 52 0 0 0 7909 /lib/ld-2.11.1.so\n 2316 32 11 24 0 0 8 7986 /lib/libncurses.so.5.7\n 2064 8 4 4 0 0 4 7947 /lib/libdl-2.11.1.so\n 3596 472 46 440 0 4 28 7933 /lib/libc-2.11.1.so\n 2084 4 0 4 0 0 0 7995 /lib/libnss_compat-2.11.1.so\n 2152 4 0 4 0 0 0 7993 /lib/libnsl-2.11.1.so\n 2092 0 0 0 0 0 0 8009 /lib/libnss_nis-2.11.1.so\n 2100 0 0 0 0 0 0 7999 /lib/libnss_files-2.11.1.so\n 3752 2736 2736 0 0 864 1872 [heap]\n 24 24 24 0 0 0 24 [anon]\n 916 616 131 584 0 0 32 /bin/bash\n-------- -------- -------- -------- -------- -------- -------- ------------------------------\n 22816 4004 3005 1116 0 876 2012 TOTAL\n</code></pre>\n" }, { "answer_id": 2816070, "author": "Anil", "author_id": 338950, "author_profile": "https://Stackoverflow.com/users/338950", "pm_score": 8, "selected": false, "text": "<p>Try the <a href=\"http://linux.die.net/man/1/pmap\" rel=\"noreferrer\">pmap</a> command:</p>\n\n<pre><code>sudo pmap -x &lt;process pid&gt;\n</code></pre>\n" }, { "answer_id": 3666523, "author": "CashCow", "author_id": 442284, "author_profile": "https://Stackoverflow.com/users/442284", "pm_score": 4, "selected": false, "text": "<p>If your code is in C or C++ you might be able to use <code>getrusage()</code> which returns you various statistics about memory and time usage of your process.</p>\n\n<p>Not all platforms support this though and will return 0 values for the memory-use options.</p>\n\n<p>Instead you can look at the virtual file created in <code>/proc/[pid]/statm</code> (where <code>[pid]</code> is replaced by your process id. You can obtain this from <code>getpid()</code>).</p>\n\n<p>This file will look like a text file with 7 integers. You are probably most interested in the first (all memory use) and sixth (data memory use) numbers in this file.</p>\n" }, { "answer_id": 5217434, "author": "Nick W.", "author_id": 647804, "author_profile": "https://Stackoverflow.com/users/647804", "pm_score": 3, "selected": false, "text": "<p>A good test of the more &quot;real world&quot; usage is to open the application, run <code>vmstat -s</code>, and check the &quot;active memory&quot; statistic. Close the application, wait a few seconds, and run <code>vmstat -s</code> again.</p>\n<p>However much active memory was freed was in evidently in use by the application.</p>\n" }, { "answer_id": 7000517, "author": "pokute", "author_id": 652691, "author_profile": "https://Stackoverflow.com/users/652691", "pm_score": 3, "selected": false, "text": "<pre><code>#!/bin/ksh\n#\n# Returns total memory used by process $1 in kb.\n#\n# See /proc/NNNN/smaps if you want to do something\n# more interesting.\n#\n\nIFS=$'\\n'\n\nfor line in $(&lt;/proc/$1/smaps)\ndo\n [[ $line =~ ^Size:\\s+(\\S+) ]] &amp;&amp; ((kb += ${.sh.match[1]}))\ndone\n\nprint $kb\n</code></pre>\n" }, { "answer_id": 12797883, "author": "Tomasz Dzięcielewski", "author_id": 1679995, "author_profile": "https://Stackoverflow.com/users/1679995", "pm_score": 3, "selected": false, "text": "<p>I'm using <a href=\"https://en.wikipedia.org/wiki/Htop\" rel=\"nofollow noreferrer\">htop</a>; it's a very good console program similar to Windows <a href=\"https://en.wikipedia.org/wiki/Windows_Task_Manager\" rel=\"nofollow noreferrer\">Task Manager</a>.</p>\n" }, { "answer_id": 13754307, "author": "thomasrutter", "author_id": 53212, "author_profile": "https://Stackoverflow.com/users/53212", "pm_score": 7, "selected": false, "text": "<p>Use <a href=\"http://manpages.ubuntu.com/manpages/precise/en/man8/smem.8.html\" rel=\"noreferrer\"><strong>smem</strong></a>, which is an alternative to <em><a href=\"https://en.wikipedia.org/wiki/Ps_(Unix)\" rel=\"noreferrer\">ps</a></em> which calculates the USS and PSS per process. You probably want the PSS.</p>\n<ul>\n<li><p><strong>USS</strong> - Unique Set Size. This is the amount of unshared memory unique to that process (think of it as <em>U</em> for <em>unique</em> memory). It does not include shared memory. Thus this will <em>under</em>-report the amount of memory a process uses, but it is helpful when you want to ignore shared memory.</p>\n</li>\n<li><p><strong>PSS</strong> - Proportional Set Size. This is what you want. It adds together the unique memory (USS), along with a proportion of its shared memory divided by the number of processes sharing that memory. Thus it will give you an accurate representation of how much actual physical memory is being used per process - with shared memory truly represented as shared. Think of the <em>P</em> being for <em>physical</em> memory.</p>\n</li>\n</ul>\n<p>How this compares to RSS as reported by <strong>ps</strong> and other utilities:</p>\n<ul>\n<li><strong>RSS</strong> - Resident Set Size. This is the amount of shared memory plus unshared memory used by each process. If any processes share memory, this will <em>over</em>-report the amount of memory actually used, because the same shared memory will be counted more than once - appearing again in each other process that shares the same memory. Thus it is <em>fairly</em> unreliable, especially when high-memory processes have a lot of forks - which is common in a server, with things like Apache or PHP (<a href=\"https://en.wikipedia.org/wiki/FastCGI\" rel=\"noreferrer\">FastCGI</a>/FPM) processes.</li>\n</ul>\n<p>Notice: smem can also (optionally) output graphs such as pie charts and the like. IMO you don't need any of that. If you just want to use it from the command line like you might use <code>ps -A v</code>, then you don't need to install the Python and Matplotlib recommended dependency.</p>\n" }, { "answer_id": 15196995, "author": "Vineeth", "author_id": 2130910, "author_profile": "https://Stackoverflow.com/users/2130910", "pm_score": 3, "selected": false, "text": "<p>The below command line will give you the total memory used by the various process running on the Linux machine in MB:</p>\n<pre><code>ps -eo size,pid,user,command --sort -size | awk '{ hr=$1/1024 ; printf(&quot;%13.2f Mb &quot;,hr) } { for ( x=4 ; x&lt;=NF ; x++ ) { printf(&quot;%s &quot;,$x) } print &quot;&quot; }' | awk '{total=total + $1} END {print total}'\n</code></pre>\n" }, { "answer_id": 16432017, "author": "Rocco Corsi", "author_id": 2360683, "author_profile": "https://Stackoverflow.com/users/2360683", "pm_score": 3, "selected": false, "text": "<p>If the process is not using up too much memory (either because you expect this to be the case, or some other command has given this initial indication), and the process can withstand being stopped for a short period of time, you can try to use the gcore command.</p>\n<pre><code>gcore &lt;pid&gt;\n</code></pre>\n<p>Check the size of the generated core file to get a good idea how much memory a particular process is using.</p>\n<p>This won't work too well if process is using hundreds of megabytes, or gigabytes, as the core generation could take several seconds or minutes to be created depending on I/O performance. During the core creation the process is stopped (or &quot;frozen&quot;) to prevent memory changes. So be careful.</p>\n<p>Also make sure the mount point where the core is generated has plenty of disk space and that the system will not react negatively to the core file being created in that particular directory.</p>\n" }, { "answer_id": 17202299, "author": "Bobbin Zachariah", "author_id": 2330046, "author_profile": "https://Stackoverflow.com/users/2330046", "pm_score": 2, "selected": false, "text": "<p>Check out this shell script to check <a href=\"http://www.linoxide.com/linux-shell-script/linux-memory-usage-program/\" rel=\"nofollow noreferrer\">memory usage by application in Linux</a>.</p>\n<p>It is also <a href=\"https://github.com/nixsavy/shell-scripts/blob/master/memstat.sh\" rel=\"nofollow noreferrer\">available on GitHub</a> and in a version <a href=\"https://github.com/asmund1/shell-scripts/blob/master/memstat.sh\" rel=\"nofollow noreferrer\">without paste and bc</a>.</p>\n" }, { "answer_id": 19494189, "author": "Jain Rach", "author_id": 2877905, "author_profile": "https://Stackoverflow.com/users/2877905", "pm_score": 2, "selected": false, "text": "<p>I would suggest that you use atop. You can find everything about it on <a href=\"http://www.atoptool.nl/downloadatop.php\" rel=\"nofollow\">this page</a>. It is capable of providing all the necessary KPI for your processes and it can also capture to a file.</p>\n" }, { "answer_id": 25184004, "author": "test30", "author_id": 781312, "author_profile": "https://Stackoverflow.com/users/781312", "pm_score": 3, "selected": false, "text": "<p>Note: <strong>this works 100% well only when memory consumption increases</strong></p>\n<p>If you want to monitor memory usage by given process (or group of processed sharing common name, e.g. <code>google-chrome</code>, you can use my bash-script:</p>\n<pre><code>while true; do ps aux | awk ‚{print $5, $11}’ | grep chrome | sort -n &gt; /tmp/a.txt; sleep 1; diff /tmp/{b,a}.txt; mv /tmp/{a,b}.txt; done;\n</code></pre>\n<p>this will continuously look for changes and print them.</p>\n<p><img src=\"https://i.stack.imgur.com/0g9yT.png\" alt=\"Enter image description here\" /></p>\n" }, { "answer_id": 26164694, "author": "jtpereyda", "author_id": 461834, "author_profile": "https://Stackoverflow.com/users/461834", "pm_score": 2, "selected": false, "text": "<p>While this question seems to be about examining currently running processes, I wanted to see the peak memory used by an application from start to finish. Besides <a href=\"https://en.wikipedia.org/wiki/Valgrind\" rel=\"nofollow noreferrer\">Valgrind</a>, you can use <a href=\"https://bitbucket.org/gsauthof/tstime\" rel=\"nofollow noreferrer\">tstime</a>, which is much simpler. It measures the &quot;highwater&quot; memory usage (RSS and virtual). From <a href=\"https://unix.stackexchange.com/a/18858/15954\">this answer</a>.</p>\n" }, { "answer_id": 29122942, "author": "Sudheesh.M.S", "author_id": 1295321, "author_profile": "https://Stackoverflow.com/users/1295321", "pm_score": -1, "selected": false, "text": "<p>Use the in-built <em>System Monitor</em> GUI tool available in Ubuntu.</p>\n" }, { "answer_id": 30298898, "author": "Yahya Yahyaoui", "author_id": 1377439, "author_profile": "https://Stackoverflow.com/users/1377439", "pm_score": 5, "selected": false, "text": "<p>Beside the solutions listed in the answers, you can use the Linux command &quot;top&quot;. It provides a dynamic real-time view of the running system, and it gives the CPU and memory usage for the whole system, along with for every program, in percentage:</p>\n<pre><code>top\n</code></pre>\n<p>to filter by a program PID:</p>\n<pre><code>top -p &lt;PID&gt;\n</code></pre>\n<p>To filter by a program name:</p>\n<pre><code>top | grep &lt;PROCESS NAME&gt;\n</code></pre>\n<p>&quot;top&quot; provides also some fields such as:</p>\n<p>VIRT -- Virtual Image (kb): The total amount of virtual memory used by the task</p>\n<p>RES -- Resident size (kb): The non-swapped physical memory a task has used ; RES = CODE + DATA.</p>\n<p>DATA -- Data+Stack size (kb): The amount of physical memory devoted to other than executable code, also known as the 'data resident set' size or DRS.</p>\n<p>SHR -- Shared Mem size (kb): The amount of shared memory used by a task. It simply reflects memory that could be potentially shared with other processes.</p>\n<p>Reference <a href=\"http://linux.die.net/man/1/top\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 33532736, "author": "Moonchild", "author_id": 2887185, "author_profile": "https://Stackoverflow.com/users/2887185", "pm_score": 6, "selected": false, "text": "<p>Use <code>time</code>.</p>\n<p>Not the <em>Bash</em> builtin <code>time</code>, but the one you can find with <code>which time</code>, for example <code>/usr/bin/time</code>.</p>\n<p>Here's what it covers, on a simple <code>ls</code>:</p>\n<pre><code>$ /usr/bin/time --verbose ls\n(...)\nCommand being timed: &quot;ls&quot;\nUser time (seconds): 0.00\nSystem time (seconds): 0.00\nPercent of CPU this job got: 0%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00\nAverage shared text size (kbytes): 0\nAverage unshared data size (kbytes): 0\nAverage stack size (kbytes): 0\nAverage total size (kbytes): 0\nMaximum resident set size (kbytes): 2372\nAverage resident set size (kbytes): 0\nMajor (requiring I/O) page faults: 1\nMinor (reclaiming a frame) page faults: 121\nVoluntary context switches: 2\nInvoluntary context switches: 9\nSwaps: 0\nFile system inputs: 256\nFile system outputs: 0\nSocket messages sent: 0\nSocket messages received: 0\nSignals delivered: 0\nPage size (bytes): 4096\nExit status: 0\n</code></pre>\n" }, { "answer_id": 34871273, "author": "Roselyn Verbo Domingo", "author_id": 3985677, "author_profile": "https://Stackoverflow.com/users/3985677", "pm_score": 0, "selected": false, "text": "<p><em>Based on an answer to <a href=\"https://stackoverflow.com/questions/14641553/how-to-find-the-memory-consumption-of-a-particular-process-in-linux-for-every-5/29090375#29090375\">a related question</a>.</em></p>\n<p>You may use <a href=\"https://en.wikipedia.org/wiki/Simple_Network_Management_Protocol\" rel=\"nofollow noreferrer\">SNMP</a> to get the memory and CPU usage of a process in a particular device on the network :)</p>\n<h3>Requirements:</h3>\n<ul>\n<li>The device running the process should have <code>snmp</code> installed and running</li>\n<li><code>snmp</code> should be configured to accept requests from where you will run the script below (it may be configured in file <em>snmpd.conf</em>)</li>\n<li>You should know the process ID (PID) of the process you want to monitor</li>\n</ul>\n<h3>Notes:</h3>\n<ul>\n<li><p><em><strong>HOST-RESOURCES-MIB::hrSWRunPerfCPU</strong></em> is the number of centi-seconds of the total system's CPU resources consumed by this process. Note that on a multi-processor system, this value may increment by more than one centi-second in one centi-second of real (wall clock) time.</p>\n</li>\n<li><p><em><strong>HOST-RESOURCES-MIB::hrSWRunPerfMem</strong></em> is the total amount of real system memory allocated to this process.</p>\n</li>\n</ul>\n<h2>Process monitoring script</h2>\n<pre><code>echo &quot;IP address: &quot;\nread ip\necho &quot;Specfiy PID: &quot;\nread pid\necho &quot;Interval in seconds: &quot;\nread interval\n\nwhile [ 1 ]\ndo\n date\n snmpget -v2c -c public $ip HOST-RESOURCES-MIB::hrSWRunPerfCPU.$pid\n snmpget -v2c -c public $ip HOST-RESOURCES-MIB::hrSWRunPerfMem.$pid\n sleep $interval;\ndone\n</code></pre>\n" }, { "answer_id": 36991325, "author": "Thomas Shaiker", "author_id": 6282986, "author_profile": "https://Stackoverflow.com/users/6282986", "pm_score": 4, "selected": false, "text": "<p>Three more methods to try:</p>\n\n<ol>\n<li><code>ps aux --sort pmem</code><br>\nIt sorts the output by <code>%MEM</code>.</li>\n<li><code>ps aux | awk '{print $2, $4, $11}' | sort -k2r | head -n 15</code><br>\nIt sorts using pipes.</li>\n<li><code>top -a</code><br>\nIt starts top sorting by <code>%MEM</code></li>\n</ol>\n\n<p><em>(Extracted from <a href=\"http://www.sysadmit.com/2016/05/linux-uso-de-memoria-por-proceso.html\" rel=\"noreferrer\">here</a>)</em></p>\n" }, { "answer_id": 42036928, "author": "ptan", "author_id": 2969684, "author_profile": "https://Stackoverflow.com/users/2969684", "pm_score": 0, "selected": false, "text": "<p>/prox/xxx/numa_maps gives some info there: N0=??? N1=???. But this result might be lower than the actual result, as it only counts those which have been touched.</p>\n" }, { "answer_id": 44711589, "author": "Lokendra Singh Rawat", "author_id": 7015811, "author_profile": "https://Stackoverflow.com/users/7015811", "pm_score": 7, "selected": false, "text": "<pre><code>ps -eo size,pid,user,command --sort -size | \\\n awk '{ hr=$1/1024 ; printf(&quot;%13.2f Mb &quot;,hr) } { for ( x=4 ; x&lt;=NF ; x++ ) { printf(&quot;%s &quot;,$x) } print &quot;&quot; }' |\\\n cut -d &quot;&quot; -f2 | cut -d &quot;-&quot; -f1\n</code></pre>\n<p>Use this as root and you can get a clear output for memory usage by each process.</p>\n<h3>Output example:</h3>\n<pre><code> 0.00 Mb COMMAND\n 1288.57 Mb /usr/lib/firefox\n 821.68 Mb /usr/lib/chromium/chromium\n 762.82 Mb /usr/lib/chromium/chromium\n 588.36 Mb /usr/sbin/mysqld\n 547.55 Mb /usr/lib/chromium/chromium\n 523.92 Mb /usr/lib/tracker/tracker\n 476.59 Mb /usr/lib/chromium/chromium\n 446.41 Mb /usr/bin/gnome\n 421.62 Mb /usr/sbin/libvirtd\n 405.11 Mb /usr/lib/chromium/chromium\n 302.60 Mb /usr/lib/chromium/chromium\n 291.46 Mb /usr/lib/chromium/chromium\n 284.56 Mb /usr/lib/chromium/chromium\n 238.93 Mb /usr/lib/tracker/tracker\n 223.21 Mb /usr/lib/chromium/chromium\n 197.99 Mb /usr/lib/chromium/chromium\n 194.07 Mb conky\n 191.92 Mb /usr/lib/chromium/chromium\n 190.72 Mb /usr/bin/mongod\n 169.06 Mb /usr/lib/chromium/chromium\n 155.11 Mb /usr/bin/gnome\n 136.02 Mb /usr/lib/chromium/chromium\n 125.98 Mb /usr/lib/chromium/chromium\n 103.98 Mb /usr/lib/chromium/chromium\n 93.22 Mb /usr/lib/tracker/tracker\n 89.21 Mb /usr/lib/gnome\n 80.61 Mb /usr/bin/gnome\n 77.73 Mb /usr/lib/evolution/evolution\n 76.09 Mb /usr/lib/evolution/evolution\n 72.21 Mb /usr/lib/gnome\n 69.40 Mb /usr/lib/evolution/evolution\n 68.84 Mb nautilus\n 68.08 Mb zeitgeist\n 60.97 Mb /usr/lib/tracker/tracker\n 59.65 Mb /usr/lib/evolution/evolution\n 57.68 Mb apt\n 55.23 Mb /usr/lib/gnome\n 53.61 Mb /usr/lib/evolution/evolution\n 53.07 Mb /usr/lib/gnome\n 52.83 Mb /usr/lib/gnome\n 51.02 Mb /usr/lib/udisks2/udisksd\n 50.77 Mb /usr/lib/evolution/evolution\n 50.53 Mb /usr/lib/gnome\n 50.45 Mb /usr/lib/gvfs/gvfs\n 50.36 Mb /usr/lib/packagekit/packagekitd\n 50.14 Mb /usr/lib/gvfs/gvfs\n 48.95 Mb /usr/bin/Xwayland :1024\n 46.21 Mb /usr/bin/gnome\n 42.43 Mb /usr/bin/zeitgeist\n 42.29 Mb /usr/lib/gnome\n 41.97 Mb /usr/lib/gnome\n 41.64 Mb /usr/lib/gvfs/gvfsd\n 41.63 Mb /usr/lib/gvfs/gvfsd\n 41.55 Mb /usr/lib/gvfs/gvfsd\n 41.48 Mb /usr/lib/gvfs/gvfsd\n 39.87 Mb /usr/bin/python /usr/bin/chrome\n 37.45 Mb /usr/lib/xorg/Xorg vt2\n 36.62 Mb /usr/sbin/NetworkManager\n 35.63 Mb /usr/lib/caribou/caribou\n 34.79 Mb /usr/lib/tracker/tracker\n 33.88 Mb /usr/sbin/ModemManager\n 33.77 Mb /usr/lib/gnome\n 33.61 Mb /usr/lib/upower/upowerd\n 33.53 Mb /usr/sbin/gdm3\n 33.37 Mb /usr/lib/gvfs/gvfsd\n 33.36 Mb /usr/lib/gvfs/gvfs\n 33.23 Mb /usr/lib/gvfs/gvfs\n 33.15 Mb /usr/lib/at\n 33.15 Mb /usr/lib/at\n 30.03 Mb /usr/lib/colord/colord\n 29.62 Mb /usr/lib/apt/methods/https\n 28.06 Mb /usr/lib/zeitgeist/zeitgeist\n 27.29 Mb /usr/lib/policykit\n 25.55 Mb /usr/lib/gvfs/gvfs\n 25.55 Mb /usr/lib/gvfs/gvfs\n 25.23 Mb /usr/lib/accountsservice/accounts\n 25.18 Mb /usr/lib/gvfs/gvfsd\n 25.15 Mb /usr/lib/gvfs/gvfs\n 25.15 Mb /usr/lib/gvfs/gvfs\n 25.12 Mb /usr/lib/gvfs/gvfs\n 25.10 Mb /usr/lib/gnome\n 25.10 Mb /usr/lib/gnome\n 25.07 Mb /usr/lib/gvfs/gvfsd\n 24.99 Mb /usr/lib/gvfs/gvfs\n 23.26 Mb /usr/lib/chromium/chromium\n 22.09 Mb /usr/bin/pulseaudio\n 19.01 Mb /usr/bin/pulseaudio\n 18.62 Mb (sd\n 18.46 Mb (sd\n 18.30 Mb /sbin/init\n 18.17 Mb /usr/sbin/rsyslogd\n 17.50 Mb gdm\n 17.42 Mb gdm\n 17.09 Mb /usr/lib/dconf/dconf\n 17.09 Mb /usr/lib/at\n 17.06 Mb /usr/lib/gvfs/gvfsd\n 16.98 Mb /usr/lib/at\n 16.91 Mb /usr/lib/gdm3/gdm\n 16.86 Mb /usr/lib/gvfs/gvfsd\n 16.86 Mb /usr/lib/gdm3/gdm\n 16.85 Mb /usr/lib/dconf/dconf\n 16.85 Mb /usr/lib/dconf/dconf\n 16.73 Mb /usr/lib/rtkit/rtkit\n 16.69 Mb /lib/systemd/systemd\n 13.13 Mb /usr/lib/chromium/chromium\n 13.13 Mb /usr/lib/chromium/chromium\n 10.92 Mb anydesk\n 8.54 Mb /sbin/lvmetad\n 7.43 Mb /usr/sbin/apache2\n 6.82 Mb /usr/sbin/apache2\n 6.77 Mb /usr/sbin/apache2\n 6.73 Mb /usr/sbin/apache2\n 6.66 Mb /usr/sbin/apache2\n 6.64 Mb /usr/sbin/apache2\n 6.63 Mb /usr/sbin/apache2\n 6.62 Mb /usr/sbin/apache2\n 6.51 Mb /usr/sbin/apache2\n 6.25 Mb /usr/sbin/apache2\n 6.22 Mb /usr/sbin/apache2\n 3.92 Mb bash\n 3.14 Mb bash\n 2.97 Mb bash\n 2.95 Mb bash\n 2.93 Mb bash\n 2.91 Mb bash\n 2.86 Mb bash\n 2.86 Mb bash\n 2.86 Mb bash\n 2.84 Mb bash\n 2.84 Mb bash\n 2.45 Mb /lib/systemd/systemd\n 2.30 Mb (sd\n 2.28 Mb /usr/bin/dbus\n 1.84 Mb /usr/bin/dbus\n 1.46 Mb ps\n 1.21 Mb openvpn hackthebox.ovpn\n 1.16 Mb /sbin/dhclient\n 1.16 Mb /sbin/dhclient\n 1.09 Mb /lib/systemd/systemd\n 0.98 Mb /sbin/mount.ntfs /dev/sda3 /media/n0bit4/Data\n 0.97 Mb /lib/systemd/systemd\n 0.96 Mb /lib/systemd/systemd\n 0.89 Mb /usr/sbin/smartd\n 0.77 Mb /usr/bin/dbus\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.76 Mb su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.75 Mb sudo su\n 0.74 Mb /usr/bin/dbus\n 0.71 Mb /usr/lib/apt/methods/http\n 0.68 Mb /bin/bash /usr/bin/mysqld_safe\n 0.68 Mb /sbin/wpa_supplicant\n 0.66 Mb /usr/bin/dbus\n 0.61 Mb /lib/systemd/systemd\n 0.54 Mb /usr/bin/dbus\n 0.46 Mb /usr/sbin/cron\n 0.45 Mb /usr/sbin/irqbalance\n 0.43 Mb logger\n 0.41 Mb awk { hr=$1/1024 ; printf(&quot;%13.2f Mb &quot;,hr) } { for ( x=4 ; x&lt;=NF ; x++ ) { printf(&quot;%s &quot;,$x) } print &quot;&quot; }\n 0.40 Mb /usr/bin/ssh\n 0.34 Mb /usr/lib/chromium/chrome\n 0.32 Mb cut\n 0.32 Mb cut\n 0.00 Mb [kthreadd]\n 0.00 Mb [ksoftirqd/0]\n 0.00 Mb [kworker/0:0H]\n 0.00 Mb [rcu_sched]\n 0.00 Mb [rcu_bh]\n 0.00 Mb [migration/0]\n 0.00 Mb [lru\n 0.00 Mb [watchdog/0]\n 0.00 Mb [cpuhp/0]\n 0.00 Mb [cpuhp/1]\n 0.00 Mb [watchdog/1]\n 0.00 Mb [migration/1]\n 0.00 Mb [ksoftirqd/1]\n 0.00 Mb [kworker/1:0H]\n 0.00 Mb [cpuhp/2]\n 0.00 Mb [watchdog/2]\n 0.00 Mb [migration/2]\n 0.00 Mb [ksoftirqd/2]\n 0.00 Mb [kworker/2:0H]\n 0.00 Mb [cpuhp/3]\n 0.00 Mb [watchdog/3]\n 0.00 Mb [migration/3]\n 0.00 Mb [ksoftirqd/3]\n 0.00 Mb [kworker/3:0H]\n 0.00 Mb [kdevtmpfs]\n 0.00 Mb [netns]\n 0.00 Mb [khungtaskd]\n 0.00 Mb [oom_reaper]\n 0.00 Mb [writeback]\n 0.00 Mb [kcompactd0]\n 0.00 Mb [ksmd]\n 0.00 Mb [khugepaged]\n 0.00 Mb [crypto]\n 0.00 Mb [kintegrityd]\n 0.00 Mb [bioset]\n 0.00 Mb [kblockd]\n 0.00 Mb [devfreq_wq]\n 0.00 Mb [watchdogd]\n 0.00 Mb [kswapd0]\n 0.00 Mb [vmstat]\n 0.00 Mb [kthrotld]\n 0.00 Mb [ipv6_addrconf]\n 0.00 Mb [acpi_thermal_pm]\n 0.00 Mb [ata_sff]\n 0.00 Mb [scsi_eh_0]\n 0.00 Mb [scsi_tmf_0]\n 0.00 Mb [scsi_eh_1]\n 0.00 Mb [scsi_tmf_1]\n 0.00 Mb [scsi_eh_2]\n 0.00 Mb [scsi_tmf_2]\n 0.00 Mb [scsi_eh_3]\n 0.00 Mb [scsi_tmf_3]\n 0.00 Mb [scsi_eh_4]\n 0.00 Mb [scsi_tmf_4]\n 0.00 Mb [scsi_eh_5]\n 0.00 Mb [scsi_tmf_5]\n 0.00 Mb [bioset]\n 0.00 Mb [kworker/1:1H]\n 0.00 Mb [kworker/3:1H]\n 0.00 Mb [kworker/0:1H]\n 0.00 Mb [kdmflush]\n 0.00 Mb [bioset]\n 0.00 Mb [kdmflush]\n 0.00 Mb [bioset]\n 0.00 Mb [jbd2/sda5\n 0.00 Mb [ext4\n 0.00 Mb [kworker/2:1H]\n 0.00 Mb [kauditd]\n 0.00 Mb [bioset]\n 0.00 Mb [drbd\n 0.00 Mb [irq/27\n 0.00 Mb [i915/signal:0]\n 0.00 Mb [i915/signal:1]\n 0.00 Mb [i915/signal:2]\n 0.00 Mb [ttm_swap]\n 0.00 Mb [cfg80211]\n 0.00 Mb [kworker/u17:0]\n 0.00 Mb [hci0]\n 0.00 Mb [hci0]\n 0.00 Mb [kworker/u17:1]\n 0.00 Mb [iprt\n 0.00 Mb [iprt\n 0.00 Mb [kworker/1:0]\n 0.00 Mb [kworker/3:0]\n 0.00 Mb [kworker/0:0]\n 0.00 Mb [kworker/2:0]\n 0.00 Mb [kworker/u16:0]\n 0.00 Mb [kworker/u16:2]\n 0.00 Mb [kworker/3:2]\n 0.00 Mb [kworker/2:1]\n 0.00 Mb [kworker/1:2]\n 0.00 Mb [kworker/0:2]\n 0.00 Mb [kworker/2:2]\n 0.00 Mb [kworker/0:1]\n 0.00 Mb [scsi_eh_6]\n 0.00 Mb [scsi_tmf_6]\n 0.00 Mb [usb\n 0.00 Mb [bioset]\n 0.00 Mb [kworker/3:1]\n 0.00 Mb [kworker/u16:1]\n</code></pre>\n" }, { "answer_id": 51389219, "author": "GypsyCosmonaut", "author_id": 6639975, "author_profile": "https://Stackoverflow.com/users/6639975", "pm_score": 5, "selected": false, "text": "<p>I am using <a href=\"https://en.wikipedia.org/wiki/Arch_Linux\" rel=\"noreferrer\">Arch Linux</a> and there's this wonderful package called <code>ps_mem</code>:</p>\n<pre><code>ps_mem -p &lt;pid&gt;\n</code></pre>\n<h3>Example Output</h3>\n<pre><code>$ ps_mem -S -p $(pgrep firefox)\n\nPrivate + Shared = RAM used Swap used Program\n\n355.0 MiB + 38.7 MiB = 393.7 MiB 35.9 MiB firefox\n---------------------------------------------\n 393.7 MiB 35.9 MiB\n=============================================\n</code></pre>\n" }, { "answer_id": 65277087, "author": "Sruli", "author_id": 6556355, "author_profile": "https://Stackoverflow.com/users/6556355", "pm_score": 2, "selected": false, "text": "<p>Given some of the answers (thanks thomasrutter), to get the actual swap and RAM for a single application, I came up with the following, say we want to know what 'firefox' is using</p>\n<p><code>sudo smem | awk '/firefox/{swap += $5; pss += $7;} END {print &quot;swap = &quot;swap/1024&quot; PSS = &quot;pss/1024}'</code></p>\n<p>Or for libvirt;</p>\n<p><code>sudo smem | awk '/libvirt/{swap += $5; pss += $7;} END {print &quot;swap = &quot;swap/1024&quot; PSS = &quot;pss/1024}'</code></p>\n<p>This will give you the total in MB like so;</p>\n<p><code>swap = 0 PSS = 2096.92</code></p>\n<p><code>swap = 224.75 PSS = 421.455</code></p>\n<p>Tested on ubuntu 16.04 through 20.04.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
How do you measure the memory usage of an application or process in Linux? From the blog article of *[Understanding memory usage on Linux](http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html)*, `ps` is not an accurate tool to use for this intent. > > **Why `ps` is "wrong"** > > > Depending on how you look at it, `ps` is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up **if it were the only process running**. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by `ps` are almost definitely *wrong*. > > > (Note: This question is covered [here](https://stackoverflow.com/q/63166/15161) in great detail.)
With `ps` or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but: * does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it * can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, [Valgrind](https://en.wikipedia.org/wiki/Valgrind) can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif': > > Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal. As explained in the [Valgrind documentation](http://valgrind.org/docs/manual/ms-manual.html), you need to run the program through Valgrind: ``` valgrind --tool=massif <executable> <arguments> ``` Massif writes a dump of memory usage snapshots (e.g. `massif.out.12345`). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is [massif-visualizer](https://github.com/KDE/massif-visualizer). But I found `ms_print`, a simple text-based tool shipped with Valgrind, to be of great help already. To find memory leaks, use the (default) `memcheck` tool of valgrind.
131,326
<p>I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.</p>
[ { "answer_id": 131339, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Do you mean multidimensional array? It's simple:</p>\n\n<pre><code>&lt;type&gt;[,] &lt;name&gt; = new &lt;type&gt;[&lt;first dimenison&gt;,&lt;second dimension&gt;];\n</code></pre>\n\n<p>Here is MSDN reference:</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays\" rel=\"nofollow noreferrer\">Multidimensional Arrays (C#)</a></p>\n" }, { "answer_id": 131347, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0521670152\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Data Structures in C#</a></p>\n\n<p>Seriously, I'm not trying to be critical of the question, but I got tons of useful results right at the top of my search when I Googled for:</p>\n\n<pre><code>data structures c#\n</code></pre>\n\n<p>If you have specific questions about specific data structures, we might have more specific answers...</p>\n" }, { "answer_id": 131363, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 0, "selected": false, "text": "<p>For performance, it's best not to use multi-dimensional arrays ([,]); instead, use jagged arrays. e.g.:</p>\n\n<pre><code>&lt;type&gt;[][] &lt;name&gt; = new &lt;type&gt;[&lt;first dimension&gt;];\nfor (int i = 0; i &lt; &lt;first dimension&gt;; i++)\n{\n &lt;name&gt;[i] = new &lt;type&gt;[&lt;second dimension&gt;];\n}\n</code></pre>\n\n<p>To access:</p>\n\n<pre><code>&lt;type&gt; item = &lt;name&gt;[&lt;first index&gt;][&lt;second index&gt;];\n</code></pre>\n" }, { "answer_id": 131387, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 2, "selected": false, "text": "<p>@Traumapony-- I'd actually state that the real performance gain is made in one giant flat array, but that may just be my C++ image processing roots showing.</p>\n\n<p>It depends on what you need the 2D structure to do. If it's storing something where each set of items in the second dimension is the same size, then you want to use something like a large 1D array, because the seek times are faster and the data management is easier. Like:</p>\n\n<pre><code>for (y = 0; y &lt; ysize; y++){\n for (x = 0; x &lt; xsize; x++){\n theArray[y*xsize + x] = //some stuff!\n }\n}\n</code></pre>\n\n<p>And then you can do operations which ignore neighboring pixels with a single passthrough:</p>\n\n<pre><code>totalsize = xsize*ysize;\nfor (x = 0; x &lt; totalsize; x++){\n theArray[x] = //some stuff!\n}\n</code></pre>\n\n<p>Except that in C# you probably want to actually call a C++ library to do this kind of processing; C++ tends to be faster for this, especially if you use the intel compiler.</p>\n\n<p>If you have the second dimension having multiple different sizes, then nothing I said applies, and you should look at some of the other solutions. You really need to know what your functional requirements are in order to be able to answer the question.</p>\n" }, { "answer_id": 131388, "author": "jarrodn", "author_id": 15273, "author_profile": "https://Stackoverflow.com/users/15273", "pm_score": 1, "selected": false, "text": "<p>Depending on the type of the data, you could look at using a straight 2 dimensional array:</p>\n\n<pre><code>int[][] intGrid;\n</code></pre>\n\n<p>If you need to get tricky, you could always go the generics approach: </p>\n\n<pre><code>Dictionary&lt;KeyValuePair&lt;int,int&gt;,string&gt;;\n</code></pre>\n\n<p>That allows you to put complex types in the value part of the dictionary, although makes indexing into the elements more difficult.</p>\n\n<p>If you're looking to store spatial 2d point data, System.Drawing has a lot of support for points in 2d space.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.
Do you mean multidimensional array? It's simple: ``` <type>[,] <name> = new <type>[<first dimenison>,<second dimension>]; ``` Here is MSDN reference: [Multidimensional Arrays (C#)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays)
131,406
<p>There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?</p> <p>Here are a few methods that I know of:</p> <pre><code>var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 a | 0; // 2 </code></pre> <p>I'm sure there are others out there. Suggestions?</p>
[ { "answer_id": 131413, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": -1, "selected": false, "text": "<p>parseInt() is probably the best one. <code>a | 0</code> doesn't do what you really want (it just assigns 0 if a is an undefined or null value, which means an empty object or array passes the test), and Math.floor works by some type trickery (it basically calls parseInt() in the background).</p>\n" }, { "answer_id": 131421, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 2, "selected": false, "text": "<p>You can use Number(a).toFixed(0);</p>\n\n<p>Or even just a.toFixed(0);</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>That's rounding to 0 places, slightly different than truncating, and as someone else suggested, toFixed returns a string, not a raw integer. Useful for display purposes.</p>\n\n<pre><code>var num = 2.7; // typeof num is \"Number\"\nnum.toFixed(0) == \"3\"\n</code></pre>\n" }, { "answer_id": 131424, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 6, "selected": true, "text": "<p>According to <a href=\"http://www.jibbering.com/faq/faq_notes/type_convert.html#tcParseIn\" rel=\"noreferrer\"><strong>this website</strong></a>:</p>\n<blockquote>\n<p>parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number...</p>\n<p>For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable...</p>\n</blockquote>\n" }, { "answer_id": 131434, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 2, "selected": false, "text": "<pre><code>var i = parseInt(n, 10);\n</code></pre>\n\n<p>If you don't specify a radix values like <code>'010'</code> will be treated as octal (and so the result will be <code>8</code> not <code>10</code>).</p>\n" }, { "answer_id": 131538, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>The question appears to be asking specifically about converting from a float to an int. My understanding is that the way to do this is to use <code>toFixed</code>. So...</p>\n\n<pre><code>var myFloat = 2.5;\nvar myInt = myFloat.toFixed(0);\n</code></pre>\n\n<p>Does anyone know if <code>Math.floor()</code> is more or less performant than <code>Number.toFixed()</code>?</p>\n" }, { "answer_id": 132109, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": false, "text": "<p>The answer has already been given but just to be clear.</p>\n\n<p>Use the Math library for this. round, ceil or floor functions.</p>\n\n<p>parseInt is for converting a string to an int which is not what is needed here</p>\n\n<p>toFixed is for converting a float to a string also not what is needed here</p>\n\n<p>Since the Math functions will not be doing any conversions to or from a string it will be faster than any of the other choices which are wrong anyway.</p>\n" }, { "answer_id": 136647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>you could also do it this way:</p>\n\n<pre><code>var string = '1';\nvar integer = a * 1;\n</code></pre>\n" }, { "answer_id": 2445014, "author": "bcherry", "author_id": 211776, "author_profile": "https://Stackoverflow.com/users/211776", "pm_score": 3, "selected": false, "text": "<p>Apparently double bitwise-not is the fastest way to floor a number:</p>\n\n<pre><code>var x = 2.5;\nconsole.log(~~x); // 2\n</code></pre>\n\n<p>Used to be an article here, getting a 404 now though: <a href=\"http://james.padolsey.com/javascript/double-bitwise-not/\" rel=\"noreferrer\">http://james.padolsey.com/javascript/double-bitwise-not/</a></p>\n\n<p><del>Google has it cached: <code>http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.com/javascript/double-bitwise-not/+double+bitwise+not&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us</code></del></p>\n\n<p>But the Wayback Machine saves the day! <a href=\"http://web.archive.org/web/20100422040551/http://james.padolsey.com/javascript/double-bitwise-not/\" rel=\"noreferrer\">http://web.archive.org/web/20100422040551/http://james.padolsey.com/javascript/double-bitwise-not/</a></p>\n" }, { "answer_id": 6362472, "author": "Ken Rosaka", "author_id": 800175, "author_profile": "https://Stackoverflow.com/users/800175", "pm_score": 3, "selected": false, "text": "<p>From \"Javascript: The Good Parts\" from Douglas Crockford:</p>\n\n<pre><code>Number.prototype.integer = function () {\n return Math[this &lt; 0 ? 'ceil' : 'floor'](this);\n}\n</code></pre>\n\n<p>Doing that your are adding a method to every Number object.</p>\n\n<p>Then you can use it like that:</p>\n\n<pre><code>var x = 1.2, y = -1.2;\n\nx.integer(); // 1\ny.integer(); // -1\n\n(-10 / 3).integer(); // -3\n</code></pre>\n" }, { "answer_id": 7337219, "author": "arunjitsingh", "author_id": 377392, "author_profile": "https://Stackoverflow.com/users/377392", "pm_score": 2, "selected": false, "text": "<p>Using bitwise operators. It may not be the clearest way of converting to an integer, but it works on any kind of datatype.</p>\n\n<p>Suppose your function takes an argument <code>value</code>, and the function works in such a way that <code>value</code> must always be an integer (and 0 is accepted). Then any of the following will assign <code>value</code> as an integer:</p>\n\n<pre><code>value = ~~(value)\nvalue = value | 0;\nvalue = value &amp; 0xFF; // one byte; use this if you want to limit the integer to\n // a predefined number of bits/bytes\n</code></pre>\n\n<p>The best part is that this works with strings (what you might get from a text input, etc) that are numbers <code>~~(\"123.45\") === 123</code>. Any non numeric values result in <code>0</code>, ie,</p>\n\n<pre><code>~~(undefined) === 0\n~~(NaN) === 0\n~~(\"ABC\") === 0\n</code></pre>\n\n<p>It does work with hexadecimal numbers as strings (with a <code>0x</code> prefix)</p>\n\n<pre><code>~~(\"0xAF\") === 175\n</code></pre>\n\n<p>There is some type coercion involved, I suppose. I'll do some performance tests to compare these to <code>parseInt()</code> and <code>Math.floor()</code>, but I like having the extra convenience of no <code>Errors</code> being thrown and getting a <code>0</code> for non-numbers</p>\n" }, { "answer_id": 28667325, "author": "Kokizzu", "author_id": 1620210, "author_profile": "https://Stackoverflow.com/users/1620210", "pm_score": 2, "selected": false, "text": "<p>So I made a benchmark, on <code>Chrome</code> when the input is already a number, the fastest would be <code>~~num</code> and <code>num|0</code>, half speed: <code>Math.floor</code>, and the slowest would be <code>parseInt</code> see <a href=\"http://jsperf.com/flooring-benchmark\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/Lo8Kq.png\" alt=\"benchmark result\"></p>\n\n<p><strong>EDIT</strong>: it seems there are already another person who made <a href=\"http://jsperf.com/truncating-decimals\" rel=\"nofollow noreferrer\">rounding</a> benchmark (more result) and additional <a href=\"http://jsperf.com/dsafdgdfsaf/3\" rel=\"nofollow noreferrer\">ways</a>: <code>num&gt;&gt;0</code> (as fast as <code>|0</code>) and <code>num - num%1</code> (sometimes fast)</p>\n" }, { "answer_id": 36131850, "author": "GitaarLAB", "author_id": 588079, "author_profile": "https://Stackoverflow.com/users/588079", "pm_score": 3, "selected": false, "text": "<p>The 'best' way <em>depends</em> on:</p>\n\n<ul>\n<li>rounding mode: what <a href=\"https://en.wikipedia.org/wiki/Rounding#Rounding_to_integer\" rel=\"noreferrer\">type of rounding</a> (of the float to integer) you expect/require<br>\nfor positive and/or negative numbers that have a fractional part.<br>\nCommon examples: \n\n<pre>float | trunc | floor | ceil | near (half up)\n------+-------+-------+-------+---------------\n+∞ | +∞ | +∞ | +∞ | +∞ \n+2.75 | +2 | +2 | +3 | +3\n+2.5 | +2 | +2 | +3 | +3\n+2.25 | +2 | +2 | +3 | +2\n+0 | +0 | +0 | +0 | +0\n NaN | NaN | NaN | NaN | NaN\n-0 | -0 | -0 | -0 | -0\n-2.25 | -2 | -3 | -2 | -2\n-2.5 | -2 | -3 | -2 | -2\n-2.75 | -2 | -3 | -2 | -3\n-∞ | -∞ | -∞ | -∞ | -∞ \n</pre> \n\nFor float to integer conversions we <em>commonly</em> expect <strong>\"truncation\"</strong><br>\n(aka <strong>\"round towards zero\"</strong> aka <strong>\"round away from infinity\"</strong>).<br>\nEffectively this just 'chops off' the fractional part of a floating point number.<br>\nMost techniques and (internally) built-in methods behave this way.</li>\n<li>input: how your (floating point) number is represented:\n\n<ul>\n<li><code>String</code><br>\nCommonly radix/base: 10 (decimal)</li>\n<li>floating point ('internal') <code>Number</code></li>\n</ul></li>\n<li>output: what you want to do with the resulting value: \n\n<ul>\n<li>(intermediate) output <code>String</code> (default radix 10) (on screen) </li>\n<li>perform further calculations on resulting value</li>\n</ul></li>\n<li>range:<br>\nin what numerical range do you expect input/calculation-results<br>\nand for which range do you expect corresponding 'correct' output.</li>\n</ul>\n\n<p>Only <em>after</em> these considerations are answered we can think about appropriate method(s) and speed!<br>\n<br><hr>\nPer ECMAScript 262 spec: <em>all</em> numbers (type <code>Number</code>) in javascript are represented/stored in:<br>\n\"<a href=\"https://en.wikipedia.org/wiki/Double-precision_floating-point_format\" rel=\"noreferrer\">IEEE 754 Double Precision Floating Point (binary64)</a>\" format.<br>\nSo integers are <em>also</em> represented in the <em>same</em> floating point format (as numbers without a fraction).<br>\n<sup>Note: most implementations <em>do</em> use more efficient (for speed and memory-size) integer-types <em>internally</em> when possible! </sup> </p>\n\n<p>As this format stores 1 sign bit, 11 exponent bits and the first 53 significant bits (\"mantissa\"), we can say that: <em>only</em> <code>Number</code>-values <em>between</em> <code>-2<sup>52</sup></code> and <code>+2<sup>52</sup></code> can have a fraction.<br>\nIn other words: <em>all</em> representable positive and negative <code>Number</code>-values <em>between</em> <code>2<sup>52</sup></code> to (almost) <code>2<sup>(2<sup>11</sup>/2=1024)</sup></code> (at which point the format calls it <strike>a day</strike> <code>Infinity</code>) are already integers (internally rounded, as there are no bits left to represent the remaining fractional and/or least significant integer digits).</p>\n\n<p>And there is the first 'gotcha':<br>\nYou can not control the internal rounding-mode of <code>Number</code>-results for the built-in Literal/String to float conversions (rounding-mode: IEEE 754-2008 \"round to nearest, ties to even\") and built-in arithmetic operations (rounding-mode: IEEE 754-2008 \"round-to-nearest\").<br>\nFor example:<br>\n<code>2<sup>52</sup>+0.25 = 4503599627370496.25</code> is rounded and stored as: <code>4503599627370496</code><br>\n<code>2<sup>52</sup>+0.50 = 4503599627370496.50</code> is rounded and stored as: <code>4503599627370496</code><br>\n<code>2<sup>52</sup>+0.75 = 4503599627370496.75</code> is rounded and stored as: <code>4503599627370497</code><br>\n<code>2<sup>52</sup>+1.25 = 4503599627370497.25</code> is rounded and stored as: <code>4503599627370497</code><br>\n<code>2<sup>52</sup>+1.50 = 4503599627370497.50</code> is rounded and stored as: <code>4503599627370498</code><br>\n<code>2<sup>52</sup>+1.75 = 4503599627370497.75</code> is rounded and stored as: <code>4503599627370498</code><br>\n<code>2<sup>52</sup>+2.50 = 4503599627370498.50</code> is rounded and stored as: <code>4503599627370498</code><br>\n<code>2<sup>52</sup>+3.50 = 4503599627370499.50</code> is rounded and stored as: <code>4503599627370500</code> </p>\n\n<p>To control rounding your <code>Number</code> needs a fractional part (and at least one bit to represent that), otherwise ceil/floor/trunc/near returns the integer you fed into it.</p>\n\n<p>To correctly ceil/floor/trunc a Number up to x significant fractional decimal digit(s), we only care if the corresponding lowest and highest decimal fractional value will still give us a binary fractional value after rounding (so not being ceiled or floored to the next integer).<br>\nSo, for example, if you expect 'correct' rounding (for ceil/floor/trunc) up to 1 significant fractional decimal digit (<code>x.1 to x.9</code>), we need <em>at least</em> 3 bits (not 4) to give us <em>a</em> binary fractional value:<br>\n<code>0.1</code> is closer to <code>1/(2<sup>3</sup>=8)=0.125</code> than it is to <code>0</code> and <code>0.9</code> is closer to <code>1-1/(2<sup>3</sup>=8)=0.875</code> than it is to <code>1</code>.</p>\n\n<p><em>only</em> up to <code>±2<sup>(53-3=50)</sup></code> will all representable values have a non-zero binary fraction for no more than the <em>first</em> significant decimal fractional digit (values <code>x.1</code> to <code>x.9</code>).<br>\nFor 2 decimals <code>±2<sup>(53-6=47)</sup></code>, for 3 decimals <code>±2<sup>(53-9=44)</sup></code>, for 4 decimals <code>±2<sup>(53-13=40)</sup></code>, for 5 decimals <code>±2<sup>(53-16=37)</sup></code>, for 6 decimals <code>±2<sup>(53-19=34)</sup></code>, for 7 decimals <code>±2<sup>(53-23=30)</sup></code>, for 8 decimals <code>±2<sup>(53-26=27)</sup></code>, for 9 decimals <code>±2<sup>(53-29=24)</sup></code>, for 10 decimals <code>±2<sup>(53-33=20)</sup></code>, for 11 decimals <code>±2<sup>(53-36=17)</sup></code>, etc..</p>\n\n<p>A <strong>\"Safe Integer\"</strong> in javascript is an integer:</p>\n\n<ul>\n<li>that can be <em>exactly</em> represented as an IEEE-754 double precision number, and</li>\n<li>whose IEEE-754 representation <em>cannot</em> be the result of rounding any other integer to fit the IEEE-754 representation<br>\n<sup>(even though <code>±2<sup>53</sup></code> (as an exact power of 2) can exactly be represented, it is <em>not</em> a safe integer because it could also have been <code>±(2<sup>53</sup>+1)</code> before it was rounded to fit into the maximum of 53 most significant bits).</sup></li>\n</ul>\n\n<p>This effectively defines a subset range of (safely representable) integers <em>between</em> <code>-2<sup>53</sup></code> and <code>+2<sup>53</sup></code>: </p>\n\n<ul>\n<li>from: <code>-(2<sup>53</sup> - 1) = -9007199254740991</code> (inclusive)<br>\n(a constant provided as static property <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-number.min_safe_integer\" rel=\"noreferrer\"><code>Number.MIN_SAFE_INTEGER</code></a> since ES6)</li>\n<li><p>to: <code>+(2<sup>53</sup> - 1) = +9007199254740991</code> (inclusive)<br>\n(a constant provided as static property <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer\" rel=\"noreferrer\"><code>Number.MAX_SAFE_INTEGER</code></a> since ES6)<br>\n<sub>Trivial polyfill for these 2 new ES6 constants:</sub> </p>\n\n<pre><code>Number.MIN_SAFE_INTEGER || (Number.MIN_SAFE_INTEGER=\n -(Number.MAX_SAFE_INTEGER=9007199254740991) //Math.pow(2,53)-1\n);\n</code></pre></li>\n</ul>\n\n<p><br>\nSince ES6 there is also a complimentary static method <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-number.issafeinteger\" rel=\"noreferrer\"><code>Number.isSafeInteger()</code></a> which tests if the passed value is of type <code>Number</code> and is an integer within the safe integer range (returning a boolean <code>true</code> or <code>false</code>).<br>\n<sup>Note: will also return <code>false</code> for: <code>NaN</code>, <code>Infinity</code> and obviously <code>String</code> (even if it represents a number).</sup><br>\nPolyfill <em>example</em>: </p>\n\n<pre><code>Number.isSafeInteger || (Number.isSafeInteger = function(value){\n return typeof value === 'number' &amp;&amp; \n value === Math.floor(value) &amp;&amp;\n value &lt; 9007199254740992 &amp;&amp;\n value &gt; -9007199254740992;\n});\n</code></pre>\n\n<hr>\n\n<p><strong><a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-math.trunc\" rel=\"noreferrer\">ECMAScript 2015 / ES6 provides a new static method <code>Math.trunc()</code></a><br>\nto truncate a float to an integer:</strong> </p>\n\n<blockquote>\n <p>Returns the integral part of the number x, removing any fractional digits. If x is already an integer, the result is x.</p>\n</blockquote>\n\n<p>Or put simpler (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc\" rel=\"noreferrer\">MDN</a>): </p>\n\n<blockquote>\n <p>Unlike other three Math methods: <code>Math.floor()</code>, <code>Math.ceil()</code> and <code>Math.round()</code>, the way <code>Math.trunc()</code> works is very simple and straightforward:<br>\n just truncate the dot and the digits behind it, no matter whether the argument is a positive number or a negative number. </p>\n</blockquote>\n\n<p>We can further explain (and polyfill) <code>Math.trunc()</code> as such: </p>\n\n<pre><code>Math.trunc || (Math.trunc = function(n){\n return n &lt; 0 ? Math.ceil(n) : Math.floor(n); \n});\n</code></pre>\n\n<p><sup>Note, the above polyfill's payload can <em>potentially</em> be better pre-optimized by the engine compared to:<br>\n<code>Math[n &lt; 0 ? 'ceil' : 'floor'](n);</code></sup> </p>\n\n<p><strong>Usage</strong>: <code>Math.trunc(/* Number or String */)</code><br>\n<strong>Input</strong>: (Integer or Floating Point) <code>Number</code> (but will happily try to convert a String to a Number)<br>\n<strong>Output</strong>: (Integer) <code>Number</code> (but will happily try to convert Number to String in a string-context)<br>\n<strong>Range</strong>: <code>-2^52</code> to <code>+2^52</code> (beyond this we should expect 'rounding-errors' (and at some point scientific/exponential notation) plain and simply because our <code>Number</code> input in IEEE 754 already lost fractional precision: since Numbers between <code>±2^52</code> to <code>±2^53</code> are already <em>internally rounded</em> integers (for example <code>4503599627370509.5</code> is internally already represented as <code>4503599627370510</code>) and beyond <code>±2^53</code> the integers also loose precision (powers of 2)).\n<br><hr></p>\n\n<p><strong>Float to integer conversion by subtracting the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder\" rel=\"noreferrer\">Remainder</a> (<code>%</code>) of a devision by <code>1</code>:</strong> </p>\n\n<p>Example: <code>result = n-n%1</code> (or <code>n-=n%1</code>)<br>\nThis should also <strong>truncate</strong> floats. Since the Remainder operator has a higher <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence\" rel=\"noreferrer\">precedence</a> than Subtraction we effectively get: <code>(n)-(n%1)</code>.<br>\nFor positive Numbers it's easy to see that this floors the value: <code>(2.5) - (0.5) = 2</code>,<br>\nfor negative Numbers this ceils the value: <code>(-2.5) - (-0.5) = -2</code> (because <code>--=+</code> so <code>(-2.5) + (0.5) = -2</code>).</p>\n\n<p>Since the <strong>input</strong> and <strong>output</strong> are <code>Number</code> we <em>should</em> get the <em>same useful range and output</em> compared to ES6 <code>Math.trunc()</code> (or it's polyfill).<br>\n<sup>Note: tough I <em>fear</em> (not sure) there might be differences: because we are doing arithmetic (which internally uses rounding mode \"nearTiesEven\" (aka Banker's Rounding)) on the original Number (the float) and a second derived Number (the fraction) this seems to invite compounding digital_representation and arithmetic rounding errors, thus potentially returning a float after all.. </sup>\n<br><hr></p>\n\n<p><strong>Float to integer conversion by (ab-)using <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators\" rel=\"noreferrer\">bitwise operations</a>:</strong> </p>\n\n<p>This works by <em>internally</em> forcing a (floating point) <code>Number</code> conversion (truncation and overflow) to a signed 32-bit integer value (two's complement) <em>by using a bitwise operation</em> on a <code>Number</code> (and the result is converted back to a (floating point) <code>Number</code> which holds just the integer value). </p>\n\n<p>Again, <strong>input</strong> and <strong>output</strong> is <code>Number</code> (and again silent conversion from String-input to Number and Number-output to String).</p>\n\n<p>More important tough (and usually forgotten and not explained):<br>\n<em>depending on bitwise operation and the number's sign</em>, the <em>useful <strong>range</em> will be <em>limited</em></strong> between:<br>\n<code>-2^31</code> to <code>+2^31</code> (like <code>~~num</code> or <code>num|0</code> or <code>num&gt;&gt;0</code>) <em>OR</em> <code>0</code> to <code>+2^32</code> (<code>num&gt;&gt;&gt;0</code>). </p>\n\n<p>This should be further clarified by the following lookup-table (containing <em>all</em> 'critical' examples): </p>\n\n<pre>\n n | n>>0 OR n&lt;&lt;0 OR | n>>>0 | n &lt; 0 ? -(-n>>>0) : n>>>0\n | n|0 OR n^0 OR ~~n | |\n | OR n&0xffffffff | |\n----------------------------+-------------------+-------------+---------------------------\n+4294967298.5 = (+2^32)+2.5 | +2 | +2 | +2\n+4294967297.5 = (+2^32)+1.5 | +1 | +1 | +1\n+4294967296.5 = (+2^32)+0.5 | 0 | 0 | 0\n+4294967296 = (+2^32) | 0 | 0 | 0\n+4294967295.5 = (+2^32)-0.5 | -1 | +4294967295 | +4294967295\n+4294967294.5 = (+2^32)-1.5 | -2 | +4294967294 | +4294967294\n etc... | etc... | etc... | etc...\n+2147483649.5 = (+2^31)+1.5 | -2147483647 | +2147483649 | +2147483649\n+2147483648.5 = (+2^31)+0.5 | -2147483648 | +2147483648 | +2147483648\n+2147483648 = (+2^31) | -2147483648 | +2147483648 | +2147483648\n+2147483647.5 = (+2^31)-0.5 | +2147483647 | +2147483647 | +2147483647\n+2147483646.5 = (+2^31)-1.5 | +2147483646 | +2147483646 | +2147483646\n etc... | etc... | etc... | etc...\n +1.5 | +1 | +1 | +1\n +0.5 | 0 | 0 | 0\n 0 | 0 | 0 | 0\n -0.5 | 0 | 0 | 0\n -1.5 | -1 | +4294967295 | -1\n etc... | etc... | etc... | etc...\n-2147483646.5 = (-2^31)+1.5 | -2147483646 | +2147483650 | -2147483646\n-2147483647.5 = (-2^31)+0.5 | -2147483647 | +2147483649 | -2147483647\n-2147483648 = (-2^31) | -2147483648 | +2147483648 | -2147483648\n-2147483648.5 = (-2^31)-0.5 | -2147483648 | +2147483648 | -2147483648\n-2147483649.5 = (-2^31)-1.5 | +2147483647 | +2147483647 | -2147483649\n-2147483650.5 = (-2^31)-2.5 | +2147483646 | +2147483646 | -2147483650\n etc... | etc... | etc... | etc...\n-4294967294.5 = (-2^32)+1.5 | +2 | +2 | -4294967294\n-4294967295.5 = (-2^32)+0.5 | +1 | +1 | -4294967295\n-4294967296 = (-2^32) | 0 | 0 | 0\n-4294967296.5 = (-2^32)-0.5 | 0 | 0 | 0\n-4294967297.5 = (-2^32)-1.5 | -1 | +4294967295 | -1\n-4294967298.5 = (-2^32)-2.5 | -2 | +4294967294 | -2\n</pre> \n\n<p><sup>Note 1: the last column has extended range <code>0</code> to <code>-4294967295</code> using <code>(n &lt; 0 ? -(-n&gt;&gt;&gt;0) : n&gt;&gt;&gt;0)</code>.<br>\nNote 2: bitwise introduces its own conversion-overhead(<em>s</em>) (severity vs <code>Math</code> depends on actual implementation, so bitwise <em>could</em> be faster (often on older historic browsers)).</sup> </p>\n\n<p><hr>\nObviously, if your 'floating point' number was a <code>String</code> to begin with,<br>\n<code>parseInt(/*String*/, /*Radix*/)</code> would be an appropriate choice to parse it into a integer <code>Number</code>.<br>\n<code>parseInt()</code> will <em>truncate</em> as well (for positive and negative numbers).<br>\nThe <em>range</em> is again limited to IEEE 754 double precision floating point as explained above for the <code>Math</code> method(s).</p>\n\n<p>Finally, if you have a <code>String</code> and expect a <code>String</code> as output you could also chop of the radix point and fraction (which also gives you a larger accurate truncation range compared to IEEE 754 double precision floating point (<code>±2^52</code>))!</p>\n\n<p><hr>\nEXTRA:<br>\nFrom the info above you should now have all you need to know. </p>\n\n<p>If for example you'd want <strong>round away from zero</strong> (aka <strong>round towards infinity</strong>) you could modify the <code>Math.trunc()</code> polyfill, for <em>example</em>: </p>\n\n<pre><code>Math.intToInf || (Math.intToInf = function(n){\n return n &lt; 0 ? Math.floor(n) : Math.ceil(n); \n});\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice? Here are a few methods that I know of: ``` var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 a | 0; // 2 ``` I'm sure there are others out there. Suggestions?
According to [**this website**](http://www.jibbering.com/faq/faq_notes/type_convert.html#tcParseIn): > > parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number... > > > For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable... > > >
131,439
<p>I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.</p>
[ { "answer_id": 131461, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 2, "selected": false, "text": "<p>The source code to produce a core dump is in 'gcore', which is part of the gdb package.</p>\n\n<p>Also, the Sun has <a href=\"http://docs.oracle.com/cd/E23823_01/html/816-5165/gcore-1.html\" rel=\"nofollow noreferrer\">gcore</a>.</p>\n\n<p>Also, you have to have a separate process running the core dump, as the current process must be suspended. You'll find the details in the gcore source, or you can just run your platform's gcore with your process as the target.</p>\n" }, { "answer_id": 131482, "author": "mat_geek", "author_id": 11032, "author_profile": "https://Stackoverflow.com/users/11032", "pm_score": 2, "selected": false, "text": "<p>Sun describes how to get a core file on Solaris, HP-UX, Redhat, and Windows <a href=\"http://docs.oracle.com/cd/E19420-01/820-0436/6nc65np82/index.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Solaris has the gcore program. HP-UX may have it.\nOtherwise use gdb and its gcore commmand.\nWindows has win-dbg-root\\tlist.exe and win-dbg-root\\adplus.vbs </p>\n" }, { "answer_id": 131492, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 2, "selected": false, "text": "<p>Do you really want a core, or just a stacktrace ?\nIf all you want is a stacktrace you could take a look at the opensource <a href=\"http://sourceforge.net/projects/lsstack/\" rel=\"nofollow noreferrer\">here</a> and try and integrate the code from there, or maybe just calling it from the command line is enough.</p>\n\n<p>I believe some code in the gdb project might also be useful.</p>\n\n<p>Another think you might want to do is to use gdb to attach to a running process.</p>\n\n<pre><code>$ gdb /path/to/exec 1234 # 1234 is the pid of the running process\n</code></pre>\n" }, { "answer_id": 131539, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 7, "selected": true, "text": "<pre><code>void create_dump(void)\n{\n if(!fork()) {\n // Crash the app in your favorite way here\n *((void*)0) = 42;\n }\n}\n</code></pre>\n<p>Fork the process then crash the child - it'll give you a snapshot whenever you want</p>\n" }, { "answer_id": 24672804, "author": "regnarg", "author_id": 809056, "author_profile": "https://Stackoverflow.com/users/809056", "pm_score": 3, "selected": false, "text": "<p>Another way might be to use the <a href=\"http://code.google.com/p/google-coredumper/\" rel=\"noreferrer\">Google Coredumper</a> library. This creates a similar result to the fork+abort technique but plays nicer with multithreaded apps (suspends all threads for a little while before forking so that they don't make a mess in the child).</p>\n\n<p>Example:</p>\n\n<pre>\n #include &lt;google/coredumper.h>\n ...\n WriteCoreDump('core.myprogram');\n /* Keep going, we generated a core file,\n * but we didn't crash.\n */\n</pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732/" ]
I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.
``` void create_dump(void) { if(!fork()) { // Crash the app in your favorite way here *((void*)0) = 42; } } ``` Fork the process then crash the child - it'll give you a snapshot whenever you want
131,449
<p>I have this code:</p> <pre><code>chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse </code></pre> <p>I want to be able to do this because I don't like knowfully causing Exceptions:</p> <pre><code>chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse </code></pre> <p>Is there a way I can do this?</p>
[ { "answer_id": 131452, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "<pre><code>if element in mylist:\n index = mylist.index(element)\n # ... do something\nelse:\n # ... do something else\n</code></pre>\n" }, { "answer_id": 131522, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 4, "selected": true, "text": "<p>Note that the latter approach is going against the generally accepted \"pythonic\" philosophy of <a href=\"http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions\" rel=\"nofollow noreferrer\">EAFP, or \"It is Easier to Ask for Forgiveness than Permission.\"</a>, while the former follows it.</p>\n" }, { "answer_id": 131930, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 0, "selected": false, "text": "<p>For the specific case where your list is a sequence of single-character strings you can get what you want by changing the list to be searched to a string in advance (eg. ''.join(chars)).</p>\n\n<p>You can then use the .find() method, which does work as you want. However, there's no corresponding method for lists or tuples.</p>\n\n<p>Another possible option is to use a dictionary instead. eg.</p>\n\n<pre><code>d = dict((x, loc) for (loc,x) in enumerate(chars))\n...\nindex = d.get(chars_to_find, -1) # Second argument is default if not found.\n</code></pre>\n\n<p>This may also perform better if you're doing a lot of searches on the list. If it's just a single search on a throwaway list though, its not worth doing.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I have this code: ``` chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse ``` I want to be able to do this because I don't like knowfully causing Exceptions: ``` chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse ``` Is there a way I can do this?
Note that the latter approach is going against the generally accepted "pythonic" philosophy of [EAFP, or "It is Easier to Ask for Forgiveness than Permission."](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions), while the former follows it.
131,456
<p>How do I apply the MarshalAsAttribute to the return type of the code below?</p> <pre><code>public ISomething Foo() { return new MyFoo(); } </code></pre>
[ { "answer_id": 131467, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 6, "selected": true, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx</a>:</p>\n\n<pre><code>[return: MarshalAs(&lt;your marshal type&gt;)]\npublic ISomething Foo()\n{\n return new MyFoo();\n}\n</code></pre>\n" }, { "answer_id": 131471, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 2, "selected": false, "text": "<pre><code>[return:MarshalAs]\npublic ISomething Foo()\n{\n return new MyFoo();\n}\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ]
How do I apply the MarshalAsAttribute to the return type of the code below? ``` public ISomething Foo() { return new MyFoo(); } ```
According to <http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx>: ``` [return: MarshalAs(<your marshal type>)] public ISomething Foo() { return new MyFoo(); } ```
131,473
<p>G'day Stackoverflowers,</p> <p>I'm the author of Perl's <a href="http://search.cpan.org/perldoc?autodie" rel="nofollow noreferrer">autodie</a> pragma, which changes Perl's built-ins to throw exceptions on failure. It's similar to <a href="http://search.cpan.org/perldoc?Fatal" rel="nofollow noreferrer">Fatal</a>, but with lexical scope, an extensible exception model, more intelligent return checking, and much, much nicer error messages. It will be replacing the <code>Fatal</code> module in future releases of Perl (provisionally 5.10.1+), but can currently be downloaded from the CPAN for Perl 5.8.0 and above.</p> <p>The next release of <code>autodie</code> will add special handling for calls to <code>flock</code> with the <code>LOCK_NB</code> (non-blocking) option. While a failed <code>flock</code> call would normally result in an exception under <code>autodie</code>, a failed call to <code>flock</code> using <code>LOCK_NB</code> will merely return false if the returned errno (<code>$!</code>) is <code>EWOULDBLOCK</code>.</p> <p>The reason for this is so people can continue to write code like:</p> <pre><code>use Fcntl qw(:flock); use autodie; # All perl built-ins now succeed or die. open(my $fh, '&lt;', 'some_file.txt'); my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can. if ($lock) { # Opportuntistically do something with the locked file. } </code></pre> <p>In the above code, a lock that fails because someone else has the file locked already (<code>EWOULDBLOCK</code>) is not considered to be a hard error, so autodying <code>flock</code> merely returns a false value. In the situation that we're working with a filesystem that doesn't support file-locks, or a network filesystem and the network just died, then autodying <code>flock</code> generates an appropriate exception when it sees that our errno is not <code>EWOULDBLOCK</code>.</p> <p>This works just fine in my dev version on Unix-flavoured systems, but it fails horribly under Windows. It appears that while Perl under Windows supports the <code>LOCK_NB</code> option, it doesn't define <code>EWOULDBLOCK</code>. Instead, the errno returned is 33 ("Domain error") when blocking would occur.</p> <p>Obviously I can hard-code this as a constant into <code>autodie</code>, but that's not what I want to do here, because it means that I'm screwed if the errno ever changes (or has changed). I would love to compare it to the Windows equivalent of <code>POSIX::EWOULDBLOCK</code>, but I can't for the life of me find where such a thing would be defined. If you can help, let me know.</p> <p>Answers I specifically don't want:</p> <ul> <li>Suggestions to hard-code it as a constant (or worse still, leave a magic number floating about).</li> <li>Not supporting <code>LOCK_NB</code> functionality at all under Windows.</li> <li>Assuming that any failure from a <code>LOCK_NB</code> call to <code>flock</code> should return merely false.</li> <li>Suggestions that I ask on p5p or <a href="http://perlmonks.org/" rel="nofollow noreferrer">perlmonks</a>. I already know about them.</li> <li>An explanation of how <code>flock</code>, or exceptions, or <code>Fatal</code> work. I already know. Intimately.</li> </ul>
[ { "answer_id": 131798, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 5, "selected": true, "text": "<p>Under Win32 \"native\" Perl, note that $^E is more descriptive at 33, \"The process cannot access the file because another process locked a portion of the file\" which is <code>ERROR_LOCK_VIOLATION</code> (available from <a href=\"http://search.cpan.org/dist/Win32-WinError/\" rel=\"nofollow noreferrer\">Win32::WinError</a>).</p>\n" }, { "answer_id": 131867, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "<p>For the Windows-specific error code, you want to use <code>$^E</code>. In this case, it's 33: \"The process cannot access the file because another process has locked a portion of the file\" (<code>ERROR_LOCK_VIOLATION</code> in <code>winerror.h</code>).</p>\n\n<p>Unfortunately, I don't think <a href=\"http://search.cpan.org/dist/Win32-WinError/\" rel=\"nofollow noreferrer\">Win32::WinError</a> is in core. On the other hand, if Microsoft ever renumbered the Windows error codes, pretty much every Windows program ever written would stop working, so I don't think there'll be a problem with hardcoding it.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19422/" ]
G'day Stackoverflowers, I'm the author of Perl's [autodie](http://search.cpan.org/perldoc?autodie) pragma, which changes Perl's built-ins to throw exceptions on failure. It's similar to [Fatal](http://search.cpan.org/perldoc?Fatal), but with lexical scope, an extensible exception model, more intelligent return checking, and much, much nicer error messages. It will be replacing the `Fatal` module in future releases of Perl (provisionally 5.10.1+), but can currently be downloaded from the CPAN for Perl 5.8.0 and above. The next release of `autodie` will add special handling for calls to `flock` with the `LOCK_NB` (non-blocking) option. While a failed `flock` call would normally result in an exception under `autodie`, a failed call to `flock` using `LOCK_NB` will merely return false if the returned errno (`$!`) is `EWOULDBLOCK`. The reason for this is so people can continue to write code like: ``` use Fcntl qw(:flock); use autodie; # All perl built-ins now succeed or die. open(my $fh, '<', 'some_file.txt'); my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can. if ($lock) { # Opportuntistically do something with the locked file. } ``` In the above code, a lock that fails because someone else has the file locked already (`EWOULDBLOCK`) is not considered to be a hard error, so autodying `flock` merely returns a false value. In the situation that we're working with a filesystem that doesn't support file-locks, or a network filesystem and the network just died, then autodying `flock` generates an appropriate exception when it sees that our errno is not `EWOULDBLOCK`. This works just fine in my dev version on Unix-flavoured systems, but it fails horribly under Windows. It appears that while Perl under Windows supports the `LOCK_NB` option, it doesn't define `EWOULDBLOCK`. Instead, the errno returned is 33 ("Domain error") when blocking would occur. Obviously I can hard-code this as a constant into `autodie`, but that's not what I want to do here, because it means that I'm screwed if the errno ever changes (or has changed). I would love to compare it to the Windows equivalent of `POSIX::EWOULDBLOCK`, but I can't for the life of me find where such a thing would be defined. If you can help, let me know. Answers I specifically don't want: * Suggestions to hard-code it as a constant (or worse still, leave a magic number floating about). * Not supporting `LOCK_NB` functionality at all under Windows. * Assuming that any failure from a `LOCK_NB` call to `flock` should return merely false. * Suggestions that I ask on p5p or [perlmonks](http://perlmonks.org/). I already know about them. * An explanation of how `flock`, or exceptions, or `Fatal` work. I already know. Intimately.
Under Win32 "native" Perl, note that $^E is more descriptive at 33, "The process cannot access the file because another process locked a portion of the file" which is `ERROR_LOCK_VIOLATION` (available from [Win32::WinError](http://search.cpan.org/dist/Win32-WinError/)).
131,516
<p>I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change </p> <pre> Uses * Uses unit1 in 'unit1.pas' * unit1 unit2 in 'unit2.pas' * unit2 ... * ... </pre> <p>in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found. This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file.<p></p> <p>I'm running <code>make -f [then some options]</code>, the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the <code>in 'unit1.pas</code> is removed. <p></p>
[ { "answer_id": 131526, "author": "Peter Turner", "author_id": 1765, "author_profile": "https://Stackoverflow.com/users/1765", "pm_score": 1, "selected": false, "text": "<p>Well this work-around worked for me. </p>\n\n<pre>\n//{$define PACKAGE}\n{$ifdef PACKAGE}\n uses \n unit1 in 'unit1.pas'\n unit2 in 'unit2.pas'\n ... \n{$else}\n uses \n unit1 \n unit2\n ...\n{$endif}\n</pre>\n\n<p>The only problem is whenever you add a new unit, delphi erases your <code>ifdef package</code> at the top. </p>\n" }, { "answer_id": 131927, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 0, "selected": false, "text": "<p>Every time I have to put conditionals into a project file I do this:</p>\n\n<pre><code>program a;\n\nuses\n ACondUnits;\n\n...\n</code></pre>\n\n<p><br/></p>\n\n<pre><code>unit ACondUnits;\n\ninterface\n\nuses\n{$IFDEF UseD7MM}\n Delphi7MM;\n{$ELSE}\n FastMM4;\n{$ENDIF}\n\nimplementation\n\nend.\n</code></pre>\n\n<p>Maybe this trick works in packages too. Never tried.</p>\n" }, { "answer_id": 132304, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>It could come from the fact, that the search path in the IDE and the search path of the command line compiler are not the same. If you change the serach path of the command line compiler you might be able to use the exactely same source code as within the IDE.</p>\n\n<p>One possibility to configure the search path for the command-line compiler is to do it in a file called dcc32.cfg. Take a look at the help, there is a short description of dcc32.cfg in the IDE-help.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change ``` Uses * Uses unit1 in 'unit1.pas' * unit1 unit2 in 'unit2.pas' * unit2 ... * ... ``` in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found. This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file. I'm running `make -f [then some options]`, the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the `in 'unit1.pas` is removed.
It could come from the fact, that the search path in the IDE and the search path of the command line compiler are not the same. If you change the serach path of the command line compiler you might be able to use the exactely same source code as within the IDE. One possibility to configure the search path for the command-line compiler is to do it in a file called dcc32.cfg. Take a look at the help, there is a short description of dcc32.cfg in the IDE-help.
131,518
<p>In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section):</p> <pre><code>&lt;httpHandlers&gt; &lt;add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" /&gt; &lt;/httpHandlers&gt; </code></pre> <p>This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working. Any idea why this would be the case?</p> <p>Cheers Greg</p>
[ { "answer_id": 131531, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>It sounds like it as an inherant &lt;clear /&gt; in it although I don't know if I've seen this behaviour before, you could just add the general handler back, let me find you the code.</p>\n\n<pre><code>&lt;add verb=\"*\" path=\"*.asmx\" type=\"System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services\" validate=\"false\"&gt;\n</code></pre>\n\n<p>I think thats the right element, give it a shot.</p>\n\n<p>EDIT: That is odd, I don't have a copy of 2003 on this machine so I can't open a 1.1 but I thought that was the right declaration. You could try adding <code>validate=\"false\"</code> into each element and see if that makes a difference.</p>\n" }, { "answer_id": 131658, "author": "Jeeby", "author_id": 21969, "author_profile": "https://Stackoverflow.com/users/21969", "pm_score": 2, "selected": false, "text": "<p>I got it... CQ you were on the right track.. i did need to add the .asmx handler again, but the .net 1.1 specific one. Final code is as follows:</p>\n\n<pre><code>&lt;httpHandlers&gt;\n &lt;add verb=\"*\" path=\"*.bcn\" type=\"Internet2008.Beacon.BeaconHandler, Internet2008\" validate=\"false\" /&gt;\n &lt;add verb=\"*\" path=\"*.asmx\" type=\"System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" validate=\"false\"/&gt;\n&lt;/httpHandlers&gt;\n</code></pre>\n\n<p>I hope there's no other file types that are not getting handled properly because of this declaration. :|</p>\n\n<p>Thanks for the help\ngreg</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section): ``` <httpHandlers> <add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" /> </httpHandlers> ``` This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working. Any idea why this would be the case? Cheers Greg
It sounds like it as an inherant <clear /> in it although I don't know if I've seen this behaviour before, you could just add the general handler back, let me find you the code. ``` <add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services" validate="false"> ``` I think thats the right element, give it a shot. EDIT: That is odd, I don't have a copy of 2003 on this machine so I can't open a 1.1 but I thought that was the right declaration. You could try adding `validate="false"` into each element and see if that makes a difference.
131,559
<p>Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique.</p> <p>So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether).</p> <p>How do I achieve that?</p>
[ { "answer_id": 131563, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": -1, "selected": false, "text": "<pre><code>/(foo|bar)\n</code></pre>\n" }, { "answer_id": 131572, "author": "ChronoPositron", "author_id": 19127, "author_profile": "https://Stackoverflow.com/users/19127", "pm_score": 0, "selected": false, "text": "<p>Vim supports regular expressions by starting in command mode with a '/'.</p>\n\n<p>So using something like \"/(foo\\|bar)\" (as was stated before) would solve the problem. It's good to know why that works and what you are using (regular expressions).</p>\n" }, { "answer_id": 131574, "author": "Codeslayer", "author_id": 4021, "author_profile": "https://Stackoverflow.com/users/4021", "pm_score": 5, "selected": true, "text": "<pre><code>/^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line)\n/fred\\|joe : Search for FRED OR JOE\n</code></pre>\n" }, { "answer_id": 131583, "author": "AJ.", "author_id": 17716, "author_profile": "https://Stackoverflow.com/users/17716", "pm_score": 2, "selected": false, "text": "<p>Actually I found the answer soon after I posted this (yes I did google earlier but was unable to locate it. Probably was just searching wrong)</p>\n\n<p>The right solution is</p>\n\n<p>/(foo\\|bar)</p>\n\n<p>@Paul Betts: The pipe has to be escaped</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17716/" ]
Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique. So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether). How do I achieve that?
``` /^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line) /fred\|joe : Search for FRED OR JOE ```
131,605
<p>What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system?</p> <p>To put this in perspective, here are a couple of use cases:</p> <ol> <li>version control for VBA modules </li> <li>more than one person is working on a Excel spreadsheet and they may be making changes to the same worksheet, which they want to merge and integrate. This worksheet may have formulae, data, charts etc</li> <li>the users are not too technical and the fewer version control systems used the better</li> <li>Space constraint is a consideration. Ideally only incremental changes are saved rather than the entire Excel spreadsheet. </li> </ol>
[ { "answer_id": 131636, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 1, "selected": false, "text": "<p>Use any of the standard version control tools like SVN or CVS. Limitations would depend on whats the objective. Apart from a small increase in size of the repository, i did'nt face any issues</p>\n" }, { "answer_id": 131637, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>It depends whether you are talking about data, or the code contained within a spreadsheet. While I have a strong dislike of Microsoft's Visual Sourcesafe and normally would not recommended it, it does integrate easily with both Access and Excel, and provides source control of modules.</p>\n\n<p>[In fact the integration with Access, includes queries, reports and modules as individual objects that can be versioned]</p>\n\n<p>The MSDN link is <a href=\"http://msdn.microsoft.com/en-us/library/aa164816(office.10).aspx\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 131638, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": -1, "selected": false, "text": "<p>It depends on what level of integration you want, I've used Subversion/TortoiseSVN which seems fine for simple usage. I have also added in keywords but there seems to be a risk of file corruption. There's an option in Subversion to make the keyword substitutions fixed length and as far as I understand it will work if the fixed length is even but not odd. In any case you don't get any useful sort of diff functionality, I think there are commercial products that will do 'diff'. I did find something that did diff based on converting stuff to plain text and comparing that, but it wasn't very nice.</p>\n" }, { "answer_id": 131654, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": -1, "selected": false, "text": "<p>It should work with most VCS (depending on other criteria you might choose SVN, CVS, Darcs, TFS, etc), however it will actually the complete file (because it is a binary format), meaning that the \"what changed\" question is not so easy to answer.</p>\n\n<p>You can still rely on log messages <em>if</em> people complete them, but you might also try the new XML based formats from Office 2007 to gain some more visibility (although it would still be hard to weed through the tons of XML, plus AFAIK the XML file is zipped on the disk, so you would need a pre-commit hook to unzip it for text diff to work correctly).</p>\n" }, { "answer_id": 131661, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>If you are looking at an office setting with regular office non technical users than Sharepoint is a viable alternative. You can setup document folders with version control enabled and checkins and checkouts. Makes it freindlier for regular office users.</p>\n" }, { "answer_id": 132084, "author": "GUI Junkie", "author_id": 11498, "author_profile": "https://Stackoverflow.com/users/11498", "pm_score": 2, "selected": false, "text": "<p>One thing you could do is to have the following snippet in your Workbook:</p>\n\n<pre><code>Sub SaveCodeModules()\n\n'This code Exports all VBA modules\nDim i%, sName$\n\n With ThisWorkbook.VBProject\n For i% = 1 To .VBComponents.Count\n If .VBComponents(i%).CodeModule.CountOfLines &gt; 0 Then\n sName$ = .VBComponents(i%).CodeModule.Name\n .VBComponents(i%).Export \"C:\\Code\\\" &amp; sName$ &amp; \".vba\"\n End If\n Next i\n End With\nEnd Sub\n</code></pre>\n\n<p>I found this snippet on the Internet.</p>\n\n<p>Afterwards, you could use Subversion to maintain version control. For example by using the command line interface of Subversion with the 'shell' command within VBA. That would do it. I'm even thinking of doing this myself :)</p>\n" }, { "answer_id": 132284, "author": "Hobbo", "author_id": 6387, "author_profile": "https://Stackoverflow.com/users/6387", "pm_score": 3, "selected": false, "text": "<p>I'm not aware of a tool that does this well but I've seen a variety of homegrown solutions. The common thread of these is to minimise the binary data under version control and maximise textual data to leverage the power of conventional scc systems. To do this:</p>\n\n<ul>\n<li>Treat the workbook like any other application. Seperate logic, config and data.</li>\n<li>Separate code from the workbook.</li>\n<li>Build the UI programmatically. </li>\n<li>Write a build script to reconstruct the workbook.</li>\n</ul>\n" }, { "answer_id": 147488, "author": "SpyJournal", "author_id": 10326, "author_profile": "https://Stackoverflow.com/users/10326", "pm_score": 2, "selected": false, "text": "<p>in response to mattlant's reply - sharepoint will work well as a version control only if the version control feature is turned on in the document library.\nin addition be aware that any code that calls other files by relative paths wont work. and finally any links to external files will break when a file is saved in sharepoint.</p>\n" }, { "answer_id": 2003792, "author": "Demosthenex", "author_id": 243588, "author_profile": "https://Stackoverflow.com/users/243588", "pm_score": 7, "selected": true, "text": "<p>I've just setup a spreadsheet that uses Bazaar, with manual checkin/out via TortiseBZR. Given that the topic helped me with the save portion, I wanted to post my solution here.</p>\n\n<p><em>The solution for me was to create a spreadsheet that exports all modules on save, and removes and re-imports the modules on open. Yes, this could be potentially dangerous for converting existing spreadsheets.</em></p>\n\n<p>This allows me to edit the macros in the modules via <strong>Emacs</strong> (yes, emacs) or natively in Excel, and commit my BZR repository after major changes. Because all the modules are text files, the standard diff-style commands in BZR work for my sources except the Excel file itself.</p>\n\n<p>I've setup a directory for my BZR repository, X:\\Data\\MySheet. In the repo are MySheet.xls and one .vba file for each of my modules (ie: Module1Macros). In my spreadsheet I've added one module that is exempt from the export/import cycle called \"VersionControl\". Each module to be exported and re-imported must end in \"Macros\".</p>\n\n<p><strong>Contents of the \"VersionControl\" module:</strong></p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub SaveCodeModules()\n\n'This code Exports all VBA modules\nDim i%, sName$\n\nWith ThisWorkbook.VBProject\n For i% = 1 To .VBComponents.Count\n If .VBComponents(i%).CodeModule.CountOfLines &gt; 0 Then\n sName$ = .VBComponents(i%).CodeModule.Name\n .VBComponents(i%).Export \"X:\\Tools\\MyExcelMacros\\\" &amp; sName$ &amp; \".vba\"\n End If\n Next i\nEnd With\n\nEnd Sub\n\nSub ImportCodeModules()\n\nWith ThisWorkbook.VBProject\n For i% = 1 To .VBComponents.Count\n\n ModuleName = .VBComponents(i%).CodeModule.Name\n\n If ModuleName &lt;&gt; \"VersionControl\" Then\n If Right(ModuleName, 6) = \"Macros\" Then\n .VBComponents.Remove .VBComponents(ModuleName)\n .VBComponents.Import \"X:\\Data\\MySheet\\\" &amp; ModuleName &amp; \".vba\"\n End If\n End If\n Next i\nEnd With\n\nEnd Sub\n</code></pre>\n\n<p>Next, we have to setup event hooks for open / save to run these macros. In the code viewer, right click on \"ThisWorkbook\" and select \"View Code\". You may have to pull down the select box at the top of the code window to change from \"(General)\" view to \"Workbook\" view.</p>\n\n<p><strong>Contents of \"Workbook\" view:</strong></p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub Workbook_Open()\n\nImportCodeModules\n\nEnd Sub\n\nPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)\n\nSaveCodeModules\n\nEnd Sub\n</code></pre>\n\n<p>I'll be settling into this workflow over the next few weeks, and I'll post if I have any problems.</p>\n\n<p>Thanks for sharing the VBComponent code!</p>\n" }, { "answer_id": 2021578, "author": "mcherm", "author_id": 14570, "author_profile": "https://Stackoverflow.com/users/14570", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://tortoisesvn.tigris.org/\" rel=\"noreferrer\">TortoiseSVN</a> is an astonishingly good Windows client for the Subversion version control system. One feature which I just discovered that it has is that when you click to get a diff between versions of an Excel file, it will open both versions in Excel and highlight (in red) the cells that were changed. This is done through the magic of a vbs script, described <a href=\"http://tortoisesvn.tigris.org/ds/viewMessage.do?dsForumId=4061&amp;dsMessageId=878721\" rel=\"noreferrer\">here</a>.</p>\n\n<p>You may find this useful even if NOT using TortoiseSVN.</p>\n" }, { "answer_id": 4038275, "author": "Jim Slavens", "author_id": 489445, "author_profile": "https://Stackoverflow.com/users/489445", "pm_score": 1, "selected": false, "text": "<p>I have been looking into this too. It apears that the latest Team Foundation Server 2010 may have an Excel Add-In.</p>\n\n<p>Here is a clue:</p>\n\n<p><a href=\"http://team-foundation-server.blogspot.com/2009/07/tf84037-there-was-problem-initializing.html\" rel=\"nofollow\">http://team-foundation-server.blogspot.com/2009/07/tf84037-there-was-problem-initializing.html</a></p>\n" }, { "answer_id": 8728724, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 0, "selected": false, "text": "<p>There is also a program called <strong>Beyond Compare</strong> that has a quite nice Excel file compare. I found a screenshot in chinese that briefly shows this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/EQw6F.jpg\" alt=\"Beyond Compare - comparing two excel files (Chinese)\"><br>\n<a href=\"http://www.cnblogs.com/HarryHuang/archive/2010/03/08/1680929.html\" rel=\"nofollow noreferrer\">Original image source</a></p>\n\n<p>There is a 30 day trial on their <a href=\"http://www.scootersoftware.com/\" rel=\"nofollow noreferrer\">page</a></p>\n" }, { "answer_id": 8738585, "author": "Nate", "author_id": 1131501, "author_profile": "https://Stackoverflow.com/users/1131501", "pm_score": -1, "selected": false, "text": "<p>I wrote a revision controlled spreadsheet using VBA.\nIt is geared more for engineering reports where you have multiple people working on a Bill Of Material or Schedule and then at some point in time you want to create a snapshot revision that shows adds, del and updates from the previous rev.</p>\n\n<p>Note: it is a macro enabled workbook that you need to sign in to download from my site (you can use OpenID)</p>\n\n<p>All the code is unlocked. </p>\n\n<p><a href=\"http://www.run8tech.com/tools.aspx\" rel=\"nofollow\">Rev Controlled Spreadsheet</a></p>\n" }, { "answer_id": 11357206, "author": "Dave Saunders", "author_id": 1505967, "author_profile": "https://Stackoverflow.com/users/1505967", "pm_score": 0, "selected": false, "text": "<p>You might have tried using Microsoft's Excel XML in zip container (.xlsx and .xslm) for version control and found the vba was stored in vbaProject.bin (which is useless for version control).</p>\n\n<p>The solution is simple.</p>\n\n<ol>\n<li> Open the excel file with LibreOffice Calc</li>\n<li> In LibreOffice Calc \n<ol>\n<li> File</li>\n<li> Save as</li>\n<li> Save as type: ODF Spreadsheet (.ods)</li>\n\n</ol>\n</li>\n<li> Close LibreOffice Calc</li>\n<li> rename the new file's file extension from .ods to .zip</li>\n<li> create a folder for the spreadsheet in a GIT maintained area</li>\n<li> extract the zip into it's GIT folder</li>\n<li> commit to GIT</li>\n\n</ol>\n\n<p>When you repeat this with the next version of the spreadsheet you'll have to make sure you make the folder's files exactly match those in the zip container (and don't leave any deleted files behind).</p>\n" }, { "answer_id": 22256698, "author": "przemo_li", "author_id": 330242, "author_profile": "https://Stackoverflow.com/users/330242", "pm_score": 3, "selected": false, "text": "<p>Working upon @Demosthenex work, @Tmdean and @Jon Crowell invaluable comments! (+1 them)</p>\n\n<p><strong>I save module files in git\\ dir beside workbook location. Change that to your liking.</strong></p>\n\n<p><strong>This will NOT track changes to Workbook code. So it's up to you to synchronize them.</strong></p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub SaveCodeModules()\n\n'This code Exports all VBA modules\nDim i As Integer, name As String\n\nWith ThisWorkbook.VBProject\n For i = .VBComponents.count To 1 Step -1\n If .VBComponents(i).Type &lt;&gt; vbext_ct_Document Then\n If .VBComponents(i).CodeModule.CountOfLines &gt; 0 Then\n name = .VBComponents(i).CodeModule.name\n .VBComponents(i).Export Application.ThisWorkbook.Path &amp; _\n \"\\git\\\" &amp; name &amp; \".vba\"\n End If\n End If\n Next i\nEnd With\n\nEnd Sub\n\nSub ImportCodeModules()\nDim i As Integer\nDim ModuleName As String\n\nWith ThisWorkbook.VBProject\n For i = .VBComponents.count To 1 Step -1\n\n ModuleName = .VBComponents(i).CodeModule.name\n\n If ModuleName &lt;&gt; \"VersionControl\" Then\n If .VBComponents(i).Type &lt;&gt; vbext_ct_Document Then\n .VBComponents.Remove .VBComponents(ModuleName)\n .VBComponents.Import Application.ThisWorkbook.Path &amp; _\n \"\\git\\\" &amp; ModuleName &amp; \".vba\"\n End If\n End If\n Next i\nEnd With\n\nEnd Sub\n</code></pre>\n\n<p>And then in Workbook module:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub Workbook_Open()\n\n ImportCodeModules\n\nEnd Sub\n\nPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)\n\n SaveCodeModules\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 26320757, "author": "MathKid", "author_id": 2780179, "author_profile": "https://Stackoverflow.com/users/2780179", "pm_score": 1, "selected": false, "text": "<p>After searching for ages and trying out many different tools, I've found my answer to the vba version control problem here: <a href=\"https://stackoverflow.com/a/25984759/2780179\">https://stackoverflow.com/a/25984759/2780179</a></p>\n\n<p>It's a simple excel addin for which the code can be found <a href=\"https://github.com/hilkoc/vbaDeveloper\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>There are no duplicate modules after importing. It exports your code automatically, as soon as you save your workbook, <em>without modifying any existing workbooks</em>.\nIt comes together with a vba code formatter.</p>\n" }, { "answer_id": 30127696, "author": "dslosky", "author_id": 4921888, "author_profile": "https://Stackoverflow.com/users/4921888", "pm_score": 3, "selected": false, "text": "<p>Taking @Demosthenex 's answer a step further, if you'd like to also keep track of the code in your Microsoft Excel Objects and UserForms you have to get a little bit tricky.</p>\n\n<p>First I altered my <code>SaveCodeModules()</code> function to account for the different types of code I plan to export:</p>\n\n\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub SaveCodeModules(dir As String)\n\n'This code Exports all VBA modules\nDim moduleName As String\nDim vbaType As Integer\n\nWith ThisWorkbook.VBProject\n For i = 1 To .VBComponents.count\n If .VBComponents(i).CodeModule.CountOfLines &gt; 0 Then\n moduleName = .VBComponents(i).CodeModule.Name\n vbaType = .VBComponents(i).Type\n\n If vbaType = 1 Then\n .VBComponents(i).Export dir &amp; moduleName &amp; \".vba\"\n ElseIf vbaType = 3 Then\n .VBComponents(i).Export dir &amp; moduleName &amp; \".frm\"\n ElseIf vbaType = 100 Then\n .VBComponents(i).Export dir &amp; moduleName &amp; \".cls\"\n End If\n\n End If\n Next i\nEnd With\n\nEnd Sub\n</code></pre>\n\n<p>The UserForms can be exported and imported just like VBA code. The only difference is that two files will be created when a form is exported (you'll get a <code>.frm</code> and a <code>.frx</code> file for each UserForm). One of these holds the software you've written and the other is a binary file which (I'm pretty sure) defines the layout of the form.</p>\n\n<p>Microsoft Excel Objects (MEOs) (meaning <code>Sheet1</code>, <code>Sheet2</code>, <code>ThisWorkbook</code> etc) can be exported as a <code>.cls</code> file. However, when you want to get this code back into your workbook, if you attempt to import it the same way you would a VBA module, you'll get an error if that sheet already exists in the workbook. </p>\n\n<p>To get around this issue, I decided not to try to import the .cls file into Excel, but to read the <code>.cls</code> file into excel as a string instead, then paste this string into the empty MEO. Here is my ImportCodeModules:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub ImportCodeModules(dir As String)\n\nDim modList(0 To 0) As String\nDim vbaType As Integer\n\n' delete all forms, modules, and code in MEOs\nWith ThisWorkbook.VBProject\n For Each comp In .VBComponents\n\n moduleName = comp.CodeModule.Name\n\n vbaType = .VBComponents(moduleName).Type\n\n If moduleName &lt;&gt; \"DevTools\" Then\n If vbaType = 1 Or _\n vbaType = 3 Then\n\n .VBComponents.Remove .VBComponents(moduleName)\n\n ElseIf vbaType = 100 Then\n\n ' we can't simply delete these objects, so instead we empty them\n .VBComponents(moduleName).CodeModule.DeleteLines 1, .VBComponents(moduleName).CodeModule.CountOfLines\n\n End If\n End If\n Next comp\nEnd With\n\n' make a list of files in the target directory\nSet FSO = CreateObject(\"Scripting.FileSystemObject\")\nSet dirContents = FSO.getfolder(dir) ' figure out what is in the directory we're importing\n\n' import modules, forms, and MEO code back into workbook\nWith ThisWorkbook.VBProject\n For Each moduleName In dirContents.Files\n\n ' I don't want to import the module this script is in\n If moduleName.Name &lt;&gt; \"DevTools.vba\" Then\n\n ' if the current code is a module or form\n If Right(moduleName.Name, 4) = \".vba\" Or _\n Right(moduleName.Name, 4) = \".frm\" Then\n\n ' just import it normally\n .VBComponents.Import dir &amp; moduleName.Name\n\n ' if the current code is a microsoft excel object\n ElseIf Right(moduleName.Name, 4) = \".cls\" Then\n Dim count As Integer\n Dim fullmoduleString As String\n Open moduleName.Path For Input As #1\n\n count = 0 ' count which line we're on\n fullmoduleString = \"\" ' build the string we want to put into the MEO\n Do Until EOF(1) ' loop through all the lines in the file\n\n Line Input #1, moduleString ' the current line is moduleString\n If count &gt; 8 Then ' skip the junk at the top of the file\n\n ' append the current line `to the string we'll insert into the MEO\n fullmoduleString = fullmoduleString &amp; moduleString &amp; vbNewLine\n\n End If\n count = count + 1\n Loop\n\n ' insert the lines into the MEO\n .VBComponents(Replace(moduleName.Name, \".cls\", \"\")).CodeModule.InsertLines .VBComponents(Replace(moduleName.Name, \".cls\", \"\")).CodeModule.CountOfLines + 1, fullmoduleString\n\n Close #1\n\n End If\n End If\n\n Next moduleName\nEnd With\n\nEnd Sub\n</code></pre>\n\n<p>In case you're confused by the <code>dir</code> input to both of these functions, that is just your code repository! So, you'd call these functions like:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>SaveCodeModules \"C:\\...\\YourDirectory\\Project\\source\\\"\nImportCodeModules \"C:\\...\\YourDirectory\\Project\\source\\\"\n</code></pre>\n" }, { "answer_id": 30273256, "author": "nmz787", "author_id": 253127, "author_profile": "https://Stackoverflow.com/users/253127", "pm_score": 3, "selected": false, "text": "<p>I use <strong>git</strong>, and today I ported <a href=\"https://github.com/tokuhirom/git-xlsx-textconv\" rel=\"noreferrer\" title=\"this (git-xlsx-textconv)\">this (git-xlsx-textconv)</a> to Python, since my project is based on Python code, and it interacts with Excel files. This works for at least <strong>.xlsx</strong> files, but I think it will work for <strong>.xls</strong> too. <a href=\"https://gist.github.com/nmz787/c43bc109db915064f188\" rel=\"noreferrer\" title=\"Here&#39;s\">Here's</a> the github link. I wrote two versions, one with each row on its own line, and another where each cell is on its own line (the latter was written because <strong>git diff</strong> doesn't like to wrap long lines by default, at least here on Windows).</p>\n\n<p>This is my <strong>.gitconfig</strong> file (this allows the differ script to reside in my project's repo):</p>\n\n<pre><code>[diff \"xlsx\"]\n binary = true\n textconv = python `git rev-parse --show-toplevel`/src/util/git-xlsx-textconv.py\n</code></pre>\n\n<p>if you want the script to be available for many different repos, then use something like this:</p>\n\n<pre><code>[diff \"xlsx\"]\n binary = true\n textconv = python C:/Python27/Scripts/git-xlsx-textconv.py\n</code></pre>\n\n<p>my <strong>.gitattributes</strong> file:</p>\n\n<pre><code>*.xlsx diff=xlsx\n</code></pre>\n" }, { "answer_id": 36402177, "author": "Bjorn Stiel", "author_id": 1741053, "author_profile": "https://Stackoverflow.com/users/1741053", "pm_score": 4, "selected": false, "text": "<p>Let me summarise what you would like to version control and why:</p>\n\n<ol>\n<li><p>What:</p>\n\n<ul>\n<li>Code (VBA)</li>\n<li>Spreadsheets (Formulae)</li>\n<li>Spreadsheets (Values)</li>\n<li>Charts</li>\n<li>...</li>\n</ul></li>\n<li><p>Why: </p>\n\n<ul>\n<li>Audit log</li>\n<li>Collaboration</li>\n<li>Version comparison (\"diffing\")</li>\n<li>Merging</li>\n</ul></li>\n</ol>\n\n<p>As others have posted here, there are a couple of solutions on top of existing version control systems such as:</p>\n\n<ul>\n<li>Git</li>\n<li>Mercurial</li>\n<li>Subversion</li>\n<li>Bazaar</li>\n</ul>\n\n<p>If your only concern is the VBA code in your workbooks, then the approach Demosthenex above proposes or VbaGit (<a href=\"https://github.com/brucemcpherson/VbaGit\" rel=\"noreferrer\">https://github.com/brucemcpherson/VbaGit</a>) work very well working and are relatively simple to implement. The advantages are that you can rely on well proven version control systems and chose one according to your needs (have a look at <a href=\"https://help.github.com/articles/what-are-the-differences-between-svn-and-git/\" rel=\"noreferrer\">https://help.github.com/articles/what-are-the-differences-between-svn-and-git/</a> for a brief comparison between Git and Subversion).</p>\n\n<p>If you not only worry about code but also about the data in your sheets (\"hardcoded\" values and formula results), you can use a similar strategy for that: Serialise the contents of your sheets into some text format (via Range.Value) and use an existing version control system. Here's a very good blog post about this: <a href=\"https://wiki.ucl.ac.uk/display/~ucftpw2/2013/10/18/Using+git+for+version+control+of+spreadsheet+models+-+part+1+of+3\" rel=\"noreferrer\">https://wiki.ucl.ac.uk/display/~ucftpw2/2013/10/18/Using+git+for+version+control+of+spreadsheet+models+-+part+1+of+3</a></p>\n\n<p>However, spreadsheet comparison is a non-trivial algorithmic problem. There are a few tools around, such as Microsoft's Spreadsheet Compare (<a href=\"https://support.office.com/en-us/article/Overview-of-Spreadsheet-Compare-13fafa61-62aa-451b-8674-242ce5f2c986\" rel=\"noreferrer\">https://support.office.com/en-us/article/Overview-of-Spreadsheet-Compare-13fafa61-62aa-451b-8674-242ce5f2c986</a>), Exceldiff (<a href=\"http://exceldiff.arstdesign.com/\" rel=\"noreferrer\">http://exceldiff.arstdesign.com/</a>) and DiffEngineX (<a href=\"https://www.florencesoft.com/compare-excel-workbooks-differences.html\" rel=\"noreferrer\">https://www.florencesoft.com/compare-excel-workbooks-differences.html</a>). But it's another challenge to integrate these comparison with a version control system like Git.</p>\n\n<p>Finally, you have to settle on a workflow that suits your needs. For a simple, tailored Git for Excel workflow, have a look at <a href=\"https://www.xltrail.com/blog/git-workflow-for-excel\" rel=\"noreferrer\">https://www.xltrail.com/blog/git-workflow-for-excel</a>.</p>\n" }, { "answer_id": 36579661, "author": "eriklind", "author_id": 6194411, "author_profile": "https://Stackoverflow.com/users/6194411", "pm_score": 1, "selected": false, "text": "<p>Actually there only a handful of solutions to track and compare changes in macro code - most of those were named here already. I have been browsing the web and came across this new tool worth mentioning: </p>\n\n<p><a href=\"https://xltools.net/version-control-for-vba-macros/\" rel=\"nofollow\">XLTools Version Control for VBA macros</a></p>\n\n<ul>\n<li>version control for Excel sheets and VBA modules</li>\n<li>preview and diff changes before committing a version</li>\n<li>great for collaborative work of several users on the same file (track who changed what/when/comments)</li>\n<li>compare versions and highlight changes in code line-by-line</li>\n<li>suitable for users who are not tech-savvy, or Excel-savvy for that matter</li>\n<li>version history is stored in Git-repository on your own PC - any version can be easily recovered </li>\n</ul>\n\n<p><a href=\"http://i.stack.imgur.com/KFiQU.png\" rel=\"nofollow\">VBA code versions side by side, changes are visualized</a></p>\n" }, { "answer_id": 38858625, "author": "Yuxiang Wang", "author_id": 2203311, "author_profile": "https://Stackoverflow.com/users/2203311", "pm_score": 2, "selected": false, "text": "<p>I would like to recommend a great open-source tool called <a href=\"http://rubberduckvba.com/\" rel=\"nofollow\">Rubberduck</a> that has version control of VBA code built in. Try it!</p>\n" }, { "answer_id": 54755379, "author": "LShaver", "author_id": 5560474, "author_profile": "https://Stackoverflow.com/users/5560474", "pm_score": 0, "selected": false, "text": "<p>I found a very simple solution to this question which meets my needs. I add one line to the bottom of all of my macros which exports a <code>*.txt</code> file with the entire macro code each time it is run. The code:</p>\n\n<pre><code>ActiveWorkbook.VBProject.VBComponents(\"moduleName\").Export\"C:\\Path\\To\\Spreadsheet\\moduleName.txt\"\n</code></pre>\n\n<p>(Found on <a href=\"https://www.atlaspm.com/toms-tutorials-for-excel/toms-tutorials-for-excel-exporting-vba-module-code-to-a-text-file/\" rel=\"nofollow noreferrer\">Tom's Tutorials</a>, which also covers some setup you may need to get this working.)</p>\n\n<p>Since I'll always run the macro whenever I'm working on the code, I'm guaranteed that git will pick up the changes. The only annoying part is that if I need to checkout an earlier version, I have to manually copy/paste from the <code>*.txt</code> into the spreadsheet.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ]
What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system? To put this in perspective, here are a couple of use cases: 1. version control for VBA modules 2. more than one person is working on a Excel spreadsheet and they may be making changes to the same worksheet, which they want to merge and integrate. This worksheet may have formulae, data, charts etc 3. the users are not too technical and the fewer version control systems used the better 4. Space constraint is a consideration. Ideally only incremental changes are saved rather than the entire Excel spreadsheet.
I've just setup a spreadsheet that uses Bazaar, with manual checkin/out via TortiseBZR. Given that the topic helped me with the save portion, I wanted to post my solution here. *The solution for me was to create a spreadsheet that exports all modules on save, and removes and re-imports the modules on open. Yes, this could be potentially dangerous for converting existing spreadsheets.* This allows me to edit the macros in the modules via **Emacs** (yes, emacs) or natively in Excel, and commit my BZR repository after major changes. Because all the modules are text files, the standard diff-style commands in BZR work for my sources except the Excel file itself. I've setup a directory for my BZR repository, X:\Data\MySheet. In the repo are MySheet.xls and one .vba file for each of my modules (ie: Module1Macros). In my spreadsheet I've added one module that is exempt from the export/import cycle called "VersionControl". Each module to be exported and re-imported must end in "Macros". **Contents of the "VersionControl" module:** ```vb Sub SaveCodeModules() 'This code Exports all VBA modules Dim i%, sName$ With ThisWorkbook.VBProject For i% = 1 To .VBComponents.Count If .VBComponents(i%).CodeModule.CountOfLines > 0 Then sName$ = .VBComponents(i%).CodeModule.Name .VBComponents(i%).Export "X:\Tools\MyExcelMacros\" & sName$ & ".vba" End If Next i End With End Sub Sub ImportCodeModules() With ThisWorkbook.VBProject For i% = 1 To .VBComponents.Count ModuleName = .VBComponents(i%).CodeModule.Name If ModuleName <> "VersionControl" Then If Right(ModuleName, 6) = "Macros" Then .VBComponents.Remove .VBComponents(ModuleName) .VBComponents.Import "X:\Data\MySheet\" & ModuleName & ".vba" End If End If Next i End With End Sub ``` Next, we have to setup event hooks for open / save to run these macros. In the code viewer, right click on "ThisWorkbook" and select "View Code". You may have to pull down the select box at the top of the code window to change from "(General)" view to "Workbook" view. **Contents of "Workbook" view:** ```vb Private Sub Workbook_Open() ImportCodeModules End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) SaveCodeModules End Sub ``` I'll be settling into this workflow over the next few weeks, and I'll post if I have any problems. Thanks for sharing the VBComponent code!
131,619
<h2>Question</h2> <p>Using XSLT 1.0, given a string with arbitrary characters how can I get back a string that meets the following rules.</p> <ol> <li>First character must be one of these: a-z, A-Z, colon, or underscore</li> <li>All other characters must be any of those above or 0-9, period, or hyphen</li> <li>If any character does not meet the above rules, replace it with an underscore</li> </ol> <h2>Background</h2> <p>In an XSLT I'm translating some attributes into elements, but I need to be sure the attribute doesn't contain any values that can't be used in an element name. I don't care much about the integrity of the attribute being converted to the name as long as it's being converted predictably. I also don't need to compensate for <em>every</em> valid character in an element name (there's a bunch).</p> <p>The problem I was having was with the attributes having spaces coming in, which the translate function can easily convert to underscores:</p> <pre><code>translate(@name,' ','_') </code></pre> <p>But soon after I found some of the attributes using slashes, so I have to add that now too. This will quickly get out of hand. I want to be able to define a whitelist of allowed characters, and replace any non-allowed characters with an underscore, but translate works as by replacing from a blacklist.</p>
[ { "answer_id": 131687, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 1, "selected": false, "text": "<p>As far as Im aware XSLT 1.0 doesnt have a builtin for this. XSLT 2.0 allows you to <a href=\"http://www.xml.com/pub/a/2003/06/04/tr.html\" rel=\"nofollow noreferrer\">use regexes</a>, though Im sure your all too aware of that.</p>\n\n<p>If, on the off chance your using the MS parser, you can write .NET extension libraries that you can leverage in your XSLT and I wrote about this <a href=\"http://www.nervoustych.com/blog/PermaLink,guid,e5e1b63a-1859-43f0-8672-abe5da8f3237.aspx\" rel=\"nofollow noreferrer\">some months ago here.</a></p>\n\n<p>If your using something like Saxon, I am pretty certain they also provide ways of coding your own extensions, and they may indeed have an extension of their own already, but Im unfamiliar with that engine.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 132240, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<p>You <em>could</em> write a recursive template to do this, working through the characters in the string one by one, testing them and changing them if necessary. Something like:</p>\n<pre><code>&lt;xsl:template name=&quot;normalizeName&quot;&gt;\n &lt;xsl:param name=&quot;name&quot; /&gt;\n &lt;xsl:param name=&quot;isFirst&quot; select=&quot;true()&quot; /&gt;\n &lt;xsl:if test=&quot;$name != ''&quot;&gt;\n &lt;xsl:variable name=&quot;first&quot; select=&quot;substring($name, 1, 1)&quot; /&gt;\n &lt;xsl:variable name=&quot;rest&quot; select=&quot;substring($name, 2)&quot; /&gt;\n &lt;xsl:choose&gt;\n &lt;xsl:when test=&quot;contains('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_', $first) or\n (not($first) and contains('0123456789.-', $first))&quot;&gt;\n &lt;xsl:value-of select=&quot;$first&quot; /&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:otherwise&gt;\n &lt;xsl:text&gt;_&lt;/xsl:text&gt;\n &lt;/xsl:otherwise&gt;\n &lt;/xsl:choose&gt;\n &lt;xsl:call-template name=&quot;normalizeName&quot;&gt;\n &lt;xsl:with-param name=&quot;name&quot; select=&quot;$rest&quot; /&gt;\n &lt;xsl:with-param name=&quot;isFirst&quot; select=&quot;false()&quot; /&gt;\n &lt;/xsl:call-template&gt;\n &lt;/xsl:if&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n<p>However, there is shorter way of doing this if you're prepared for some hackery. First declare some variables:</p>\n<pre><code>&lt;xsl:variable name=&quot;underscores&quot;\n select=&quot;'_______________________________________________________'&quot; /&gt;\n&lt;xsl:variable name=&quot;initialNameChars&quot;\n select=&quot;'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_'&quot; /&gt;\n&lt;xsl:variable name=&quot;nameChars&quot;\n select=&quot;concat($initialNameChars, '0123456789.-')&quot; /&gt;\n</code></pre>\n<p>Now the technique is to take the name and identify the characters that <em>aren't</em> legal by replacing all the characters in the name that <em>are</em> legal with nothing. You can do this with the <code>translate()</code> function. Once you've got the set of illegal characters that appear in the string, you can replace them with underscores using the <code>translate()</code> function again. Here's the template:</p>\n<pre><code>&lt;xsl:template name=&quot;normalizeName&quot;&gt;\n &lt;xsl:param name=&quot;name&quot; /&gt;\n &lt;xsl:variable name=&quot;first&quot; select=&quot;substring($name, 1, 1)&quot; /&gt;\n &lt;xsl:variable name=&quot;rest&quot; select=&quot;substring($name, 2)&quot; /&gt;\n &lt;xsl:variable name=&quot;illegalFirst&quot;\n select=&quot;translate($first, $initialNameChars, '')&quot; /&gt;\n &lt;xsl:variable name=&quot;illegalRest&quot;\n select=&quot;translate($rest, $nameChars, '')&quot; /&gt;\n &lt;xsl:value-of select=&quot;concat(translate($first, $illegalFirst, $underscores),\n translate($rest, $illegalRest, $underscores))&quot; /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n<p>The only thing you have to watch out for is that the string of underscores needs to be long enough to cover all the illegal characters that might appear within a single name. Making it the same length as the longest name you're likely to encounter will do the trick (though probably you could get away with it being a lot shorter).</p>\n<p>UPDATE:</p>\n<p>I wanted to add to this answer. In order to generate required length underscore string you can use this template.</p>\n<pre><code>&lt;!--Generate string with given number of replacement--&gt;\n&lt;xsl:template name=&quot;gen-replacement&quot;&gt;\n&lt;xsl:param name=&quot;n&quot;/&gt;\n &lt;xsl:if test=&quot;$n &gt; 0&quot;&gt;\n &lt;xsl:call-template name=&quot;gen-replacement&quot;&gt;\n &lt;xsl:with-param name=&quot;n&quot; select=&quot;$n - 1&quot;/&gt;\n &lt;/xsl:call-template&gt;\n &lt;xsl:text&gt;_&lt;/xsl:text&gt;\n &lt;/xsl:if&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n<p>And call it when you need to generate underscores:</p>\n<pre><code>&lt;xsl:variable name=&quot;replacement&quot;&gt;&lt;xsl:call-template name=&quot;gen-replacement&quot;&gt;&lt;xsl:with-param name=&quot;n&quot; select=&quot;string-length($value)&quot;/&gt;&lt;/xsl:call-template&gt;&lt;/xsl:variable&gt;\n</code></pre>\n" }, { "answer_id": 136577, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 0, "selected": false, "text": "<p>As another alternative there is a string function that might work for you in the XSLT standard library. <a href=\"http://xsltsl.sourceforge.net/string.html#template.str:string-match\" rel=\"nofollow noreferrer\">http://xsltsl.sourceforge.net/string.html#template.str:string-match</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507/" ]
Question -------- Using XSLT 1.0, given a string with arbitrary characters how can I get back a string that meets the following rules. 1. First character must be one of these: a-z, A-Z, colon, or underscore 2. All other characters must be any of those above or 0-9, period, or hyphen 3. If any character does not meet the above rules, replace it with an underscore Background ---------- In an XSLT I'm translating some attributes into elements, but I need to be sure the attribute doesn't contain any values that can't be used in an element name. I don't care much about the integrity of the attribute being converted to the name as long as it's being converted predictably. I also don't need to compensate for *every* valid character in an element name (there's a bunch). The problem I was having was with the attributes having spaces coming in, which the translate function can easily convert to underscores: ``` translate(@name,' ','_') ``` But soon after I found some of the attributes using slashes, so I have to add that now too. This will quickly get out of hand. I want to be able to define a whitelist of allowed characters, and replace any non-allowed characters with an underscore, but translate works as by replacing from a blacklist.
You *could* write a recursive template to do this, working through the characters in the string one by one, testing them and changing them if necessary. Something like: ``` <xsl:template name="normalizeName"> <xsl:param name="name" /> <xsl:param name="isFirst" select="true()" /> <xsl:if test="$name != ''"> <xsl:variable name="first" select="substring($name, 1, 1)" /> <xsl:variable name="rest" select="substring($name, 2)" /> <xsl:choose> <xsl:when test="contains('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_', $first) or (not($first) and contains('0123456789.-', $first))"> <xsl:value-of select="$first" /> </xsl:when> <xsl:otherwise> <xsl:text>_</xsl:text> </xsl:otherwise> </xsl:choose> <xsl:call-template name="normalizeName"> <xsl:with-param name="name" select="$rest" /> <xsl:with-param name="isFirst" select="false()" /> </xsl:call-template> </xsl:if> </xsl:template> ``` However, there is shorter way of doing this if you're prepared for some hackery. First declare some variables: ``` <xsl:variable name="underscores" select="'_______________________________________________________'" /> <xsl:variable name="initialNameChars" select="'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_'" /> <xsl:variable name="nameChars" select="concat($initialNameChars, '0123456789.-')" /> ``` Now the technique is to take the name and identify the characters that *aren't* legal by replacing all the characters in the name that *are* legal with nothing. You can do this with the `translate()` function. Once you've got the set of illegal characters that appear in the string, you can replace them with underscores using the `translate()` function again. Here's the template: ``` <xsl:template name="normalizeName"> <xsl:param name="name" /> <xsl:variable name="first" select="substring($name, 1, 1)" /> <xsl:variable name="rest" select="substring($name, 2)" /> <xsl:variable name="illegalFirst" select="translate($first, $initialNameChars, '')" /> <xsl:variable name="illegalRest" select="translate($rest, $nameChars, '')" /> <xsl:value-of select="concat(translate($first, $illegalFirst, $underscores), translate($rest, $illegalRest, $underscores))" /> </xsl:template> ``` The only thing you have to watch out for is that the string of underscores needs to be long enough to cover all the illegal characters that might appear within a single name. Making it the same length as the longest name you're likely to encounter will do the trick (though probably you could get away with it being a lot shorter). UPDATE: I wanted to add to this answer. In order to generate required length underscore string you can use this template. ``` <!--Generate string with given number of replacement--> <xsl:template name="gen-replacement"> <xsl:param name="n"/> <xsl:if test="$n > 0"> <xsl:call-template name="gen-replacement"> <xsl:with-param name="n" select="$n - 1"/> </xsl:call-template> <xsl:text>_</xsl:text> </xsl:if> </xsl:template> ``` And call it when you need to generate underscores: ``` <xsl:variable name="replacement"><xsl:call-template name="gen-replacement"><xsl:with-param name="n" select="string-length($value)"/></xsl:call-template></xsl:variable> ```
131,653
<p>I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in:</p> <pre><code>&lt;p style="font-size: 24px"&gt;asdf&lt;/p&gt; </code></pre> <p>What's the syntax for embedding a rule like:</p> <pre><code>a:hover {text-decoration: underline;} </code></pre> <p>into the style attribute of an A tag? It's obviously not this...</p> <pre><code>&lt;a href="foo" style="text-decoration: underline"&gt;bar&lt;/a&gt; </code></pre> <p>...since that would apply all the time, as opposed to just during hover.</p>
[ { "answer_id": 131660, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 8, "selected": true, "text": "<p>I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.</p>\n\n<p>I should mention that <em>technically</em> you <em>should</em> be able to do it <a href=\"http://www.w3.org/TR/css-style-attr#cascading\" rel=\"noreferrer\">according to the CSS spec</a>, but most browsers don't support it</p>\n\n<p><strong>Edit:</strong> I just did a quick test with this:</p>\n\n<pre><code>&lt;a href=\"test.html\" style=\"{color: blue; background: white} \n :visited {color: green}\n :hover {background: yellow}\n :visited:hover {color: purple}\"&gt;Test&lt;/a&gt;\n</code></pre>\n\n<p>And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?</p>\n" }, { "answer_id": 131664, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 5, "selected": false, "text": "<p>If you are only debugging, you might use javascript to modify the css:</p>\n\n<pre><code>&lt;a onmouseover=\"this.style.textDecoration='underline';\" \n onmouseout=\"this.style.textDecoration='none';\"&gt;bar&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 131682, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 4, "selected": false, "text": "<p>If it's for debugging, just add a css class for hovering (since elements can have more than one class):</p>\n\n<pre><code>a.hovertest:hover\n{\ntext-decoration:underline;\n}\n\n&lt;a href=\"http://example.com\" class=\"foo bar hovertest\"&gt;blah&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 25333956, "author": "Roberto", "author_id": 3945826, "author_profile": "https://Stackoverflow.com/users/3945826", "pm_score": 5, "selected": false, "text": "<p>A simple solution:</p>\n<pre><code>&lt;a href=&quot;#&quot; onmouseover=&quot;this.style.color='orange';&quot; onmouseout=&quot;this.style.color='';&quot;&gt;My Link&lt;/a&gt;\n</code></pre>\n<p>Or</p>\n<pre><code>&lt;script&gt;\n /** Change the style **/\n function overStyle(object){\n object.style.color = 'orange';\n // Change some other properties ...\n }\n\n /** Restores the style **/\n function outStyle(object){\n object.style.color = 'orange';\n // Restore the rest ...\n }\n&lt;/script&gt;\n\n&lt;a href=&quot;#&quot; onmouseover=&quot;overStyle(this)&quot; onmouseout=&quot;outStyle(this)&quot;&gt;My Link&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 26372047, "author": "Josh Kernich", "author_id": 2205806, "author_profile": "https://Stackoverflow.com/users/2205806", "pm_score": 1, "selected": false, "text": "<p>I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.</p>\n\n<p><a href=\"http://jsfiddle.net/Lk9w1mkv/\" rel=\"nofollow\">http://jsfiddle.net/Lk9w1mkv/</a></p>\n\n<pre><code>&lt;div style=\"position:relative;width:100px;background:#ddffdd;overflow:hidden;\" onmouseover=\"this.style.overflow='';\" onmouseout=\"this.style.overflow='hidden';\"&gt;first hover&lt;div style=\"width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;\"&gt;stuff inside&lt;/div&gt;&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 60869890, "author": "michielbdejong", "author_id": 680454, "author_profile": "https://Stackoverflow.com/users/680454", "pm_score": 0, "selected": false, "text": "<p>If that <code>&lt;p&gt;</code> tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support <code>'&amp;:hover'</code>. <a href=\"https://cssinjs.org/\" rel=\"nofollow noreferrer\">https://cssinjs.org/</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in: ``` <p style="font-size: 24px">asdf</p> ``` What's the syntax for embedding a rule like: ``` a:hover {text-decoration: underline;} ``` into the style attribute of an A tag? It's obviously not this... ``` <a href="foo" style="text-decoration: underline">bar</a> ``` ...since that would apply all the time, as opposed to just during hover.
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet. I should mention that *technically* you *should* be able to do it [according to the CSS spec](http://www.w3.org/TR/css-style-attr#cascading), but most browsers don't support it **Edit:** I just did a quick test with this: ``` <a href="test.html" style="{color: blue; background: white} :visited {color: green} :hover {background: yellow} :visited:hover {color: purple}">Test</a> ``` And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?
131,704
<p>Eclipse 3.4[.x] - also known as <a href="http://www.eclipse.org/downloads/packages/" rel="noreferrer">Ganymede</a> - comes with this new mechanism of provisioning called <strong>p2</strong>.</p> <p>"Provisioning" is the process allowing to discover and update on demand some parts of an application, as explained in general in this article on the <a href="http://developers.sun.com/mobility/midp/articles/ota" rel="noreferrer">Sun Web site</a>.</p> <p>Eclipse has an extended <a href="http://wiki.eclipse.org/Category:Equinox_p2" rel="noreferrer">wiki section</a> in which p2 details are presented. Specifically, it says in this wiki page that p2 will look for new components However after reading it.</p> <p>I suppose (but you may confirm that point by your own experience), that p2 can function file "file://" protocol, which would allow it to provision with <strong>local</strong> file (either on your computer or on an UNC path '\server\path'), as <a href="http://wiki.eclipse.org/Equinox_p2_PDE_Integration" rel="noreferrer">illustrated here</a>, but also by the files:</p> <ul> <li>[eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.artifact.repository.prefs</li> <li>[eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.metadata.repository.prefs</li> </ul> <p>p2 mechanism is used to update eclipse itself, through an <a href="http://download.eclipse.org/eclipse/updates/3.4" rel="noreferrer">eclipse 3.4 update site</a>, and reference in those '.prefs' files with line like:</p> <blockquote> <p>repositories/file:_C:_jv_eclipse_eclipse-SDK-3.4-win32_eclipse/url=file:/C:/jv/eclipse/eclipse-SDK-3.4-win32/eclipse/</p> </blockquote> <p>Now, how could I replicate the eclipse components present in that update site into a local directory and reference those components through the mentioned '.prefs' files, <strong>in order to have an upgrade process entirely run locally</strong>, without having to access the web?<br> I suppose that some p2 metadata files present in the distant 'update site' need to be replicated and changed as well.</p> <p>Do you have any thoughts/advice/tips on that ? (i.e. on how to discover and retrieve and update the complete structure needed for a full eclipse installation, in order to run that installation locally)</p>
[ { "answer_id": 182019, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 1, "selected": false, "text": "<p>It seems like you need to have one update work via the web which will mirror (download) what you need. But after that it should be able to get the files from the local peer. But I guess that is your question - does it need web access to determine that...</p>\n" }, { "answer_id": 711754, "author": "lothar", "author_id": 44434, "author_profile": "https://Stackoverflow.com/users/44434", "pm_score": 5, "selected": true, "text": "<p>Yes, you can specify the repository locations if you use the p2.director</p>\n\n<p>this for example is a snippet of a script that I use to install eclipse (Ganymede) from a local copy of the Ganymede repository</p>\n\n<pre><code>./eclipse\\\n -nosplash -consolelog -debug\\\n -vm \"${VM}\"\\\n -application org.eclipse.equinox.p2.director.app.application\\\n -metadataRepository file:${SHARED_REPOSITORY_DIR}\\\n -artifactRepository file:${SHARED_REPOSITORY_DIR}\\\n -installIU \"${4-org.eclipse.sdk.ide}\"\\\n -destination \"${3}\"\\\n -profile \"${1}\"\\\n -profileProperties org.eclipse.update.install.features=true\\\n -bundlepool ${SHARED_BUNDLEPOOL_DIR}\\\n -p2.os linux\\\n -p2.ws gtk\\\n -p2.arch \"${2}\"\\\n \\\n -vmargs\\\n -Xms64m -Xmx1024m -XX:MaxPermSize=256m\\\n -Declipse.p2.data.area=${SHARED_P2_DIR}\n</code></pre>\n\n<p>Here are some links to use the p2 director</p>\n\n<p><a href=\"http://eclipse.dzone.com/articles/understanding-eclipse-p2-provi\" rel=\"noreferrer\">http://eclipse.dzone.com/articles/understanding-eclipse-p2-provi</a><br>\n<a href=\"http://wiki.eclipse.org/Equinox_p2_director_application\" rel=\"noreferrer\">http://wiki.eclipse.org/Equinox_p2_director_application</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
Eclipse 3.4[.x] - also known as [Ganymede](http://www.eclipse.org/downloads/packages/) - comes with this new mechanism of provisioning called **p2**. "Provisioning" is the process allowing to discover and update on demand some parts of an application, as explained in general in this article on the [Sun Web site](http://developers.sun.com/mobility/midp/articles/ota). Eclipse has an extended [wiki section](http://wiki.eclipse.org/Category:Equinox_p2) in which p2 details are presented. Specifically, it says in this wiki page that p2 will look for new components However after reading it. I suppose (but you may confirm that point by your own experience), that p2 can function file "file://" protocol, which would allow it to provision with **local** file (either on your computer or on an UNC path '\server\path'), as [illustrated here](http://wiki.eclipse.org/Equinox_p2_PDE_Integration), but also by the files: * [eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.artifact.repository.prefs * [eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.metadata.repository.prefs p2 mechanism is used to update eclipse itself, through an [eclipse 3.4 update site](http://download.eclipse.org/eclipse/updates/3.4), and reference in those '.prefs' files with line like: > > repositories/file:\_C:\_jv\_eclipse\_eclipse-SDK-3.4-win32\_eclipse/url=file:/C:/jv/eclipse/eclipse-SDK-3.4-win32/eclipse/ > > > Now, how could I replicate the eclipse components present in that update site into a local directory and reference those components through the mentioned '.prefs' files, **in order to have an upgrade process entirely run locally**, without having to access the web? I suppose that some p2 metadata files present in the distant 'update site' need to be replicated and changed as well. Do you have any thoughts/advice/tips on that ? (i.e. on how to discover and retrieve and update the complete structure needed for a full eclipse installation, in order to run that installation locally)
Yes, you can specify the repository locations if you use the p2.director this for example is a snippet of a script that I use to install eclipse (Ganymede) from a local copy of the Ganymede repository ``` ./eclipse\ -nosplash -consolelog -debug\ -vm "${VM}"\ -application org.eclipse.equinox.p2.director.app.application\ -metadataRepository file:${SHARED_REPOSITORY_DIR}\ -artifactRepository file:${SHARED_REPOSITORY_DIR}\ -installIU "${4-org.eclipse.sdk.ide}"\ -destination "${3}"\ -profile "${1}"\ -profileProperties org.eclipse.update.install.features=true\ -bundlepool ${SHARED_BUNDLEPOOL_DIR}\ -p2.os linux\ -p2.ws gtk\ -p2.arch "${2}"\ \ -vmargs\ -Xms64m -Xmx1024m -XX:MaxPermSize=256m\ -Declipse.p2.data.area=${SHARED_P2_DIR} ``` Here are some links to use the p2 director <http://eclipse.dzone.com/articles/understanding-eclipse-p2-provi> <http://wiki.eclipse.org/Equinox_p2_director_application>
131,718
<p>Is there a simple way to write a common function for each of the <code>CRUD (create, retreive, update, delete)</code> operations in <code>PHP</code> WITHOUT using any framework. For example I wish to have a single create function that takes the table name and field names as parameters and inserts data into a <code>mySQL database</code>. Another requirement is that the function should be able to support joins I.e. it should be able to insert data into multiple tables if required. </p> <p>I know that these tasks could be done by using a framework but because of various reasons - too lengthy to explain here - I cannot use them.</p>
[ { "answer_id": 131727, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 2, "selected": false, "text": "<p>Without any frameworks includes without any ORMs? Otherwise I would suggest to have a look at <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine</a> or <a href=\"http://propel.phpdb.org/trac/\" rel=\"nofollow noreferrer\">Propel</a>.</p>\n" }, { "answer_id": 131749, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Of course not, that's why those frameworks exist and implement crud facilities. I'd first try to convince whomever it takes to actually use an existing framework and second, failing the above, I'd take a look at one or two of them and copy the implementation ideas. Failing all that you could take a look at <a href=\"http://www.phpobjectgenerator.com/\" rel=\"nofollow noreferrer\">http://www.phpobjectgenerator.com/</a></p>\n" }, { "answer_id": 131814, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 0, "selected": false, "text": "<p>it is possible but I wouldn't recommend it. </p>\n\n<p>If there's absolutely NO way to use a framework you could create a base class that all other model objects extend. You can then make the base class generate &amp; execute SQL based on <code>get_class()</code> and <code>get_class_vars()</code>.</p>\n\n<p>Is it possible? Yes.<br>\nWould I recommend it? nope</p>\n" }, { "answer_id": 132008, "author": "Sergey Stolyarov", "author_id": 15958, "author_profile": "https://Stackoverflow.com/users/15958", "pm_score": 3, "selected": false, "text": "<p>If you try to write such function you'll soon discover that you've just realized yet another framework.</p>\n" }, { "answer_id": 132369, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 2, "selected": false, "text": "<p>I know the way you feel.</p>\n\n<p>Pork.DbObject is a simple class that you can extend your objects from. It just needs a db connection class to work.</p>\n\n<p>please check out:\n<a href=\"http://www.schizofreend.nl/pork.dbobject/\" rel=\"nofollow noreferrer\">www.schizofreend.nl/pork.dbobject/</a></p>\n\n<p>(oh yeah, yuk @ php object generator. <em>bloat alert!</em> who wants to have those custom functions in every class???)</p>\n" }, { "answer_id": 133479, "author": "lewis", "author_id": 14442, "author_profile": "https://Stackoverflow.com/users/14442", "pm_score": 2, "selected": true, "text": "<p>I wrote this very thing, it's kind of a polished scaffold. It's basically a class the constructor of which takes the table to be used, an array containing field names and types, and an action. Based on this action the object calls a method on itself. For example:</p>\n\n<p>This is the array I pass:</p>\n\n<pre><code>$data = array(array('name' =&gt; 'id', 'type' =&gt; 'hidden')\n , array('name' =&gt; 'student', 'type' =&gt; 'text', 'title' =&gt; 'Student'));\n</code></pre>\n\n<p>Then I call the constructor:</p>\n\n<pre><code>new MyScaffold($table, 'edit', $data, $_GET['id']);\n</code></pre>\n\n<p>In the above case the constructor calls the 'edit' method which presents a form displaying data from the $table, but only fields I set up in my array. The record it uses is determined by the $_GET method. In this example the 'student' field is presented as a text-box (hence the 'text' type). The 'title' is simply the label used. Being 'hidden' the ID field is not shown for editing but is available to the program for use.</p>\n\n<p>If I had passed 'delete' instead of 'edit' it would delete the record from the GET variable. If I passed only a table name it would default to a list of records with buttons for edit, delete, and new.</p>\n\n<p>It's just one class that contains all the CRUD with lots of customisability. You can make it as complicated or as simple as you wish. By making it a generic class I can drop it in to any project and just pass instructions, table information and configuration information. I might for one table not want to permit new records from being added through the scaffold, in this case I might set \"newbutton\" to be false in my parameters array.</p>\n\n<p>It's not a framework in the conventional sense. Just a standalone class that handles everything internally. There are some drawbacks to this. The key ones must be that all my tables must have a primary key called 'id', you could get away without this but it would complicate matters. Another being that a large array detailing information about each table to be managed must be prepared, but you need only do this once.</p>\n\n<p>For a tutorial on this idea see <a href=\"http://www.shadow-fox.net/site/tutorial/39-Creating-A-Scaffold-like-Class-in-PHP-or-An-Automatic-CMS-For-a-Table\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 133519, "author": "Ronald Conco", "author_id": 16092, "author_profile": "https://Stackoverflow.com/users/16092", "pm_score": 1, "selected": false, "text": "<p>I think you should write your own functions that achieve CRUD unless you are stressed for time. it might be a framework on it's own but you need to learn what the framework does before screaming framework....it also becomes handy to know these things because you can easily pickup bugs on the framework and fix them your self........ </p>\n" }, { "answer_id": 13592020, "author": "ArthurD", "author_id": 432393, "author_profile": "https://Stackoverflow.com/users/432393", "pm_score": 2, "selected": false, "text": "<p>I came across this question on SO a while back and I ended up not finding anything at that time that did this in a light-weight fashion. </p>\n\n<p>I ended up writing my own and I recently got around to open sourcing it (MIT license) in case others may find it useful. It's up on Github, feel free to check it out and use it if it fits your needs!</p>\n\n<p><a href=\"https://github.com/ArthurD/php-crud-model-class\" rel=\"nofollow\">https://github.com/ArthurD/php-crud-model-class</a></p>\n\n<p>Hopefully it will find some use - would love to see some improvements / contributions, too so feel free to submit pull requests! :-)</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22009/" ]
Is there a simple way to write a common function for each of the `CRUD (create, retreive, update, delete)` operations in `PHP` WITHOUT using any framework. For example I wish to have a single create function that takes the table name and field names as parameters and inserts data into a `mySQL database`. Another requirement is that the function should be able to support joins I.e. it should be able to insert data into multiple tables if required. I know that these tasks could be done by using a framework but because of various reasons - too lengthy to explain here - I cannot use them.
I wrote this very thing, it's kind of a polished scaffold. It's basically a class the constructor of which takes the table to be used, an array containing field names and types, and an action. Based on this action the object calls a method on itself. For example: This is the array I pass: ``` $data = array(array('name' => 'id', 'type' => 'hidden') , array('name' => 'student', 'type' => 'text', 'title' => 'Student')); ``` Then I call the constructor: ``` new MyScaffold($table, 'edit', $data, $_GET['id']); ``` In the above case the constructor calls the 'edit' method which presents a form displaying data from the $table, but only fields I set up in my array. The record it uses is determined by the $\_GET method. In this example the 'student' field is presented as a text-box (hence the 'text' type). The 'title' is simply the label used. Being 'hidden' the ID field is not shown for editing but is available to the program for use. If I had passed 'delete' instead of 'edit' it would delete the record from the GET variable. If I passed only a table name it would default to a list of records with buttons for edit, delete, and new. It's just one class that contains all the CRUD with lots of customisability. You can make it as complicated or as simple as you wish. By making it a generic class I can drop it in to any project and just pass instructions, table information and configuration information. I might for one table not want to permit new records from being added through the scaffold, in this case I might set "newbutton" to be false in my parameters array. It's not a framework in the conventional sense. Just a standalone class that handles everything internally. There are some drawbacks to this. The key ones must be that all my tables must have a primary key called 'id', you could get away without this but it would complicate matters. Another being that a large array detailing information about each table to be managed must be prepared, but you need only do this once. For a tutorial on this idea see [here](http://www.shadow-fox.net/site/tutorial/39-Creating-A-Scaffold-like-Class-in-PHP-or-An-Automatic-CMS-For-a-Table)
131,728
<p>I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution.</p> <p>I would like to be able to upload files using the Document Manager of this control.</p> <p>However, these files are larger than whatever the default setting is for maximum upload file size.</p> <p>Can anyone point me in the right direction to fix this?</p> <p><hr> Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.</p>
[ { "answer_id": 131737, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": true, "text": "<p>The Telerik website has instructions <a href=\"http://www.telerik.com/help/aspnet-ajax/upload_uploadinglargefiles.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Short version: in Web.config set the maxRequestLength</p>\n\n<pre><code>&lt;system.web&gt;\n &lt;httpRuntime maxRequestLength=\"102400\" executionTimeout= \"3600\" /&gt;\n&lt;/system.web&gt;\n</code></pre>\n" }, { "answer_id": 131773, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.telerik.com/community/forums/thread/b311D-ekgdc.aspx\" rel=\"nofollow noreferrer\">This thread</a> in combination with <a href=\"https://stackoverflow.com/questions/131728/how-do-i-change-the-maximum-upload-file-size-for-the-document-manager-in-a-tele#131737\">Yaakov Ellis's answer</a> may help others.</p>\n\n<p>However, I've found for my problem, putting the following code in the code-behind for the user control FieldTemplate (Dynamic Data) in combination th <a href=\"https://stackoverflow.com/questions/131728/how-do-i-change-the-maximum-upload-file-size-for-the-document-manager-in-a-tele#131737\">Yaakov Ellis's answer</a> solved things.</p>\n\n<pre><code>RadEditor1.DocumentManager.MaxUploadFileSize = 4194304;\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution. I would like to be able to upload files using the Document Manager of this control. However, these files are larger than whatever the default setting is for maximum upload file size. Can anyone point me in the right direction to fix this? --- Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.
The Telerik website has instructions [here](http://www.telerik.com/help/aspnet-ajax/upload_uploadinglargefiles.html). Short version: in Web.config set the maxRequestLength ``` <system.web> <httpRuntime maxRequestLength="102400" executionTimeout= "3600" /> </system.web> ```
131,788
<p>I'm writing a Perl script and I've come to a point where I need to parse a Java source file line by line checking for references to a fully qualified Java class name. I know the class I'm looking for up front; also the fully qualified name of the source file that is being searched (based on its path). </p> <p>For example find all valid references to foo.bar.Baz inside the com/bob/is/YourUncle.java file.</p> <p>At this moment the cases I can think of that it needs to account for are:</p> <ol> <li><p>The file being parsed is in the same package as the search class. </p> <p>find foo.bar.Baz references in foo/bar/Boing.java</p></li> <li><p>It should ignore comments.</p> <pre><code>// this is a comment saying this method returns a foo.bar.Baz or Baz instance // it shouldn't count /* a multiline comment as well this shouldn't count if I put foo.bar.Baz or Baz in here either */ </code></pre></li> <li><p>In-line fully qualified references.</p> <pre><code>foo.bar.Baz fb = new foo.bar.Baz(); </code></pre></li> <li><p>References based off an import statement.</p> <pre><code>import foo.bar.Baz; ... Baz b = new Baz(); </code></pre></li> </ol> <p>What would be the most efficient way to do this in Perl 5.8? Some fancy regex perhaps?</p> <pre><code>open F, $File::Find::name or die; # these three things are already known # $classToFind looking for references of this class # $pkgToFind the package of the class you're finding references of # $currentPkg package name of the file being parsed while(&lt;F&gt;){ # ... do work here } close F; # the results are availble here in some form </code></pre>
[ { "answer_id": 131869, "author": "Paul Wicks", "author_id": 85, "author_profile": "https://Stackoverflow.com/users/85", "pm_score": 3, "selected": false, "text": "<p>A Regex is probably the best solution for this, although I did find the following module in CPAN that you might be able to use</p>\n\n<ul>\n<li><a href=\"http://search.cpan.org/~lbrocard/Java-JVM-Classfile-0.20/lib/Java/JVM/Classfile.pm\" rel=\"nofollow noreferrer\">Java::JVM::Classfile</a> - Parses compiled class files and returns info about them. You would have to compile the files before you could use this.</li>\n</ul>\n\n<p>Also, remember that it can be tricky to catch all possible variants of a multi-line comment with a regex. </p>\n" }, { "answer_id": 131959, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 4, "selected": true, "text": "<p>You also need to skip quoted strings (you can't even skip comments correctly if you don't also deal with quoted strings).</p>\n\n<p>I'd probably write a fairly simple, efficient, and incomplete tokenizer very similar to the one I wrote in <a href=\"http://perlmonks.org/?node_id=566467\" rel=\"nofollow noreferrer\">node 566467</a>.</p>\n\n<p>Based on that code I'd probably just dig through the non-comment/non-string chunks looking for <code>\\bimport\\b</code> and <code>\\b\\Q$toFind\\E\\b</code> matches. Perhaps similar to:</p>\n\n<pre><code>if( m[\n \\G\n (?:\n [^'\"/]+\n | /(?![/*])\n )+\n ]xgc\n) {\n my $code = substr( $_, $-[0], $+[0] - $-[0] );\n my $imported = 0;\n while( $code =~ /\\b(import\\s+)?\\Q$package\\E\\b/g ) {\n if( $1 ) {\n ... # Found importing of package\n while( $code =~ /\\b\\Q$class\\E\\b/g ) {\n ... # Found mention of imported class\n }\n last;\n }\n ... # Found a package reference\n }\n} elsif( m[ \\G ' (?: [^'\\\\]+ | \\\\. )* ' ]xgc\n || m[ \\G \" (?: [^\"\\\\]+ | \\\\. )* \" ]xgc\n) {\n # skip quoted strings\n} elsif( m[\\G//.*]g­c ) {\n # skip C++ comments\n</code></pre>\n" }, { "answer_id": 131970, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>This is really just a straight grep for Baz (or for /(foo.bar.| )Baz/ if you're concerned about false positives from some.other.Baz), but ignoring comments, isn't it?</p>\n\n<p>If so, I'd knock together a state engine to track whether you're in a multiline comment or not. The regexes needed aren't anything special. Something along the lines of (<em>untested code</em>):</p>\n\n<pre><code>my $in_comment;\nmy %matches;\nmy $line_num = 0;\nmy $full_target = 'foo.bar.Baz';\nmy $short_target = (split /\\./, $full_target)[-1]; # segment after last . (Baz)\n\nwhile (my $line = &lt;F&gt;) {\n $line_num++;\n if ($in_comment) {\n next unless $line =~ m|\\*/|; # ignore line unless it ends the comment\n $line =~ s|.*\\*/||; # delete everything prior to end of comment\n } elsif ($line =~ m|/\\*|) {\n if ($line =~ m|\\*/|) { # catch /* and */ on same line\n $line =~ s|/\\*.*\\*/||;\n } else {\n $in_comment = 1;\n $line =~ s|/\\*.*||; # clear from start of comment to end of line\n }\n }\n\n $line =~ s/\\\\\\\\.*//; # remove single-line comments\n $matches{$line_num} = $line if $line =~ /$full_target| $short_target/;\n}\n\nfor my $key (sort keys %matches) {\n print $key, ': ', $matches{$key}, \"\\n\";\n}\n</code></pre>\n\n<p>It's not perfect and the in/out of comment state can be messed up by nested multiline comments or if there are multiple multiline comments on the same line, but that's probably good enough for most real-world cases.</p>\n\n<p>To do it without the state engine, you'd need to slurp into a single string, delete the /<em>...</em>/ comments, and split it back into separate lines, and grep those for non-//-comment hits. But you wouldn't be able to include line numbers in the output that way.</p>\n" }, { "answer_id": 142497, "author": "polarbear", "author_id": 3636, "author_profile": "https://Stackoverflow.com/users/3636", "pm_score": 2, "selected": false, "text": "<p>This is what I came up with that works for all the different cases I've thrown at it. I'm still a Perl noob and its probably not the fastest thing in the world but it should work for what I need. Thanks for all the answers they helped me look at it in different ways.</p>\n\n<pre><code> my $className = 'Baz';\n my $searchPkg = 'foo.bar';\n my @potentialRefs, my @confirmedRefs;\n my $samePkg = 0;\n my $imported = 0;\n my $currentPkg = 'com.bob';\n $currentPkg =~ s/\\//\\./g;\n if($currentPkg eq $searchPkg){\n $samePkg = 1; \n }\n my $inMultiLineComment = 0;\n open F, $_ or die;\n my $lineNum = 0;\n while(&lt;F&gt;){\n $lineNum++;\n if($inMultiLineComment){\n if(m|^.*?\\*/|){\n s|^.*?\\*/||; #get rid of the closing part of the multiline comment we're in\n $inMultiLineComment = 0;\n }else{\n next;\n }\n }\n if(length($_) &gt; 0){\n s|\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"||g; #remove strings first since java cannot have multiline string literals\n s|/\\*.*?\\*/||g; #remove any multiline comments that start and end on the same line\n s|//.*$||; #remove the // comments from what's left\n if (m|/\\*.*$|){\n $inMultiLineComment = 1 ;#now if you have any occurence of /* then then at least some of the next line is in the multiline comment\n s|/\\*.*$||g;\n }\n }else{\n next; #no sense continuing to process a blank string\n }\n\n if (/^\\s*(import )?($searchPkg)?(.*)?\\b$className\\b/){\n if($imported || $samePkg){\n push(@confirmedRefs, $lineNum);\n }else {\n push(@potentialRefs, $lineNum);\n }\n if($1){\n $imported = 1;\n } elsif($2){\n push(@confirmedRefs, $lineNum);\n }\n }\n }\n close F; \n if($imported){\n push(@confirmedRefs,@potentialRefs);\n }\n\n for (@confirmedRefs){\n print \"$_\\n\";\n }\n</code></pre>\n" }, { "answer_id": 149769, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 1, "selected": false, "text": "<p>If you are feeling adventurous enough you could have a look at <a href=\"http://search.cpan.org/dist/Parse-RecDescent/\" rel=\"nofollow noreferrer\">Parse::RecDescent</a>.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636/" ]
I'm writing a Perl script and I've come to a point where I need to parse a Java source file line by line checking for references to a fully qualified Java class name. I know the class I'm looking for up front; also the fully qualified name of the source file that is being searched (based on its path). For example find all valid references to foo.bar.Baz inside the com/bob/is/YourUncle.java file. At this moment the cases I can think of that it needs to account for are: 1. The file being parsed is in the same package as the search class. find foo.bar.Baz references in foo/bar/Boing.java 2. It should ignore comments. ``` // this is a comment saying this method returns a foo.bar.Baz or Baz instance // it shouldn't count /* a multiline comment as well this shouldn't count if I put foo.bar.Baz or Baz in here either */ ``` 3. In-line fully qualified references. ``` foo.bar.Baz fb = new foo.bar.Baz(); ``` 4. References based off an import statement. ``` import foo.bar.Baz; ... Baz b = new Baz(); ``` What would be the most efficient way to do this in Perl 5.8? Some fancy regex perhaps? ``` open F, $File::Find::name or die; # these three things are already known # $classToFind looking for references of this class # $pkgToFind the package of the class you're finding references of # $currentPkg package name of the file being parsed while(<F>){ # ... do work here } close F; # the results are availble here in some form ```
You also need to skip quoted strings (you can't even skip comments correctly if you don't also deal with quoted strings). I'd probably write a fairly simple, efficient, and incomplete tokenizer very similar to the one I wrote in [node 566467](http://perlmonks.org/?node_id=566467). Based on that code I'd probably just dig through the non-comment/non-string chunks looking for `\bimport\b` and `\b\Q$toFind\E\b` matches. Perhaps similar to: ``` if( m[ \G (?: [^'"/]+ | /(?![/*]) )+ ]xgc ) { my $code = substr( $_, $-[0], $+[0] - $-[0] ); my $imported = 0; while( $code =~ /\b(import\s+)?\Q$package\E\b/g ) { if( $1 ) { ... # Found importing of package while( $code =~ /\b\Q$class\E\b/g ) { ... # Found mention of imported class } last; } ... # Found a package reference } } elsif( m[ \G ' (?: [^'\\]+ | \\. )* ' ]xgc || m[ \G " (?: [^"\\]+ | \\. )* " ]xgc ) { # skip quoted strings } elsif( m[\G//.*]g­c ) { # skip C++ comments ```
131,793
<p>I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?</p>
[ { "answer_id": 131826, "author": "John Ferguson", "author_id": 8312, "author_profile": "https://Stackoverflow.com/users/8312", "pm_score": 4, "selected": true, "text": "<p>Check if the default .RES file exists in the project source location. Delphi includes the version number of the project in a .res file with the same name as the .dpr file. If the .RES file does not exist, the simplest way to recreate it is to add the {$R *.RES} compiler directive to the .DPR file, immediately after the uses clause.</p>\n\n<pre><code>library foolib; \n\nuses\n foo in 'foo.pas',\n baz in 'baz.pas';\n\n{$R *.RES}\n\nexports\n foofunc name 'foofunc';\n\nend;\n</code></pre>\n\n<p>As soon as you add the {$R *.RES} compiler directive Delphi will tell you it has recreated the foolib.res resource file.</p>\n" }, { "answer_id": 131836, "author": "Andrew", "author_id": 1389, "author_profile": "https://Stackoverflow.com/users/1389", "pm_score": 2, "selected": false, "text": "<p>You can create and embed resource files in libraries created under Delphi, by using the $R directive.</p>\n\n<p>This <a href=\"http://msdn.microsoft.com/en-us/library/aa381058(VS.85).aspx\" rel=\"nofollow noreferrer\">link</a> has information relevant to constructing the RES file.\nDelphi has its own resource compiler: BRCC32</p>\n" }, { "answer_id": 132065, "author": "mj2008", "author_id": 5544, "author_profile": "https://Stackoverflow.com/users/5544", "pm_score": 0, "selected": false, "text": "<p>I use a build control system (FinalBuilder) and that is able to add version resources to all my DLLs and EXEs that are all coherent. Therefore I can be confident that the file set is all labelled with the same build. There are some Delphi projects that don't have versions by default, and FB will add them for you anyway.</p>\n" }, { "answer_id": 132227, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 3, "selected": false, "text": "<p>It seems the resource directive <code>{$R *.RES}</code> is missing (or enclosed in conditional defines) in your .dpr file so that the IDE doesn't find it.</p>\n" }, { "answer_id": 1950030, "author": "David M", "author_id": 237274, "author_profile": "https://Stackoverflow.com/users/237274", "pm_score": 0, "selected": false, "text": "<p>Inclusion of version info in dll's is a bit erratic. If you specify a lib_suffix the version info is not updated.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312/" ]
I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?
Check if the default .RES file exists in the project source location. Delphi includes the version number of the project in a .res file with the same name as the .dpr file. If the .RES file does not exist, the simplest way to recreate it is to add the {$R \*.RES} compiler directive to the .DPR file, immediately after the uses clause. ``` library foolib; uses foo in 'foo.pas', baz in 'baz.pas'; {$R *.RES} exports foofunc name 'foofunc'; end; ``` As soon as you add the {$R \*.RES} compiler directive Delphi will tell you it has recreated the foolib.res resource file.
131,805
<p>What is the SQL command to copy a table from one database to another database? I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database. Sorry if the question is too novice.</p> <p>Thanks.</p>
[ { "answer_id": 131824, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 1, "selected": false, "text": "<p>If you just want to copy the contents, you might be looking for <code>select into</code>:\n<a href=\"http://www.w3schools.com/Sql/sql_select_into.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/Sql/sql_select_into.asp</a>. This will not create an identical copy though, it will just copy every row from one table to another.</p>\n" }, { "answer_id": 131825, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 3, "selected": false, "text": "<p>If the target table doesn't exist....</p>\n\n<pre><code>CREATE TABLE dest_table AS (SELECT * FROM source_table);\n</code></pre>\n\n<p>If the target table does exist</p>\n\n<pre><code>INSERT INTO dest_table (SELECT * FROM source_table);\n</code></pre>\n\n<p>Caveat: Only tested in Oracle</p>\n" }, { "answer_id": 131856, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 2, "selected": false, "text": "<p>Since your scenario involves two different databases, the correct query should be...</p>\n\n<p>INSERT INTO Y..dest_table (SELECT * FROM source_table);</p>\n\n<p>Query assumes, you are running it using X database.</p>\n" }, { "answer_id": 131861, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 4, "selected": true, "text": "<p>If your two database are separated, the simplest thing to do would be to create a dump of your table and to load it into the second database. Refer to your database manual to see how a dump can be performed.</p>\n\n<p>Otherwise you can use the following syntax (for MySQL)</p>\n\n<pre><code>INSERT INTO database_b.table (SELECT * FROM database_a.table)\n</code></pre>\n" }, { "answer_id": 134190, "author": "indentation", "author_id": 7706, "author_profile": "https://Stackoverflow.com/users/7706", "pm_score": 1, "selected": false, "text": "<p>At the command line</p>\n\n<pre><code>mysqldump somedb sometable -u user -p | mysql otherdb -u user -p\n</code></pre>\n\n<p>then type both passwords.</p>\n\n<p>This works even if they are on different hosts (just add the -h parameter as usual), which you can't do with insert select.</p>\n\n<p>Be careful not to accidentally pipe into the wrong db or you will end up dropping the sometable table in that db! (The dump will start with 'drop table sometable').</p>\n" }, { "answer_id": 134267, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 1, "selected": false, "text": "<p>insert blah from select suggested by others is good for copying the data under mysql.</p>\n\n<p>If you want to copy the table structure you might want to use the <strong>show create table Tablename;</strong> statement.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11193/" ]
What is the SQL command to copy a table from one database to another database? I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database. Sorry if the question is too novice. Thanks.
If your two database are separated, the simplest thing to do would be to create a dump of your table and to load it into the second database. Refer to your database manual to see how a dump can be performed. Otherwise you can use the following syntax (for MySQL) ``` INSERT INTO database_b.table (SELECT * FROM database_a.table) ```
131,811
<p>Can someone explain why how the result for the following unpack is computed?</p> <pre><code>"aaa".unpack('h2H2') #=&gt; ["16", "61"] </code></pre> <p>In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).</p>
[ { "answer_id": 131850, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 3, "selected": false, "text": "<p>Check out the Programming Ruby <a href=\"http://www.ruby-doc.org/core-1.9.3/String.html#method-i-unpack\" rel=\"nofollow noreferrer\">reference</a> on unpack. Here's a snippet:</p>\n<blockquote>\n<p>Decodes str (which may contain binary\ndata) according to the format string,\nreturning an array of each value\nextracted. The format string consists\nof a sequence of single-character\ndirectives, summarized in Table 22.8\non page 379. Each directive may be\nfollowed by a number, indicating the\nnumber of times to repeat with this\ndirective. An asterisk (&quot;*&quot;) will\nuse up all remaining elements. The\ndirectives sSiIlL may each be followed\nby an underscore (&quot;_&quot;) to use the\nunderlying platform's native size for\nthe specified type; otherwise, it uses\na platform-independent consistent\nsize. Spaces are ignored in the format\nstring. See also Array#pack on page\n286.</p>\n</blockquote>\n<p>And the relevant characters from your example:</p>\n<blockquote>\n<p>H Extract hex nibbles from each character (most significant first).</p>\n<p>h Extract hex nibbles from each character (least significant first).</p>\n</blockquote>\n" }, { "answer_id": 131858, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": false, "text": "<p>The hex code of char <code>a</code> is 61.</p>\n\n<p>Template <code>h2</code> is a hex string (low nybble first), <code>H2</code> is the same with high nibble first.</p>\n\n<p>Also see the <a href=\"http://perldoc.perl.org/functions/pack.html\" rel=\"nofollow noreferrer\">perl documentation</a>.</p>\n" }, { "answer_id": 131862, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": "<p>Not 16 - it is showing 1 and then 6. h is giving the hex value of each nibble, so you get 0110 (6), then 0001 (1), depending on whether its the high or low bit you're looking at. Use the high nibble first and you get 61, which is hex for 97 - the value of 'a'</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18432/" ]
Can someone explain why how the result for the following unpack is computed? ``` "aaa".unpack('h2H2') #=> ["16", "61"] ``` In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).
Not 16 - it is showing 1 and then 6. h is giving the hex value of each nibble, so you get 0110 (6), then 0001 (1), depending on whether its the high or low bit you're looking at. Use the high nibble first and you get 61, which is hex for 97 - the value of 'a'
131,847
<p>I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3)</p> <p>I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at.</p> <p>seems like the answer must be really simple but I'm just not seeing it... thanks for the help!</p>
[ { "answer_id": 131876, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side of the ellipse. In your case, that's the line from (-2.5,6) to (5,-3), the top side of your ellipse. That line has a vertical drop of 9 and a horizontal run of 7.5.</p>\n\n<p>So we end up with the following right-angled triangle.</p>\n\n<pre><code>(-2.5,6)\n *-----\n |\\x\n | \\\n | \\\n9 | \\\n | \\\n | x\\\n +------* (5,-3)\n 7.5\n</code></pre>\n\n<p>The angle we're looking for is x which is the same in both locations.</p>\n\n<p>We can calculate it as:</p>\n\n<pre><code> -1\ntan (9/7.5)\n</code></pre>\n\n<p>which gives us an angle of -50.19 degrees</p>\n" }, { "answer_id": 132068, "author": "Maciej Hehl", "author_id": 19939, "author_profile": "https://Stackoverflow.com/users/19939", "pm_score": 2, "selected": false, "text": "<p>If (0, 0) is the center, than equation of Your ellipse is:</p>\n\n<p>F(x, y) = Ax^2 +By^2 + Cxy + D = 0</p>\n\n<p>For any given ellipse, not all of the coefficients A, B, C and D are uniquely determined. One can multiply the equation by any nonzero constant and obtain new equation of the same ellipse.</p>\n\n<p>4 points You have, give You 4 equations, but since those points are two pairs of symmetrical points, those equations won't be independent. You will get 2 independent equations. You can get 2 more equations by using the fact, that the ellipse is tangent to the rectangle in hose points (that's how I understand it). </p>\n\n<p>So if F(x, y) = Ax^2 +By^2 + Cxy + D Your conditions are:<br>\ndF/dx = 0 in points (-2.5,6) and (2.5,-6)<br>\ndF/dy = 0 in points (-5,3) and (5,-3)</p>\n\n<p>Here are four linear equations that You get </p>\n\n<pre><code>F(5, -3) = 5^2 * A + (-3)^2 * B + (-15) * C + D = 0 \nF(2.5, -6) = (2.5)^2 * A + (-6)^2 * B + (-15) * C + D = 0 \ndF(2.5, -6)/dx = 2*(2.5) * A + (-6) * C = 0 \ndF(5, -3)/dy = 2*(-3) * B + 5 * C = 0 \n</code></pre>\n\n<p>After a bit of cleaning: </p>\n\n<pre><code> 25A + 9B - 15C + D = 0 //1\n6.25A + 36B - 15C + D = 0 //2\n 5A - 6C = 0 //3\n - 6B + 5C = 0 //4\n</code></pre>\n\n<p>Still not all 4 equations are independent and that's a good thing. The set is homogeneous and if they were independent You would get unique but useless solution A = 0, B = 0, C = 0, D = 0.</p>\n\n<p>As I said before coefficients are not uniquely determined, so You can set one of the coefficient as You like and get rid of one equation. For example </p>\n\n<pre><code> 25A + 9B - 15C = 1 //1\n 5A - 6C = 0 //3\n - 6B + 5C = 0 //4\n</code></pre>\n\n<p>From that You get: A = 4/75, B = 1/27, C = 2/45 (D is of course -1) </p>\n\n<p>Now, to get to the angle, apply transformation of the coordinates: </p>\n\n<pre><code>x = ξcos(φ) - ηsin(φ)\ny = ξsin(φ) + ηcos(φ)\n</code></pre>\n\n<p>(I just couldn't resist to use those letters :) )<br>\nto the equation F(x, y) = 0</p>\n\n<pre><code>F(x(ξ, η), y(ξ, η)) = G(ξ, η) =\n A (ξ^2cos^2(φ) + η^2sin^2(φ) - 2ξηcos(φ)sin(φ))\n+ B (ξ^2sin^2(φ) + η^2cos^2(φ) + 2ξηcos(φ)sin(φ))\n+ C (ξ^2cos(φ)sin(φ) - η^2cos(φ)sin(φ) + ξη(cos^2(φ) - sin^2(φ))) + D\n</code></pre>\n\n<p>Using those two identities:</p>\n\n<pre><code>2cos(φ)sin(φ) = sin(2φ)\ncos^2(φ) - sin^2(φ) = cos(2φ)\n</code></pre>\n\n<p>You will get coefficient C' that stands by the product ξη in G(ξ, η) to be:</p>\n\n<p>C' = (B-A)sin(2φ) + Ccos(2φ)</p>\n\n<p>Now your question is: For what angle φ coefficient C' disappears (equals zero)<br>\nThere is more than one angle φ as there is more than one axis. In case of the main axis B' > A'</p>\n" }, { "answer_id": 132199, "author": "Andy Brice", "author_id": 455552, "author_profile": "https://Stackoverflow.com/users/455552", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Set the angle of the ellipse = 0</li>\n<li>Calculate the 4 points of intersection </li>\n<li>Work out the error between the calculated intersection points and the desired ones (i.e. sum the 4 distances).</li>\n<li>If error is too large use the secant method or Newton-Rhapson to work out a new angle for the ellipse and go to 2.</li>\n</ol>\n\n<p>I used a similar approach to work out another ellipse problem:</p>\n\n<p><a href=\"http://successfulsoftware.net/2008/07/18/a-mathematical-digression/\" rel=\"nofollow noreferrer\">http://successfulsoftware.net/2008/07/18/a-mathematical-digression/</a></p>\n\n<p><a href=\"http://successfulsoftware.net/2008/08/25/a-mathematical-digression-revisited/\" rel=\"nofollow noreferrer\">http://successfulsoftware.net/2008/08/25/a-mathematical-digression-revisited/</a></p>\n\n<p>See also:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Secant_method\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Secant_method</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Newton_Rhapson\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Newton_Rhapson</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3) I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at. seems like the answer must be really simple but I'm just not seeing it... thanks for the help!
The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side of the ellipse. In your case, that's the line from (-2.5,6) to (5,-3), the top side of your ellipse. That line has a vertical drop of 9 and a horizontal run of 7.5. So we end up with the following right-angled triangle. ``` (-2.5,6) *----- |\x | \ | \ 9 | \ | \ | x\ +------* (5,-3) 7.5 ``` The angle we're looking for is x which is the same in both locations. We can calculate it as: ``` -1 tan (9/7.5) ``` which gives us an angle of -50.19 degrees
131,871
<p>I'd love to figure it out myself but I was wondering <strong>roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?</strong> For example how does C# turn this:</p> <pre><code>IEnumerator&lt;string&gt; strings(IEnumerable&lt;string&gt; args) { IEnumerator&lt;string&gt; enumerator2 = getAnotherEnumerator(); foreach(var arg in arg) { enumerator2.MoveNext(); yield return arg+enumerator.Current; } } </code></pre> <p>into this:</p> <pre><code>bool MoveNext() { switch (this.state) { case 0: this.state = -1; this.enumerator2 = getAnotherEnumerator(); this.argsEnumerator = this.args.GetEnumerator(); this.state = 1; while (this.argsEnumerator.MoveNext()) { this.arg = this.argsEnumerator.Current; this.enumerator2.MoveNext(); this.current = this.arg + this.enumerator2.Current; this.state = 2; return true; state1: this.state = 1; } this.state = -1; if (this.argsEnumerator != null) this.argsEnumerator.Dispose(); break; case 2: goto state1; } return false; } </code></pre> <p>Of course the result can be completely different depending on the original code.</p>
[ { "answer_id": 131891, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": false, "text": "<p>Raymond Chen answers this <a href=\"https://devblogs.microsoft.com/oldnewthing/20080812-00/?p=21273\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 132085, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 7, "selected": true, "text": "<p>The particular code sample you are looking at involves a series of transformations.\nPlease note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however.</p>\n\n<p>The first transformation is the \"foreach\" transformation, which transforms this code:</p>\n\n<pre><code>foreach (var x in y)\n{\n //body\n}\n</code></pre>\n\n<p>into this code:</p>\n\n<pre><code>var enumerator = y.GetEnumerator();\nwhile (enumerator.MoveNext())\n{\n var x = enumerator.Current;\n //body\n}\n\nif (y != null)\n{\n enumerator.Dispose();\n}\n</code></pre>\n\n<p>The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a \"goto label\" right after the yield. </p>\n\n<p>The third transformation lifts all the local variables and function arguments in the method body into an object called a closure. </p>\n\n<p>Given the code in your example, that would look similar to this:</p>\n\n<pre><code> class ClosureEnumerable : IEnumerable&lt;string&gt;\n {\n private IEnumerable&lt;string&gt; args;\n private ClassType originalThis;\n public ClosureEnumerator(ClassType origThis, IEnumerable&lt;string&gt; args)\n {\n this.args = args;\n this.origianlThis = origThis;\n }\n public IEnumerator&lt;string&gt; GetEnumerator()\n {\n return new Closure(origThis, args);\n }\n }\n\nclass Closure : IEnumerator&lt;string&gt;\n{\n public Closure(ClassType originalThis, IEnumerable&lt;string&gt; args)\n {\n state = 0;\n this.args = args;\n this.originalThis = originalThis;\n }\n\n private IEnumerable&lt;string&gt; args;\n private IEnumerator&lt;string&gt; enumerator2;\n private IEnumerator&lt;string&gt; argEnumerator;\n\n //- Here ClassType is the type of the object that contained the method\n // This may be optimized away if the method does not access any \n // class members\n private ClassType originalThis;\n\n //This holds the state value.\n private int state;\n //The current value to return\n private string currentValue;\n\n public string Current\n {\n get \n {\n return currentValue;\n }\n }\n}\n</code></pre>\n\n<p>The method body is then moved from the original method to a method inside \"Closure\" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext.\nAny access to any locals is routed through \"this\", and any access to any class members are routed through this.originalThis.</p>\n\n<p>Any \"yield return expr\" is translated into:</p>\n\n<pre><code>currentValue = expr;\nstate = //the state number of the yield statement;\nreturn true;\n</code></pre>\n\n<p>Any yield break statement is translated into:</p>\n\n<pre><code>state = -1;\nreturn false;\n</code></pre>\n\n<p>There is an \"implicit\" yield break statement at the end of the function.\nA switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label. </p>\n\n<p>The original method is then translated into something like this:</p>\n\n<pre><code>IEnumerator&lt;string&gt; strings(IEnumerable&lt;string&gt; args)\n{\n return new ClosureEnumerable(this,args);\n}\n</code></pre>\n\n<p>The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last \"yield return\" statement the next time \"MoveNext\" is called.</p>\n\n<p>It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use \"yield\" with recursive algorithms. There is a good paper that outlines a better way to do this here:</p>\n\n<p><a href=\"http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf\" rel=\"nofollow noreferrer\">http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf</a></p>\n\n<p>It's worth a read if you haven't read it yet.</p>\n" }, { "answer_id": 177405, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Just spotted this question - I <a href=\"http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx\" rel=\"noreferrer\">wrote an article</a> on it recently. I'll have to add the other links mentioned here to the article though...</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
I'd love to figure it out myself but I was wondering **roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?** For example how does C# turn this: ``` IEnumerator<string> strings(IEnumerable<string> args) { IEnumerator<string> enumerator2 = getAnotherEnumerator(); foreach(var arg in arg) { enumerator2.MoveNext(); yield return arg+enumerator.Current; } } ``` into this: ``` bool MoveNext() { switch (this.state) { case 0: this.state = -1; this.enumerator2 = getAnotherEnumerator(); this.argsEnumerator = this.args.GetEnumerator(); this.state = 1; while (this.argsEnumerator.MoveNext()) { this.arg = this.argsEnumerator.Current; this.enumerator2.MoveNext(); this.current = this.arg + this.enumerator2.Current; this.state = 2; return true; state1: this.state = 1; } this.state = -1; if (this.argsEnumerator != null) this.argsEnumerator.Dispose(); break; case 2: goto state1; } return false; } ``` Of course the result can be completely different depending on the original code.
The particular code sample you are looking at involves a series of transformations. Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however. The first transformation is the "foreach" transformation, which transforms this code: ``` foreach (var x in y) { //body } ``` into this code: ``` var enumerator = y.GetEnumerator(); while (enumerator.MoveNext()) { var x = enumerator.Current; //body } if (y != null) { enumerator.Dispose(); } ``` The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a "goto label" right after the yield. The third transformation lifts all the local variables and function arguments in the method body into an object called a closure. Given the code in your example, that would look similar to this: ``` class ClosureEnumerable : IEnumerable<string> { private IEnumerable<string> args; private ClassType originalThis; public ClosureEnumerator(ClassType origThis, IEnumerable<string> args) { this.args = args; this.origianlThis = origThis; } public IEnumerator<string> GetEnumerator() { return new Closure(origThis, args); } } class Closure : IEnumerator<string> { public Closure(ClassType originalThis, IEnumerable<string> args) { state = 0; this.args = args; this.originalThis = originalThis; } private IEnumerable<string> args; private IEnumerator<string> enumerator2; private IEnumerator<string> argEnumerator; //- Here ClassType is the type of the object that contained the method // This may be optimized away if the method does not access any // class members private ClassType originalThis; //This holds the state value. private int state; //The current value to return private string currentValue; public string Current { get { return currentValue; } } } ``` The method body is then moved from the original method to a method inside "Closure" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext. Any access to any locals is routed through "this", and any access to any class members are routed through this.originalThis. Any "yield return expr" is translated into: ``` currentValue = expr; state = //the state number of the yield statement; return true; ``` Any yield break statement is translated into: ``` state = -1; return false; ``` There is an "implicit" yield break statement at the end of the function. A switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label. The original method is then translated into something like this: ``` IEnumerator<string> strings(IEnumerable<string> args) { return new ClosureEnumerable(this,args); } ``` The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last "yield return" statement the next time "MoveNext" is called. It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use "yield" with recursive algorithms. There is a good paper that outlines a better way to do this here: <http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf> It's worth a read if you haven't read it yet.
131,901
<p>I am trying to copy a file using the following code:</p> <pre><code>File targetFile = new File(targetPath + File.separator + filename); ... targetFile.createNewFile(); fileInputStream = new FileInputStream(fileToCopy); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[64*1024]; int i = 0; while((i = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, i); } </code></pre> <p>For some users the <code>targetFile.createNewFile</code> results in this exception:</p> <pre><code>java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:850) </code></pre> <p>Filename and directory name seem to be correct. The directory <code>targetPath</code> is even checked for existence before the copy code is executed and the filename looks like this: <code>AB_timestamp.xml</code></p> <p>The user has write permissions to the <code>targetPath</code> and can copy the file without problems using the OS.</p> <p>As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.</p>
[ { "answer_id": 131943, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<p>Do you check that the targetPath is a directory, or just that something exists with that name? (I know you say the user can copy it from the operating system, but maybe they're typing something else).</p>\n\n<p>Does targetPath end with a File.separator already?</p>\n\n<p>(It would help if you could log and tell us what the value of targetPath and filename are on a failing case)</p>\n" }, { "answer_id": 131948, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 0, "selected": false, "text": "<p>Maybe the problem is that it is copying the file over the network, to a shared drive? I think java can have problems when writing files using NFS when the path is something like \\mypc\\myshared folder.</p>\n\n<p>What is the path where this problem happens?</p>\n" }, { "answer_id": 131952, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 0, "selected": false, "text": "<p>Try adding some logging to see exactly what is the name and path the file is trying to create, to ensure that the parent is well a directory.</p>\n\n<p>In addition, you can also take a look at Channels instead of using a loop. ;-)</p>\n" }, { "answer_id": 131978, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 0, "selected": false, "text": "<p>You say \"for some users\" - so it works for others? What is the difference here, are the users running different instances on different machines, or is this a server that services concurrent users?</p>\n\n<p>If the latter, I'd say it is a concurrency bug somehow - two threads check try to create the file with WinNTFileSystem.createFileExclusively(Native Method) simultaniously.</p>\n\n<p>Neither createNewFile or createFileExclusively are synchronized when I look at the OpenJDK source, so you may have to synchronize this block yourself.</p>\n" }, { "answer_id": 131994, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 1, "selected": false, "text": "<p>Try to create the file in a different directory - e.g. \"C:\\\" after you made sure you have write access to that directory. If that works, the path name of the file is wrong.</p>\n\n<p>Take a look at the comment in the Exception and try to vary all the elements in the path name of the file. Experiment. Draw conclusions.</p>\n" }, { "answer_id": 132311, "author": "bernardn", "author_id": 21548, "author_profile": "https://Stackoverflow.com/users/21548", "pm_score": 0, "selected": false, "text": "<p>Maybe the file already exists. It could be the case if your timestamp resolution is not good enough. As it is an IOException that you are getting, it might not be a permission issue (in which case you would get a SecurityException).</p>\n\n<p>I would first check for file existence before trying to create the file and try to log what's happening.</p>\n\n<p>Look at <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html#createNewFile()\" rel=\"nofollow noreferrer\">public boolean createNewFile()</a> for more information on the method you are using.</p>\n" }, { "answer_id": 133845, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 4, "selected": true, "text": "<p>Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:</p>\n\n<pre><code>File targetFile = new File(targetPath, filename);\n</code></pre>\n" }, { "answer_id": 204143, "author": "Turismo", "author_id": 5271, "author_profile": "https://Stackoverflow.com/users/5271", "pm_score": 0, "selected": false, "text": "<p>As I was not able to reproduce the error on my own machine or get hands on the machine of the user where the code failed I waited until now to declare an accepted answer.\nI changed the code to the following:</p>\n\n<pre><code>File parentFolder = new File(targetPath);\n... do some checks on parentFolder here ...\nFile targetFile = new File(parentFolder, filename);\ntargetFile.createNewFile();\nfileInputStream = new FileInputStream(fileToCopy);\nfileOutputStream = new FileOutputStream(targetFile);\nbyte[] buffer = new byte[64*1024];\nint i = 0;\nwhile((i = fileInputStream.read(buffer)) != -1) {\n fileOutputStream.write(buffer, 0, i);\n}\n</code></pre>\n\n<p>After that it worked for the user reporting the problem. </p>\n\n<p>So it seems Alexanders answer did the trick - although I actually use a slightly different constructor than he gave, but along the same lines.</p>\n\n<p>I yet have to talk that user into helping me verifying that the code change fixed the error (instead of him doing something differently) by running the old version again and checking if it still fails.</p>\n\n<p>btw. logging was in place and the logged path seemed ok - sorry for not mentioning that. I took that for granted and found it unnecessarily complicated the code in the question. </p>\n\n<p>Thanks for the helpful answers.</p>\n" }, { "answer_id": 2707804, "author": "Sensei", "author_id": 325329, "author_profile": "https://Stackoverflow.com/users/325329", "pm_score": 3, "selected": false, "text": "<p>I just encountered the same problem. I think it has to something do with write access permission. I got the error while trying to write to c:\\ but on changing to D:\\ everything worked fine.\nApparently Java did not have permission to write to my System Drive (Running Windows 7 installed on C:)</p>\n" }, { "answer_id": 4921530, "author": "w.pasman", "author_id": 606450, "author_profile": "https://Stackoverflow.com/users/606450", "pm_score": 2, "selected": false, "text": "<p>Here is the test program I use</p>\n\n<pre><code>import java.io.File;\npublic class TestWrite {\n\n public static void main(String[] args) {\n if (args.length!=1) {\n throw new IllegalArgumentException(\"Expected 1 argument: dir for tmp file\");\n }\n try {\n File.createTempFile(\"bla\",\".tmp\",new File(args[0]));\n } catch (Exception e) {\n System.out.println(\"exception:\"+e);\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 13643716, "author": "MikeRoger", "author_id": 459655, "author_profile": "https://Stackoverflow.com/users/459655", "pm_score": 0, "selected": false, "text": "<p>A very similar error:-\n \" ... java.io.IOException: The filename, directory name, or volume label syntax is incorrect\"\nwas generated in Eclipse for me when the TOMCAT home setting had a training backslash.</p>\n\n<p>The minor edit suggested at:-\n <a href=\"http://www.coderanch.com/t/556633/Tomcat/java-io-IOException-filename-directory\" rel=\"nofollow\">http://www.coderanch.com/t/556633/Tomcat/java-io-IOException-filename-directory</a>\nfixed it for me. </p>\n" }, { "answer_id": 35444964, "author": "Adam Hughes", "author_id": 4076764, "author_profile": "https://Stackoverflow.com/users/4076764", "pm_score": 5, "selected": false, "text": "<p>This can occur when filename has timestamp with colons, eg. <code>myfile_HH:mm:ss.csv</code> Removing colons fixed the issue.</p>\n" }, { "answer_id": 56770950, "author": "urupani", "author_id": 11022773, "author_profile": "https://Stackoverflow.com/users/11022773", "pm_score": 1, "selected": false, "text": "<p>Remove any special characters in the file/folder name in the complete path.</p>\n" }, { "answer_id": 74408100, "author": "user20481302", "author_id": 20481302, "author_profile": "https://Stackoverflow.com/users/20481302", "pm_score": 0, "selected": false, "text": "<pre><code>FileUtils.copyFile(src,new File(&quot;C:\\\\Users\\\\daiva\\\\eclipse-workspace\\\\PracticeProgram\\\\Screenshot\\\\adi.png&quot;));\n</code></pre>\n<p>Try to copy file like this.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5271/" ]
I am trying to copy a file using the following code: ``` File targetFile = new File(targetPath + File.separator + filename); ... targetFile.createNewFile(); fileInputStream = new FileInputStream(fileToCopy); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[64*1024]; int i = 0; while((i = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, i); } ``` For some users the `targetFile.createNewFile` results in this exception: ``` java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:850) ``` Filename and directory name seem to be correct. The directory `targetPath` is even checked for existence before the copy code is executed and the filename looks like this: `AB_timestamp.xml` The user has write permissions to the `targetPath` and can copy the file without problems using the OS. As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename: ``` File targetFile = new File(targetPath, filename); ```
131,902
<p>I am wondering what security concerns there are to implementing a <code>PHP evaluator</code> like this:</p> <pre><code>&lt;?php eval($_POST['codeInput']); %&gt; </code></pre> <p>This is in the context of making a <code>PHP sandbox</code> so sanitising against <code>DB input</code> etc. isn't a massive issue.</p> <p>Users destroying the server the file is hosted on is.</p> <p>I've seen <code>Ruby simulators</code> so I was curious what's involved security wise (vague details at least).</p> <hr> <p>Thanks all. I'm not even sure on which answer to accept because they are all useful.</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#131911">Owen's answer</a> summarises what I suspected (the server itself would be at risk).</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137019">arin's answer</a> gives a great example of the potential problems.</p> <p><a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137167">Geoff's answer</a> and <a href="https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137118">randy's answer</a> echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.</p>
[ { "answer_id": 131911, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": false, "text": "<p>don't do that.</p>\n\n<p>they basically have access to anything you can do in PHP (look around the file system, get/set any sort of variables, open connections to other machines to insert code to run, etc...)</p>\n" }, { "answer_id": 131965, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 2, "selected": false, "text": "<p>There are a lot of things you could say.. The concerns are <strong>not specific to PHP.</strong></p>\n\n<p>Here's the simple answer:</p>\n\n<p><strong>Any input to your machine (or database) needs to be sanitized.</strong></p>\n\n<p>The code snippet you've posted pretty much lets a user run any code they want, so it's especially dangerous.</p>\n\n<p>There is a pretty good introductory article on code injection here:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Code_injection\" rel=\"nofollow noreferrer\">Wikipedia on Code Injection</a>.</p>\n" }, { "answer_id": 131984, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 2, "selected": false, "text": "<p>If you allow arbitrary code to be run on your server, it's not your server any more.</p>\n" }, { "answer_id": 132095, "author": "ehm", "author_id": 15214, "author_profile": "https://Stackoverflow.com/users/15214", "pm_score": -1, "selected": false, "text": "<p>As already answered, you need to sanitize your inputs. I guess you could use some regex-filtring of some kind to remove unwanted commands such as \"exec\" and basically every malicious command PHP has got to offer (or which could be exploited), and that's a lot.</p>\n" }, { "answer_id": 137019, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 4, "selected": true, "text": "<p>could potentially be in really big trouble if you <code>eval()</code>'d something like </p>\n\n<pre><code>&lt;?php\n eval(\"shell_exec(\\\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\\\");\");\n?&gt;\n</code></pre>\n\n<p>it's an extreme example but it that case your site would just get deleted. hopefully your permissions wouldn't allow it but, it helps illustrate the need for sanitization &amp; checks.</p>\n" }, { "answer_id": 137066, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 2, "selected": false, "text": "<p>Dear god <strong>NO</strong>. I cringe even at the title. Allowing user to run any kind of arbitrary code is like handing the server over to them</p>\n\n<p>I know the people above me already said that. But believe me. That's never enough times that someone can tell you to sanitize your input.</p>\n\n<p>If you <em>really, really</em> want to allow user to run some kind of code. Make a subset of the commands available to the user by creating some sort of psudo language that the user can use to do that. A-la the way bbcode or markdown works. </p>\n" }, { "answer_id": 137118, "author": "randy", "author_id": 22465, "author_profile": "https://Stackoverflow.com/users/22465", "pm_score": 2, "selected": false, "text": "<p>Do <strong>NOT</strong> allow unfiltered code to be executed on your server, period.</p>\n\n<p>If you'd like to create a tool that allows for interactive demonstration of a language such as the tool seen here: <a href=\"http://tryruby.hobix.com/\" rel=\"nofollow noreferrer\">http://tryruby.hobix.com/</a> I would work on coding a sub portion of the language yourself. Ideally, you'll be using it to demonstrate simple concepts to new programmers, so it's irrelevant if you properly implement all the features.</p>\n\n<p>By doing this you can control the input via a <strong>white list</strong> of known acceptable input. If the input isn't on the white list it isn't executed.</p>\n\n<p>Best of luck!</p>\n" }, { "answer_id": 137167, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 2, "selected": false, "text": "<p>If you are looking to build an <a href=\"http://www.hping.org/phpinteractive/\" rel=\"nofollow noreferrer\">online PHP interpreter</a>, you will need to build an actual <a href=\"http://en.wikipedia.org/wiki/REPL\" rel=\"nofollow noreferrer\">REPL</a> interpreter and not use eval.</p>\n\n<p>Otherwise, never ever execute arbitrary user code. Ever. </p>\n" }, { "answer_id": 739930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The <code>eval()</code> function is hard to sanitize and even if you did there would surely be a way around it. Even if you filtered <code>exec</code>, all you need to do is to somehow glue the string <code>exec</code> into a variable, and then do <code>$variable()</code>. You'd need to really cripple the language to achieve at least some sort of imaginary security.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I am wondering what security concerns there are to implementing a `PHP evaluator` like this: ``` <?php eval($_POST['codeInput']); %> ``` This is in the context of making a `PHP sandbox` so sanitising against `DB input` etc. isn't a massive issue. Users destroying the server the file is hosted on is. I've seen `Ruby simulators` so I was curious what's involved security wise (vague details at least). --- Thanks all. I'm not even sure on which answer to accept because they are all useful. [Owen's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#131911) summarises what I suspected (the server itself would be at risk). [arin's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137019) gives a great example of the potential problems. [Geoff's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137167) and [randy's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137118) echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.
could potentially be in really big trouble if you `eval()`'d something like ``` <?php eval("shell_exec(\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\");"); ?> ``` it's an extreme example but it that case your site would just get deleted. hopefully your permissions wouldn't allow it but, it helps illustrate the need for sanitization & checks.
131,923
<p>Here's my situation:</p> <ul> <li>Windows Server</li> <li>Apache</li> <li>CruiseControl</li> </ul> <p>The last step of my CruiseControl deploy scripts copies the build to Apache's htdocs folder, in a "demos" folder (I believe this is referred to as a "hot deploy"?)</p> <p>All is good and dandy, except that SOMETIMES (not common, but it happens enough that it bugs me), the demos folder doesn't contain the files I built! The old one is gone and the new one isn't there, just vanished.</p> <p>My gut feeling is that if I try to overwrite a file while someone on the web is downloading it, Apache just deletes it after the download is done? I don't know, it doesn't make any sense.</p> <p>I looked everywhere and couldn't find even a hint...let's see how good this StackOverflow community really is! :)</p> <p>Here's the "deploy" target in my ANT script:</p> <pre><code>&lt;target name="deploy" depends="revertVersionFile"&gt; &lt;copy todir="${deploy.dir}"&gt; &lt;fileset dir="${bin.dir}"/&gt; &lt;/copy&gt; &lt;copy todir="${deploy.dir}"&gt; &lt;fileset dir="${bin.dir}"/&gt; &lt;/copy&gt; &lt;available file="${deploy.dir}/MockupsLive.swf" property="mockupsFile"/&gt; &lt;fail unless="mockupsFile" message="MockupsLive doesn't exist!"/&gt; &lt;available file="${deploy.dir}/skins/sketch/sketch.swf" property="skinFile"/&gt; &lt;fail unless="skinFile" message="sketch.swf doesn't exist!"/&gt; &lt;/target&gt; </code></pre>
[ { "answer_id": 136751, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": 0, "selected": false, "text": "<p>Apache won't delete the contents of the directory. Something in the script is removing the contents would be my guess. Does the script create a backup of any kind? Maybe it moves the contents to a backup folder and then copies the build. </p>\n\n<p>You could add a bit of security to that folder to prevent its deletion. Maybe then an error would pop up somewhere and give you an idea as to what is conveniently deleting the directory. :) My guess is its in the script.</p>\n" }, { "answer_id": 167589, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 1, "selected": false, "text": "<p>I would suggest creating a backup of the old files prior to copying the new files out. Name the old files with the timestamp for when they were replaced. Doing this and then seeing what is in the directory the next time it fails will most likely give you a clue as to where to look next.</p>\n" }, { "answer_id": 174546, "author": "Sarat", "author_id": 18937, "author_profile": "https://Stackoverflow.com/users/18937", "pm_score": 0, "selected": false, "text": "<p>I think the problem might be somewhere in the CruiseControl file. Most likely what is happening is that the CruiseControl process is tidying up the files somewhere, but maybe due to a lock on the files (potentially by Apache) it cannot write the files back into that folder.</p>\n\n<p>Either way, since \"deploy\" seems to be the last step, previous steps probably clear the directory and deploy is failing to run, leaving your folder empty at the end of the steps.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199623/" ]
Here's my situation: * Windows Server * Apache * CruiseControl The last step of my CruiseControl deploy scripts copies the build to Apache's htdocs folder, in a "demos" folder (I believe this is referred to as a "hot deploy"?) All is good and dandy, except that SOMETIMES (not common, but it happens enough that it bugs me), the demos folder doesn't contain the files I built! The old one is gone and the new one isn't there, just vanished. My gut feeling is that if I try to overwrite a file while someone on the web is downloading it, Apache just deletes it after the download is done? I don't know, it doesn't make any sense. I looked everywhere and couldn't find even a hint...let's see how good this StackOverflow community really is! :) Here's the "deploy" target in my ANT script: ``` <target name="deploy" depends="revertVersionFile"> <copy todir="${deploy.dir}"> <fileset dir="${bin.dir}"/> </copy> <copy todir="${deploy.dir}"> <fileset dir="${bin.dir}"/> </copy> <available file="${deploy.dir}/MockupsLive.swf" property="mockupsFile"/> <fail unless="mockupsFile" message="MockupsLive doesn't exist!"/> <available file="${deploy.dir}/skins/sketch/sketch.swf" property="skinFile"/> <fail unless="skinFile" message="sketch.swf doesn't exist!"/> </target> ```
I would suggest creating a backup of the old files prior to copying the new files out. Name the old files with the timestamp for when they were replaced. Doing this and then seeing what is in the directory the next time it fails will most likely give you a clue as to where to look next.
131,944
<p>How do I read a time value and then insert it into a TimeSpan variables?</p>
[ { "answer_id": 131960, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 1, "selected": false, "text": "<pre><code>TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);\n</code></pre>\n\n<p>Or, if you mean DateTime:</p>\n\n<pre><code>DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);\n</code></pre>\n\n<p>Where all of the parameters are ints.</p>\n" }, { "answer_id": 131963, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 0, "selected": false, "text": "<p>Perhaps using:</p>\n\n<pre><code>var span = new TimeSpan(hours, minutes, seconds);\n</code></pre>\n\n<p>If you mean adding two timespans together use:</p>\n\n<pre><code>var newSpan = span.Add(new TimeSpan(hours, minutes, seconds));\n</code></pre>\n\n<p>For more information see <a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.aspx\" rel=\"nofollow noreferrer\">msdn</a>.</p>\n" }, { "answer_id": 131964, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 0, "selected": false, "text": "<p>You can't change the properties of a TimeSpan. You need to create a new instance and pass the new values there.</p>\n" }, { "answer_id": 131968, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.aspx\" rel=\"nofollow noreferrer\">MSDN</a>: A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day. </p>\n\n<p>Here's how you can initialize it to CurrentTime (in ticks):</p>\n\n<pre><code>TimeSpan ts = new TimeSpan(DateTime.Now.Ticks);\n</code></pre>\n" }, { "answer_id": 131980, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": true, "text": "<p>If I understand you correctly you're trying to get some user input in the form of \"08:00\" and want to store the time in a timespan variable?</p>\n\n<p>So.. something like this?</p>\n\n<pre><code>string input = \"08:00\";\nDateTime time;\nif (!DateTime.TryParse(input, out time))\n{\n // invalid input\n return;\n}\n\nTimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I read a time value and then insert it into a TimeSpan variables?
If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable? So.. something like this? ``` string input = "08:00"; DateTime time; if (!DateTime.TryParse(input, out time)) { // invalid input return; } TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second); ```
131,955
<p>Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)?</p> <p>The typical <kbd>Shift</kbd>+<kbd>Insert</kbd> does not seem to work here.</p>
[ { "answer_id": 131969, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 9, "selected": false, "text": "<p>Yes.. but awkward. <a href=\"https://learn.microsoft.com/en-gb/archive/blogs/adioltean/useful-copypaste-trick-in-cmd-exe\" rel=\"nofollow noreferrer\">Link</a></p>\n\n<p><kbd>alt</kbd> + <kbd>Space</kbd>, <kbd>e</kbd>, <kbd>k</kbd> &lt;-- for copy and<br>\n<kbd>alt</kbd> + <kbd>Space</kbd>, <kbd>e</kbd>, <kbd>p</kbd> &lt;-- for paste. </p>\n" }, { "answer_id": 131973, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "<p>This is not really a shortcut but just a quick access to the control menu: Alt-space E P</p>\n\n<p>If you can use your mouse, right click on the cmd window works as paste when I tried it.</p>\n" }, { "answer_id": 131977, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 7, "selected": false, "text": "<p>Not really programming related, but I found <a href=\"http://windowsitpro.com/article/articleid/79505/jsi-tip-7363-how-do-i-copy--paste-between-a-command-prompt-or-ms-dos-program-and-a-windows-program.html\" rel=\"noreferrer\">this</a> on Google, <strong>there is not a direct keyboard shortcut</strong>, but makes it a little quicker.</p>\n<h2>To enable or disable QuickEdit mode:</h2>\n<ol>\n<li>Open the MS-DOS program, or the command prompt.</li>\n<li>Right-click the title bar and press Properties.</li>\n<li>Select the Options tab.</li>\n<li>Check or un-check the QuickEdit Mode box.</li>\n<li>Press OK.</li>\n<li>In the Apply Properties To Shortcut dialog, select the Apply properties to current window only if you wish to change the QuickEdit setting for this session of this window only, or select Modify shortcut that started this window to change the QuickEdit setting for all future invocations of the command prompt, or MS-DOS program.</li>\n</ol>\n<p><img src=\"https://i.stack.imgur.com/viWyn.png\" alt=\"QuickEdit\" /></p>\n<h2>To Copy text when QuickEdit is enabled:</h2>\n<ol>\n<li>Click and drag the mouse pointer over the text you want.</li>\n<li>Press Enter (or right-click anywhere in the window) to copy the text to the clipboard.</li>\n</ol>\n<h2>To Paste text when QuickEdit is enabled:</h2>\n<ol>\n<li>Right-click anywhere in the window.</li>\n</ol>\n<h2>To Copy text when QuickEdit is disabled:</h2>\n<ol>\n<li>Right-click the title bar, press Edit on the menu, and press Mark.</li>\n<li>Drag the mouse over the text you want to copy.</li>\n<li>Press Enter (or right-click anywhere in the window) to copy the text to the clipboard.</li>\n</ol>\n<h2>To Paste text when QuickEdit is disabled:</h2>\n<ol>\n<li>Right-click the title bar, press Edit on the menu, and press Paste.</li>\n</ol>\n" }, { "answer_id": 131997, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 1, "selected": false, "text": "<p>You could try using <a href=\"http://lifehacker.com/software/texter/lifehacker-code-texter-windows-238306.php\" rel=\"nofollow noreferrer\" title=\"Texter\">Texter</a> and create something unlikely like:</p>\n\n<p>./p , triggered by space and replacing the text with %c</p>\n\n<p>I just tested it and it works fine. The only gotcha is to use a rare sequence, as Texter cannot restrict this to just cmd.</p>\n\n<p>There are probably other utilities of this kind which could work, and even <a href=\"http://www.autohotkey.com\" rel=\"nofollow noreferrer\" title=\"AutoHotKey\">AutoHotKey</a>, upon which Texter is built could do it better, but Texter is easy :-)</p>\n" }, { "answer_id": 133332, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 8, "selected": true, "text": "<p>I personally use a little <a href=\"http://www.autohotkey.com/\" rel=\"noreferrer\">AutoHotkey</a> script to remap certain keyboard functions, for the console window (CMD) I use:</p>\n\n<pre><code>; Redefine only when the active window is a console window \n#IfWinActive ahk_class ConsoleWindowClass\n\n; Close Command Window with Ctrl+w\n$^w::\nWinGetTitle sTitle\nIf (InStr(sTitle, \"-\")=0) { \n Send EXIT{Enter}\n} else {\n Send ^w\n}\n\nreturn \n\n\n; Ctrl+up / Down to scroll command window back and forward\n^Up::\nSend {WheelUp}\nreturn\n\n^Down::\nSend {WheelDown}\nreturn\n\n\n; Paste in command window\n^V::\n; Spanish menu (Editar-&gt;Pegar, I suppose English version is the same, Edit-&gt;Paste)\nSend !{Space}ep\nreturn\n\n#IfWinActive \n</code></pre>\n" }, { "answer_id": 2421490, "author": "Huw Walters", "author_id": 291033, "author_profile": "https://Stackoverflow.com/users/291033", "pm_score": 5, "selected": false, "text": "<p>Thanks Pablo, just what I was looking for! However, if I can take the liberty of improving your script slightly, I suggest replacing your ^V macro with the following:</p>\n\n<pre><code>; Use backslash instead of backtick (yes, I am a C++ programmer).\n#EscapeChar \\\n\n; Paste in command window.\n^V::\nStringReplace clipboard2, clipboard, \\r\\n, \\n, All\nSendInput {Raw}%clipboard2%\nreturn\n</code></pre>\n\n<p>The advantage of using SendInput is that</p>\n\n<ul>\n<li>it doesn't rely on the command prompt system menu having an \"Alt+Space E P\" menu item to do the pasting (works for English and Spanish, but not for all languages).</li>\n<li>it avoids that nasty flicker you get as the menu is created and destroyed.</li>\n</ul>\n\n<p>Note, it's important to include the \"{Raw}\" in the SendInput command, in case the clipboard happens to contain \"!\", \"+\", \"^\" or \"#\".</p>\n\n<p>Note, it uses StringReplace to remove excess Windows carriage return characters. Thanks hugov for that suggestion!</p>\n" }, { "answer_id": 2762050, "author": "Maksym Kozlenko", "author_id": 171847, "author_profile": "https://Stackoverflow.com/users/171847", "pm_score": 2, "selected": false, "text": "<p>Thanks, Pablo, for referring to AutoHotkey utility. \nSince I have Launchy installed which uses <kbd>Alt</kbd>+<kbd>Space</kbd> I had to modify it a but to add <kbd>Shift</kbd> key as shown:</p>\n\n<pre><code>; Paste in command window\n^V::\n; Spanish menu (Editar-&gt;Pegar, I suppose English version is the same, Edit-&gt;Paste)\nSend !+{Space}ep\nreturn\n</code></pre>\n" }, { "answer_id": 3475037, "author": "ilcredo", "author_id": 419330, "author_profile": "https://Stackoverflow.com/users/419330", "pm_score": 1, "selected": false, "text": "<p>A simpler way is to use windows powershell instead of cmd. itworks fine with texter.</p>\n" }, { "answer_id": 4554292, "author": "Denis Vuyka", "author_id": 80816, "author_profile": "https://Stackoverflow.com/users/80816", "pm_score": 1, "selected": false, "text": "<p>I've recently found that command prompt has support for context menu via the right mouse click. You can find more details here: <a href=\"http://www.askdavetaylor.com/copy_paste_within_microsoft_windows_command_prompt.html\" rel=\"nofollow\">http://www.askdavetaylor.com/copy_paste_within_microsoft_windows_command_prompt.html</a></p>\n" }, { "answer_id": 6221566, "author": "Richard", "author_id": 781987, "author_profile": "https://Stackoverflow.com/users/781987", "pm_score": -1, "selected": false, "text": "<p>Under VISTA Command prompt:\nClick on the System Icon\nSelect Defaults from the Menu\nOn the Options tab in the Options group I have\n\"Quick Edit Mode\", \"Insert Mode\", and \"Auto Complete\" selected\nI think that \"Quick Edit Mode\" is what makes it work.</p>\n\n<p>To paste whatever is in the Clipboard at the insertion point: Right Click.\nTo copy from the Command Window\n Select by holding down the left mouse button and dragging the pointer across what you want to copy\n Once selected, right click\n To paste at the insertion point, right click again.</p>\n" }, { "answer_id": 17630810, "author": "Djee", "author_id": 2500798, "author_profile": "https://Stackoverflow.com/users/2500798", "pm_score": 2, "selected": false, "text": "<p>It took me a small while to figure out why your <a href=\"http://www.autohotkey.com\" rel=\"nofollow\">AutoHotkey</a> script does not work with me:</p>\n\n<pre><code>; Use backslash instead of backtick (yes, I am a C++ programmer).\n#EscapeChar \\\n\n; Paste in command window.\n^V::\nStringReplace clipboard2, clipboard, \\r\\n, \\n, All\nSendInput {Raw}%clipboard2%\nreturn\n</code></pre>\n\n<p>In fact, it relies on keystrokes and consequently on keyboard layout!\nSo when you are, as I am, unfortunate to have only an AZERTY keyboard, your suggestion just does not work. And worse, I found no easy way to replace SendInput method or twist its environment to fix this. For example SendInput \"1\" just does not send digit 1.</p>\n\n<p>I had to turn every character into its unicode to make it work on my computer:</p>\n\n<pre><code>#EscapeChar \\\n\n; Paste in command window.\n^V::\nStringReplace clipboard2, clipboard, \\r\\n, \\n, All\nclipboard3 := \"\"\nLoop {\n if (a_index&gt;strlen(clipboard2))\n break \n char_asc := Asc(SubStr(clipboard2, a_Index, 1)) \n if (char_asc &gt; 127 and char_asc &lt; 256)\n add_zero := \"0\"\n else\n add_zero := \"\" \n clipboard3 := clipboard3 . \"{Asc \" . add_zero . char_asc . \"}\"\n}\nSendInput %clipboard3%\nreturn\n</code></pre>\n\n<p>Not very simple...</p>\n" }, { "answer_id": 21241776, "author": "sibbl", "author_id": 1701563, "author_profile": "https://Stackoverflow.com/users/1701563", "pm_score": 4, "selected": false, "text": "<p>There is also <a href=\"http://mridgers.github.io/clink/\" rel=\"noreferrer\">a great open source tool called clink</a>, which extends cmd by many features. One of them is being able to use ctrl+v to insert text.</p>\n" }, { "answer_id": 23428782, "author": "Bruno", "author_id": 1347601, "author_profile": "https://Stackoverflow.com/users/1347601", "pm_score": 1, "selected": false, "text": "<p>Pretty simple solution may be <a href=\"http://sourceforge.net/projects/console/\" rel=\"nofollow\">Console 2</a>, redefine keys and you go.</p>\n" }, { "answer_id": 31506358, "author": "Franck Dernoncourt", "author_id": 395857, "author_profile": "https://Stackoverflow.com/users/395857", "pm_score": 4, "selected": false, "text": "<p>On Windows 10, you <a href=\"http://www.howtogeek.com/197749/how-to-power-up-the-windows-10-command-prompt-with-ctrlc-and-ctrlv/\">can enable <kbd>Ctrl</kbd> + <kbd>C</kbd> and <kbd>Ctrl</kbd> + <kbd>V</kbd> to work in the command prompt</a>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/U6WkL.png\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/hhS0B.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 32226999, "author": "Pravin W", "author_id": 2599419, "author_profile": "https://Stackoverflow.com/users/2599419", "pm_score": 2, "selected": false, "text": "<p>I followed @PabloG's steps as follows</p>\n\n<ol>\n<li>goto <a href=\"http://www.autohotkey.com/\" rel=\"nofollow noreferrer\">http://www.autohotkey.com/</a> - download autohotkey</li>\n<li>follow simple installation steps</li>\n<li>after installation create new *.ahk file as follows right click on desktop > new > Autohotkey Script > giveAnyFileName.ahk</li>\n<li>right click on this file > Edit</li>\n<li>copy paste autohotkey script given by @PabloG in his answer</li>\n<li>save and close</li>\n<li>double click on file to run</li>\n<li>Done now you should be able to use <kbd>Ctrl</kbd>+<kbd>v</kbd> for paste in command prompt</li>\n</ol>\n" }, { "answer_id": 32227072, "author": "i486", "author_id": 2417459, "author_profile": "https://Stackoverflow.com/users/2417459", "pm_score": 2, "selected": false, "text": "<p>Theoretically, the application in DOS Prompt has its own clipboard and shortcuts. To import text from Windows clipboard is \"extra\". However you can use Alt-Space to open system menu of Prompt window, then press E, P to select Edit, Paste menu. However, MS could provide shortcut using Win-key. There is no chance to be used in DOS application.</p>\n" }, { "answer_id": 32935945, "author": "Franck Dernoncourt", "author_id": 395857, "author_profile": "https://Stackoverflow.com/users/395857", "pm_score": 2, "selected": false, "text": "<p>If you use the clipboard manager <a href=\"http://ditto-cp.sourceforge.net/index.php\" rel=\"nofollow noreferrer\">Ditto</a> (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.</p>\n\n<p><a href=\"https://i.stack.imgur.com/dtApe.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dtApe.gif\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 35676684, "author": "U007D", "author_id": 1541330, "author_profile": "https://Stackoverflow.com/users/1541330", "pm_score": 1, "selected": false, "text": "<p>If you're a Cygwin user, you can append the following to your ~/.bashrc file:</p>\n\n<p><code>stty lnext ^q stop undef start undef</code></p>\n\n<p>And the following to your ~/.inputrc file:</p>\n\n<pre><code>\"\\C-v\": paste-from-clipboard\n\"\\C-C\": copy-to-clipboard\n</code></pre>\n\n<p>Restart your Cygwin terminal.</p>\n\n<p>(Note, I've used an uppercase C for copy, since CTRL+c is assigned to the break function on most consoles. Season to taste.)</p>\n\n<p><a href=\"http://www.saltycrane.com/blog/2008/05/how-to-paste-in-cygwin-bash-using-ctrl/\" rel=\"nofollow\">Source</a></p>\n" }, { "answer_id": 37289004, "author": "Michael Scott", "author_id": 6346733, "author_profile": "https://Stackoverflow.com/users/6346733", "pm_score": 1, "selected": false, "text": "<p>Instead of \"right click\"....start your session (once you're in the command prompt window) by keying Alt/SpaceBar. That will open the Command Prompt window menu and you'll see your familiar, underlined keyboard command shortcuts, just like in Windows GUI.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 38418674, "author": "Vignesh VRT", "author_id": 6599346, "author_profile": "https://Stackoverflow.com/users/6599346", "pm_score": 2, "selected": false, "text": "<p>simplest method is just the copy the text that you want to paste it in cmd and open cmd goto \"properties\"---> \"option\" tab----> check the (give tick mark) \"quickEdit mode\" and click \"ok\" .....now you can paste any text from clipboard by doing <strong>right click</strong> from ur mouse.</p>\n\n<p>Thank you..</p>\n" }, { "answer_id": 40419159, "author": "c00000fd", "author_id": 843732, "author_profile": "https://Stackoverflow.com/users/843732", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://dennisbabkin.com/clc/\" rel=\"noreferrer\">Here</a>'s a free tool that will do it on Windows. I prefer it to a script as it's easy to set up. It runs as a fast native app, works on XP and up, has configuration settings that allow to remap copy/paste/selection keys for command windows:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MA02D.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MA02D.png\" alt=\"enter image description here\"></a></p>\n\n<p>Plus I know the developers.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ]
Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)? The typical `Shift`+`Insert` does not seem to work here.
I personally use a little [AutoHotkey](http://www.autohotkey.com/) script to remap certain keyboard functions, for the console window (CMD) I use: ``` ; Redefine only when the active window is a console window #IfWinActive ahk_class ConsoleWindowClass ; Close Command Window with Ctrl+w $^w:: WinGetTitle sTitle If (InStr(sTitle, "-")=0) { Send EXIT{Enter} } else { Send ^w } return ; Ctrl+up / Down to scroll command window back and forward ^Up:: Send {WheelUp} return ^Down:: Send {WheelDown} return ; Paste in command window ^V:: ; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste) Send !{Space}ep return #IfWinActive ```
131,975
<p>I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as:</p> <pre><code>&lt;bean id="Mary" class="foo.bar.Female"&gt; &lt;property name="age" value="23"/&gt; &lt;/bean&gt; &lt;bean id="John" class="foo.bar.Male"&gt; &lt;property name="girlfriend" ref="Mary"/&gt; &lt;/bean&gt; </code></pre> <p>compared to plain old java code such as:</p> <pre><code>Female mary = new Female(); mary.setAge(23); Male john = new Male(); john.setGirlfriend(mary); </code></pre> <p>which is easier debugged, compile time checked and can be understood by anyone who knows only java. So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.)</p> <hr> <p><strong>UPDATE:</strong><br/> In case of</p> <pre><code>IService myService;// ... public void doSomething() { myService.fetchData(); } </code></pre> <p>How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it.</p> <p>It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use.</p> <hr> <p><strong>UPDATE 2:</strong><br/> I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file.</p> <hr> <p><strong>UPDATE 3:</strong><br/></p> <blockquote> <p>External configuration of mapping between interfaces and their concrete implementations </p> </blockquote> <p>What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?!</p> <blockquote> <p>You save coding time because you provide mappings declaratively, not in a procedural code </p> </blockquote> <p>I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it.</p> <blockquote> <p>Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)</p> </blockquote> <p>I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values.</p> <pre><code>mary = new FakeFemale(); </code></pre> <p>I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it?</p> <p>When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it?</p> <hr> <p><strong>LAST UPDATE:</strong><br/> Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD. The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer. The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.</p>
[ { "answer_id": 131986, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 1, "selected": false, "text": "<p>In the .NET world, most of IoC frameworks provide both XML and Code configuration.</p>\n\n<p>StructureMap and Ninject, for example, use fluent interfaces to configure containers. You are no longer constrained to use XML configuration files. Spring, which also exists in .NET, heavily relies on XML files since it is his historical main configuration interface, but it is still possible to configure containers programmatically.</p>\n" }, { "answer_id": 131988, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>You don't need to recompile your code each time you change something in configuration. It will simplify program deployment and maintenance. For example you can swap one component with another with just 1 change in config file.</p>\n" }, { "answer_id": 131991, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "<p>This is a bit of a loaded question, but I tend to agree that huge amounts of xml configuration doesn't really amount to much benefit. I like my applications to be as light on dependencies as possible, including the hefty frameworks.</p>\n\n<p>They simplify the code a lot of the times, but they also have an overhead in complexity that makes tracking down problems rather difficult (I have seen such problems first hand, and straight Java I would be a lot more comfortable dealing with).</p>\n\n<p>I guess it depends on style a bit, and what you are comfortable with... do you like to fly your own solution and have the benefit of knowing it inside out, or bank on existing solutions that may prove difficult when the configuration isn't just right? It's all a tradeoff.</p>\n\n<p>However, XML configuration is a bit of a pet peeve of mine... I try to avoid it at all costs.</p>\n" }, { "answer_id": 131992, "author": "Jeroen Wyseur", "author_id": 15490, "author_profile": "https://Stackoverflow.com/users/15490", "pm_score": 0, "selected": false, "text": "<p>Spring also has a properties loader. We use this method to set variables that are dependant on the environment (e.g. development, testing, acceptance, production, ...). This could be for example the queue to listen to.</p>\n\n<p>If there is no reason why the property would change, there is also no reason to configure it in this way.</p>\n" }, { "answer_id": 132011, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 0, "selected": false, "text": "<p>Your case is very simple and therefore doesn't need an IoC (Inversion of Control) container like Spring. On the other hand, when you \"program to interfaces, not implementations\" (which is a good practice in OOP), you can have code like this:</p>\n\n<pre><code>IService myService;\n// ...\npublic void doSomething() {\n myService.fetchData();\n}\n</code></pre>\n\n<p>(note that the type of myService is IService -- an interface, not a concrete implementation). Now it can be handy to let your IoC container automatically provide the correct concrete instance of IService during initialization - when you have many interfaces and many implementations, it can be cumbersome to do that by hand. Main benefits of an IoC container (dependency injection framework) are:</p>\n\n<ul>\n<li>External configuration of mapping between interfaces and their concrete implementations</li>\n<li>IoC container handles some tricky issues like resolving complicated dependency graphs, managing component's lifetime etc.</li>\n<li>You save coding time because you provide mappings declaratively, not in a procedural code</li>\n<li>Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)</li>\n</ul>\n" }, { "answer_id": 132049, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>You can slot in a new implementation for girlfriend. So new female can be injected without recompiling your code. </p>\n\n<pre><code>&lt;bean id=\"jane\" class=\"foo.bar.HotFemale\"&gt;\n &lt;property name=\"age\" value=\"19\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"mary\" class=\"foo.bar.Female\"&gt;\n &lt;property name=\"age\" value=\"23\"/&gt;\n&lt;/bean&gt;\n&lt;bean id=\"john\" class=\"foo.bar.Male\"&gt;\n &lt;property name=\"girlfriend\" ref=\"jane\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>(The above assumes Female and HotFemale implement the same GirlfFriend interface) </p>\n" }, { "answer_id": 132097, "author": "Kevin S.", "author_id": 21583, "author_profile": "https://Stackoverflow.com/users/21583", "pm_score": 4, "selected": false, "text": "<p>Dependency injection is a coding style that has its roots in the observation that object delegation is usually a more useful design pattern than object inheritance (i.e., the object has-a relationship is more useful than the object is-a relationship). One other ingredient is necessary however for DI to work, that of creating object interfaces. Combining these two powerful design patterns software engineers quickly realized that they could create flexible loosely coupled code and thus the concept of Dependency Injection was born. However it wasn't until object reflection became available in certain high level languages that DI really took off. The reflection component is core to most of today's DI systems today because the really cool aspects of DI require the ability to programmatically select objects and configure and inject them into other objects using a system external and independent to the objects themselves.</p>\n\n<p>A language must provide good support for both normal Object Oriented programming techniques as well as support for object interfaces and object reflection (for example Java and C#). While you can build programs using DI patterns in C++ systems its lack of reflection support within the language proper prevents it from supporting application servers and other DI platforms and hence limits the expressiveness of the DI patterns.</p>\n\n<p>Strengths of a system built using DI patterns:</p>\n\n<ol>\n<li>DI code is much easier to reuse as the 'depended' functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will.</li>\n<li>DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building 'mock' objects implementing the interfaces expected by your application logic.</li>\n<li>DI code is more flexible. It is innately loosely coupled code -- to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.</li>\n<li>External (Xml) configuration of DI objects means that others can customize your code in unforeseen directions.</li>\n<li>External configuration is also a separation of concern pattern in that all problems of object initialization and object interdependency management can be handled by the application server.</li>\n<li>Note that external configuration is not required to use the DI pattern, for simple interconnections a small builder object is often adequate. There is a tradeoff in flexibility between the two. A builder object is not as flexible an option as an externally visible configuration file. The developer of the DI system must weigh the advantages of flexibility over convenience, taking care that small scale, fine grain control over object construction as expressed in a configuration file may increase confusion and maintenance costs down the line.</li>\n</ol>\n\n<p>Definitely DI code seems more cumbersome, the disadvantages of having all of those XML files that configure objects to be injected into other objects appears difficult. This is, however, the point of DI systems. Your ability to mix and match code objects as a series of configuration settings allows you to build complex systems using 3rd party code with minimal coding on your part.</p>\n\n<p>The example provided in the question merely touches on the surface of the expressive power that a properly factored DI object library can provide. With some practice and a lot of self discipline most DI practitioners find that they can build systems that have 100% test coverage of application code. This one point alone is extraordinary. This is not 100% test coverage of a small application of a few hundred lines of code, but 100% test coverage of applications comprising hundreds of thousands of lines of code. I am at a loss of being able to describe any other design pattern that provides this level of testability.</p>\n\n<p>You are correct in that an application of a mere 10s of lines of code is easier to understand than several objects plus a series of XML configuration files. However as with most powerful design patterns, the gains are found as you continue to add new features to the system.</p>\n\n<p>In short, large scale DI based applications are both easier to debug and easier to understand. While the Xml configuration is not 'compile time checked' all application services that this author is aware of will provide the developer with error messages if they attempt to inject an object having an incompatible interface into another object. And most provide a 'check' feature that covers all known objects configurations. This is easily and quickly done by checking that the to-be-injected object A implements the interface required by object B for all configured object injections.</p>\n" }, { "answer_id": 132215, "author": "jan.vdbergh", "author_id": 9540, "author_profile": "https://Stackoverflow.com/users/9540", "pm_score": -1, "selected": false, "text": "<p>One of the most appealing reasons is the \"<a href=\"http://en.wikipedia.org/wiki/Hollywood_Principle\" rel=\"nofollow noreferrer\">Hollywood principle</a>\": don't call us, we'll call you. A component is not required to do the lookups to other components and services itself; instead they are provided to it automatically. In Java, this means that it is no longer necessary to do JNDI lookups inside the component.</p>\n\n<p>It is also lots easier to unit test a component in isolation: instead of giving it an actual implementation of the components it needs, you simply use (possibly auto generated) mocks.</p>\n" }, { "answer_id": 137714, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 1, "selected": false, "text": "<p>Ease of <strong>combining partial configurations</strong> into a final complete configuration.</p>\n\n<p>For example, in web applications, the model, view and controllers are typically specified in separate configuration files. Use the declarative approach, you can load, for example:\n<code><pre>\n UI-context.xml\n Model-context.xml\n Controller-context.xml\n</pre></code></p>\n\n<p>Or load with a different UI and a few extra controllers:\n<code><pre>\n AlternateUI-context.xml\n Model-context.xml\n Controller-context.xml\n ControllerAdditions-context.xml\n</pre></code></p>\n\n<p>To do the same in code requires an infrastructure for combining partial configurations. Not impossible to do in code, but certainly easier to do using an IoC framework.</p>\n" }, { "answer_id": 155963, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 2, "selected": false, "text": "<p>The reason for using a DI container are that you don't have to have a billion properties pre-configured in your code that are simply getters and setters. Do you really want to hardcode all those with new X()? Sure, you can have a default, but the DI container allows the creation of singletons which is extremely easy and allows you to focus on the details of the code, not the miscellaneous task of initializing it. </p>\n\n<p>For example, Spring allows you to implement the InitializingBean interface and add an afterPropertiesSet method (you may also specify an \"init-method\" to avoid coupling your code to Spring). These methods will allow you to ensure that any interface specified as a field in your class instance is configured correctly upon startup, and then you no longer have to null-check your getters and setters (assuming you do allow your singletons to remain thread-safe).</p>\n\n<p>Furthermore, it is much easier to do complex initializations with a DI container instead of doing them yourself. For instance, I assist with using XFire (not CeltiXFire, we only use Java 1.4). The app used Spring, but it unfortunately used XFire's services.xml configuration mechanism. When a Collection of elements needed to declare that it had ZERO or more instances instead of ONE or more instances, I had to override some of the provided XFire code for this particular service.</p>\n\n<p>There are certain XFire defaults defined in its Spring beans schema. So, if we were using Spring to configure the services, the beans could have been used. Instead, what happened was that I had to supply an instance of a specific class in the services.xml file instead of using the beans. To do this, I needed to provide the constructor and set up the references declared in the XFire configuration. The real change that I needed to make required that I overload a single class.</p>\n\n<p>But, thanks to the services.xml file, I had to create four new classes, setting their defaults according to their defaults in the Spring configuration files in their constructors. If we had been able to use the Spring configuration, I could have just stated:</p>\n\n<pre><code>&lt;bean id=\"base\" parent=\"RootXFireBean\"&gt;\n &lt;property name=\"secondProperty\" ref=\"secondBean\" /&gt;\n&lt;/bean&gt;\n\n&lt;bean id=\"secondBean\" parent=\"secondaryXFireBean\"&gt;\n &lt;property name=\"firstProperty\" ref=\"thirdBean\" /&gt;\n&lt;/bean&gt;\n\n&lt;bean id=\"thirdBean\" parent=\"thirdXFireBean\"&gt;\n &lt;property name=\"secondProperty\" ref=\"myNewBean\" /&gt;\n&lt;/bean&gt;\n\n&lt;bean id=\"myNewBean\" class=\"WowItsActuallyTheCodeThatChanged\" /&gt;\n</code></pre>\n\n<p>Instead, it looked more like this:</p>\n\n<pre><code>public class TheFirstPointlessClass extends SomeXFireClass {\n public TheFirstPointlessClass() {\n setFirstProperty(new TheSecondPointlessClass());\n setSecondProperty(new TheThingThatWasHereBefore());\n }\n}\n\npublic class TheSecondPointlessClass extends YetAnotherXFireClass {\n public TheSecondPointlessClass() {\n setFirstProperty(TheThirdPointlessClass());\n }\n}\n\npublic class TheThirdPointlessClass extends GeeAnotherXFireClass {\n public TheThirdPointlessClass() {\n setFirstProperty(new AnotherThingThatWasHereBefore());\n setSecondProperty(new WowItsActuallyTheCodeThatChanged());\n }\n}\n\npublic class WowItsActuallyTheCodeThatChanged extends TheXFireClassIActuallyCareAbout {\n public WowItsActuallyTheCodeThatChanged() {\n }\n\n public overrideTheMethod(Object[] arguments) {\n //Do overridden stuff\n }\n}\n</code></pre>\n\n<p>So the net result is that four additional, mostly pointless Java classes had to be added to the codebase to achieve the affect that one additional class and some simple dependency container information achieved. This isn't the \"exception that proves the rule\", this IS the rule...handling quirks in code is much cleaner when the properties are already provided in a DI container and you're simply changing them to suit a special situation, which happens more often than not.</p>\n" }, { "answer_id": 182447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of:</p>\n\n<ul>\n<li>Testing</li>\n<li>Production maintenance</li>\n</ul>\n\n<p><strong>Testing</strong></p>\n\n<p>If you split your testing into 3 scenarios (which is fairly normal in large scale development):</p>\n\n<ol>\n<li>Unit testing</li>\n<li>Integration testing</li>\n<li>Black box testing</li>\n</ol>\n\n<p>What you will want to do is for the last two test scenarios (Integration &amp; Black box), is not recompile any part of the application.</p>\n\n<p>If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though.</p>\n\n<p>Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes.</p>\n\n<p><strong>Production</strong></p>\n\n<p>As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component).</p>\n\n<p><strong>Summary</strong></p>\n\n<p>The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances:</p>\n\n<ul>\n<li>Application is distributed to multiple sites/clients where environments will differ.</li>\n<li>Limited development control/input over the production environment and setup.</li>\n<li>Testing scenarios.</li>\n</ul>\n\n<p>In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration:</p>\n\n<ul>\n<li>When developing you don't know when it will change (the app is so useful your company sells it to someone else).</li>\n<li>I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model. </li>\n</ul>\n\n<p><em>Note: Application refers to the complete solution (not just the executable), so all files required for the application to run</em>.</p>\n" }, { "answer_id": 753304, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "<p>Any time you can change your code to data you're making a step in the right direction.</p>\n\n<p>Coding anything as data means that your code itself is more general and reusable. It also means that your data may be specified in a language that fits it exactly.</p>\n\n<p>Also, an XML file can be read into a GUI or some other tool and easily manipulated pragmatically. How would you do that with the code example?</p>\n\n<p>I'm constantly factoring things most people would implement as code into data, it makes what code is left MUCH cleaner. I find it inconceivable that people will create a menu in code rather than as data--it should be obvious that doing it in code is just plain wrong because of the boilerplate.</p>\n" }, { "answer_id": 3066107, "author": "Miro A.", "author_id": 369692, "author_profile": "https://Stackoverflow.com/users/369692", "pm_score": 1, "selected": false, "text": "<p>Often, the important point is <em>who</em> is changing the configuration after the program was written. With configuration in code you implicitly assume that person changing it has the same skills and access to source code etc as the original author had.</p>\n\n<p>In production systems it is very practical to extract some subset of settings (e.g. age in you example) to XML file and allow e.g. system administrator or support personal to change the value without giving them the full power over source code or other settings - or just to isolate them from complexities.</p>\n" }, { "answer_id": 4166461, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 0, "selected": false, "text": "<p>Initializing in an XML config file will simplify your debugging / adapting work with a client who has your app deployed on their computers. (Because it doesn't require recompilation + binary files replacement)</p>\n" }, { "answer_id": 5099433, "author": "badunk", "author_id": 631459, "author_profile": "https://Stackoverflow.com/users/631459", "pm_score": 2, "selected": false, "text": "<p>I have your answer</p>\n\n<p>There are obviously trade offs in each approach, but externalized XML configuration files are useful for enterprise development in which build systems are used to compile the code and not your IDE. Using the build system, you may want to inject certain values into your code - for example the version of the build (which could be painful to have to update manually each time you compile). The pain is greater when your build system pulls code off of some version control system. Modifying simple values at compile time would require you to change a file, commit it, compile, and then revert each time for each change. These aren't changes that you want to commit into your version control.</p>\n\n<p>Other useful use cases regarding the build system and external configs:</p>\n\n<ul>\n<li>injecting styles/stylesheets for a single code base for different builds</li>\n<li>injecting different sets of dynamic content (or references to them) for your single code base</li>\n<li>injecting localization context for different builds/clients</li>\n<li>changing a webservice URI to a backup server (when the main one goes down)</li>\n</ul>\n\n<p>Update:\nAll the above examples were on things that didn't necessarily require dependencies on classes. But you can easily build up cases where both a complex object and automation is necessary - for example:</p>\n\n<ul>\n<li>Imagine you had a system in which it monitored the traffic of your website. Depending on the # of concurrent users, it turns on/off a logging mechanism. Perhaps while the mechanism is off, a stub object is put in its place.</li>\n<li>Imagine you had a web conferencing system in which depending on the # of users, you want to switch out the ability to do P2P depending on # of participants</li>\n</ul>\n" }, { "answer_id": 5558486, "author": "David W Crook", "author_id": 291205, "author_profile": "https://Stackoverflow.com/users/291205", "pm_score": 1, "selected": false, "text": "<p>From a Spring perspecitve I can give you two answers. </p>\n\n<p>First the XML configuration isn't the only way to define the configuration. Most things can be configured using annotations and the things that must be done with XML are configuration for code that you aren't writing anyways, like a connection pool that you are using from a library. Spring 3 includes a method for defining the DI configuration using Java similar to the hand rolled DI configuration in your example. So using Spring does not mean that you have to use an XML based configuration file.</p>\n\n<p>Secondly Spring is a lot more than just a DI framework. It has lots of other features including transaction management and AOP. The Spring XML configuration mixes all these concepts together. Often in the same configuration file I'm specifying bean dependencies, transaction settings and adding session scoped beans that actually handled using AOP in the background. I find the XML configuration provides a better place to manage all these features. I also feel that the annotation based configuration and XML configuration scale up better than doing Java based configuration.</p>\n\n<p>But I do see your point and there isn't anything wrong with defining the dependency injection configuration in Java. I normally do that myself in unit tests and when I'm working on a project small enough that I haven't added a DI framework. I don't normally specify configuration in Java because to me that's the kind plumbing code that I'm trying to get away from writing when I chose to use Spring. That's a preference though, it doesn't mean that XML configuration is superior to Java based configuration.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ]
I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as: ``` <bean id="Mary" class="foo.bar.Female"> <property name="age" value="23"/> </bean> <bean id="John" class="foo.bar.Male"> <property name="girlfriend" ref="Mary"/> </bean> ``` compared to plain old java code such as: ``` Female mary = new Female(); mary.setAge(23); Male john = new Male(); john.setGirlfriend(mary); ``` which is easier debugged, compile time checked and can be understood by anyone who knows only java. So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.) --- **UPDATE:** In case of ``` IService myService;// ... public void doSomething() { myService.fetchData(); } ``` How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it. It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use. --- **UPDATE 2:** I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file. --- **UPDATE 3:** > > External configuration of mapping between interfaces and their concrete implementations > > > What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?! > > You save coding time because you provide mappings declaratively, not in a procedural code > > > I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it. > > Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one) > > > I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values. ``` mary = new FakeFemale(); ``` I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it? When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it? --- **LAST UPDATE:** Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD. The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer. The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.
For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of: * Testing * Production maintenance **Testing** If you split your testing into 3 scenarios (which is fairly normal in large scale development): 1. Unit testing 2. Integration testing 3. Black box testing What you will want to do is for the last two test scenarios (Integration & Black box), is not recompile any part of the application. If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though. Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes. **Production** As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component). **Summary** The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances: * Application is distributed to multiple sites/clients where environments will differ. * Limited development control/input over the production environment and setup. * Testing scenarios. In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration: * When developing you don't know when it will change (the app is so useful your company sells it to someone else). * I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model. *Note: Application refers to the complete solution (not just the executable), so all files required for the application to run*.
131,989
<p>I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option:</p> <pre><code>dig @ns1.foo.example example.com axfr </code></pre> <p>But this never works. Has anyone a better idea/approach</p>
[ { "answer_id": 131998, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "<p>If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.</p>\n" }, { "answer_id": 132009, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 3, "selected": false, "text": "<p>In Windows <code>nslookup</code> the command is</p>\n<pre><code>ls -d example.com &gt; outfile.txt\n</code></pre>\n<p>which stores the subdomain list in <code>outfile.txt</code></p>\n<p>few domains these days allow this</p>\n" }, { "answer_id": 132014, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 8, "selected": true, "text": "<p>The hint (using axfr) only works if the NS you're querying (<code>ns1.foo.example</code> in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question.</p>\n<p>Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. <code>dig a.example.com</code>, <code>dig b.example.com</code>, ...), which I can't recommend, as it could be viewed as a denial of service attack.</p>\n" }, { "answer_id": 147568, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 3, "selected": false, "text": "<p>You can only do this if you are connecting to a DNS server for the domain -and- AXFR is enabled for your IP address. This is the mechanism that secondary systems use to load a zone from the primary. In the old days, this was not restricted, but due to security concerns, most primary name servers have a whitelist of: secondary name servers + a couple special systems.</p>\n<p>If the nameserver you are using allows this then you can use dig or nslookup.</p>\n<p>For example:</p>\n<pre><code>#nslookup\n\n&gt;ls example.com\n</code></pre>\n<p>NOTE: because nslookup is being deprecated for dig and other newere tools, some versions of nslookup do not support &quot;ls&quot;, most notably macOS X's bundled version.</p>\n" }, { "answer_id": 2337811, "author": "Miroslav Mirkov", "author_id": 281620, "author_profile": "https://Stackoverflow.com/users/281620", "pm_score": 5, "selected": false, "text": "<ol>\n<li><code>dig example.com soa</code></li>\n<li><code>dig @ns.SOA.example example.com axfr</code></li>\n</ol>\n" }, { "answer_id": 2636917, "author": "techjacker", "author_id": 316428, "author_profile": "https://Stackoverflow.com/users/316428", "pm_score": 3, "selected": false, "text": "<p>robotex tools which are free will let you do this but they make you enter the ip of the domain first:</p>\n\n<ol>\n<li>find out the ip (there's a good ff plugin which does this but I can't post the link cos this is my first post here!)</li>\n<li>do an ip search on robotex: <a href=\"http://www.robtex.com/ip/\" rel=\"noreferrer\">http://www.robtex.com/ip/</a></li>\n<li>in the results page that follows click on the domain you're interested in></li>\n<li>you are taken to a page that lists all subdomains + a load of other information such as mail server info</li>\n</ol>\n" }, { "answer_id": 2865955, "author": "Paul Melici", "author_id": 345104, "author_profile": "https://Stackoverflow.com/users/345104", "pm_score": 7, "selected": false, "text": "<p>If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use <a href=\"http://www.wolframalpha.com/\" rel=\"noreferrer\">Wolfram Alpha</a>. </p>\n\n<ol>\n<li>Enter the domain into the search box and run the search. (E.g. <a href=\"http://www.wolframalpha.com/input/?i=stackexchange.com\" rel=\"noreferrer\"><code>stackexchange.com</code></a>)</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/8Edyc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8Edyc.png\" alt=\"Wolfram - Homepage\"></a></p>\n\n<ol start=\"2\">\n<li>In the 3rd section from the top (named \"Web statistics for all of stackexchange.com\") click <strong>Subdomains</strong></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/rQJ99.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rQJ99.png\" alt=\"Wolfram - Subdomains button\"></a></p>\n\n<ol start=\"3\">\n<li>In the Subdomains section click <strong>More</strong></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/0LkNp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0LkNp.png\" alt=\"Wolfram - More subdomains button\"></a></p>\n\n<p>You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.</p>\n" }, { "answer_id": 5044496, "author": "Victor Klos", "author_id": 623543, "author_profile": "https://Stackoverflow.com/users/623543", "pm_score": 6, "selected": false, "text": "<p>You can use:</p>\n<pre><code>$ host -l example.com</code></pre>\n<p>Under the hood, this uses the <code>AXFR</code> query mentioned above. You might not be allowed to do this though. In that case, you'll get a <code>transfer failed</code> message.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22029/" ]
I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option: ``` dig @ns1.foo.example example.com axfr ``` But this never works. Has anyone a better idea/approach
The hint (using axfr) only works if the NS you're querying (`ns1.foo.example` in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question. Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. `dig a.example.com`, `dig b.example.com`, ...), which I can't recommend, as it could be viewed as a denial of service attack.
131,993
<p>Subversion is a great way to update our web applications on our servers. With a simple <code>svn update</code> all changed files get... well, changed.</p> <p>Except for the omnipresent configuration files such as <code>config.php</code> which hold the database access configuration, server paths etc. And are therefore different on my local development system and the remote server.</p> <p>With the <code>update</code> command, a file modified on the server won't get overwritten, but if I change the file locally and commit it, the server gets the wrong configuration file.</p> <p>But I don't want to set the <code>svn:ignore</code> property either, since the config file belongs to the project.</p> <p>Is there a Subversion-mechanism which will allow me to easily handle these kind of files? Or is the only way to solve this problem to make a system switch within the config file which will determine the executing system and sets the configuration accordingly?</p>
[ { "answer_id": 132002, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 2, "selected": false, "text": "<p>Create a template for the file (e.g. config.php-default) and let the user copy the template. She can also do a diff to see what changed between versions to incorporate these changes in the locally deployed version of the file.</p>\n" }, { "answer_id": 132010, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 1, "selected": false, "text": "<p>On the projects I am currently working on we have 2 properties files for the database schema information - one for the production environment and one for development. We have a class that loads all of our properties for the module being executed, with logic that determines which file to load.</p>\n\n<p>Since our development environment locally is a Windows file system and the production servers operate on UNIX file systems, our solution was to determine the operating system of the host and load the correct file.</p>\n\n<p>We keep these directly within our source control in order to keep a history of any changes made. I think we learned a lesson from our (internal) client finger pointing in regards to <strong>INSANELY FREQUENT REQUIREMENTS CHANGES</strong>, in that we needed to be able to defend any of the past changes to the files.</p>\n\n<p>This may be unique for our situation, but I've found this to be extremely helpful, especially if I am trying to replicate a test run from a previous revision.</p>\n" }, { "answer_id": 132034, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 1, "selected": false, "text": "<p>Some possible solutions:</p>\n\n<p>If you are using a J2EE app server, you can look up properties through JNDI, there are tools to easily set and view them on the server.</p>\n\n<p>You can have a default properties file in your subversion server, but look elsewhere on the servers (outside the parts of the project that are checked into svn) for the real properties file, but then you usually get OS dependent paths and have to remember to update the real properties files manually when you add new properties in your svn file.</p>\n\n<p>You can set the properties in a properties file as part of the build, and pass in a parameter to the build command to tell it which server environment to build for. This can feel a bit roundabout, and you have to remember to update the build script with new properties. But it can work well - if you set up a Continuous Integration server, it can build for all the different environments and test the bundles for you. Then you know you have something deployment ready.</p>\n" }, { "answer_id": 132036, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 2, "selected": true, "text": "<p>I find the easiest way is to switch on the machine's hostname. I have a .ini file with a general section that also overrides this for production, testing and development systems.</p>\n\n<pre><code>[general]\ninfo=misc\ndb.password=secret\ndb.host=localhost\n\n[production : general]\ninfo=only on production system\ndb.password=secret1\n\n[testing : general]\ninfo=only on test system\ndb.password=secret2\n\n[dev : general]\ninfo=only on dev system\ndb.password=secret3\n</code></pre>\n\n<p>So dev:db.password == 'secret3', but dev:db.host == 'localhost', from the original 'general' group.</p>\n\n<p>The 'production', 'testing' and 'dev' could be the machine hostnames, or they are aliases for them set from some other mechanism in a configuration control script.</p>\n" }, { "answer_id": 132071, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 2, "selected": false, "text": "<p>You may want to consider the fact that developers won't (And probably shouldn't) have access to the username/passwords for the production machine.</p>\n\n<p>To cope with this, such configuration should be considered to be 'deployment details', rather than overall application configuration.\nEven when you make this conceptual distinction, you still need to deal with the different deployment environments but, as you seem to be dealing with PHP, I can't comment on specifics for your case.</p>\n\n<p>As Lars mentioned, one possible J2EE solution is to store such details under JNDI, making the exact same application binary deployable on any environment, leaving DBAs/Admins to set the username/password for each machine.</p>\n" }, { "answer_id": 136670, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can also make your config file domain depended. This way you can create a configuration for you local machine and for the production server(s). You do need to build the logic of course to handle this.</p>\n\n<p>If you run apache webserver you can easily configure it to have every developer using their own (sub)domain on their local box instead of just using localhost. This way, every developer can use their own configuration.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/131993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260/" ]
Subversion is a great way to update our web applications on our servers. With a simple `svn update` all changed files get... well, changed. Except for the omnipresent configuration files such as `config.php` which hold the database access configuration, server paths etc. And are therefore different on my local development system and the remote server. With the `update` command, a file modified on the server won't get overwritten, but if I change the file locally and commit it, the server gets the wrong configuration file. But I don't want to set the `svn:ignore` property either, since the config file belongs to the project. Is there a Subversion-mechanism which will allow me to easily handle these kind of files? Or is the only way to solve this problem to make a system switch within the config file which will determine the executing system and sets the configuration accordingly?
I find the easiest way is to switch on the machine's hostname. I have a .ini file with a general section that also overrides this for production, testing and development systems. ``` [general] info=misc db.password=secret db.host=localhost [production : general] info=only on production system db.password=secret1 [testing : general] info=only on test system db.password=secret2 [dev : general] info=only on dev system db.password=secret3 ``` So dev:db.password == 'secret3', but dev:db.host == 'localhost', from the original 'general' group. The 'production', 'testing' and 'dev' could be the machine hostnames, or they are aliases for them set from some other mechanism in a configuration control script.
132,030
<p>Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this. </p> <p>Now, I would like to do 2 things. </p> <p>First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?</p> <p>Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?</p> <p>Looking forward to see your suggestions, cheers.</p> <p>Did as described in the first answer. Worked like a charm.</p>
[ { "answer_id": 146879, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "<p>Use <a href=\"http://www.codeplex.com/stsdev\" rel=\"nofollow noreferrer\">STSDev</a> to create the solution package. \nThat should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.</p>\n\n<p>To deploy the xslt, your feature will have an</p>\n\n<p><code>&lt;ElementManifest Location=\"mywebpartManifest.xml\"&gt;</code></p>\n\n<p>This then points to a files such as</p>\n\n<pre><code>&lt;Elements xmlns=\"http://schemas.microsoft.com/sharepoint/\"&gt;\n &lt;Module Name=\"Yourfile.xslt\" Url=\"Style Library\" Path=\"\" RootWebOnly=\"TRUE\"&gt;\n &lt;File Url=\"yourfile.xslt\" Type=\"GhostableInLibrary\" /&gt;\n &lt;/Module&gt;\n&lt;/Elements&gt;\n</code></pre>\n\n<p>for the webpart:</p>\n\n<pre><code>&lt;Module Name=\"myWebpart\" List=\"113\" Url=\"_catalogs/wp\" RootWebOnly=\"FALSE\"&gt;\n &lt;File Url=\"myWebpart.webpart\" Type=\"GhostableInLibrary\" /&gt;\n&lt;/Module&gt;\n</code></pre>\n\n<p>Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.</p>\n\n<p>e.g.</p>\n\n<pre><code>&lt;Resources&gt;\n &lt;Resource Location=\"SimpleFeature\\Feature.xml\"/&gt;\n</code></pre>\n\n<p>The actual schemas are:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa544502.aspx\" rel=\"nofollow noreferrer\">Site</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms442108.aspx\" rel=\"nofollow noreferrer\">Solution</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms414322.aspx\" rel=\"nofollow noreferrer\">Feature</a></p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/\" rel=\"nofollow noreferrer\">and a link to someone else with the issue</a></p>\n" }, { "answer_id": 147876, "author": "mortenbpost", "author_id": 17577, "author_profile": "https://Stackoverflow.com/users/17577", "pm_score": 0, "selected": false, "text": "<p>But where in the folder structure do you deploy the form and the .xsl to?</p>\n" }, { "answer_id": 313919, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have followed your guide and although it deploys the xslt to the feature in 12 Hive it does not place it in the correct style library folder</p>\n" }, { "answer_id": 1917244, "author": "Daniel", "author_id": 158622, "author_profile": "https://Stackoverflow.com/users/158622", "pm_score": 0, "selected": false, "text": "<p>You need to deactivate / reactivate the feature. This will give you any error messages that are associated with copying the file over. </p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17577/" ]
Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this. Now, I would like to do 2 things. First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it? Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL? Looking forward to see your suggestions, cheers. Did as described in the first answer. Worked like a charm.
Use [STSDev](http://www.codeplex.com/stsdev) to create the solution package. That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project. To deploy the xslt, your feature will have an `<ElementManifest Location="mywebpartManifest.xml">` This then points to a files such as ``` <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE"> <File Url="yourfile.xslt" Type="GhostableInLibrary" /> </Module> </Elements> ``` for the webpart: ``` <Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE"> <File Url="myWebpart.webpart" Type="GhostableInLibrary" /> </Module> ``` Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project. e.g. ``` <Resources> <Resource Location="SimpleFeature\Feature.xml"/> ``` The actual schemas are: [Site](http://msdn.microsoft.com/en-us/library/aa544502.aspx) [Solution](http://msdn.microsoft.com/en-us/library/ms442108.aspx) [Feature](http://msdn.microsoft.com/en-us/library/ms414322.aspx) [and a link to someone else with the issue](http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/)
132,038
<p>I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate <code>Outlook.Application</code> and directly calling its methods.</p> <p>I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to...</p> <p>What I have found is that the actual work is done by <code>sendmail.dll</code>, there is a handler defined in registry under <code>HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}</code>. I would like either to use this dll somehow or to simulate the same steps it does.</p> <p>Thanks for your input.</p>
[ { "answer_id": 146879, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 2, "selected": true, "text": "<p>Use <a href=\"http://www.codeplex.com/stsdev\" rel=\"nofollow noreferrer\">STSDev</a> to create the solution package. \nThat should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.</p>\n\n<p>To deploy the xslt, your feature will have an</p>\n\n<p><code>&lt;ElementManifest Location=\"mywebpartManifest.xml\"&gt;</code></p>\n\n<p>This then points to a files such as</p>\n\n<pre><code>&lt;Elements xmlns=\"http://schemas.microsoft.com/sharepoint/\"&gt;\n &lt;Module Name=\"Yourfile.xslt\" Url=\"Style Library\" Path=\"\" RootWebOnly=\"TRUE\"&gt;\n &lt;File Url=\"yourfile.xslt\" Type=\"GhostableInLibrary\" /&gt;\n &lt;/Module&gt;\n&lt;/Elements&gt;\n</code></pre>\n\n<p>for the webpart:</p>\n\n<pre><code>&lt;Module Name=\"myWebpart\" List=\"113\" Url=\"_catalogs/wp\" RootWebOnly=\"FALSE\"&gt;\n &lt;File Url=\"myWebpart.webpart\" Type=\"GhostableInLibrary\" /&gt;\n&lt;/Module&gt;\n</code></pre>\n\n<p>Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.</p>\n\n<p>e.g.</p>\n\n<pre><code>&lt;Resources&gt;\n &lt;Resource Location=\"SimpleFeature\\Feature.xml\"/&gt;\n</code></pre>\n\n<p>The actual schemas are:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa544502.aspx\" rel=\"nofollow noreferrer\">Site</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms442108.aspx\" rel=\"nofollow noreferrer\">Solution</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms414322.aspx\" rel=\"nofollow noreferrer\">Feature</a></p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/\" rel=\"nofollow noreferrer\">and a link to someone else with the issue</a></p>\n" }, { "answer_id": 147876, "author": "mortenbpost", "author_id": 17577, "author_profile": "https://Stackoverflow.com/users/17577", "pm_score": 0, "selected": false, "text": "<p>But where in the folder structure do you deploy the form and the .xsl to?</p>\n" }, { "answer_id": 313919, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have followed your guide and although it deploys the xslt to the feature in 12 Hive it does not place it in the correct style library folder</p>\n" }, { "answer_id": 1917244, "author": "Daniel", "author_id": 158622, "author_profile": "https://Stackoverflow.com/users/158622", "pm_score": 0, "selected": false, "text": "<p>You need to deactivate / reactivate the feature. This will give you any error messages that are associated with copying the file over. </p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10560/" ]
I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate `Outlook.Application` and directly calling its methods. I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to... What I have found is that the actual work is done by `sendmail.dll`, there is a handler defined in registry under `HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}`. I would like either to use this dll somehow or to simulate the same steps it does. Thanks for your input.
Use [STSDev](http://www.codeplex.com/stsdev) to create the solution package. That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project. To deploy the xslt, your feature will have an `<ElementManifest Location="mywebpartManifest.xml">` This then points to a files such as ``` <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE"> <File Url="yourfile.xslt" Type="GhostableInLibrary" /> </Module> </Elements> ``` for the webpart: ``` <Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE"> <File Url="myWebpart.webpart" Type="GhostableInLibrary" /> </Module> ``` Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project. e.g. ``` <Resources> <Resource Location="SimpleFeature\Feature.xml"/> ``` The actual schemas are: [Site](http://msdn.microsoft.com/en-us/library/aa544502.aspx) [Solution](http://msdn.microsoft.com/en-us/library/ms442108.aspx) [Feature](http://msdn.microsoft.com/en-us/library/ms414322.aspx) [and a link to someone else with the issue](http://social.msdn.microsoft.com/Forums/en-US/sharepointecm/thread/335399ea-f07f-43a5-a4e2-21d88ba2743e/)
132,052
<p>I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (<a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=42411" rel="noreferrer">details</a>).</p> <p>I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:</p> <ul> <li>No external dependencies</li> <li>Simple and reliable</li> <li>Support for <a href="http://www.freesoft.org/CIE/RFC/1945/58.htm" rel="noreferrer"><code>If-Modified-Since</code></a> header (i.e. custom <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)" rel="noreferrer"><code>getLastModified</code></a> method)</li> <li>(Optional) support for gzip encoding, etags,...</li> </ul> <p>Is such a servlet available somewhere? The closest I can find is <a href="http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758" rel="noreferrer">example 4-10</a> from the servlet book.</p> <p><strong>Update:</strong> The URL structure I want to use - in case you are wondering - is simply:</p> <pre class="lang-xml prettyprint-override"><code> &lt;servlet-mapping&gt; &lt;servlet-name&gt;main&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;default&lt;/servlet-name&gt; &lt;url-pattern&gt;/static/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>So all requests should be passed to the main servlet, unless they are for the <code>static</code> path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the <code>static</code> folder).</p>
[ { "answer_id": 132103, "author": "Panagiotis Korros", "author_id": 19331, "author_profile": "https://Stackoverflow.com/users/19331", "pm_score": 4, "selected": false, "text": "<p>I had the same problem and I solved it by using the code of the 'default servlet' from the Tomcat codebase.</p>\n<p><a href=\"https://github.com/apache/tomcat/blob/master/java/org/apache/catalina/servlets/DefaultServlet.java\" rel=\"nofollow noreferrer\">https://github.com/apache/tomcat/blob/master/java/org/apache/catalina/servlets/DefaultServlet.java</a></p>\n<p>The <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/default-servlet.html\" rel=\"nofollow noreferrer\">DefaultServlet</a> is the servlet that serves the static resources (jpg,html,css,gif etc) in Tomcat.</p>\n<p>This servlet is very efficient and has some the properties you defined above.</p>\n<p>I think that this source code, is a good way to start and remove the functionality or depedencies you don't need.</p>\n<ul>\n<li>References to the org.apache.naming.resources package can be removed or replaced with java.io.File code.</li>\n<li>References to the org.apache.catalina.util package are propably only utility methods/classes that can be duplicated in your source code.</li>\n<li>References to the org.apache.catalina.Globals class can be inlined or removed.</li>\n</ul>\n" }, { "answer_id": 132932, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": true, "text": "<p>I ended up rolling my own <code>StaticServlet</code>. It supports <code>If-Modified-Since</code>, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either.</p>\n\n<p>The code is available: <a href=\"http://bruno.defraine.net/StaticServlet.java\" rel=\"noreferrer\">StaticServlet.java</a>. Feel free to comment.</p>\n\n<p><strong>Update:</strong> Khurram asks about the <code>ServletUtils</code> class which is referenced in <code>StaticServlet</code>. It is simply a class with auxiliary methods that I used for my project. The only method you need is <code>coalesce</code> (which is identical to the SQL function <a href=\"http://en.wikipedia.org/wiki/Null_(SQL)#COALESCE\" rel=\"noreferrer\"><code>COALESCE</code></a>). This is the code:</p>\n\n<pre><code>public static &lt;T&gt; T coalesce(T...ts) {\n for(T t: ts)\n if(t != null)\n return t;\n return null;\n}\n</code></pre>\n" }, { "answer_id": 558771, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 0, "selected": false, "text": "<p>Use org.mortbay.jetty.handler.ContextHandler. You don't need additional components like StaticServlet.</p>\n\n<p>At the jetty home,</p>\n\n<p>$ cd contexts</p>\n\n<p>$ cp javadoc.xml static.xml</p>\n\n<p>$ vi static.xml</p>\n\n<p>...</p>\n\n<pre><code>&lt;Configure class=\"org.mortbay.jetty.handler.ContextHandler\"&gt;\n&lt;Set name=\"contextPath\"&gt;/static&lt;/Set&gt;\n&lt;Set name=\"resourceBase\"&gt;&lt;SystemProperty name=\"jetty.home\" default=\".\"/&gt;/static/&lt;/Set&gt;\n&lt;Set name=\"handler\"&gt;\n &lt;New class=\"org.mortbay.jetty.handler.ResourceHandler\"&gt;\n &lt;Set name=\"cacheControl\"&gt;max-age=3600,public&lt;/Set&gt;\n &lt;/New&gt;\n &lt;/Set&gt;\n&lt;/Configure&gt;\n</code></pre>\n\n<p>Set the value of contextPath with your URL prefix, and set the value of resourceBase as the file path of the static content.</p>\n\n<p>It worked for me.</p>\n" }, { "answer_id": 837020, "author": "axtavt", "author_id": 103154, "author_profile": "https://Stackoverflow.com/users/103154", "pm_score": 6, "selected": false, "text": "<p>There is no need for completely custom implementation of the default servlet in this case, you can use this simple servlet to wrap request to the container's implementation:</p>\n\n<pre><code>\npackage com.example;\n\nimport java.io.*;\n\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\npublic class DefaultWrapperServlet extends HttpServlet\n{ \n public void doGet(HttpServletRequest req, HttpServletResponse resp)\n throws ServletException, IOException\n {\n RequestDispatcher rd = getServletContext().getNamedDispatcher(\"default\");\n\n HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {\n public String getServletPath() { return \"\"; }\n };\n\n rd.forward(wrapped, resp);\n }\n}\n</code></pre>\n" }, { "answer_id": 1052224, "author": "Coldbeans Software", "author_id": 129760, "author_profile": "https://Stackoverflow.com/users/129760", "pm_score": -1, "selected": false, "text": "<p>See StaticFile in JSOS: <a href=\"http://www.servletsuite.com/servlets/staticfile.htm\" rel=\"nofollow noreferrer\">http://www.servletsuite.com/servlets/staticfile.htm</a></p>\n" }, { "answer_id": 1346028, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I found great tutorial on the web about some workaround. It is simple and efficient, I used it in several projects with REST urls styles approach:</p>\n\n<p><a href=\"http://www.kuligowski.pl/java/rest-style-urls-and-url-mapping-for-static-content-apache-tomcat,5\" rel=\"noreferrer\">http://www.kuligowski.pl/java/rest-style-urls-and-url-mapping-for-static-content-apache-tomcat,5</a></p>\n" }, { "answer_id": 1467740, "author": "delux247", "author_id": 5569, "author_profile": "https://Stackoverflow.com/users/5569", "pm_score": 2, "selected": false, "text": "<p>I did this by extending the tomcat <a href=\"http://tomcat.apache.org/tomcat-5.5-doc/default-servlet.html\" rel=\"nofollow noreferrer\">DefaultServlet</a> (<a href=\"http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/servlets/DefaultServlet.java\" rel=\"nofollow noreferrer\">src</a>) and overriding the getRelativePath() method.</p>\n\n<pre><code>package com.example;\n\nimport javax.servlet.ServletConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport org.apache.catalina.servlets.DefaultServlet;\n\npublic class StaticServlet extends DefaultServlet\n{\n protected String pathPrefix = \"/static\";\n\n public void init(ServletConfig config) throws ServletException\n {\n super.init(config);\n\n if (config.getInitParameter(\"pathPrefix\") != null)\n {\n pathPrefix = config.getInitParameter(\"pathPrefix\");\n }\n }\n\n protected String getRelativePath(HttpServletRequest req)\n {\n return pathPrefix + super.getRelativePath(req);\n }\n}\n</code></pre>\n\n<p>... And here are my servlet mappings</p>\n\n<pre><code>&lt;servlet&gt;\n &lt;servlet-name&gt;StaticServlet&lt;/servlet-name&gt;\n &lt;servlet-class&gt;com.example.StaticServlet&lt;/servlet-class&gt;\n &lt;init-param&gt;\n &lt;param-name&gt;pathPrefix&lt;/param-name&gt;\n &lt;param-value&gt;/static&lt;/param-value&gt;\n &lt;/init-param&gt; \n&lt;/servlet&gt;\n\n&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;StaticServlet&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/static/*&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt; \n</code></pre>\n" }, { "answer_id": 1467780, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 5, "selected": false, "text": "<p>I've had good results with <a href=\"http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and.html\" rel=\"noreferrer\">FileServlet</a>, as it supports pretty much all of HTTP (etags, chunking, etc.).</p>\n" }, { "answer_id": 1483443, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>To serve all requests from a Spring app as well as /favicon.ico and the JSP files from /WEB-INF/jsp/* that Spring's AbstractUrlBasedView will request you can just remap the jsp servlet and default servlet:</p>\n\n<pre><code> &lt;servlet&gt;\n &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;\n &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;\n &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;\n &lt;/servlet&gt;\n\n &lt;servlet-mapping&gt;\n &lt;servlet-name&gt;jsp&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/WEB-INF/jsp/*&lt;/url-pattern&gt;\n &lt;/servlet-mapping&gt;\n\n &lt;servlet-mapping&gt;\n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/favicon.ico&lt;/url-pattern&gt;\n &lt;/servlet-mapping&gt;\n\n &lt;servlet-mapping&gt;\n &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/*&lt;/url-pattern&gt;\n &lt;/servlet-mapping&gt;\n</code></pre>\n\n<p>We can't rely on the *.jsp url-pattern on the standard mapping for the jsp servlet because the path pattern '/*' is matched before any extension mapping is checked. Mapping the jsp servlet to a deeper folder means it's matched first. Matching '/favicon.ico' exactly happens before path pattern matching. Deeper path matches will work, or exact matches, but no extension matches can make it past the '/*' path match. Mapping '/' to default servlet doesn't appear to work. You'd think the exact '/' would beat the '/*' path pattern on springapp.</p>\n\n<p>The above filter solution doesn't work for forwarded/included JSP requests from the application. To make it work I had to apply the filter to springapp directly, at which point the url-pattern matching was useless as all requests that go to the application also go to its filters. So I added pattern matching to the filter and then learned about the 'jsp' servlet and saw that it doesn't remove the path prefix like the default servlet does. That solved my problem, which was not exactly the same but common enough.</p>\n" }, { "answer_id": 3582215, "author": "Taylor Gautier", "author_id": 19013, "author_profile": "https://Stackoverflow.com/users/19013", "pm_score": 6, "selected": false, "text": "<p>I came up with a slightly different solution. It's a bit hack-ish, but here is the mapping:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;servlet-mapping&gt; \n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;*.html&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt;\n&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;*.jpg&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt;\n&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;*.png&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt;\n&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;*.css&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt;\n&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;*.js&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt;\n\n&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;myAppServlet&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt;\n</code></pre>\n\n<p>This basically just maps all content files by extension to the default servlet, and everything else to \"myAppServlet\". </p>\n\n<p>It works in both Jetty and Tomcat. </p>\n" }, { "answer_id": 5035663, "author": "Jeff Stice-Hall", "author_id": 279638, "author_profile": "https://Stackoverflow.com/users/279638", "pm_score": 4, "selected": false, "text": "<p>Judging from the example information above, I think this entire article is based on a bugged behavior in Tomcat 6.0.29 and earlier. See <a href=\"https://issues.apache.org/bugzilla/show_bug.cgi?id=50026\">https://issues.apache.org/bugzilla/show_bug.cgi?id=50026</a>. Upgrade to Tomcat 6.0.30 and the behavior between (Tomcat|Jetty) should merge. </p>\n" }, { "answer_id": 9046095, "author": "Fareed Alnamrouti", "author_id": 427622, "author_profile": "https://Stackoverflow.com/users/427622", "pm_score": 4, "selected": false, "text": "<p>try this </p>\n\n<pre><code>&lt;servlet-mapping&gt;\n &lt;servlet-name&gt;default&lt;/servlet-name&gt;\n &lt;url-pattern&gt;*.js&lt;/url-pattern&gt;\n &lt;url-pattern&gt;*.css&lt;/url-pattern&gt;\n &lt;url-pattern&gt;*.ico&lt;/url-pattern&gt;\n &lt;url-pattern&gt;*.png&lt;/url-pattern&gt;\n &lt;url-pattern&gt;*.jpg&lt;/url-pattern&gt;\n &lt;url-pattern&gt;*.htc&lt;/url-pattern&gt;\n &lt;url-pattern&gt;*.gif&lt;/url-pattern&gt;\n&lt;/servlet-mapping&gt; \n</code></pre>\n\n<p>Edit: This is only valid for the servlet 2.5 spec and up.</p>\n" }, { "answer_id": 29991447, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 5, "selected": false, "text": "<h1>Abstract template for a static resource servlet</h1>\n\n<p>Partly based on <a href=\"http://balusc.blogspot.com/2007/07/fileservlet.html\" rel=\"noreferrer\">this blog</a> from 2007, here's a modernized and highly reusable abstract template for a servlet which properly deals with caching, <code>ETag</code>, <code>If-None-Match</code> and <code>If-Modified-Since</code> (but no Gzip and Range support; just to keep it simple; Gzip could be done with a filter or via container configuration).</p>\n\n<pre><code>public abstract class StaticResourceServlet extends HttpServlet {\n\n private static final long serialVersionUID = 1L;\n private static final long ONE_SECOND_IN_MILLIS = TimeUnit.SECONDS.toMillis(1);\n private static final String ETAG_HEADER = \"W/\\\"%s-%s\\\"\";\n private static final String CONTENT_DISPOSITION_HEADER = \"inline;filename=\\\"%1$s\\\"; filename*=UTF-8''%1$s\";\n\n public static final long DEFAULT_EXPIRE_TIME_IN_MILLIS = TimeUnit.DAYS.toMillis(30);\n public static final int DEFAULT_STREAM_BUFFER_SIZE = 102400;\n\n @Override\n protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException {\n doRequest(request, response, true);\n }\n\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n doRequest(request, response, false);\n }\n\n private void doRequest(HttpServletRequest request, HttpServletResponse response, boolean head) throws IOException {\n response.reset();\n StaticResource resource;\n\n try {\n resource = getStaticResource(request);\n }\n catch (IllegalArgumentException e) {\n response.sendError(HttpServletResponse.SC_BAD_REQUEST);\n return;\n }\n\n if (resource == null) {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n return;\n }\n\n String fileName = URLEncoder.encode(resource.getFileName(), StandardCharsets.UTF_8.name());\n boolean notModified = setCacheHeaders(request, response, fileName, resource.getLastModified());\n\n if (notModified) {\n response.sendError(HttpServletResponse.SC_NOT_MODIFIED);\n return;\n }\n\n setContentHeaders(response, fileName, resource.getContentLength());\n\n if (head) {\n return;\n }\n\n writeContent(response, resource);\n }\n\n /**\n * Returns the static resource associated with the given HTTP servlet request. This returns &lt;code&gt;null&lt;/code&gt; when\n * the resource does actually not exist. The servlet will then return a HTTP 404 error.\n * @param request The involved HTTP servlet request.\n * @return The static resource associated with the given HTTP servlet request.\n * @throws IllegalArgumentException When the request is mangled in such way that it's not recognizable as a valid\n * static resource request. The servlet will then return a HTTP 400 error.\n */\n protected abstract StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException;\n\n private boolean setCacheHeaders(HttpServletRequest request, HttpServletResponse response, String fileName, long lastModified) {\n String eTag = String.format(ETAG_HEADER, fileName, lastModified);\n response.setHeader(\"ETag\", eTag);\n response.setDateHeader(\"Last-Modified\", lastModified);\n response.setDateHeader(\"Expires\", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME_IN_MILLIS);\n return notModified(request, eTag, lastModified);\n }\n\n private boolean notModified(HttpServletRequest request, String eTag, long lastModified) {\n String ifNoneMatch = request.getHeader(\"If-None-Match\");\n\n if (ifNoneMatch != null) {\n String[] matches = ifNoneMatch.split(\"\\\\s*,\\\\s*\");\n Arrays.sort(matches);\n return (Arrays.binarySearch(matches, eTag) &gt; -1 || Arrays.binarySearch(matches, \"*\") &gt; -1);\n }\n else {\n long ifModifiedSince = request.getDateHeader(\"If-Modified-Since\");\n return (ifModifiedSince + ONE_SECOND_IN_MILLIS &gt; lastModified); // That second is because the header is in seconds, not millis.\n }\n }\n\n private void setContentHeaders(HttpServletResponse response, String fileName, long contentLength) {\n response.setHeader(\"Content-Type\", getServletContext().getMimeType(fileName));\n response.setHeader(\"Content-Disposition\", String.format(CONTENT_DISPOSITION_HEADER, fileName));\n\n if (contentLength != -1) {\n response.setHeader(\"Content-Length\", String.valueOf(contentLength));\n }\n }\n\n private void writeContent(HttpServletResponse response, StaticResource resource) throws IOException {\n try (\n ReadableByteChannel inputChannel = Channels.newChannel(resource.getInputStream());\n WritableByteChannel outputChannel = Channels.newChannel(response.getOutputStream());\n ) {\n ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_STREAM_BUFFER_SIZE);\n long size = 0;\n\n while (inputChannel.read(buffer) != -1) {\n buffer.flip();\n size += outputChannel.write(buffer);\n buffer.clear();\n }\n\n if (resource.getContentLength() == -1 &amp;&amp; !response.isCommitted()) {\n response.setHeader(\"Content-Length\", String.valueOf(size));\n }\n }\n }\n\n}\n</code></pre>\n\n<p>Use it together with the below interface representing a static resource.</p>\n\n<pre><code>interface StaticResource {\n\n /**\n * Returns the file name of the resource. This must be unique across all static resources. If any, the file\n * extension will be used to determine the content type being set. If the container doesn't recognize the\n * extension, then you can always register it as &lt;code&gt;&amp;lt;mime-type&amp;gt;&lt;/code&gt; in &lt;code&gt;web.xml&lt;/code&gt;.\n * @return The file name of the resource.\n */\n public String getFileName();\n\n /**\n * Returns the last modified timestamp of the resource in milliseconds.\n * @return The last modified timestamp of the resource in milliseconds.\n */\n public long getLastModified();\n\n /**\n * Returns the content length of the resource. This returns &lt;code&gt;-1&lt;/code&gt; if the content length is unknown.\n * In that case, the container will automatically switch to chunked encoding if the response is already\n * committed after streaming. The file download progress may be unknown.\n * @return The content length of the resource.\n */\n public long getContentLength();\n\n /**\n * Returns the input stream with the content of the resource. This method will be called only once by the\n * servlet, and only when the resource actually needs to be streamed, so lazy loading is not necessary.\n * @return The input stream with the content of the resource.\n * @throws IOException When something fails at I/O level.\n */\n public InputStream getInputStream() throws IOException;\n\n}\n</code></pre>\n\n<p>All you need is just extending from the given abstract servlet and implementing the <code>getStaticResource()</code> method according the javadoc.</p>\n\n<h1>Concrete example serving from file system:</h1>\n\n<p>Here's a concrete example which serves it via an URL like <code>/files/foo.ext</code> from the local disk file system:</p>\n\n<pre><code>@WebServlet(\"/files/*\")\npublic class FileSystemResourceServlet extends StaticResourceServlet {\n\n private File folder;\n\n @Override\n public void init() throws ServletException {\n folder = new File(\"/path/to/the/folder\");\n }\n\n @Override\n protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {\n String pathInfo = request.getPathInfo();\n\n if (pathInfo == null || pathInfo.isEmpty() || \"/\".equals(pathInfo)) {\n throw new IllegalArgumentException();\n }\n\n String name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());\n final File file = new File(folder, Paths.get(name).getFileName().toString());\n\n return !file.exists() ? null : new StaticResource() {\n @Override\n public long getLastModified() {\n return file.lastModified();\n }\n @Override\n public InputStream getInputStream() throws IOException {\n return new FileInputStream(file);\n }\n @Override\n public String getFileName() {\n return file.getName();\n }\n @Override\n public long getContentLength() {\n return file.length();\n }\n };\n }\n\n}\n</code></pre>\n\n<h1>Concrete example serving from database:</h1>\n\n<p>Here's a concrete example which serves it via an URL like <code>/files/foo.ext</code> from the database via an EJB service call which returns your entity having a <code>byte[] content</code> property:</p>\n\n<pre><code>@WebServlet(\"/files/*\")\npublic class YourEntityResourceServlet extends StaticResourceServlet {\n\n @EJB\n private YourEntityService yourEntityService;\n\n @Override\n protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {\n String pathInfo = request.getPathInfo();\n\n if (pathInfo == null || pathInfo.isEmpty() || \"/\".equals(pathInfo)) {\n throw new IllegalArgumentException();\n }\n\n String name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());\n final YourEntity yourEntity = yourEntityService.getByName(name);\n\n return (yourEntity == null) ? null : new StaticResource() {\n @Override\n public long getLastModified() {\n return yourEntity.getLastModified();\n }\n @Override\n public InputStream getInputStream() throws IOException {\n return new ByteArrayInputStream(yourEntityService.getContentById(yourEntity.getId()));\n }\n @Override\n public String getFileName() {\n return yourEntity.getName();\n }\n @Override\n public long getContentLength() {\n return yourEntity.getContentLength();\n }\n };\n }\n\n}\n</code></pre>\n" }, { "answer_id": 41531500, "author": "Grigory Kislin", "author_id": 548473, "author_profile": "https://Stackoverflow.com/users/548473", "pm_score": 1, "selected": false, "text": "<p>Checked for Tomcat 8.x: static resources work OK if root servlet map to \"\".\nFor servlet 3.x it could be done by <code>@WebServlet(\"\")</code></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6918/" ]
I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use ([details](http://issues.apache.org/bugzilla/show_bug.cgi?id=42411)). I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties: * No external dependencies * Simple and reliable * Support for [`If-Modified-Since`](http://www.freesoft.org/CIE/RFC/1945/58.htm) header (i.e. custom [`getLastModified`](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)) method) * (Optional) support for gzip encoding, etags,... Is such a servlet available somewhere? The closest I can find is [example 4-10](http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758) from the servlet book. **Update:** The URL structure I want to use - in case you are wondering - is simply: ```xml <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> ``` So all requests should be passed to the main servlet, unless they are for the `static` path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the `static` folder).
I ended up rolling my own `StaticServlet`. It supports `If-Modified-Since`, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either. The code is available: [StaticServlet.java](http://bruno.defraine.net/StaticServlet.java). Feel free to comment. **Update:** Khurram asks about the `ServletUtils` class which is referenced in `StaticServlet`. It is simply a class with auxiliary methods that I used for my project. The only method you need is `coalesce` (which is identical to the SQL function [`COALESCE`](http://en.wikipedia.org/wiki/Null_(SQL)#COALESCE)). This is the code: ``` public static <T> T coalesce(T...ts) { for(T t: ts) if(t != null) return t; return null; } ```
132,058
<p>I have this Python application that gets stuck from time to time and I can't find out where.</p> <p>Is there any way to signal Python interpreter to show you the exact code that's running? </p> <p>Some kind of on-the-fly stacktrace?</p> <p><strong><em>Related questions:</em></strong></p> <ul> <li><a href="https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code">Print current call stack from a method in Python code</a></li> <li><a href="https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py">Check what a running process is doing: print stack trace of an uninstrumented Python program</a></li> </ul>
[ { "answer_id": 132108, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 4, "selected": false, "text": "<p><em>python -dv yourscript.py</em></p>\n\n<p>That will make the interpreter to run in debug mode and to give you a trace of what the interpreter is doing.</p>\n\n<p>If you want to interactively debug the code you should run it like this:</p>\n\n<p><em>python -m pdb yourscript.py</em></p>\n\n<p>That tells the python interpreter to run your script with the module \"pdb\" which is the python debugger, if you run it like that the interpreter will be executed in interactive mode, much like GDB</p>\n" }, { "answer_id": 132114, "author": "gulgi", "author_id": 1109480, "author_profile": "https://Stackoverflow.com/users/1109480", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"https://docs.python.org/2/library/traceback.html\" rel=\"nofollow noreferrer\"><strong>traceback</strong></a> module has some nice functions, among them: print_stack:</p>\n\n<pre><code>import traceback\n\ntraceback.print_stack()\n</code></pre>\n" }, { "answer_id": 132123, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 5, "selected": false, "text": "<pre><code>&gt;&gt;&gt; import traceback\n&gt;&gt;&gt; def x():\n&gt;&gt;&gt; print traceback.extract_stack()\n\n&gt;&gt;&gt; x()\n[('&lt;stdin&gt;', 1, '&lt;module&gt;', None), ('&lt;stdin&gt;', 2, 'x', None)]\n</code></pre>\n\n<p>You can also nicely format the stack trace, see the <a href=\"http://docs.python.org/lib/module-traceback.html\" rel=\"noreferrer\">docs</a>.</p>\n\n<p><strong>Edit</strong>: To simulate Java's behavior, as suggested by @Douglas Leeder, add this:</p>\n\n<pre><code>import signal\nimport traceback\n\nsignal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack))\n</code></pre>\n\n<p>to the startup code in your application. Then you can print the stack by sending <code>SIGUSR1</code> to the running Python process.</p>\n" }, { "answer_id": 132260, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 0, "selected": false, "text": "<p>I don't know of anything similar to <a href=\"http://java.sun.com/developer/onlineTraining/Programming/JDCBook/stack.html\" rel=\"nofollow noreferrer\">java's response to SIGQUIT</a>, so you might have to build it in to your application. Maybe you could make a server in another thread that can get a stacktrace on response to a message of some kind?</p>\n" }, { "answer_id": 132268, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "<p>There is no way to hook into a running python process and get reasonable results. What I do if processes lock up is hooking strace in and trying to figure out what exactly is happening.</p>\n\n<p>Unfortunately often strace is the observer that \"fixes\" race conditions so that the output is useless there too.</p>\n" }, { "answer_id": 133384, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 9, "selected": true, "text": "<p>I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals):</p>\n\n<pre><code>import code, traceback, signal\n\ndef debug(sig, frame):\n \"\"\"Interrupt running process, and provide a python prompt for\n interactive debugging.\"\"\"\n d={'_frame':frame} # Allow access to frame object.\n d.update(frame.f_globals) # Unless shadowed by global\n d.update(frame.f_locals)\n\n i = code.InteractiveConsole(d)\n message = \"Signal received : entering python shell.\\nTraceback:\\n\"\n message += ''.join(traceback.format_stack(frame))\n i.interact(message)\n\ndef listen():\n signal.signal(signal.SIGUSR1, debug) # Register handler\n</code></pre>\n\n<p>To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python:</p>\n\n<pre><code> os.kill(pid, signal.SIGUSR1)\n</code></pre>\n\n<p>This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive.</p>\n\n<p>I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a <a href=\"http://code.activestate.com/recipes/576515/\" rel=\"noreferrer\">python cookbook recipe</a>.</p>\n" }, { "answer_id": 147114, "author": "spiv", "author_id": 22701, "author_profile": "https://Stackoverflow.com/users/22701", "pm_score": 7, "selected": false, "text": "<p>The suggestion to install a signal handler is a good one, and I use it a lot. For example, <a href=\"http://bazaar-vcs.org/\" rel=\"nofollow noreferrer\">bzr</a> by default installs a SIGQUIT handler that invokes <code>pdb.set_trace()</code> to immediately drop you into a <a href=\"http://docs.python.org/lib/module-pdb.html\" rel=\"nofollow noreferrer\">pdb</a> prompt. (See the <a href=\"https://bazaar.launchpad.net/%7Ebzr-pqm/bzr/bzr.dev/view/head:/bzrlib/breakin.py\" rel=\"nofollow noreferrer\">bzrlib.breakin</a> module's source for the exact details.) With pdb you can not only get the current stack trace (with the <code>(w)here</code> command) but also inspect variables, etc.</p>\n<p>However, sometimes I need to debug a process that I didn't have the foresight to install the signal handler in. On linux, you can attach gdb to the process and get a python stack trace with some gdb macros. Put <a href=\"http://svn.python.org/projects/python/trunk/Misc/gdbinit\" rel=\"nofollow noreferrer\">http://svn.python.org/projects/python/trunk/Misc/gdbinit</a> in <code>~/.gdbinit</code>, then:</p>\n<ul>\n<li>Attach gdb: <code>gdb -p</code> <em><code>PID</code></em></li>\n<li>Get the python stack trace: <code>pystack</code></li>\n</ul>\n<p>It's not totally reliable unfortunately, but it works most of the time. See also <a href=\"https://wiki.python.org/moin/DebuggingWithGdb\" rel=\"nofollow noreferrer\">https://wiki.python.org/moin/DebuggingWithGdb</a></p>\n<p>Finally, attaching <code>strace</code> can often give you a good idea what a process is doing.</p>\n" }, { "answer_id": 490172, "author": "rcoup", "author_id": 2662, "author_profile": "https://Stackoverflow.com/users/2662", "pm_score": 2, "selected": false, "text": "<p>It's worth looking at <a href=\"http://bashdb.sourceforge.net/pydb/\" rel=\"nofollow noreferrer\">Pydb</a>, \"an expanded version of the Python debugger loosely based on the gdb command set\". It includes signal managers which can take care of starting the debugger when a specified signal is sent.</p>\n\n<p>A 2006 Summer of Code project looked at adding remote-debugging features to pydb in a module called <a href=\"http://svn.python.org/projects/sandbox/trunk/pdb/\" rel=\"nofollow noreferrer\">mpdb</a>. </p>\n" }, { "answer_id": 618748, "author": "Gunnlaugur Briem", "author_id": 74683, "author_profile": "https://Stackoverflow.com/users/74683", "pm_score": 4, "selected": false, "text": "<p>What really helped me here is <a href=\"https://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application/147114#147114\">spiv's tip</a> (which I would vote up and comment on if I had the reputation points) for getting a stack trace out of an <em>unprepared</em> Python process. Except it didn't work until I <a href=\"http://lists.osafoundation.org/pipermail/chandler-dev/2007-January/007519.html\" rel=\"nofollow noreferrer\">modified the gdbinit script</a>. So:</p>\n<ul>\n<li><p>download <a href=\"https://svn.python.org/projects/python/trunk/Misc/gdbinit\" rel=\"nofollow noreferrer\">https://svn.python.org/projects/python/trunk/Misc/gdbinit</a> and put it in <code>~/.gdbinit</code></p>\n</li>\n<li><p><del>edit it, changing <code>PyEval_EvalFrame</code> to <code>PyEval_EvalFrameEx</code></del> [edit: no longer needed; the linked file already has this change as of 2010-01-14]</p>\n</li>\n<li><p>Attach gdb: <code>gdb -p PID</code></p>\n</li>\n<li><p>Get the python stack trace: <code>pystack</code></p>\n</li>\n</ul>\n" }, { "answer_id": 1431341, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>use the inspect module.</p>\n\n<blockquote>\n <blockquote>\n <blockquote>\n <p>import inspect\n help(inspect.stack)\n Help on function stack in module inspect:</p>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>stack(context=1)\n Return a list of records for the stack above the caller's frame.</p>\n\n<p>I find it very helpful indeed.</p>\n" }, { "answer_id": 2569696, "author": "haridsv", "author_id": 95750, "author_profile": "https://Stackoverflow.com/users/95750", "pm_score": 6, "selected": false, "text": "<p>I am almost always dealing with multiple threads and main thread is generally not doing much, so what is most interesting is to dump all the stacks (which is more like the Java's dump). Here is an implementation based on <a href=\"http://bzimmer.ziclix.com/2008/12/17/python-thread-dumps/\" rel=\"noreferrer\">this blog</a>:</p>\n<pre><code>import threading, sys, traceback\n\ndef dumpstacks(signal, frame):\n id2name = dict([(th.ident, th.name) for th in threading.enumerate()])\n code = []\n for threadId, stack in sys._current_frames().items():\n code.append(&quot;\\n# Thread: %s(%d)&quot; % (id2name.get(threadId,&quot;&quot;), threadId))\n for filename, lineno, name, line in traceback.extract_stack(stack):\n code.append('File: &quot;%s&quot;, line %d, in %s' % (filename, lineno, name))\n if line:\n code.append(&quot; %s&quot; % (line.strip()))\n print(&quot;\\n&quot;.join(code))\n\nimport signal\nsignal.signal(signal.SIGQUIT, dumpstacks)\n</code></pre>\n" }, { "answer_id": 5503185, "author": "Konstantin Tarashchanskiy", "author_id": 686041, "author_profile": "https://Stackoverflow.com/users/686041", "pm_score": 4, "selected": false, "text": "<p>I would add this as a comment to <a href=\"https://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application/2569696#2569696\">haridsv's response</a>, but I lack the reputation to do so:</p>\n\n<p>Some of us are still stuck on a version of Python older than 2.6 (required for Thread.ident), so I got the code working in Python 2.5 (though without the thread name being displayed) as such:</p>\n\n<pre><code>import traceback\nimport sys\ndef dumpstacks(signal, frame):\n code = []\n for threadId, stack in sys._current_frames().items():\n code.append(\"\\n# Thread: %d\" % (threadId))\n for filename, lineno, name, line in traceback.extract_stack(stack):\n code.append('File: \"%s\", line %d, in %s' % (filename, lineno, name))\n if line:\n code.append(\" %s\" % (line.strip()))\n print \"\\n\".join(code)\n\nimport signal\nsignal.signal(signal.SIGQUIT, dumpstacks)\n</code></pre>\n" }, { "answer_id": 7224091, "author": "Tim Foster", "author_id": 916854, "author_profile": "https://Stackoverflow.com/users/916854", "pm_score": 3, "selected": false, "text": "<p>On Solaris, you can use pstack(1) No changes to the python code are necessary. eg.</p>\n\n<pre><code># pstack 16000 | grep : | head\n16000: /usr/bin/python2.6 /usr/lib/pkg.depotd --cfg svc:/application/pkg/serv\n[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:282 (_wait) ]\n[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:295 (wait) ]\n[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:242 (block) ]\n[ /usr/lib/python2.6/vendor-packages/cherrypy/_init_.py:249 (quickstart) ]\n[ /usr/lib/pkg.depotd:890 (&lt;module&gt;) ]\n[ /usr/lib/python2.6/threading.py:256 (wait) ]\n[ /usr/lib/python2.6/Queue.py:177 (get) ]\n[ /usr/lib/python2.6/vendor-packages/pkg/server/depot.py:2142 (run) ]\n[ /usr/lib/python2.6/threading.py:477 (run)\netc.\n</code></pre>\n" }, { "answer_id": 9019164, "author": "Matt Joiner", "author_id": 149482, "author_profile": "https://Stackoverflow.com/users/149482", "pm_score": 4, "selected": false, "text": "<p>Take a look at the <a href=\"http://docs.python.org/3.3/whatsnew/3.3.html#faulthandler\" rel=\"noreferrer\"><code>faulthandler</code></a> module, new in Python 3.3. A <a href=\"https://pypi.python.org/pypi/faulthandler/\" rel=\"noreferrer\"><code>faulthandler</code> backport</a> for use in Python 2 is available on PyPI.</p>\n" }, { "answer_id": 10047855, "author": "Albert", "author_id": 133374, "author_profile": "https://Stackoverflow.com/users/133374", "pm_score": 2, "selected": false, "text": "<p>I hacked together some tool which attaches into a running Python process and injects some code to get a Python shell.</p>\n\n<p>See here: <a href=\"https://github.com/albertz/pydbattach\" rel=\"nofollow\">https://github.com/albertz/pydbattach</a></p>\n" }, { "answer_id": 10165776, "author": "Stefan", "author_id": 1019572, "author_profile": "https://Stackoverflow.com/users/1019572", "pm_score": 3, "selected": false, "text": "<p>I was looking for a while for a solution to debug my threads and I found it here thanks to haridsv. I use slightly simplified version employing the traceback.print_stack():</p>\n\n<pre><code>import sys, traceback, signal\nimport threading\nimport os\n\ndef dumpstacks(signal, frame):\n id2name = dict((th.ident, th.name) for th in threading.enumerate())\n for threadId, stack in sys._current_frames().items():\n print(id2name[threadId])\n traceback.print_stack(f=stack)\n\nsignal.signal(signal.SIGQUIT, dumpstacks)\n\nos.killpg(os.getpgid(0), signal.SIGQUIT)\n</code></pre>\n\n<p>For my needs I also filter threads by name.</p>\n" }, { "answer_id": 16246063, "author": "vstinner", "author_id": 2325489, "author_profile": "https://Stackoverflow.com/users/2325489", "pm_score": 5, "selected": false, "text": "<p>You can try the <a href=\"http://docs.python.org/dev/library/faulthandler.html\">faulthandler module</a>. Install it using <code>pip install faulthandler</code> and add:</p>\n\n<pre><code>import faulthandler, signal\nfaulthandler.register(signal.SIGUSR1)\n</code></pre>\n\n<p>at the beginning of your program. Then send SIGUSR1 to your process (ex: <code>kill -USR1 42</code>) to display the Python traceback of all threads to the standard output. <a href=\"http://docs.python.org/dev/library/faulthandler.html\">Read the documentation</a> for more options (ex: log into a file) and other ways to display the traceback.</p>\n\n<p>The module is now part of Python 3.3. For Python 2, see <a href=\"http://faulthandler.readthedocs.org/\">http://faulthandler.readthedocs.org/</a></p>\n" }, { "answer_id": 16247213, "author": "asmeurer", "author_id": 161801, "author_profile": "https://Stackoverflow.com/users/161801", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"https://pypi.python.org/pypi/pudb\" rel=\"nofollow\">PuDB</a>, a Python debugger with a curses interface to do this. Just add </p>\n\n<pre><code>from pudb import set_interrupt_handler; set_interrupt_handler()\n</code></pre>\n\n<p>to your code and use Ctrl-C when you want to break. You can continue with <code>c</code> and break again multiple times if you miss it and want to try again. </p>\n" }, { "answer_id": 17270641, "author": "anatoly techtonik", "author_id": 239247, "author_profile": "https://Stackoverflow.com/users/239247", "pm_score": 3, "selected": false, "text": "<p>If you're on a Linux system, use the awesomeness of <code>gdb</code> with Python debug extensions (can be in <code>python-dbg</code> or <code>python-debuginfo</code> package). It also helps with multithreaded applications, GUI applications and C modules.</p>\n\n<p>Run your program with:</p>\n\n<pre><code>$ gdb -ex r --args python &lt;programname&gt;.py [arguments]\n</code></pre>\n\n<p>This instructs <code>gdb</code> to prepare <code>python &lt;programname&gt;.py &lt;arguments&gt;</code> and <code>r</code>un it.</p>\n\n<p>Now when you program hangs, switch into <code>gdb</code> console, press <kbd>Ctr+C</kbd> and execute:</p>\n\n<pre><code>(gdb) thread apply all py-list\n</code></pre>\n\n<p>See <a href=\"https://code.google.com/p/spyderlib/wiki/HowToDebugDeadlock\" rel=\"noreferrer\">example session</a> and more info <a href=\"http://wiki.python.org/moin/DebuggingWithGdb\" rel=\"noreferrer\">here</a> and <a href=\"http://fedoraproject.org/wiki/Features/EasierPythonDebugging\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 23405280, "author": "Dan Lecocq", "author_id": 173556, "author_profile": "https://Stackoverflow.com/users/173556", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/google/pyringe\" rel=\"nofollow\">pyringe</a> is a debugger that can interact with running python processes, print stack traces, variables, etc. without any a priori setup.</p>\n\n<p>While I've often used the signal handler solution in the past, it can still often be difficult to reproduce the issue in certain environments.</p>\n" }, { "answer_id": 27465699, "author": "jtatum", "author_id": 746040, "author_profile": "https://Stackoverflow.com/users/746040", "pm_score": 0, "selected": false, "text": "<p>In Python 3, pdb will automatically install a signal handler the first time you use c(ont(inue)) in the debugger. Pressing Control-C afterwards will drop you right back in there. In Python 2, here's a one-liner which should work even in relatively old versions (tested in 2.7 but I checked Python source back to 2.4 and it looked okay):</p>\n\n<pre><code>import pdb, signal\nsignal.signal(signal.SIGINT, lambda sig, frame: pdb.Pdb().set_trace(frame))\n</code></pre>\n\n<p>pdb is worth learning if you spend any amount of time debugging Python. The interface is a bit obtuse but should be familiar to anyone who has used similar tools, such as gdb.</p>\n" }, { "answer_id": 29881630, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 6, "selected": false, "text": "<p>Getting a stack trace of an <em>unprepared</em> python program, running in a stock python <em>without debugging symbols</em> can be done with <a href=\"http://pyrasite.readthedocs.org/\">pyrasite</a>. Worked like a charm for me in on Ubuntu Trusty:</p>\n\n<pre><code>$ sudo pip install pyrasite\n$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope\n$ sudo pyrasite 16262 dump_stacks.py # dumps stacks to stdout/stderr of the python program\n</code></pre>\n\n<p>(Hat tip to @Albert, whose answer contained a pointer to this, among other tools.)</p>\n" }, { "answer_id": 29911672, "author": "Michal Čihař", "author_id": 225718, "author_profile": "https://Stackoverflow.com/users/225718", "pm_score": 0, "selected": false, "text": "<p>In case you need to do this with uWSGI, it has <a href=\"http://uwsgi-docs.readthedocs.org/en/latest/Tracebacker.html\" rel=\"nofollow\">Python Tracebacker</a> built-in and it's just matter of enabling it in the configuration (number is attached to the name for each worker):</p>\n\n<pre><code>py-tracebacker=/var/run/uwsgi/pytrace\n</code></pre>\n\n<p>Once you have done this, you can print backtrace simply by connecting to the socket:</p>\n\n<pre><code>uwsgi --connect-and-read /var/run/uwsgi/pytrace1\n</code></pre>\n" }, { "answer_id": 49899783, "author": "user7610", "author_id": 1047788, "author_profile": "https://Stackoverflow.com/users/1047788", "pm_score": 1, "selected": false, "text": "<p>I am in the GDB camp with the python extensions. Follow <a href=\"https://wiki.python.org/moin/DebuggingWithGdb\" rel=\"nofollow noreferrer\">https://wiki.python.org/moin/DebuggingWithGdb</a>, which means</p>\n\n<ol>\n<li><code>dnf install gdb python-debuginfo</code> or <code>sudo apt-get install gdb python2.7-dbg</code></li>\n<li><code>gdb python &lt;pid of running process&gt;</code></li>\n<li><code>py-bt</code></li>\n</ol>\n\n<p>Also consider <code>info threads</code> and <code>thread apply all py-bt</code>.</p>\n" }, { "answer_id": 54225121, "author": "jakvb", "author_id": 10924488, "author_profile": "https://Stackoverflow.com/users/10924488", "pm_score": 1, "selected": false, "text": "<p>How to debug any function <strong>in console</strong>:</p>\n\n<p><strong>Create function</strong> where you <strong>use pdb.set_trace()</strong>, then function you want debug.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import pdb\n&gt;&gt;&gt; import my_function\n\n&gt;&gt;&gt; def f():\n... pdb.set_trace()\n... my_function()\n... \n</code></pre>\n\n<p>Then call created function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; f()\n&gt; &lt;stdin&gt;(3)f()\n(Pdb) s\n--Call--\n&gt; &lt;stdin&gt;(1)my_function()\n(Pdb) \n</code></pre>\n\n<p>Happy debugging :)</p>\n" }, { "answer_id": 60975328, "author": "saaj", "author_id": 2072035, "author_profile": "https://Stackoverflow.com/users/2072035", "pm_score": 3, "selected": false, "text": "<p>It can be done with excellent <a href=\"https://pypi.org/project/py-spy/\" rel=\"noreferrer\">py-spy</a>. It's <em>a sampling profiler for Python programs</em>, so its job is to attach to a Python processes and sample their call stacks. Hence, <code>py-spy dump --pid $SOME_PID</code> is all you need to do to dump call stacks of all threads in the <code>$SOME_PID</code> process. Typically it needs escalated privileges (to read the target process' memory). </p>\n\n<p>Here's an example of how it looks like for a threaded Python application.</p>\n\n<pre><code>$ sudo py-spy dump --pid 31080\nProcess 31080: python3.7 -m chronologer -e production serve -u www-data -m\nPython v3.7.1 (/usr/local/bin/python3.7)\n\nThread 0x7FEF5E410400 (active): \"MainThread\"\n _wait (cherrypy/process/wspbus.py:370)\n wait (cherrypy/process/wspbus.py:384)\n block (cherrypy/process/wspbus.py:321)\n start (cherrypy/daemon.py:72)\n serve (chronologer/cli.py:27)\n main (chronologer/cli.py:84)\n &lt;module&gt; (chronologer/__main__.py:5)\n _run_code (runpy.py:85)\n _run_module_as_main (runpy.py:193)\nThread 0x7FEF55636700 (active): \"_TimeoutMonitor\"\n run (cherrypy/process/plugins.py:518)\n _bootstrap_inner (threading.py:917)\n _bootstrap (threading.py:885)\nThread 0x7FEF54B35700 (active): \"HTTPServer Thread-2\"\n accept (socket.py:212)\n tick (cherrypy/wsgiserver/__init__.py:2075)\n start (cherrypy/wsgiserver/__init__.py:2021)\n _start_http_thread (cherrypy/process/servers.py:217)\n run (threading.py:865)\n _bootstrap_inner (threading.py:917)\n _bootstrap (threading.py:885)\n...\nThread 0x7FEF2BFFF700 (idle): \"CP Server Thread-10\"\n wait (threading.py:296)\n get (queue.py:170)\n run (cherrypy/wsgiserver/__init__.py:1586)\n _bootstrap_inner (threading.py:917)\n _bootstrap (threading.py:885) \n</code></pre>\n" }, { "answer_id": 61975590, "author": "Wayne Lambert", "author_id": 11211077, "author_profile": "https://Stackoverflow.com/users/11211077", "pm_score": -1, "selected": false, "text": "<p>At the point where the code is run, you can insert this small snippet to see a nicely formatted printed stack trace. It assumes that you have a folder called <code>logs</code> at your project's root directory.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># DEBUG: START DEBUG --&gt;\nimport traceback\n\nwith open('logs/stack-trace.log', 'w') as file:\n traceback.print_stack(file=file)\n# DEBUG: END DEBUG --!\n</code></pre>\n" }, { "answer_id": 63302111, "author": "kmaork", "author_id": 2907819, "author_profile": "https://Stackoverflow.com/users/2907819", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"https://pypi.org/project/hypno/\" rel=\"nofollow noreferrer\">hypno</a> package, like so:</p>\n<pre><code>hypno &lt;pid&gt; &quot;import traceback; traceback.print_stack()&quot;\n</code></pre>\n<p>This would print a stack trace into the program's stdout.</p>\n<p>Alternatively, if you don't want to print anything to stdout, or you don't have access to it (a daemon for example), you could use the <a href=\"https://github.com/kmaork/madbg\" rel=\"nofollow noreferrer\">madbg</a> package, which is a python debugger that allows you to attach to a running python program and debug it in your current terminal. It is similar to <code>pyrasite</code> and <code>pyringe</code>, but newer, doesn't require gdb, and uses <code>IPython</code> for the debugger (which means colors and autocomplete).</p>\n<p>To see the stack trace of a running program, you could run:</p>\n<pre><code>madbg attach &lt;pid&gt;\n</code></pre>\n<p>And in the debugger shell, enter:\n<code>bt</code></p>\n<p>Disclaimer - I wrote both packages</p>\n" }, { "answer_id": 68686580, "author": "Phoenix87", "author_id": 1838793, "author_profile": "https://Stackoverflow.com/users/1838793", "pm_score": 2, "selected": false, "text": "<p>Since Austin 3.3, you can use the <code>-w/--where</code> option to emit the current stack trace. See <a href=\"https://stackoverflow.com/a/70905181/1838793\">https://stackoverflow.com/a/70905181/1838793</a></p>\n<p><a href=\"https://i.stack.imgur.com/B6vFQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B6vFQ.png\" alt=\"enter image description here\" /></a></p>\n<p>If you want to peek at a running Python application to see the &quot;live&quot; call stack in a top-like fashon you can use austin-tui (<a href=\"https://github.com/p403n1x87/austin-tui\" rel=\"nofollow noreferrer\">https://github.com/p403n1x87/austin-tui</a>). You can install it from PyPI with e.g.</p>\n<pre><code>pipx install austin-tui\n</code></pre>\n<p>Note that it requires the austin binary to work (<a href=\"https://github.com/p403n1x87/austin\" rel=\"nofollow noreferrer\">https://github.com/p403n1x87/austin</a>), but then you can attach to a running Python process with</p>\n<pre><code>austin-tui -p &lt;pid&gt;\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189/" ]
I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? ***Related questions:*** * [Print current call stack from a method in Python code](https://stackoverflow.com/questions/1156023/print-current-call-stack-from-a-method-in-python-code) * [Check what a running process is doing: print stack trace of an uninstrumented Python program](https://stackoverflow.com/questions/6849138/check-what-a-running-process-is-doing-print-stack-trace-of-an-uninstrumented-py)
I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals): ``` import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message) def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler ``` To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python: ``` os.kill(pid, signal.SIGUSR1) ``` This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive. I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a [python cookbook recipe](http://code.activestate.com/recipes/576515/).
132,070
<p>I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on). I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.</p> <p>How can I check that I'll not delete data that should not be deleted?</p> <p>I have a test database - just a copy of real one where I can do what I want :)</p> <p>The only idea I have is dump database before and after and check it. But it not looks comfortable. Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?</p> <p>Any other ideas how to solve the problem?</p>
[ { "answer_id": 132080, "author": "DrStalker", "author_id": 17007, "author_profile": "https://Stackoverflow.com/users/17007", "pm_score": 0, "selected": false, "text": "<p>If the worry is keys left dangling (i.e.: pointing to a deleted record) then run the deletion on your test database, then use queries to find any keys that now point to invalid targets. (while you're doing this you can also make sure the part that should be unaffected did not change)</p>\n\n<p>A better solution would be to spend time mapping out the delete cascades so you know what to expect - knowing how your database works is pretty valuable so the effort spent on this will be useful beyond this particular deletion.</p>\n\n<p>And no matter how sure you are back the DB up before doing big changes!</p>\n" }, { "answer_id": 132106, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": true, "text": "<p>You can query the information_schema to draw yourself a picture on how the constraints are defined in the database. Then you'll know what is going to happen when you delete. This will be useful not only for this case, but always. </p>\n\n<p>Something like (for constraints)</p>\n\n<pre><code>select table_catalog,table_schema,table_name,column_name,rc.* from\ninformation_schema.constraint_column_usage ccu, \ninformation_schema.referential_constraints rc \nwhere ccu.constraint_name = rc.constraint_name\n</code></pre>\n" }, { "answer_id": 132222, "author": "Pavel", "author_id": 19101, "author_profile": "https://Stackoverflow.com/users/19101", "pm_score": 0, "selected": false, "text": "<p>Thanks for answers!</p>\n\n<p>Vinko, your answer is very useful for me and I'll study it dipper. </p>\n\n<p>actually, for my case, it was enough to compare tables counts before and after records deletion and check what tables were affected by it.</p>\n\n<p>it was done by simple commands described below </p>\n\n<pre><code>psql -U U_NAME -h`hostname` -c '\\d' | awk '{print $3}' &gt; tables.list\n\nfor i in `cat tables.list `; do echo -n \"$i: \" &gt;&gt; tables.counts; psql -U U_NAME -h`hostname` -t -c \"select count(*) from $i\" &gt;&gt; tables.counts; done\n\nfor i in `cat tables.list `; do echo -n \"$i: \" &gt;&gt; tables.counts2; psql -U U_NAME -h`hostname` -t -c \"select count(*) from $i\" &gt;&gt; tables.counts2; done\n\ndiff tables.counts tables.counts2\n</code></pre>\n" }, { "answer_id": 132851, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 1, "selected": false, "text": "<p>Using psql, start a transaction, perform your deletes, then run whatever checking queries you can think of. You can then either rollback or commit.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19101/" ]
I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on). I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals. How can I check that I'll not delete data that should not be deleted? I have a test database - just a copy of real one where I can do what I want :) The only idea I have is dump database before and after and check it. But it not looks comfortable. Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it? Any other ideas how to solve the problem?
You can query the information\_schema to draw yourself a picture on how the constraints are defined in the database. Then you'll know what is going to happen when you delete. This will be useful not only for this case, but always. Something like (for constraints) ``` select table_catalog,table_schema,table_name,column_name,rc.* from information_schema.constraint_column_usage ccu, information_schema.referential_constraints rc where ccu.constraint_name = rc.constraint_name ```
132,092
<p>I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.</p> <p>What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.</p>
[ { "answer_id": 132096, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 4, "selected": false, "text": "<p>Here's a quick example:</p>\n\n<p>I find the comma separated list syntax quite useful for building function calls:</p>\n\n<pre><code>% Build a list of args, like so:\nargs = {'a', 1, 'b', 2};\n% Then expand this into arguments:\noutput = func(args{:})\n</code></pre>\n" }, { "answer_id": 132099, "author": "Rorick", "author_id": 11732, "author_profile": "https://Stackoverflow.com/users/11732", "pm_score": 3, "selected": false, "text": "<p>Invoking Java code from Matlab</p>\n" }, { "answer_id": 132843, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 5, "selected": false, "text": "<p>Turn a matrix into a vector using a single colon.</p>\n\n<pre><code>x = rand(4,4);\nx(:)\n</code></pre>\n" }, { "answer_id": 132878, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 5, "selected": false, "text": "<p>Provide quick access to other function documentation by adding a \"SEE ALSO\" line to the help comments. First, you must include the name of the function in all caps as the first comment line. Do your usual comment header stuff, then put SEE ALSO with a comma separated list of other related functions.</p>\n\n<pre><code>function y = transmog(x)\n%TRANSMOG Transmogrifies a matrix X using reverse orthogonal eigenvectors\n%\n% Usage:\n% y = transmog(x)\n%\n% SEE ALSO\n% UNTRANSMOG, TRANSMOG2\n</code></pre>\n\n<p>When you type \"help transmog\" at the command line, you will see all the comments in this comment header, with hyperlinks to the comment headers for the other functions listed.</p>\n" }, { "answer_id": 133034, "author": "KennyMorton", "author_id": 4135, "author_profile": "https://Stackoverflow.com/users/4135", "pm_score": 3, "selected": false, "text": "<p>cellfun and arrayfun for automated for loops.</p>\n" }, { "answer_id": 138688, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": 3, "selected": false, "text": "<p>The colon operator for the manipulation of arrays.</p>\n\n<p>@ScottieT812, mentions one: flattening an array, but there's all the other variants of selecting bits of an array:</p>\n\n<pre><code>\nx=rand(10,10);\nflattened=x(:);\nAcolumn=x(:,10);\nArow=x(10,:);\n\ny=rand(100);\nfirstSix=y(1:6);\nlastSix=y(end-5:end);\nalternate=y(1:2:end);\n</code></pre>\n" }, { "answer_id": 146875, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 3, "selected": false, "text": "<p>Using nargin to set default values for optional arguments and using nargout to set optional output arguments. Quick example</p>\n\n<pre><code>function hLine=myplot(x,y,plotColor,markerType)\n% set defaults for optional paramters\nif nargin&lt;4, markerType='none'; end\nif nargin&lt;3, plotColor='k'; end\n\nhL = plot(x,y,'linetype','-', ... \n 'color',plotColor, ...\n 'marker',markerType, ...\n 'markerFaceColor',plotColor,'markerEdgeColor',plotColor);\n\n% return handle of plot object if required\nif nargout&gt;0, hLine = hL; end\n</code></pre>\n" }, { "answer_id": 192271, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": 5, "selected": false, "text": "<p>Directly extracting the elements of a matrix that satisfy a particular condition, using logical arrays:</p>\n\n<pre><code>x = rand(1,50) .* 100;\nxpart = x( x &gt; 20 &amp; x &lt; 35);\n</code></pre>\n\n<p>Now xpart contains only those elements of x which lie in the specified range.</p>\n" }, { "answer_id": 202418, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 5, "selected": false, "text": "<p>Using the built-in profiler to see where the hot parts of my code are:</p>\n\n<pre><code>profile on\n% some lines of code\nprofile off\nprofile viewer\n</code></pre>\n\n<p>or just using the built in <code>tic</code> and <code>toc</code> to get quick timings:</p>\n\n<pre><code>tic;\n% some lines of code\ntoc;\n</code></pre>\n" }, { "answer_id": 202439, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 2, "selected": false, "text": "<p>Using ismember() to merge data organized by text identfiers. Useful when you are analyzing differing periods when entries, in my case company symbols, come and go.</p>\n\n<pre><code>%Merge B into A based on Text identifiers\nUniverseA = {'A','B','C','D'};\nUniverseB = {'A','C','D'};\n\nDataA = [20 40 60 80];\nDataB = [30 50 70];\n\nMergeData = NaN(length(UniverseA),2);\n\nMergeData(:,1) = DataA;\n\n[tf, loc] = ismember(UniverseA, UniverseB);\n\nMergeData(tf,2) = DataB(loc(tf));\n\n MergeData =\n\n20 30\n40 NaN\n60 50\n80 70\n</code></pre>\n" }, { "answer_id": 202449, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 3, "selected": false, "text": "<p>Oh, and reverse an array</p>\n\n<pre><code>v = 1:10;\nv_reverse = v(length(v):-1:1);\n</code></pre>\n" }, { "answer_id": 202475, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://www.mathworks.com/support/tech-notes/1100/1109.html\" rel=\"noreferrer\">Vectorizing loops</a>. There are lots of ways to do this, and it is entertaining to look for loops in your code and see how they can be vectorized. The performance is astonishingly faster with vector operations!</p>\n" }, { "answer_id": 284347, "author": "user36927", "author_id": 36927, "author_profile": "https://Stackoverflow.com/users/36927", "pm_score": 2, "selected": false, "text": "<p>Vectorization:</p>\n\n<pre><code>function iNeedle = findClosest(hay,needle)\n%FINDCLOSEST find the indicies of the closest elements in an array.\n% Given two vectors [A,B], findClosest will find the indicies of the values\n% in vector A closest to the values in vector B.\n[hay iOrgHay] = sort(hay(:)'); %#ok must have row vector\n\n% Use histogram to find indices of elements in hay closest to elements in\n% needle. The bins are centered on values in hay, with the edges on the\n% midpoint between elements.\n[iNeedle iNeedle] = histc(needle,[-inf hay+[diff(hay)/2 inf]]); %#ok\n\n% Reversing the sorting.\niNeedle = iOrgHay(iNeedle);\n</code></pre>\n" }, { "answer_id": 382258, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 4, "selected": false, "text": "<p>Here's a bunch of nonobvious functions that are useful from time to time:</p>\n\n<ul>\n<li><code>mfilename</code> (returns the name of the currently running MATLAB script)</li>\n<li><code>dbstack</code> (gives you access to the names &amp; line numbers of the matlab function stack)</li>\n<li><code>keyboard</code> (stops execution and yields control to the debugging prompt; this is why there's a K in the debug prompt <code>K&gt;&gt;</code></li>\n<li><code>dbstop error</code> (automatically puts you in debug mode stopped at the line that triggers an error)</li>\n</ul>\n" }, { "answer_id": 382264, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f0-4741.html#f0-28104\" rel=\"nofollow noreferrer\">LaTeX mode for formulas in graphs</a>: In one of the recent releases (R2006?) you add the additional arguments <code>,'Interpreter','latex'</code> at the end of a function call and it will use LaTeX rendering. Here's an example:</p>\n\n<pre><code>t=(0:0.001:1);\nplot(t,sin(2*pi*[t ; t+0.25]));\nxlabel('t'); \nylabel('$\\hat{y}_k=sin 2\\pi (t+{k \\over 4})$','Interpreter','latex');\nlegend({'$\\hat{y}_0$','$\\hat{y}_1$'},'Interpreter','latex');\n</code></pre>\n\n<p>Not sure when they added it, but it works with R2006b in the text(), title(), xlabel(), ylabel(), zlabel(), and even legend() functions. Just make sure the syntax you are using is not ambiguous (so with legend() you need to specify the strings as a cell array).</p>\n" }, { "answer_id": 382294, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 2, "selected": false, "text": "<p>Executing a Simulink model directly from a script (rather than interactively) using the <code>sim</code> command. You can do things like take parameters from a workspace variable, and repeatedly run <code>sim</code> in a loop to simulate something while varying the parameter to see how the behavior changes, and graph the results with whatever graphical commands you like. Much easier than trying to do this interactively, and it gives you much more flexibility than the Simulink \"oscilloscope\" blocks when visualizing the results. (although you can't use it to see what's going on in realtime while the simulation is running)</p>\n\n<p>A really important thing to know is the <code>DstWorkspace</code> and <code>SrcWorkspace</code> options of the <a href=\"http://www.mathworks.com/access/helpdesk/help/toolbox/simulink/slref/simset.html\" rel=\"nofollow noreferrer\"><code>simset</code></a> command. These control where the \"To Workspace\" and \"From Workspace\" blocks get and put their results. <code>Dstworkspace</code> defaults to the current workspace (e.g. if you call <code>sim</code> from inside a function the \"To Workspace\" blocks will show up as variables accessible from within that same function) but <code>SrcWorkspace</code> defaults to the base workspace and if you want to encapsulate your call to <code>sim</code> you'll want to set <code>SrcWorkspace</code> to <code>current</code> so there is a clean interface to providing/retrieving simulation input parameters and outputs. For example:</p>\n\n<pre><code>function Y=run_my_sim(t,input1,params)\n% runs \"my_sim.mdl\" \n% with a From Workspace block referencing I1 as an input signal\n% and parameters referenced as fields of the \"params\" structure\n% and output retrieved from a To Workspace block with name O1.\nopt = simset('SrcWorkspace','current','DstWorkspace','current');\nI1 = struct('time',t,'signals',struct('values',input1,'dimensions',1));\nY = struct;\nY.t = sim('my_sim',t,opt);\nY.output1 = O1.signals.values;\n</code></pre>\n" }, { "answer_id": 382303, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 2, "selected": false, "text": "<p>Contour plots with <code>[c,h]=contour</code> and <code>clabel(c,h,'fontsize',fontsize)</code>. I usually use the <code>fontsize</code> parameter to reduce the font size so the numbers don't run into each other. This is great for viewing the value of 2-D functions without having to muck around with 3D graphs.</p>\n" }, { "answer_id": 382370, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 4, "selected": false, "text": "<p>Anonymous functions, for a few reasons:</p>\n\n<ol>\n<li>to make a quick function for one-off uses, like 3x^2+2x+7. (see listing below) This is useful for functions like <code>quad</code> and <code>fminbnd</code> that take functions as arguments. It's also convenient in scripts (.m files that don't start with a function header) since unlike true functions you can't include subfunctions.</li>\n<li>for <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"nofollow noreferrer\">closures</a> -- although anonymous functions are a little limiting as there doesn't seem to be a way to have assignment within them to mutate state.</li>\n</ol>\n\n<p>. </p>\n\n<pre><code>% quick functions\nf = @(x) 3*x.^2 + 2*x + 7;\nt = (0:0.001:1);\nplot(t,f(t),t,f(2*t),t,f(3*t));\n\n% closures (linfunc below is a function that returns a function,\n% and the outer functions arguments are held for the lifetime\n% of the returned function.\nlinfunc = @(m,b) @(x) m*x+b;\nC2F = linfunc(9/5, 32);\nF2C = linfunc(5/9, -32*5/9);\n</code></pre>\n" }, { "answer_id": 382390, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 3, "selected": false, "text": "<p>conditional arguments in the left-hand side of an assignment:</p>\n\n<pre><code>t = (0:0.005:10)';\nx = sin(2*pi*t);\nx(x&gt;0.5 &amp; t&lt;5) = 0.5;\n% This limits all values of x to a maximum of 0.5, where t&lt;5\nplot(t,x);\n</code></pre>\n" }, { "answer_id": 423347, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 3, "selected": false, "text": "<p>I like using function handles for lots of reasons. For one, they are the closest thing I've found in MATLAB to pointers, so you can create reference-like behavior for objects. There are a few neat (and simpler) things you can do with them, too. For example, replacing a switch statement:</p>\n\n<pre><code>switch number,\n case 1,\n outargs = fcn1(inargs);\n case 2,\n outargs = fcn2(inargs);\n ...\nend\n%\n%can be turned into\n%\nfcnArray = {@fcn1, @fcn2, ...};\noutargs = fcnArray{number}(inargs);\n</code></pre>\n\n<p>I just think little things like that are cool.</p>\n" }, { "answer_id": 474071, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 3, "selected": false, "text": "<p>Know your <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html\" rel=\"noreferrer\">axis properties</a>! There are all sorts of things you can set to tweak the default plotting properties to do what you want:</p>\n\n<pre><code>set(gca,'fontsize',8,'linestyleorder','-','linewidth',0.3,'xtick',1:2:9);\n</code></pre>\n\n<p>(as an example, sets the fontsize to 8pt, linestyles of all new lines to all be solid and their width 0.3pt, and the xtick points to be [1 3 5 7 9])</p>\n\n<p><a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/line_props.html\" rel=\"noreferrer\">Line</a> and <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/figure_props.html\" rel=\"noreferrer\">figure</a> properties are also useful, but I find myself using axis properties the most.</p>\n" }, { "answer_id": 729942, "author": "ymihere", "author_id": 74606, "author_profile": "https://Stackoverflow.com/users/74606", "pm_score": 4, "selected": false, "text": "<p>Matlab's <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/bsxfun.html\" rel=\"noreferrer\">bsxfun</a>, <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/arrayfun.html\" rel=\"noreferrer\">arrayfun</a>, <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html\" rel=\"noreferrer\">cellfun</a>, and <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/structfun.html\" rel=\"noreferrer\">structfun</a> are quite interesting and often save a loop.</p>\n\n<pre><code>M = rand(1000, 1000);\nv = rand(1000, 1);\nc = bsxfun(@plus, M, v);\n</code></pre>\n\n<p>This code, for instance, adds column-vector v to each column of matrix M.</p>\n\n<p>Though, in performance critical parts of your application you should benchmark these functions versus the trivial for-loop because often loops are still faster.</p>\n" }, { "answer_id": 730068, "author": "ymihere", "author_id": 74606, "author_profile": "https://Stackoverflow.com/users/74606", "pm_score": 3, "selected": false, "text": "<p>Be strict with specifying dimensions when using aggregation functions like min, max, mean, diff, sum, any, all,...</p>\n\n<p>For instance the line:</p>\n\n<pre><code>reldiff = diff(a) ./ a(1:end-1)\n</code></pre>\n\n<p>might work well to compute relative differences of elements in a vector, however in case the vector degenerates to just one element the computation fails:</p>\n\n<pre><code>&gt;&gt; a=rand(1,7);\n&gt;&gt; diff(a) ./ a(1:end-1)\n\nans =\n -0.5822 -0.9935 224.2015 0.2708 -0.3328 0.0458\n\n&gt;&gt; a=1;\n&gt;&gt; diff(a) ./ a(1:end-1)\n??? Error using ==&gt; rdivide\nMatrix dimensions must agree.\n</code></pre>\n\n<p>If you specify the correct dimensions to your functions, this line returns an empty 1-by-0 matrix, which is correct:</p>\n\n<pre><code>&gt;&gt; diff(a, [], 2) ./ a(1, 1:end-1)\n\nans =\n\n Empty matrix: 1-by-0\n\n&gt;&gt; \n</code></pre>\n\n<p>The same goes for a min-function which usually computes minimums over columns on a matrix, until the matrix only consists of one row. - Then it will return the minimum over the row unless the dimension parameter states otherwise, and probably break your application.</p>\n\n<p>I can almost guarantee you that consequently setting the dimensions of these aggregation functions will save you quite some debugging work later on. </p>\n\n<p>At least that would have been the case for me. :)</p>\n" }, { "answer_id": 730137, "author": "simon", "author_id": 14143, "author_profile": "https://Stackoverflow.com/users/14143", "pm_score": 2, "selected": false, "text": "<p>I'm surprised that while people mentioned the logical array approach of indexing an array, nobody mentioned the find command.</p>\n\n<p>e.g. if x is an NxMxO array</p>\n\n<p>x(x>20) works by generating an NxMxO logical array and using it to index x (which can be bad if you have large arrays and are looking for a small subset</p>\n\n<p>x(find(x>20)) works by generating list (i.e. 1xwhatever) of indices of x that satisfy x>20, and indexing x by it. \"find\" should be used more than it is, in my experience.</p>\n\n<p>More what I would call 'tricks'</p>\n\n<p>you can grow/append to arrays and cell arrays if you don't know the size you'll need, by using end + 1 (works with higher dimensions too, so long as the dimensions of the slice match -- so you'll have to initialize x to something other than [] in that case). Not good for numerics but for small dynamic lists of things (or cell arrays), e.g. parsing files.</p>\n\n<p>e.g.</p>\n\n<pre>\n>> x=[1,2,3]\nx = 1 2 3\n>> x(end+1)=4\nx = 1 2 3 4\n</pre>\n\n<p>Another think many people don't know is that for works on any dim 1 array, so to continue the example</p>\n\n<pre>\n>> for n = x;disp(n);end\n 1\n 2\n 3\n 4\n</pre>\n\n<p>Which means if all you need is the members of x you don't need to index them.</p>\n\n<p>This also works with cell arrays but it's a bit annoying because as it walks them the element is still wrapped in a cell:</p>\n\n<pre>\n>> for el = {1,2,3,4};disp(el);end\n [1]\n [2]\n [3]\n [4]\n</pre>\n\n<p>So to get at the elements you have to subscript them</p>\n\n<pre>\n>> for el = {1,2,3,4};disp(el{1});end\n 1\n 2\n 3\n 4\n</pre>\n\n<p>I can't remember if there is a nicer way around that.</p>\n" }, { "answer_id": 1506841, "author": "temp2290", "author_id": 72071, "author_profile": "https://Stackoverflow.com/users/72071", "pm_score": 2, "selected": false, "text": "<p>-You can make a Matlab shortcut to an initialization file called startup.m. Here, I define formatting, precision of the output, and plot parameters for my Matlab session (for example, I use a larger plot axis/font size so that .fig's can be seen plainly when I put them in presentations.) See a good blog post from one of the developers about it <a href=\"http://blogs.mathworks.com/loren/2009/03/03/whats-in-your-startupm/\" rel=\"nofollow noreferrer\">http://blogs.mathworks.com/loren/2009/03/03/whats-in-your-startupm/</a> .</p>\n\n<p>-You can load an entire numerical ascii file using the \"load\" function. This isn't particularly fast, but gets the job done quickly for prototyping (shouldn't that be the Matlab motto?)</p>\n\n<p>-As mentioned, the colon operator and vectorization are lifesavers. Screw loops.</p>\n" }, { "answer_id": 1611773, "author": "Samil", "author_id": 51358, "author_profile": "https://Stackoverflow.com/users/51358", "pm_score": 4, "selected": false, "text": "<p>Using xlim and ylim to draw vertical and horizontal lines. Examples:</p>\n\n<ol>\n<li><p>Draw a horizontal line at y=10:</p>\n\n<p><code>line(xlim, [10 10])</code></p></li>\n<li><p>Draw vertical line at x=5:</p>\n\n<p><code>line([5 5], ylim)</code></p></li>\n</ol>\n" }, { "answer_id": 3931742, "author": "Samil", "author_id": 51358, "author_profile": "https://Stackoverflow.com/users/51358", "pm_score": 3, "selected": false, "text": "<p>In order to be able to quickly test a function, I use <code>nargin</code> like so:</p>\n\n<pre><code>function result = multiply(a, b)\nif nargin == 0 %no inputs provided, run using defaults for a and b\n clc;\n disp('RUNNING IN TEST MODE')\n a = 1;\n b = 2;\nend\n\nresult = a*b;\n</code></pre>\n\n<p>Later on, I add a unit test script to test the function for different input conditions.</p>\n" }, { "answer_id": 4505702, "author": "Y.T.", "author_id": 526015, "author_profile": "https://Stackoverflow.com/users/526015", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>x=repmat([1:10],3,1); % say, x is an example array of data</p>\n<p>l=x&gt;=3; % l is a logical vector (1s/0s) to highlight those elements in the array that would meet a certain condition.</p>\n<p>N=sum(sum(l));% N is the number of elements that meet that given condition.</p>\n</blockquote>\n<p>cheers -- happy scripting!</p>\n" }, { "answer_id": 5813559, "author": "lightw8", "author_id": 22528, "author_profile": "https://Stackoverflow.com/users/22528", "pm_score": 2, "selected": false, "text": "<p>Asking 'why' (useful for jarring me out of a Matlab runtime-fail debugging trance at 3am...)</p>\n" }, { "answer_id": 6492123, "author": "petrichor", "author_id": 198428, "author_profile": "https://Stackoverflow.com/users/198428", "pm_score": 2, "selected": false, "text": "<p>Using <a href=\"http://www.mathworks.com/help/techdoc/ref/persistent.html\" rel=\"nofollow\"><code>persistent</code></a> (static) variables when running an online algorithm. It may speed up the code in areas like Bayesian machine learning where the model is trained iteratively for the new samples. For example, for computing the independent loglikelihoods, I compute the loglikelihood initially from scratch and update it by summing this previously computed loglikelihood and the additional loglikelihood. </p>\n\n<p>Instead of giving a more specialized machine learning problem, let me give a general online averaging code which I took <a href=\"http://undergraduate.csse.uwa.edu.au/units/CITS1005/lectures/topic10.pdf\" rel=\"nofollow\">from here</a>:</p>\n\n<pre><code>function av = runningAverage(x)\n% The number of values entered so far - declared persistent.\npersistent n;\n% The sum of values entered so far - declared persistent.\npersistent sumOfX;\nif x == 'reset' % Initialise the persistent variables.\n n = 0;\n sumOfX = 0;\n av = 0;\nelse % A data value has been added.\n n = n + 1;\n sumOfX = sumOfX + x;\n av = sumOfX / n; % Update the running average.\nend\n</code></pre>\n\n<p>Then, the calls will give the following results</p>\n\n<pre><code>runningAverage('reset')\nans = 0\n&gt;&gt; runningAverage(5)\nans = 5\n&gt;&gt; runningAverage(10)\nans = 7.5000\n&gt;&gt; runningAverage(3)\nans = 6\n&gt;&gt; runningAverage('reset')\nans = 0\n&gt;&gt; runningAverage(8)\nans = 8\n</code></pre>\n" }, { "answer_id": 6816888, "author": "user244795", "author_id": 244795, "author_profile": "https://Stackoverflow.com/users/244795", "pm_score": 2, "selected": false, "text": "<p>Here's what I use frequently:</p>\n\n<p><code>\n % useful abbreviations</p>\n\n<pre><code>flat=@(x) x(:);\n\n% print basic statistics\nstats=@(x) sprintf('mean +/- s.d. \\t= %f +/- %f\\nmin, max \\t\\t= %f, %f\\nmedian, mode \\t= %f, %f', ...\n mean(flat(x)), std(flat(x)), min(flat(x)), max(flat(x)), median(flat(x)), mode(flat(x)) );\n\nnrows=@(x) size(x,1);\nncols=@(x) size(x,2);\nnslices=@(x) size(x,3);\n\n% this is just like ndims except it returns 0 for an empty matrix and\n% ignores dimensions of size 0.\nndim=@(x) length(find(size(x)));\n</code></pre>\n\n<p></code></p>\n\n<p>These abbreviations are useful for finding the mean and standard deviation of pixel values in a small area of an image. I would use the following logic:</p>\n\n<p><code>\n phantomData = phantom();</p>\n\n<pre><code>stats( phantomData(50:80, 50:80) )\n</code></pre>\n\n<p></code></p>\n\n<p>What if I wanted to put the size of an image in its title?</p>\n\n<p><code>\n imagesc( phantomData );</p>\n\n<pre><code>title( sprintf('The image size is %d by %d by %d.', nrows(phantomData), ncols(phantomData), nslices(phantomData)) )\n</code></pre>\n\n<p></code></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15368/" ]
I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done. What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.
Turn a matrix into a vector using a single colon. ``` x = rand(4,4); x(:) ```
132,118
<p>When you're using Tiles with Struts and do...</p> <pre><code>request.getRequestURL() </code></pre> <p>...you get the URL to e.g. <code>/WEB-INF/jsp/layout/newLayout.jsp</code> instead of the real URL that was entered/clicked by the user, something like <code>/context/action.do</code>.</p> <p>In newer Struts versions, 1.3.x and after, you can use the <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=58&amp;t=012300" rel="nofollow noreferrer">solution mentioned on javaranch</a> and get the real URL using the request attribute <a href="http://struts.apache.org/1.x/apidocs/org/apache/struts/Globals.html#ORIGINAL_URI_KEY" rel="nofollow noreferrer"><code>ORIGINAL_URI_KEY</code></a>.</p> <p>But how to do this in Struts 1.2.x?</p>
[ { "answer_id": 135713, "author": "Mwanji Ezana", "author_id": 7288, "author_profile": "https://Stackoverflow.com/users/7288", "pm_score": 1, "selected": false, "text": "<p>I don't know if Struts 1.2.x has a similar Globals constant, but you could create your own in at least two ways:</p>\n\n<ul>\n<li>get the original request URL in the Action and set it on the request, and call that from the JSP</li>\n<li>use a Servlet Filter to do the same thing</li>\n</ul>\n" }, { "answer_id": 157120, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 1, "selected": false, "text": "<p>This works in Struts 1.2</p>\n\n<pre><code>private String getOriginalUri(HttpServletRequest request) {\n String targetUrl = request.getServletPath();\n if (request.getQueryString() != null) {\n targetUrl += \"?\" + request.getQueryString();\n }\n return targetUrl;\n}\n</code></pre>\n" }, { "answer_id": 3298572, "author": "digz6666", "author_id": 386213, "author_profile": "https://Stackoverflow.com/users/386213", "pm_score": 4, "selected": false, "text": "<p>I use this, which also works on Spring:</p>\n\n<pre><code>&lt;% out.println(request.getAttribute(\"javax.servlet.forward.request_uri\")); %&gt;\n</code></pre>\n\n<p>If you also need the query string (contributed by <a href=\"https://stackoverflow.com/users/638649/matchew\">matchew</a>):</p>\n\n<pre><code>&lt;% out.println(request.getAttribute(\"javax.servlet.forward.query_string\")); %&gt;\n</code></pre>\n" }, { "answer_id": 3711907, "author": "adlerer", "author_id": 447672, "author_profile": "https://Stackoverflow.com/users/447672", "pm_score": 2, "selected": false, "text": "<p>When you query request.getRequestURL() from your view/jsp/tiles layer, it's already another rewritten request. </p>\n\n<p>As Mwanji Ezana mentions, the most suitable way is to save it to separate property on the action execution phase. You may want to automate this process with the help of interceptors in Struts2.</p>\n" }, { "answer_id": 62894801, "author": "Carlos Fernando", "author_id": 10975299, "author_profile": "https://Stackoverflow.com/users/10975299", "pm_score": 0, "selected": false, "text": "<p>You just need to do this in your action:</p>\n<pre><code> request.getAttribute(&quot;javax.servlet.forward.request_uri&quot;)\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When you're using Tiles with Struts and do... ``` request.getRequestURL() ``` ...you get the URL to e.g. `/WEB-INF/jsp/layout/newLayout.jsp` instead of the real URL that was entered/clicked by the user, something like `/context/action.do`. In newer Struts versions, 1.3.x and after, you can use the [solution mentioned on javaranch](http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=58&t=012300) and get the real URL using the request attribute [`ORIGINAL_URI_KEY`](http://struts.apache.org/1.x/apidocs/org/apache/struts/Globals.html#ORIGINAL_URI_KEY). But how to do this in Struts 1.2.x?
I use this, which also works on Spring: ``` <% out.println(request.getAttribute("javax.servlet.forward.request_uri")); %> ``` If you also need the query string (contributed by [matchew](https://stackoverflow.com/users/638649/matchew)): ``` <% out.println(request.getAttribute("javax.servlet.forward.query_string")); %> ```
132,136
<p>Does anyone know if IE6 ever misrenders pages with hidden <code>divs</code>? We currently have several <code>divs</code> which we display in the same space on the page, only showing one at a time and hiding all others.</p> <p>The problem is that the hidden <code>divs</code> components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear.</p> <p>How do we fix this?</p>
[ { "answer_id": 132162, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 2, "selected": false, "text": "<p>One hack you could use is to move your div outside the screen:</p>\n\n<pre><code>MyDiv.style.left = \"-1000px\";\n</code></pre>\n\n<p>And then put it back on its original position when you want to show it.</p>\n" }, { "answer_id": 132193, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "<p>How are they hidden? using <code>display:none;</code> or <code>visibility:hidden;</code> ? are they absolutely positioned by any chance? IE6 has a z-Index problem and there are several hacks to deal with it.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anyone know if IE6 ever misrenders pages with hidden `divs`? We currently have several `divs` which we display in the same space on the page, only showing one at a time and hiding all others. The problem is that the hidden `divs` components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear. How do we fix this?
One hack you could use is to move your div outside the screen: ``` MyDiv.style.left = "-1000px"; ``` And then put it back on its original position when you want to show it.
132,164
<p>These <code>for</code>-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions:</p> <pre><code>1 for ( int i = 0; i != N; ++i ) 2 for ( int i = 0; i &lt; N; ++i ) </code></pre> <p>The difference becomes clear in the postconditions:</p> <ul> <li><p>The first one gives the strong guarantee that <code>i == N</code> after the loop terminates.</p></li> <li><p>The second one only gives the weak guarantee that <code>i &gt;= N</code> after the loop terminates, but you will be tempted to assume that <code>i == N</code>.</p></li> </ul> <p>If for any reason the increment <code>++i</code> is ever changed to something like <code>i += 2</code>, or if <code>i</code> gets modified inside the loop, or if <code>N</code> is negative, the program can fail:</p> <ul> <li><p>The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy.</p></li> <li><p>The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of <code>i == N</code>. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse.</p></li> </ul> <p>Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?</p>
[ { "answer_id": 132175, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>In C++, using the <code>!=</code> test is preferred for generality. Iterators in C++ have various concepts, like <a href=\"http://www.sgi.com/tech/stl/InputIterator.html\" rel=\"nofollow noreferrer\">input iterator</a>, <a href=\"http://www.sgi.com/tech/stl/ForwardIterator.html\" rel=\"nofollow noreferrer\">forward iterator</a>, <a href=\"http://www.sgi.com/tech/stl/BidirectionalIterator.html\" rel=\"nofollow noreferrer\">bidirectional iterator</a>, <a href=\"http://www.sgi.com/tech/stl/RandomAccessIterator.html\" rel=\"nofollow noreferrer\">random access iterator</a>, each of which extends the previous one with new capabilities. For <code>&lt;</code> to work, random access iterator is required, whereas <code>!=</code> merely requires input iterator.</p>\n" }, { "answer_id": 132176, "author": "Svet", "author_id": 8934, "author_profile": "https://Stackoverflow.com/users/8934", "pm_score": 2, "selected": false, "text": "<p>We shouldn't look at the counter in isolation - if for any reason someone changed the way the counter is incremented they would change the termination conditions and the resulting logic if it's required for i==N.</p>\n\n<p>I would prefer the the second condition since it's more standard and will not result in endless loop.</p>\n" }, { "answer_id": 132180, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 1, "selected": false, "text": "<p>If you trust your code, you can do either. </p>\n\n<p>If you want your code to be readable and easily understood (and thus more tolerant to change from someone who you've got to assume to be a klutz), I'd use something like; </p>\n\n<pre><code>for ( int i = 0 ; i &gt;= 0 &amp;&amp; i &lt; N ; ++i) \n</code></pre>\n" }, { "answer_id": 132185, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 1, "selected": false, "text": "<p>I always use #2 as then you can be sure the loop will terminate... Relying on it being equal to N afterwards is relying on a side effect... Wouldn't you just be better using the variable N itself?</p>\n\n<p>[edit] Sorry...I meant #2</p>\n" }, { "answer_id": 132196, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "<p>In general I would prefer </p>\n\n<pre><code>for ( int i = 0; i &lt; N; ++i )\n</code></pre>\n\n<p>The punishment for a buggy program in production, seems a lot less severe, you will not have a thread stuck forever in a for loop, a situation that can be very risky and very hard to diagnose. </p>\n\n<p>Also, in general I like to avoid these kind of loops in favour of the more readable foreach style loops.</p>\n" }, { "answer_id": 132198, "author": "Allan Mertner", "author_id": 13394, "author_profile": "https://Stackoverflow.com/users/13394", "pm_score": 1, "selected": false, "text": "<p>I think most programmers use the 2nd one, because it helps figure out what goes on inside the loop. I can look at it, and \"know\" that i will start as 0, and will definitely be less than N.</p>\n\n<p>The 1st variant doesn't have this quality. I can look at it, and all I know is that i will start as 0 and that it won't ever be equal to N. Not quite as helpful.</p>\n\n<p>Irrespective of how you terminate the loop, it is always good to be very wary of using a loop control variable outside the loop. In your examples you (correctly) declare i inside the loop, so it is not in scope outside the loop and the question of its value is moot...</p>\n\n<p>Of course, the 2nd variant also has the advantage that it's what all of the C references I have seen use :-)</p>\n" }, { "answer_id": 132200, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": "<p>I prefer to use #2, only because I try not to extend the meaning of i outside of the for loop. If I were tracking a variable like that, I would create an additional test. Some may say this is redundant or inefficient, but it reminds the reader of my intent: <strong>At this point, i must equal N</strong> </p>\n\n<p>@timyates - I agree one shouldn't rely on side-effects</p>\n" }, { "answer_id": 132225, "author": "Martin McNulty", "author_id": 4507, "author_profile": "https://Stackoverflow.com/users/4507", "pm_score": 2, "selected": false, "text": "<p>I tend to use the second form, simply because then I can be more sure that the loop will terminate. I.e. it's harder to introduce a non-termination bug by altering i inside the loop. </p>\n\n<p>Of course, it also has the slightly lazy advantage of being one less character to type ;)</p>\n\n<p>I would also argue, that in a language with sensible scope rules, as i is declared inside the loop construct, it shouldn't be available outside the loop. This would mitigate any reliance on i being equal to N at the end of the loop...</p>\n" }, { "answer_id": 132230, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 0, "selected": false, "text": "<p>I think you stated very well the difference between the two. I do have the following comments, though:</p>\n\n<ul>\n<li><p>This is not \"language-agnostic\", I can see your examples are in C++ but there\nare languages where you are not allowed to modify the loop variable inside the\nloop and others that don't guarantee that the value of the index is usable after\nthe loop (and some do both).</p></li>\n<li><p>You have declared the <code>i</code>\nindex within the <code>for</code> so I would not bet on the value of <code>i</code> after the loop.\nThe examples are a little bit misleading as they implictly assume that <code>for</code> is\na definite loop. In reality it is just a more convenient way of writing:</p>\n\n<pre><code>// version 1\n{ int i = 0;\n while (i != N) {\n ...\n ++i;\n }\n}\n</code></pre>\n\n<p>Note how <code>i</code> is undefined after the block.</p></li>\n</ul>\n\n<p>If a programmer knew all of the above would not make general assumption of the value of <code>i</code> and would be wise enough to choose <code>i&lt;N</code> as the ending conditions, to ensure that the the exit condition will be eventually met.</p>\n" }, { "answer_id": 132289, "author": "Mesh", "author_id": 15710, "author_profile": "https://Stackoverflow.com/users/15710", "pm_score": 0, "selected": false, "text": "<p>Using either of the above in c# would cause a compiler error if you used i outside the loop</p>\n" }, { "answer_id": 132297, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "<p>I prefer this sometimes:</p>\n\n<pre><code>for (int i = 0; (i &lt;= (n-1)); i++) { ... }\n</code></pre>\n\n<p>This version shows directly the range of values that i can have. My take on checking lower and upper bound of the range is that if you really need this, your code has too many side effects and needs to be rewritten.</p>\n\n<p>The other version:</p>\n\n<pre><code>for (int i = 1; (i &lt;= n); i++) { ... }\n</code></pre>\n\n<p>helps you determine how often the loop body is called. This also has valid use cases.</p>\n" }, { "answer_id": 1581115, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 0, "selected": false, "text": "<p>For general programming work I prefer </p>\n\n<pre><code>for ( int i = 0; i &lt; N; ++i )\n</code></pre>\n\n<p>to</p>\n\n<pre><code>for ( int i = 0; i != N; ++i )\n</code></pre>\n\n<p>Because it is less error prone, especially when code gets refactored. I have seen this kind of code turned into an infinite loop by accident. </p>\n\n<p>That argument made that \"you will be tempted to assume that i == N\", I don't believe is true. I have never made that assumption or seen another programmer make it. </p>\n" }, { "answer_id": 12937813, "author": "C-Otto", "author_id": 947526, "author_profile": "https://Stackoverflow.com/users/947526", "pm_score": 0, "selected": false, "text": "<p>From my standpoint of formal verification and automatic termination analysis, I strongly prefer #2 (<code>&lt;</code>). It is quite easy to track that some variable is increased (before <code>var = x</code>, after <code>var = x+n</code> for some non-negative number <code>n</code>). However, it is not that easy to see that <code>i==N</code> eventually holds. For this, one needs to infer that <code>i</code> is increased by exactly <code>1</code> in each step, which (in more complicated examples) might be lost due to abstraction.</p>\n\n<p>If you think about the loop which increments by two (<code>i = i + 2</code>), this general idea becomes more understandable. To guarantee termination one now needs to know that <code>i%2 == N%2</code>, whereas this is irrelevant when using <code>&lt;</code> as the condition.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686/" ]
These `for`-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions: ``` 1 for ( int i = 0; i != N; ++i ) 2 for ( int i = 0; i < N; ++i ) ``` The difference becomes clear in the postconditions: * The first one gives the strong guarantee that `i == N` after the loop terminates. * The second one only gives the weak guarantee that `i >= N` after the loop terminates, but you will be tempted to assume that `i == N`. If for any reason the increment `++i` is ever changed to something like `i += 2`, or if `i` gets modified inside the loop, or if `N` is negative, the program can fail: * The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy. * The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of `i == N`. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse. Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?
We shouldn't look at the counter in isolation - if for any reason someone changed the way the counter is incremented they would change the termination conditions and the resulting logic if it's required for i==N. I would prefer the the second condition since it's more standard and will not result in endless loop.
132,186
<p>I wish to test a function that will generate <code>lorem ipsum</code> text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits. So what I am wondering is if the assertTags can do this in a way paraphrased bellow:</p> <pre><code>Result = "&lt;p&gt;Some text&lt;/p&gt;"; Expected = array( '&lt;p' , 'regex', '/p' ); assertTags(resutl, expected) </code></pre> <p>I am using SimpleTest with CakePHP, but I think it should be a general question.</p>
[ { "answer_id": 132420, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "<p>Extend the SimpleExpectation class and then use your new Expectation class in the assert statement</p>\n\n<p>see: <a href=\"http://www.lastcraft.com/expectation_documentation.php#extending\" rel=\"nofollow noreferrer\">http://www.lastcraft.com/expectation_documentation.php#extending</a></p>\n\n<p>the example given is for validating an IP address but should be applicable to your problem:</p>\n\n<pre><code>class ValidIp extends SimpleExpectation {\n\n function test($ip) {\n return (ip2long($ip) != -1);\n }\n\n function testMessage($ip) {\n return \"Address [$ip] should be a valid IP address\";\n }\n}\n</code></pre>\n\n<p>then in your test</p>\n\n<pre><code>$this-&gt;assert(new ValidIp(),$server-&gt;getIp());\n</code></pre>\n" }, { "answer_id": 132481, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 3, "selected": true, "text": "<pre><code>$expected = array(\n '&lt;p',\n 'preg:/[A-Za-z\\.\\s\\,]+/',\n '/p'\n);\n</code></pre>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
I wish to test a function that will generate `lorem ipsum` text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits. So what I am wondering is if the assertTags can do this in a way paraphrased bellow: ``` Result = "<p>Some text</p>"; Expected = array( '<p' , 'regex', '/p' ); assertTags(resutl, expected) ``` I am using SimpleTest with CakePHP, but I think it should be a general question.
``` $expected = array( '<p', 'preg:/[A-Za-z\.\s\,]+/', '/p' ); ```
132,231
<p>When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?</p>
[ { "answer_id": 132546, "author": "Bradley Beddoes", "author_id": 22087, "author_profile": "https://Stackoverflow.com/users/22087", "pm_score": 1, "selected": false, "text": "<p>Here is an example to boot strap spring for a Main method, simply grab the passed params as normal then make the function you call on your bean (in the case deployer.execute()) take them as Strings or via any format you feel suitable.</p>\n\n<pre><code>public static void main(String[] args) throws IOException, ConfigurationException {\n Deployer deployer = bootstrapSpring();\n\n deployer.execute();\n}\n\nprivate static Deployer bootstrapSpring()\n{\n FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext(\"spring/deployerContext.xml\");\n\n Deployer deployer = (Deployer)appContext.getBean(\"deployer\");\n return deployer;\n}\n</code></pre>\n" }, { "answer_id": 134974, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 6, "selected": true, "text": "<p>Two possibilities I can think of.</p>\n\n<p>1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation). </p>\n\n<pre><code>public class MyApp {\n public static String[] ARGS; \n public static void main(String[] args) {\n ARGS = args;\n // create context\n }\n}\n</code></pre>\n\n<p>You can then reference the command line arguments in Spring via:</p>\n\n<pre><code>&lt;util:constant static-field=\"MyApp.ARGS\"/&gt;\n</code></pre>\n\n<p>Alternatively (if you are completely opposed to static variables), you can:</p>\n\n<p>2) Programmatically add the args to the application context:</p>\n\n<pre><code> public class MyApp2 {\n public static void main(String[] args) {\n DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();\n\n // Define a bean and register it\n BeanDefinition beanDefinition = BeanDefinitionBuilder.\n rootBeanDefinition(Arrays.class, \"asList\")\n .addConstructorArgValue(args).getBeanDefinition();\n beanFactory.registerBeanDefinition(\"args\", beanDefinition);\n GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);\n // Must call refresh to initialize context \n cmdArgCxt.refresh();\n\n // Create application context, passing command line context as parent\n ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt);\n\n // See if it's in the context\n System.out.println(\"Args: \" + mainContext.getBean(\"args\"));\n }\n\n private static String[] CONFIG_LOCATIONS = new String[] {\n \"applicationContext.xml\"\n };\n\n }\n</code></pre>\n\n<p>Parsing the command line arguments is left as an exercise to the reader. </p>\n" }, { "answer_id": 304026, "author": "BeWarned", "author_id": 37110, "author_profile": "https://Stackoverflow.com/users/37110", "pm_score": 3, "selected": false, "text": "<p>You can also pass an Object array as a second parameter to <code>getBean</code> which will be used as arguments to the constructor or factory.</p>\n\n<pre><code>public static void main(String[] args) {\n Mybean m = (Mybean)context.getBean(\"mybean\", new Object[] {args});\n}\n</code></pre>\n" }, { "answer_id": 1195240, "author": "Brian Dilley", "author_id": 71050, "author_profile": "https://Stackoverflow.com/users/71050", "pm_score": 2, "selected": false, "text": "<p>Consider the following class:</p>\n\n<pre><code>public class ExternalBeanReferneceFactoryBean \n extends AbstractFactoryBean\n implements BeanNameAware {\n\n private static Map&lt;String, Object&gt; instances = new HashMap&lt;String, Object&gt;();\n private String beanName;\n\n /**\n * @param instance the instance to set\n */\n public static void setInstance(String beanName, Object instance) {\n instances.put(beanName, instance);\n }\n\n @Override\n protected Object createInstance() \n throws Exception {\n return instances.get(beanName);\n }\n\n @Override\n public Class&lt;?&gt; getObjectType() {\n return instances.get(beanName).getClass();\n }\n\n @Override\n public void setBeanName(String name) {\n this.beanName = name;\n }\n\n}\n</code></pre>\n\n<p>along with:</p>\n\n<pre><code>/**\n * Starts the job server.\n * @param args command line arguments\n */\npublic static void main(String[] args) {\n\n // parse the command line\n CommandLineParser parser = new GnuParser();\n CommandLine cmdLine = null;\n try {\n cmdLine = parser.parse(OPTIONS, args);\n } catch(ParseException pe) {\n System.err.println(\"Error parsing command line: \"+pe.getMessage());\n new HelpFormatter().printHelp(\"command\", OPTIONS);\n return;\n }\n\n // create root beanFactory\n DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();\n\n // register bean definition for the command line\n ExternalBeanReferneceFactoryBean.setInstance(\"commandLine\", cmdLine);\n beanFactory.registerBeanDefinition(\"commandLine\", BeanDefinitionBuilder\n .rootBeanDefinition(ExternalBeanReferneceFactoryBean.class)\n .getBeanDefinition());\n\n // create application context\n GenericApplicationContext rootAppContext = new GenericApplicationContext(beanFactory);\n rootAppContext.refresh();\n\n // create the application context\n ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { \n \"/commandlineapp/applicationContext.xml\"\n }, rootAppContext);\n\n System.out.println(appContext.getBean(\"commandLine\"));\n\n}\n</code></pre>\n" }, { "answer_id": 2071474, "author": "Graham", "author_id": 59724, "author_profile": "https://Stackoverflow.com/users/59724", "pm_score": 3, "selected": false, "text": "<p>Have a look at my Spring-CLI library - at <a href=\"http://github.com/sazzer/spring-cli\" rel=\"noreferrer\">http://github.com/sazzer/spring-cli</a> - as one way of doing this. It gives you a main class that automatically loads spring contexts and has the ability to use Commons-CLI for parsing command line arguments automatically and injecting them into your beans.</p>\n" }, { "answer_id": 41889084, "author": "S. Pauk", "author_id": 4680812, "author_profile": "https://Stackoverflow.com/users/4680812", "pm_score": 3, "selected": false, "text": "<p>Starting from Spring 3.1 there is no need in any custom code suggested in other answers. Check <a href=\"http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html\" rel=\"noreferrer\">CommandLinePropertySource</a>, it provides a natural way to inject CL arguments into your context.</p>\n<p>And if you are a lucky Spring Boot developer you could simplify your code one step forward leveraging the fact that <a href=\"http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/SpringApplication.html\" rel=\"noreferrer\">SpringApplication</a> gives you the following:</p>\n<blockquote>\n<p>By default class will perform the following steps to bootstrap your\napplication:</p>\n<p>...</p>\n<p>Register a CommandLinePropertySource to expose command line arguments\nas Spring properties</p>\n</blockquote>\n<p>And if you are interested in the Spring Boot property resolution order please consult <a href=\"https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html\" rel=\"noreferrer\">this page</a>.</p>\n" }, { "answer_id": 58031369, "author": "Gerardo Roza", "author_id": 6661361, "author_profile": "https://Stackoverflow.com/users/6661361", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what you are trying to achieve exactly, maybe you can add some details on what the command and the arguments will look like, and what outcome you expect from your application.</p>\n\n<p>I think this is not what you need, but it might help other readers: Spring supports receiving properties from the command line using double hyphen (e.g. <code>java -jar app.jar --my.property=\"Property Value\"</code>\nHave a look at this documentation for more information:\n<a href=\"https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-command-line-args\" rel=\"nofollow noreferrer\">https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-command-line-args</a></p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
Two possibilities I can think of. 1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation). ``` public class MyApp { public static String[] ARGS; public static void main(String[] args) { ARGS = args; // create context } } ``` You can then reference the command line arguments in Spring via: ``` <util:constant static-field="MyApp.ARGS"/> ``` Alternatively (if you are completely opposed to static variables), you can: 2) Programmatically add the args to the application context: ``` public class MyApp2 { public static void main(String[] args) { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // Define a bean and register it BeanDefinition beanDefinition = BeanDefinitionBuilder. rootBeanDefinition(Arrays.class, "asList") .addConstructorArgValue(args).getBeanDefinition(); beanFactory.registerBeanDefinition("args", beanDefinition); GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory); // Must call refresh to initialize context cmdArgCxt.refresh(); // Create application context, passing command line context as parent ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt); // See if it's in the context System.out.println("Args: " + mainContext.getBean("args")); } private static String[] CONFIG_LOCATIONS = new String[] { "applicationContext.xml" }; } ``` Parsing the command line arguments is left as an exercise to the reader.
132,242
<p>Consider this case:</p> <pre><code>dll = LoadDLL() dll-&gt;do() ... void do() { char *a = malloc(1024); } ... UnloadDLL(dll); </code></pre> <p>At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.</p>
[ { "answer_id": 132308, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": -1, "selected": true, "text": "<p>No, you do not leak. </p>\n\n<p>If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)</p>\n\n<p>This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.</p>\n\n<p>If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)</p>\n" }, { "answer_id": 132309, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p>One could do a test and see if there are memory leaks. You run a simple test 30 times allocating 1 MB each time. You should figure that out quite quickly.</p>\n\n<p>One thing is for sure. If you allocated memory in the DLL you should also free that memory there (in the DLL).</p>\n\n<p>For example you should have something like this (simple but intuitive pseudocode):</p>\n\n<pre><code>dll = DllLoad();\n\nptr = dll-&gt;alloc();\n\ndll-&gt;free(ptr);\n\nDllUnload(dll);\n</code></pre>\n\n<p>This must be done because the DLL has a different heap than the original process (that loads the dll).</p>\n" }, { "answer_id": 132348, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 2, "selected": false, "text": "<p>From MSDN <a href=\"http://msdn.microsoft.com/en-us/library/ms235460(VS.80).aspx\" rel=\"nofollow noreferrer\">Potential Errors Passing CRT Objects Across DLL Boundaries</a></p>\n\n<blockquote>\n <p>Each copy of the CRT library has a\n separate and distinct state. As such,\n CRT objects such as file handles,\n environment variables, and locales are\n only valid for the copy of the CRT\n where these objects are allocated or\n set. When a DLL and its users use\n different copies of the CRT library,\n you cannot pass these CRT objects\n across the DLL boundary and expect\n them to be picked up correctly on the\n other side.</p>\n \n <p>Also, because each copy of the CRT\n library has its own heap manager,\n allocating memory in one CRT library\n and passing the pointer across a DLL\n boundary to be freed by a different\n copy of the CRT library is a potential\n cause for heap corruption.</p>\n</blockquote>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 132424, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": false, "text": "<p>You can't tell. This depends on the implementation of your static and dynamic CRT. It may even depend on the <em>size</em> of the allocation, as there are CRTs that forward large allocations to the OS, but implement their own heap for small allocations.</p>\n\n<p>The problem with a CRT that leaks is of course that it leaks. The problem with a CRT that does not leak is that the executable might reasonable expect to use the memory, as malloc'ed memory should remain usable until free is called.</p>\n" }, { "answer_id": 132460, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>Memory used by a process as tracked by the OS is applicable to the full process and not specific to a DLL. </p></li>\n<li><p>Memory is given to the program in chunks by the OS, called heaps </p></li>\n<li><p>The heap managers (malloc / new etc) further divide up the chunks and hands it out to requesting code.</p></li>\n<li><p>Only when a new heap is allocated does the OS detect an increase in memory.</p></li>\n<li><p>When a DLL is statically linked to the C Run time library (CRT), a private copy of CRT with the CRT functions that the DLL's code invokes is compiled and put into the DLL's binary. Malloc is also inclued in this.</p></li>\n<li><p>This private copy of malloc will be invoked whenever the code present inside the statically linked DLL tries to allocate memory. </p></li>\n<li><p>Consequently, a private heap visible only to this copy of malloc, is acquired from the OS by this malloc and it allocates the memory requested by the code within this private heap. </p></li>\n<li><p><strong>When the DLL unloads, it unloads its private heap, and this leak goes unnoticed as the entire heap is returned back to the OS</strong>. </p></li>\n<li><p>However If the DLL is dynamically linked, the memory is allocated by a single shared version of malloc, global to all code that is linked in the shared mode. </p></li>\n<li><p>Memory allocated by this global malloc, comes out of a heap which is also the heap used for all other code that is linked in the dynamic aka shared mode and hence is common. Any leaks from this heap therefore becomes a leak which affects the whole process. </p></li>\n</ol>\n\n<p>Edit - Added descriptions of the linking scenario.</p>\n" }, { "answer_id": 2624394, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 2, "selected": false, "text": "<p>Actually, the marked answer is incorrect. That right there is a leak. While it is technically feasible for each dll to implement its own heap, and free it on shutdown, most \"runtime\" heaps - static or dynamic - are wrappers around the Win32 process heap API.</p>\n\n<p>Unless one has taken specific care to guarantee that this is not the case, the dll will leak the allocation per load,do,unload cycle.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17424/" ]
Consider this case: ``` dll = LoadDLL() dll->do() ... void do() { char *a = malloc(1024); } ... UnloadDLL(dll); ``` At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.
No, you do not leak. If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe) This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT. If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)
132,245
<p>The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store.</p> <p>It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods.</p> <p>So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario.</p> <p>I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex.</p> <pre><code>public class BaseDataObject { // internal data store private Dictionary&lt;string, object&gt; attachedData = new Dictionary&lt;string, object&gt;(); public void SetData(string key, object value) { attachedData[key] = value; } public object GetData(string key) { return attachedData[key]; } public int SomeValue { get; set; } public int SomeOtherValue { get; set; } } public static class Extensions { public static void SetBarValue(this BaseDataObject dataObject, int barValue) { /// Cannot attach a property to BaseDataObject? dataObject.SetData("bar", barValue); } } public class TestDemo { public void CreateTest() { // this works BaseDataObject test1 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }; // this does not work - it does not compile // cannot use extension method in the initialiser block // cannot make an exension property BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) }; } } </code></pre> <p>One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.:</p> <pre><code>// fluent interface style public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue) { dataObject.SetData("bar", barValue); return dataObject; } // this works BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5); </code></pre> <p>But will this work in a LINQ query?</p>
[ { "answer_id": 132275, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 3, "selected": false, "text": "<p>Object Initializers are just syntactic sugar that requires a clever compiler, and as of the current implementation you can't call methods in the initializer.</p>\n\n<pre><code>var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };\n</code></pre>\n\n<p>Will get compiler to something like this:</p>\n\n<pre><code>BaseDataObject tempObject = new BaseDataObject();\ntempObject.SomeValue = 3;\ntempObject.SomeOtherValue = 4;\nBaseDataObject x = tempObject;\n</code></pre>\n\n<p>The difference is that there can't be any synchronization issues. The variable x get's assigned the fully assigned BaseDataObject at once, you can't mess with the object during it's initialization.</p>\n\n<p>You could just call the extension method after the object creation:</p>\n\n<pre><code>var x = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 };\nx.SetBarValue()\n</code></pre>\n\n<p>You could change SetBarValue to be a property with get/set that can be assigned during initialization:</p>\n\n<pre><code>public int BarValue\n{\n set\n {\n //Value should be ignored\n }\n}\n</code></pre>\n\n<p>Or, you could subclass / use the facade pattern to add the method onto your object:</p>\n\n<pre><code>public class DataObjectWithBarValue : BaseDataObject\n{\n public void BarValue\n {\n set\n {\n SetData(\"bar\", value);\n }\n get\n {\n (int) GetData(\"bar\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 132279, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>No but you could do this....:</p>\n\n<pre><code>BaseDataObject test2 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4}).SetBarValue(5);\n</code></pre>\n\n<p>ANd have your extension return the object like Linq Does.</p>\n\n<p>EDIT: This was a good thought untill i reread and saw that the base class was developed by a third person: aka you dont have the code. Others here have posted a correct solution.</p>\n" }, { "answer_id": 132324, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": true, "text": "<p>Even better:</p>\n\n<pre><code>public static T SetBarValue&lt;T&gt;(this T dataObject, int barValue)\n where T : BaseDataObject \n {\n dataObject.SetData(\"bar\", barValue);\n return dataObject;\n }\n</code></pre>\n\n<p>and you can use this extension method for derived types of BaseDataObject to chain methods without casts and preserve the real type when inferred into a var field or anonymous type. </p>\n" }, { "answer_id": 132331, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 0, "selected": false, "text": "<p>Is extending the class a possibility? Then you could easily add the property you need.</p>\n\n<p>Failing that, you can create a new class that has similar properties that simply call back to a private instance of the class you are interested in.</p>\n" }, { "answer_id": 132356, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<pre><code> static T WithBarValue&lt;T&gt;(this T dataObject, int barValue)\n where T : BaseDataObject \n { dataObject.SetData(\"bar\", barValue); \n return dataObject;\n }\n\nvar x = new BaseDataObject{SomeValue=3, OtherValue=4}.WithBarValue(5);\n</code></pre>\n" }, { "answer_id": 136085, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": "<p>Right, having learned from the answerers, the short answer to \"Is there any way to use an extension method in an object initializer block in C#?\" is \"<strong>No.</strong>\"</p>\n\n<p>The way that I eventually solved the problem that I faced (similar, but more complex that the toy problem that I posed here) was a hybrid approach, as follows:</p>\n\n<p>I created a subclass, e.g.</p>\n\n<pre><code>public class SubClassedDataObject : BaseDataObject\n{\n public int Bar\n {\n get { return (int)GetData(\"bar\"); }\n set { SetData(\"bar\", value); }\n }\n}\n</code></pre>\n\n<p>Which works fine in LINQ, the initialisation block looking like </p>\n\n<pre><code> SubClassedDataObject testSub = new SubClassedDataObject\n { SomeValue = 3, SomeOtherValue = 4, Bar = 5 };\n</code></pre>\n\n<p>But the reason that I didn't like this approach in the first place is that these objects are put into XML and come back out as BaseDataObject, and casting back was going to be an annoyance, an unnecessary data copy, and would put two copies of the same object in play.</p>\n\n<p>In the rest of the code, I ignored the subclasses and used extension methods:</p>\n\n<pre><code> public static void SetBar(this BaseDataObject dataObject, int barValue)\n {\n dataObject.SetData(\"bar\", barValue);\n }\n public static int GetBar(this BaseDataObject dataObject)\n {\n return (int)dataObject.GetData(\"bar\");\n }\n</code></pre>\n\n<p>And it works nicely.</p>\n" } ]
2008/09/25
[ "https://Stackoverflow.com/questions/132245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5599/" ]
The simple demo below captures what I am trying to do. In the real program, I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression, and there is a value that that I want to read off the database and store on the object, but the object doesn't have a simple property that I can set for that value. Instead it has an XML data store. It looks like I can't call an extension method in the object initialiser block, and that I can't attach a property using extension methods. So am I out of luck with this approach? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario. I have an existing solution where I subclass BaseDataObject, but this has problems too that don't show up in this simple example. The objects are persisted and restored as BaseDataObject - the casts and tests would get complex. ``` public class BaseDataObject { // internal data store private Dictionary<string, object> attachedData = new Dictionary<string, object>(); public void SetData(string key, object value) { attachedData[key] = value; } public object GetData(string key) { return attachedData[key]; } public int SomeValue { get; set; } public int SomeOtherValue { get; set; } } public static class Extensions { public static void SetBarValue(this BaseDataObject dataObject, int barValue) { /// Cannot attach a property to BaseDataObject? dataObject.SetData("bar", barValue); } } public class TestDemo { public void CreateTest() { // this works BaseDataObject test1 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }; // this does not work - it does not compile // cannot use extension method in the initialiser block // cannot make an exension property BaseDataObject test2 = new BaseDataObject { SomeValue = 3, SomeOtherValue = 4, SetBarValue(5) }; } } ``` One of the answers (from mattlant) suggests using a fluent interface style extension method. e.g.: ``` // fluent interface style public static BaseDataObject SetBarValueWithReturn(this BaseDataObject dataObject, int barValue) { dataObject.SetData("bar", barValue); return dataObject; } // this works BaseDataObject test3 = (new BaseDataObject { SomeValue = 3, SomeOtherValue = 4 }).SetBarValueWithReturn(5); ``` But will this work in a LINQ query?
Even better: ``` public static T SetBarValue<T>(this T dataObject, int barValue) where T : BaseDataObject { dataObject.SetData("bar", barValue); return dataObject; } ``` and you can use this extension method for derived types of BaseDataObject to chain methods without casts and preserve the real type when inferred into a var field or anonymous type.