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
128,305
<p>How to tag images in the image itself in a web page? </p> <p>I know <a href="http://www.taggify.net/" rel="nofollow noreferrer">Taggify</a>, but... is there other options?</p> <p><a href="http://en.blog.orkut.com/2008/06/tag-thats-me.html" rel="nofollow noreferrer">Orkut</a> also does it to tag people faces... How is it done?</p> <p>Anyone knows any public framework that is able to do it?</p> <p>See a sample bellow from Taggify:</p> <p><img src="https://i.stack.imgur.com/gT1zq.jpg" alt="alt text" title="Taggify Sample&quot;"></p>
[ { "answer_id": 128518, "author": "Luke Foust", "author_id": 646, "author_profile": "https://Stackoverflow.com/users/646", "pm_score": 2, "selected": false, "text": "<p>I know this isn't javascript but C# 3.0 has an API for doing this. The <strong>System.Windows.Media.Imaging</strong> namespace has a class called <strong>BitmapMetadata</strong> which can be used to read and write image metadata (which is stored in the image itself). Here is a method for retrieving the metadata for an image given a file path:</p>\n\n<pre><code>public static BitmapMetadata GetMetaData(string path)\n{\n using (Stream s = new System.IO.FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))\n {\n var decoder = BitmapDecoder.Create(s, BitmapCreateOptions.None, BitmapCacheOption.OnDemand);\n var frame = decoder.Frames.FirstOrDefault();\n if (frame != null)\n {\n return frame.Metadata as BitmapMetadata;\n }\n return null;\n }\n}\n</code></pre>\n\n<p>The BitmapMetadata class has a property for tags as well as other common image metadata. To save metadata back to the image, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.inplacebitmapmetadatawriter.aspx\" rel=\"nofollow noreferrer\">InPlaceBitmapMetadataWriter Class</a>.</p>\n" }, { "answer_id": 128581, "author": "Rui Curado", "author_id": 15970, "author_profile": "https://Stackoverflow.com/users/15970", "pm_score": 1, "selected": false, "text": "<p>You can check out Image.InfoCards (IIC) at <a href=\"http://www.imageinfocards.com\" rel=\"nofollow noreferrer\">http://www.imageinfocards.com</a> . With the IIC meta-data utilities you can add meta-data in very user-friendly groups called \"cards\".</p>\n\n<p>The supplied utilities (including a Java applet) allow you to tag GIF's, JPEG's and PNG's without changing them visually.</p>\n\n<p>IIC is presently proprietary but there are plans to make it an open protocol in Q1 2009.</p>\n\n<p>The difference between IIC and others like IPTC/DIG35/DublinCore/etc is that it is much more consumer-centric and doesn't require a CS degree to understand and use it...</p>\n" }, { "answer_id": 152681, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 2, "selected": false, "text": "<p>There's a map tag in HTML that could be used in conjunction with Javascript to 'tag' different parts of an image.</p>\n\n<p>You can see the details <a href=\"http://www.w3schools.com/TAGS/tag_map.asp\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 1290362, "author": "Xidobix", "author_id": 153445, "author_profile": "https://Stackoverflow.com/users/153445", "pm_score": 2, "selected": false, "text": "<p>I will re-activate this question and help a bit. Currently the only thing i have found about is <a href=\"http://www.sanisoft.com/downloads/imgnotes-0.2/example.html\" rel=\"nofollow noreferrer\">http://www.sanisoft.com/downloads/imgnotes-0.2/example.html</a> . A jQuery tagging implementation. If anyone knows about another way please tell us.</p>\n\n<p>;)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
How to tag images in the image itself in a web page? I know [Taggify](http://www.taggify.net/), but... is there other options? [Orkut](http://en.blog.orkut.com/2008/06/tag-thats-me.html) also does it to tag people faces... How is it done? Anyone knows any public framework that is able to do it? See a sample bellow from Taggify: ![alt text](https://i.stack.imgur.com/gT1zq.jpg "Taggify Sample\"")
I know this isn't javascript but C# 3.0 has an API for doing this. The **System.Windows.Media.Imaging** namespace has a class called **BitmapMetadata** which can be used to read and write image metadata (which is stored in the image itself). Here is a method for retrieving the metadata for an image given a file path: ``` public static BitmapMetadata GetMetaData(string path) { using (Stream s = new System.IO.FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { var decoder = BitmapDecoder.Create(s, BitmapCreateOptions.None, BitmapCacheOption.OnDemand); var frame = decoder.Frames.FirstOrDefault(); if (frame != null) { return frame.Metadata as BitmapMetadata; } return null; } } ``` The BitmapMetadata class has a property for tags as well as other common image metadata. To save metadata back to the image, you can use the [InPlaceBitmapMetadataWriter Class](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.inplacebitmapmetadatawriter.aspx).
128,342
<p>For a project of mine I would love to provide auto completion for a specific textarea. Similar to how intellisense/omnicomplete works. For that however I have to find out the absolute cursor position so that I know where the DIV should appear.</p> <p>Turns out: that's (nearly I hope) impossible to achieve. Does anyone has some neat ideas how to solve that problem?</p>
[ { "answer_id": 128461, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://web.archive.org/web/20201022015103/http://geekswithblogs.net/svanvliet/archive/2005/03/24/textarea-cursor-position-with-javascript.aspx\" rel=\"nofollow noreferrer\">This</a> blog post seems to address your question, but unfortunately the author admits he has only tested it in IE 6.</p>\n<blockquote>\n<p>The DOM in IE does not provide information regarding relative position in terms of characters; however, it does provide bounding and offset values for browser-rendered controls. Thus, I used these values to determine the relative bounds of a character. Then, using the JavaScript TextRange, I created a mechanism for working with such measures to calculate the Line and Column position for fixed-width fonts within a given TextArea.</p>\n</blockquote>\n<blockquote>\n<p>First, the relative bounds for the TextArea must be calculated based upon the size of the fixed-width font used. To do this, the original value of the TextArea must be stored in a local JavaScript variable and clear the value. Then, a TextRange is created to determine the Top and Left bounds of the TextArea.</p>\n</blockquote>\n" }, { "answer_id": 163395, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 5, "selected": false, "text": "<p><strong>Version 2 of My Hacky Experiment</strong></p>\n\n<p><em>This new version works with any font, which can be adjusted on demand, and any textarea size.</em></p>\n\n<p>After noticing that some of you are still trying to get this to work, I decided to try a new approach. My results are FAR better this time around - at least on google chrome on linux. I no longer have a windows PC available to me, so I can only test on chrome / firefox on Ubuntu. My results work 100% consistently on Chrome, and let's say somewhere around 70 - 80% on Firefox, but I don't imagine it would be incredibly difficult to find the inconsistencies.</p>\n\n<p>This new version relies on a Canvas object. In my <a href=\"http://enobrev.info/cursor2/\" rel=\"nofollow noreferrer\">example</a>, I actually show that very canvas - just so you can see it in action, but it could very easily be done with a hidden canvas object.</p>\n\n<p>This is most certainly a hack, and I apologize ahead of time for my rather thrown together code. At the very least, in google chrome, it works consistently, no matter what font I set it to, or size of textarea. I used <a href=\"https://stackoverflow.com/users/17174/sam-saffron\">Sam Saffron</a>'s example to show cursor coordinates (a gray-background div). I also added a \"Randomize\" link, so you can see it work in different font / texarea sizes and styles, and watch the cursor position update on the fly. I recommend looking at <a href=\"http://enobrev.info/cursor2/\" rel=\"nofollow noreferrer\">the full page demo</a> so you can better see the companion canvas play along.</p>\n\n<p><em>I'll summarize how it works</em>...</p>\n\n<p>The underlying idea is that we're trying to redraw the textarea on a canvas, as closely as possible. Since the browser uses the same font engine for both and texarea, we can use canvas's font measurement functionality to figure out where things are. From there, we can use the canvas methods available to us to figure out our coordinates.</p>\n\n<p>First and foremost, we adjust our canvas to match the dimensions of the textarea. This is entirely for visual purposes since the canvas size doesn't really make a difference in our outcome. Since Canvas doesn't actually provide a means of word wrap, I had to conjure (steal / borrow / munge together) a means of breaking up lines to as-best-as-possible match the textarea. This is where you'll likely find you need to do the most cross-browser tweaking.</p>\n\n<p>After word wrap, everything else is basic math. We split the lines into an array to mimic the word wrap, and now we want to loop through those lines and go all the way down until the point where our current selection ends. In order to do that, we're just counting characters and once we surpass <code>selection.end</code>, we know we have gone down far enough. Multiply the line count up until that point with the line-height and you have a <code>y</code> coordinate. </p>\n\n<p>The <code>x</code> coordinate is very similar, except we're using <code>context.measureText</code>. As long as we're printing out the right number of characters, that will give us the width of the line that's being drawn to Canvas, which happens to end after the last character written out, which is the character before the currentl <code>selection.end</code> position.</p>\n\n<p>When trying to debug this for other browsers, the thing to look for is where the lines don't break properly. You'll see in some places that the last word on a line in canvas may have wrapped over on the textarea or vice-versa. This has to do with how the browser handles word wraps. As long as you get the wrapping in the canvas to match the textarea, your cursor should be correct.</p>\n\n<p>I'll paste the source below. You should be able to copy and paste it, but if you do, I ask that you download your own copy of jquery-fieldselection instead of hitting the one on my server. </p>\n\n<p>I've also upped <a href=\"http://enobrev.info/cursor2/\" rel=\"nofollow noreferrer\">a new demo</a> as well as <a href=\"http://jsfiddle.net/9QAtz/\" rel=\"nofollow noreferrer\">a fiddle</a>.</p>\n\n<p>Good luck!</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en-US\"&gt;\n &lt;head&gt;\n &lt;meta charset=\"utf-8\" /&gt;\n &lt;title&gt;Tooltip 2&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\" src=\"http://enobrev.info/cursor/js/jquery-fieldselection.js\"&gt;&lt;/script&gt;\n &lt;style type=\"text/css\"&gt;\n form {\n float: left;\n margin: 20px;\n }\n\n #textariffic {\n height: 400px;\n width: 300px;\n font-size: 12px;\n font-family: 'Arial';\n line-height: 12px;\n }\n\n #tip {\n width:5px;\n height:30px;\n background-color: #777;\n position: absolute;\n z-index:10000\n }\n\n #mock-text {\n float: left;\n margin: 20px;\n border: 1px inset #ccc;\n }\n\n /* way the hell off screen */\n .scrollbar-measure {\n width: 100px;\n height: 100px;\n overflow: scroll;\n position: absolute;\n top: -9999px;\n }\n\n #randomize {\n float: left;\n display: block;\n }\n &lt;/style&gt;\n &lt;script type=\"text/javascript\"&gt;\n var oCanvas;\n var oTextArea;\n var $oTextArea;\n var iScrollWidth;\n\n $(function() {\n iScrollWidth = scrollMeasure();\n oCanvas = document.getElementById('mock-text');\n oTextArea = document.getElementById('textariffic');\n $oTextArea = $(oTextArea);\n\n $oTextArea\n .keyup(update)\n .mouseup(update)\n .scroll(update);\n\n $('#randomize').bind('click', randomize);\n\n update();\n });\n\n function randomize() {\n var aFonts = ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Impact', 'Times New Roman', 'Verdana', 'Webdings'];\n var iFont = Math.floor(Math.random() * aFonts.length);\n var iWidth = Math.floor(Math.random() * 500) + 300;\n var iHeight = Math.floor(Math.random() * 500) + 300;\n var iFontSize = Math.floor(Math.random() * 18) + 10;\n var iLineHeight = Math.floor(Math.random() * 18) + 10;\n\n var oCSS = {\n 'font-family': aFonts[iFont],\n width: iWidth + 'px',\n height: iHeight + 'px',\n 'font-size': iFontSize + 'px',\n 'line-height': iLineHeight + 'px'\n };\n\n console.log(oCSS);\n\n $oTextArea.css(oCSS);\n\n update();\n return false;\n }\n\n function showTip(x, y) {\n $('#tip').css({\n left: x + 'px',\n top: y + 'px'\n });\n }\n\n // https://stackoverflow.com/a/11124580/14651\n // https://stackoverflow.com/a/3960916/14651\n\n function wordWrap(oContext, text, maxWidth) {\n var aSplit = text.split(' ');\n var aLines = [];\n var sLine = \"\";\n\n // Split words by newlines\n var aWords = [];\n for (var i in aSplit) {\n var aWord = aSplit[i].split('\\n');\n if (aWord.length &gt; 1) {\n for (var j in aWord) {\n aWords.push(aWord[j]);\n aWords.push(\"\\n\");\n }\n\n aWords.pop();\n } else {\n aWords.push(aSplit[i]);\n }\n }\n\n while (aWords.length &gt; 0) {\n var sWord = aWords[0];\n if (sWord == \"\\n\") {\n aLines.push(sLine);\n aWords.shift();\n sLine = \"\";\n } else {\n // Break up work longer than max width\n var iItemWidth = oContext.measureText(sWord).width;\n if (iItemWidth &gt; maxWidth) {\n var sContinuous = '';\n var iWidth = 0;\n while (iWidth &lt;= maxWidth) {\n var sNextLetter = sWord.substring(0, 1);\n var iNextWidth = oContext.measureText(sContinuous + sNextLetter).width;\n if (iNextWidth &lt;= maxWidth) {\n sContinuous += sNextLetter;\n sWord = sWord.substring(1);\n }\n iWidth = iNextWidth;\n }\n aWords.unshift(sContinuous);\n }\n\n // Extra space after word for mozilla and ie\n var sWithSpace = (jQuery.browser.mozilla || jQuery.browser.msie) ? ' ' : '';\n var iNewLineWidth = oContext.measureText(sLine + sWord + sWithSpace).width;\n if (iNewLineWidth &lt;= maxWidth) { // word fits on current line to add it and carry on\n sLine += aWords.shift() + \" \";\n } else {\n aLines.push(sLine);\n sLine = \"\";\n }\n\n if (aWords.length === 0) {\n aLines.push(sLine);\n }\n }\n }\n return aLines;\n }\n\n // http://davidwalsh.name/detect-scrollbar-width\n function scrollMeasure() {\n // Create the measurement node\n var scrollDiv = document.createElement(\"div\");\n scrollDiv.className = \"scrollbar-measure\";\n document.body.appendChild(scrollDiv);\n\n // Get the scrollbar width\n var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n\n // Delete the DIV\n document.body.removeChild(scrollDiv);\n\n return scrollbarWidth;\n }\n\n function update() {\n var oPosition = $oTextArea.position();\n var sContent = $oTextArea.val();\n var oSelection = $oTextArea.getSelection();\n\n oCanvas.width = $oTextArea.width();\n oCanvas.height = $oTextArea.height();\n\n var oContext = oCanvas.getContext(\"2d\");\n var sFontSize = $oTextArea.css('font-size');\n var sLineHeight = $oTextArea.css('line-height');\n var fontSize = parseFloat(sFontSize.replace(/[^0-9.]/g, ''));\n var lineHeight = parseFloat(sLineHeight.replace(/[^0-9.]/g, ''));\n var sFont = [$oTextArea.css('font-weight'), sFontSize + '/' + sLineHeight, $oTextArea.css('font-family')].join(' ');\n\n var iSubtractScrollWidth = oTextArea.clientHeight &lt; oTextArea.scrollHeight ? iScrollWidth : 0;\n\n oContext.save();\n oContext.clearRect(0, 0, oCanvas.width, oCanvas.height);\n oContext.font = sFont;\n var aLines = wordWrap(oContext, sContent, oCanvas.width - iSubtractScrollWidth);\n\n var x = 0;\n var y = 0;\n var iGoal = oSelection.end;\n aLines.forEach(function(sLine, i) {\n if (iGoal &gt; 0) {\n oContext.fillText(sLine.substring(0, iGoal), 0, (i + 1) * lineHeight);\n\n x = oContext.measureText(sLine.substring(0, iGoal + 1)).width;\n y = i * lineHeight - oTextArea.scrollTop;\n\n var iLineLength = sLine.length;\n if (iLineLength == 0) {\n iLineLength = 1;\n }\n\n iGoal -= iLineLength;\n } else {\n // after\n }\n });\n oContext.restore();\n\n showTip(oPosition.left + x, oPosition.top + y);\n }\n\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n\n &lt;a href=\"#\" id=\"randomize\"&gt;Randomize&lt;/a&gt;\n\n &lt;form id=\"tipper\"&gt;\n &lt;textarea id=\"textariffic\"&gt;Aliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi.\n\nPhasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus.\n\nSed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus.&lt;/textarea&gt;\n\n &lt;/form&gt;\n\n &lt;div id=\"tip\"&gt;&lt;/div&gt;\n\n &lt;canvas id=\"mock-text\"&gt;&lt;/canvas&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p><strong>Bug</strong></p>\n\n<p><em>There's one bug I do recall. If you put the cursor before the first letter on a line, it shows the \"position\" as the last letter on the previous line. This has to do with how selection.end work. I don't think it should be too difficult to look for that case and fix it accordingly.</em></p>\n\n<hr>\n\n<p><strong>Version 1</strong></p>\n\n<p><em>Leaving this here so you can see the progress without having to dig through the edit history.</em></p>\n\n<p>It's not perfect and it's most Definitely a hack, but I got it to work pretty well on WinXP IE, FF, Safari, Chrome and Opera.</p>\n\n<p>As far as I can tell there's no way to directly find out the x/y of a cursor on any browser. The <a href=\"http://weblogs.asp.net/skillet/archive/2005/03/24/395838.aspx\" rel=\"nofollow noreferrer\">IE method</a>, <a href=\"https://stackoverflow.com/questions/128342/display-div-at-cursor-position-in-textarea#128461\">mentioned</a> by <a href=\"https://stackoverflow.com/users/21632/adam-bellaire\">Adam Bellaire</a> is interesting, but unfortunately not cross-browser. I figured the next best thing would be to use the characters as a grid.</p>\n\n<p>Unfortunately there's no font metric information built into any of the browsers, which means a monospace font is the only font type that's going to have a consistent measurement. Also, there's no reliable means of figuring out a font-width from the font-height. At first I'd tried using a percentage of the height, which worked great. Then I changed the font-size and everything went to hell. </p>\n\n<p>I tried one method to figure out character width, which was to create a temporary textarea and keep adding characters until the scrollHeight (or scrollWidth) changed. It seems plausable, but about halfway down that road, I realized I could just use the cols attribute on the textarea and figured there are enough hacks in this ordeal to add another one. This means you can't set the width of the textarea via css. You HAVE to use the cols for this to work.</p>\n\n<p>The next problem I ran into is that, even when you set the font via css, the browsers report the font differently. When you don't set a font, mozilla uses <code>monospace</code> by default, IE uses <code>Courier New</code>, Opera <code>\"Courier New\"</code> (with quotes), Safari, <code>'Lucida Grand'</code> (with single quotes). When you do set the font to <code>monospace</code>, mozilla and ie take what you give them, Safari comes out as <code>-webkit-monospace</code> and Opera stays with <code>\"Courier New\"</code>.</p>\n\n<p>So now we initialize some vars. Make sure to set your line height in the css as well. Firefox reports the correct line height, but IE was reporting \"normal\" and I didn't bother with the other browsers. I just set the line height in my css and that resolved the difference. I haven't tested with using ems instead of pixels. Char height is just font size. Should probably pre-set that in your css as well.</p>\n\n<p>Also, one more pre-setting before we start placing characters - which really had me scratching my head. For ie and mozilla, texarea chars are &lt; cols, everything else is &lt;= chars. So Chrome can fit 50 chars across, but mozilla and ie would break the last word off the line.</p>\n\n<p>Now we're going to create an array of first-character positions for every line. We loop through every char in the textarea. If it's a newline, we add a new position to our line array. If it's a space, we try to figure out if the current \"word\" will fit on the line we're on or if it's going to get pushed to the next line. Punctuation counts as a part of the \"word\". I haven't tested with tabs, but there's a line there for adding 4 chars for a tab char.</p>\n\n<p>Once we have an array of line positions, we loop through and try to find which line the cursor is on. We're using hte \"End\" of the selection as our cursor.</p>\n\n<p>x = (cursor position - first character position of cursor line) * character width</p>\n\n<p>y = ((cursor line + 1) * line height) - scroll position</p>\n\n<p>I'm using <a href=\"http://docs.jquery.com/Downloading_jQuery\" rel=\"nofollow noreferrer\">jquery 1.2.6</a>, <a href=\"http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html\" rel=\"nofollow noreferrer\">jquery-fieldselection</a>, and <a href=\"http://plugins.jquery.com/project/dimensions\" rel=\"nofollow noreferrer\">jquery-dimensions</a></p>\n\n<p>The Demo: <a href=\"http://enobrev.info/cursor/\" rel=\"nofollow noreferrer\">http://enobrev.info/cursor/</a></p>\n\n<p>And the code:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" ?&gt;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /&gt;\n &lt;title&gt;Tooltip&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"js/jquery-1.2.6.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\" src=\"js/jquery-fieldselection.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\" src=\"js/jquery.dimensions.js\"&gt;&lt;/script&gt;\n &lt;style type=\"text/css\"&gt;\n form {\n margin: 20px auto;\n width: 500px;\n }\n\n #textariffic {\n height: 400px;\n font-size: 12px;\n font-family: monospace;\n line-height: 15px;\n }\n\n #tip {\n position: absolute;\n z-index: 2;\n padding: 20px;\n border: 1px solid #000;\n background-color: #FFF;\n }\n &lt;/style&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(function() {\n $('textarea')\n .keyup(update)\n .mouseup(update)\n .scroll(update);\n });\n\n function showTip(x, y) { \n y = y + $('#tip').height();\n\n $('#tip').css({\n left: x + 'px',\n top: y + 'px'\n });\n }\n\n function update() {\n var oPosition = $(this).position();\n var sContent = $(this).val();\n\n var bGTE = jQuery.browser.mozilla || jQuery.browser.msie;\n\n if ($(this).css('font-family') == 'monospace' // mozilla\n || $(this).css('font-family') == '-webkit-monospace' // Safari\n || $(this).css('font-family') == '\"Courier New\"') { // Opera\n var lineHeight = $(this).css('line-height').replace(/[^0-9]/g, '');\n lineHeight = parseFloat(lineHeight);\n var charsPerLine = this.cols;\n var charWidth = parseFloat($(this).innerWidth() / charsPerLine);\n\n\n var iChar = 0;\n var iLines = 1;\n var sWord = '';\n\n var oSelection = $(this).getSelection();\n var aLetters = sContent.split(\"\");\n var aLines = [];\n\n for (var w in aLetters) {\n if (aLetters[w] == \"\\n\") {\n iChar = 0;\n aLines.push(w);\n sWord = '';\n } else if (aLetters[w] == \" \") { \n var wordLength = parseInt(sWord.length);\n\n\n if ((bGTE &amp;&amp; iChar + wordLength &gt;= charsPerLine)\n || (!bGTE &amp;&amp; iChar + wordLength &gt; charsPerLine)) {\n iChar = wordLength + 1;\n aLines.push(w - wordLength);\n } else { \n iChar += wordLength + 1; // 1 more char for the space\n }\n\n sWord = '';\n } else if (aLetters[w] == \"\\t\") {\n iChar += 4;\n } else {\n sWord += aLetters[w]; \n }\n }\n\n var iLine = 1;\n for(var i in aLines) {\n if (oSelection.end &lt; aLines[i]) {\n iLine = parseInt(i) - 1;\n break;\n }\n }\n\n if (iLine &gt; -1) {\n var x = parseInt(oSelection.end - aLines[iLine]) * charWidth;\n } else {\n var x = parseInt(oSelection.end) * charWidth;\n }\n var y = (iLine + 1) * lineHeight - this.scrollTop; // below line\n\n showTip(oPosition.left + x, oPosition.top + y);\n }\n }\n\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form id=\"tipper\"&gt;\n &lt;textarea id=\"textariffic\" cols=\"50\"&gt;\nAliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi.\n\nPhasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus.\n\nSed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus. \n &lt;/textarea&gt;\n\n &lt;/form&gt;\n\n &lt;p id=\"tip\"&gt;Here I Am!!&lt;/p&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 2290719, "author": "prike", "author_id": 276322, "author_profile": "https://Stackoverflow.com/users/276322", "pm_score": 2, "selected": false, "text": "<p>I posted a topic related to this problem on a Russian JavaScript site.</p>\n\n<p>If you don't understand Russian try translated by Google version: <a href=\"http://translate.google.ru/translate?js=y&amp;prev=_t&amp;hl=ru&amp;ie=UTF-8&amp;layout=1&amp;eotf=1&amp;u=http://javascript.ru/forum/events/7771-poluchit-koordinaty-kursora-v-tekstovom-pole-v-pikselyakh.html&amp;sl=ru&amp;tl=en\" rel=\"nofollow noreferrer\">http://translate.google.ru/translate?js=y&amp;prev=_t&amp;hl=ru&amp;ie=UTF-8&amp;layout=1&amp;eotf=1&amp;u=http://javascript.ru/forum/events/7771-poluchit-koordinaty-kursora-v-tekstovom-pole-v-pikselyakh.html&amp;sl=ru&amp;tl=en</a></p>\n\n<p>Thre is some markup issues in the code examples in translated version so you can <a href=\"http://javascript.ru/forum/events/7771-poluchit-koordinaty-kursora-v-tekstovom-pole-v-pikselyakh.html&amp;sl=ru&amp;tl=en\" rel=\"nofollow noreferrer\">read the code in the original Russian post</a>.</p>\n\n<p>The idea is simple. There is no easy, universal and cross-browser method to get cursor position in pixels. Frankly speaking there is, but only for Internet Explorer. </p>\n\n<p>In other browsers if you do really need to calculate it you have to ...</p>\n\n<ul>\n<li>create an invisible DIV</li>\n<li>copy all styles and content of the text box into that DIV</li>\n<li>then insert HTML element at exactly the same position in text where the caret is in the text box </li>\n<li>get coordinates of that HTML element</li>\n</ul>\n" }, { "answer_id": 13058306, "author": "snoopy-do", "author_id": 66845, "author_profile": "https://Stackoverflow.com/users/66845", "pm_score": 1, "selected": false, "text": "<p>This <a href=\"http://kirblog.idetalk.com/2010/03/calculating-cursor-position-in-textarea.html\" rel=\"nofollow\">blog</a> appears to be close too answering the question. I haven't tried it my self, but author says its tested with FF3, Chrome, IE, Opera, Safari. Code is on <a href=\"https://github.com/kir/js_cursor_position\" rel=\"nofollow\">GitHub</a></p>\n" }, { "answer_id": 13079085, "author": "Halcyon", "author_id": 722762, "author_profile": "https://Stackoverflow.com/users/722762", "pm_score": 0, "selected": false, "text": "<p>I don't know a solution for <code>textarea</code> but it sure works for a <code>div</code> with <strong><code>contenteditable</code></strong>.</p>\n\n<p>You can use the <code>Range</code> API. Like so: (yes, you really only need just these 3 lines of code)</p>\n\n<pre><code>// get active selection\nvar selection = window.getSelection();\n// get the range (you might want to check selection.rangeCount\n// to see if it's popuplated)\nvar range = selection.getRangeAt(0);\n\n// will give you top, left, width, height\nconsole.log(range.getBoundingClientRect());\n</code></pre>\n\n<p>I'm not sure about browser compatibility but I've found it works in the latest Chrome, Firefox and even IE7 (I think I tested 7, otherwise it was 9).</p>\n\n<p>You can even do 'crazy' things like this: if you're typing <code>\"#hash\"</code> and the cursor is at the last <code>h</code>, you can look in the current range for the <code>#</code> character, move the range back by <code>n</code> characters and get the <em>bounding-rect</em> of that range, this will make the popup-div seem to 'stick' to the word.</p>\n\n<p>One minor drawback is that <code>contenteditable</code> can be a bit buggy sometimes. The cursor likes to go to impossible places and you now have to deal with HTML input. But I'm sure browser vendors will address these problems are more sites starting using them.</p>\n\n<p>Another tip I can give is: look at the <a href=\"http://code.google.com/p/rangy/\" rel=\"nofollow\"><code>rangy</code></a> library. It attempts to be a fully featured cross-compatible range library. You don't <em>need</em> it, but if you're dealing with old browsers it might be worth you while.</p>\n" }, { "answer_id": 13083337, "author": "Ma Jerez", "author_id": 1316510, "author_profile": "https://Stackoverflow.com/users/1316510", "pm_score": 2, "selected": false, "text": "<p><strong>I won't explain the problems related to this stuff again because they are well explained in other posts. Just will point a possible solution, it has some bug but it's a starting point.</strong> </p>\n\n<p>Fortunately there is a scrip on Github to calculate the caret position relative to it's container, but it requires jQuery. <strong>GitHub page here: <a href=\"https://github.com/beviz/jquery-caret-position-getter\" rel=\"nofollow\">jquery-caret-position-getter,</a></strong> Thanxs to Bevis.Zhao.</p>\n\n<p>Based on it I have implemented the next code: <strong>check it in action <a href=\"http://jsfiddle.net/mjerez/kBY75/\" rel=\"nofollow\">here in jsFiddle.net</a></strong></p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;\n &lt;meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"&gt;\n &lt;title&gt;- jsFiddle demo by mjerez&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.8.2.js\"&gt;&lt;/script&gt;\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"http://jsfiddle.net/css/normalize.css\"&gt;\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"http://jsfiddle.net/css/result-light.css\"&gt; \n &lt;script type=\"text/javascript\" src=\"https://raw.github.com/beviz/jquery-caret-position-getter/master/jquery.caretposition.js\"&gt;&lt;/script&gt; \n &lt;style type=\"text/css\"&gt;\n body{position:relative;font:normal 100% Verdana, Geneva, sans-serif;padding:10px;}\n .aux{background:#ccc;opacity: 0.5;width:50%;padding:5px;border:solid 1px #aaa;}\n .hidden{display:none}\n .show{display:block; position:absolute; top:0px; left:0px;}\n &lt;/style&gt;\n &lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[ \n $(document).keypress(function(e) {\n if ($(e.target).is('input, textarea')) {\n var key = String.fromCharCode(e.which);\n var ctrl = e.ctrlKey;\n if (ctrl) {\n var display = $(\"#autocomplete\");\n var editArea = $('#editArea'); \n var pos = editArea.getCaretPosition();\n var offset = editArea.offset();\n // now you can use left, top(they are relative position)\n display.css({\n left: offset.left + pos.left,\n top: offset.top + pos.top,\n color : \"#449\"\n })\n display.toggleClass(\"show\");\n return false;\n }\n }\n\n });\n window.onload = (function() {\n $(\"#editArea\").blur(function() {\n if ($(\"#autocomplete\").hasClass(\"show\")) $(\"#autocomplete\").toggleClass(\"show\");\n })\n });\n //]]&gt; \n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;p&gt;Click ctrl+space to while you write to diplay the autocmplete pannel.&lt;/p&gt;\n &lt;/br&gt;\n &lt;textarea id=\"editArea\" rows=\"4\" cols=\"50\"&gt;&lt;/textarea&gt;\n &lt;/br&gt;\n &lt;/br&gt;\n &lt;/br&gt;\n &lt;div id=\"autocomplete\" class=\"aux hidden \"&gt;\n &lt;ol&gt;\n &lt;li&gt;Option a&lt;/li&gt;\n &lt;li&gt;Option b&lt;/li&gt;\n &lt;li&gt;Option c&lt;/li&gt;\n &lt;li&gt;Option d&lt;/li&gt;\n &lt;/ol&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 13104080, "author": "lrsjng", "author_id": 1184032, "author_profile": "https://Stackoverflow.com/users/1184032", "pm_score": 1, "selected": false, "text": "<p>fixed it here: <a href=\"http://jsfiddle.net/eMwKd/4/\" rel=\"nofollow\">http://jsfiddle.net/eMwKd/4/</a></p>\n\n<p>only downside is that the already provided function <code>getCaret()</code> resolves to the wrong position on key down. therefor the red cursor seems to be behind the real cursor unless you release the key.</p>\n\n<p>I will have another look into it.</p>\n\n<p>update: hm, word-wrapping is not accurate if lines too long..</p>\n" }, { "answer_id": 13111593, "author": "echo_Me", "author_id": 998158, "author_profile": "https://Stackoverflow.com/users/998158", "pm_score": 0, "selected": false, "text": "<p>maybe this will please you , it will tell the position of selection and the positition of the cursor so try to check the timer to get automatic position or uncheck to get position by clicking on Get Selection button</p>\n\n<pre><code> &lt;form&gt;\n &lt;p&gt;\n &lt;input type=\"button\" onclick=\"evalOnce();\" value=\"Get Selection\"&gt;\ntimer:\n&lt;input id=\"eval_switch\" type=\"checkbox\" onclick=\"evalSwitchClicked(this)\"&gt;\n&lt;input id=\"eval_time\" type=\"text\" value=\"200\" size=\"6\"&gt;\nms\n&lt;/p&gt;\n&lt;textarea id=\"code\" cols=\"50\" rows=\"20\"&gt;01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 Sample text area. Please select above text. &lt;/textarea&gt;\n&lt;textarea id=\"out\" cols=\"50\" rows=\"20\"&gt;&lt;/textarea&gt;\n&lt;/form&gt;\n&lt;div id=\"test\"&gt;&lt;/div&gt;\n&lt;script&gt;\n\nfunction Selection(textareaElement) {\nthis.element = textareaElement;\n}\nSelection.prototype.create = function() {\nif (document.selection != null &amp;&amp; this.element.selectionStart == null) {\nreturn this._ieGetSelection();\n} else {\nreturn this._mozillaGetSelection();\n}\n}\nSelection.prototype._mozillaGetSelection = function() {\nreturn {\nstart: this.element.selectionStart,\nend: this.element.selectionEnd\n };\n }\nSelection.prototype._ieGetSelection = function() {\nthis.element.focus();\nvar range = document.selection.createRange();\nvar bookmark = range.getBookmark();\nvar contents = this.element.value;\nvar originalContents = contents;\nvar marker = this._createSelectionMarker();\nwhile(contents.indexOf(marker) != -1) {\nmarker = this._createSelectionMarker();\n }\nvar parent = range.parentElement();\nif (parent == null || parent.type != \"textarea\") {\nreturn { start: 0, end: 0 };\n}\nrange.text = marker + range.text + marker;\ncontents = this.element.value;\nvar result = {};\nresult.start = contents.indexOf(marker);\ncontents = contents.replace(marker, \"\");\nresult.end = contents.indexOf(marker);\nthis.element.value = originalContents;\nrange.moveToBookmark(bookmark);\nrange.select();\nreturn result;\n}\nSelection.prototype._createSelectionMarker = function() {\nreturn \"##SELECTION_MARKER_\" + Math.random() + \"##\";\n}\n\nvar timer;\nvar buffer = \"\";\nfunction evalSwitchClicked(e) {\nif (e.checked) {\nevalStart();\n} else {\nevalStop();\n}\n}\nfunction evalStart() {\nvar o = document.getElementById(\"eval_time\");\ntimer = setTimeout(timerHandler, o.value);\n}\nfunction evalStop() {\nclearTimeout(timer);\n}\nfunction timerHandler() {\nclearTimeout(timer);\nvar sw = document.getElementById(\"eval_switch\");\nif (sw.checked) {\nevalOnce();\nevalStart();\n}\n}\nfunction evalOnce() {\ntry {\nvar selection = new Selection(document.getElementById(\"code\"));\nvar s = selection.create();\nvar result = s.start + \":\" + s.end;\nbuffer += result;\nflush();\n } catch (ex) {\nbuffer = ex;\nflush();\n}\n}\nfunction getCode() {\n// var s.create()\n// return document.getElementById(\"code\").value;\n}\nfunction clear() {\nvar out = document.getElementById(\"out\");\nout.value = \"\";\n}\nfunction print(str) {\nbuffer += str + \"\\n\";\n}\nfunction flush() {\nvar out = document.getElementById(\"out\");\nout.value = buffer;\nbuffer = \"\";\n } \n&lt;/script&gt;\n</code></pre>\n\n<p>look the demo here : <a href=\"http://jsbin.com/obekot/2/edit\" rel=\"nofollow\">jsbin.com</a></p>\n" }, { "answer_id": 13146099, "author": "Andrey Sbrodov", "author_id": 1648497, "author_profile": "https://Stackoverflow.com/users/1648497", "pm_score": 0, "selected": false, "text": "<p>There is description of one hack for caret offset:\n<a href=\"https://stackoverflow.com/questions/3510009/textarea-caret-coordinates-jquery\">Textarea X/Y caret coordinates - jQuery plugin</a></p>\n\n<p>Also it will be better to use div element with <code>contenteditable</code> attribute if you can use html5 features.</p>\n" }, { "answer_id": 13151607, "author": "Satyajit", "author_id": 168762, "author_profile": "https://Stackoverflow.com/users/168762", "pm_score": -1, "selected": false, "text": "<p>How about appending a span element to the cloning div and setting the fake cursor based on this span's offsets? I have updated your fiddle <a href=\"http://jsfiddle.net/2Rzfb/2/\" rel=\"nofollow noreferrer\">here</a>. Also here's the JS bit only</p>\n<pre><code>// http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea\nvar map = [];\nvar pan = '&lt;span&gt;|&lt;/span&gt;'\n\n//found @ http://davidwalsh.name/detect-scrollbar-width\n\nfunction getScrollbarWidth() {\n var scrollDiv = document.createElement(&quot;div&quot;);\n scrollDiv.className = &quot;scrollbar-measure&quot;;\n document.body.appendChild(scrollDiv);\n\n // Get the scrollbar width\n var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n\n // Delete the DIV \n document.body.removeChild(scrollDiv);\n\n return scrollbarWidth;\n}\n\nfunction getCaret(el) {\n if (el.selectionStart) {\n return el.selectionStart;\n } else if (document.selection) {\n el.focus();\n\n var r = document.selection.createRange();\n if (r == null) {\n return 0;\n }\n\n var re = el.createTextRange(),\n rc = re.duplicate();\n re.moveToBookmark(r.getBookmark());\n rc.setEndPoint('EndToStart', re);\n\n return rc.text.length;\n }\n return 0;\n}\n\n\n$(function() {\n var span = $('#pos span');\n var textarea = $('textarea');\n\n var note = $('#note');\n\n css = getComputedStyle(document.getElementById('textarea'));\n try {\n for (i in css) note.css(css[i]) &amp;&amp; (css[i] != 'width' &amp;&amp; css[i] != 'height') &amp;&amp; note.css(css[i], css.getPropertyValue(css[i]));\n } catch (e) {}\n\n note.css('max-width', '300px');\n document.getElementById('note').style.visibility = 'hidden';\n var height = note.height();\n var fakeCursor, hidePrompt;\n\n textarea.on('keyup click', function(e) {\n if (document.getElementById('textarea').scrollHeight &gt; 100) {\n note.css('max-width', 300 - getScrollbarWidth());\n }\n\n var pos = getCaret(textarea[0]);\n\n note.text(textarea.val().substring(0, pos));\n $(pan).appendTo(note);\n span.text(pos);\n\n if (hidePrompt) {\n hidePrompt.remove();\n }\n if (fakeCursor) {\n fakeCursor.remove();\n }\n\n fakeCursor = $(&quot;&lt;div style='width:5px;height:30px;background-color: #777;position: absolute;z-index:10000'&gt;&amp;nbsp;&lt;/div&gt;&quot;);\n\n fakeCursor.css('opacity', 0.5);\n fakeCursor.css('left', $('#note span').offset().left + 'px');\n fakeCursor.css('top', textarea.offset().top + note.height() - (30 + textarea.scrollTop()) + 'px');\n\n hidePrompt = fakeCursor.clone();\n hidePrompt.css({\n 'width': '2px',\n 'background-color': 'white',\n 'z-index': '1000',\n 'opacity': '1'\n });\n\n hidePrompt.appendTo(textarea.parent());\n fakeCursor.appendTo(textarea.parent());\n\n\n\n return true;\n });\n});\n</code></pre>\n<p>​\n<strong>UPDATE</strong>: I can see that there's an error if the first line contains no hard line-breaks but if it does it seems to work well.</p>\n" }, { "answer_id": 22454744, "author": "Dan Dascalescu", "author_id": 1269037, "author_profile": "https://Stackoverflow.com/users/1269037", "pm_score": 2, "selected": false, "text": "<p>Note that this question is a duplicate of a one asked a month earlier, and I've answered it <strong><a href=\"https://stackoverflow.com/a/22446703/1269037\">here</a></strong>. I'll only maintain the answer at that link, since this question should have been closed as duplicate years ago.</p>\n\n<h3><em>Copy of the answer</em></h3>\n\n<p>I've looked for a textarea caret coordinates plugin for <a href=\"https://github.com/mizzao/meteor-autocomplete\" rel=\"nofollow noreferrer\">meteor-autocomplete</a>, so I've evaluated all the 8 plugins on GitHub. The winner is, by far, <a href=\"https://github.com/component/textarea-caret-position\" rel=\"nofollow noreferrer\">textarea-caret-position</a> from <strong>Component</strong>.</p>\n\n<h2>Features</h2>\n\n<ul>\n<li>pixel precision</li>\n<li>no dependencies whatsoever</li>\n<li>browser compatibility: Chrome, Safari, Firefox (despite <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=753662\" rel=\"nofollow noreferrer\">two</a> <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=984275\" rel=\"nofollow noreferrer\">bugs</a> it has), IE9+; may work but not tested in Opera, IE8 or older</li>\n<li>supports any font family and size, as well as text-transforms</li>\n<li>the text area can have arbitrary padding or borders</li>\n<li>not confused by horizontal or vertical scrollbars in the textarea</li>\n<li>supports hard returns, tabs (except on IE) and consecutive spaces in the text</li>\n<li>correct position on lines longer than the columns in the text area</li>\n<li>no <a href=\"https://github.com/component/textarea-caret-position/blob/06d2197f85f96405b43724e56dc56f220c0092a5/test/position_off_after_wrapping_with_whitespace_before_EOL.gif\" rel=\"nofollow noreferrer\">\"ghost\" position in the empty space</a> at the end of a line when wrapping long words</li>\n</ul>\n\n<h3>Here's a demo - <a href=\"http://jsfiddle.net/dandv/aFPA7/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/dandv/aFPA7/</a></h3>\n\n<p><img src=\"https://i.stack.imgur.com/LJiUS.png\" alt=\"enter image description here\"></p>\n\n<h2>How it works</h2>\n\n<p>A mirror <code>&lt;div&gt;</code> is created off-screen and styled exactly like the <code>&lt;textarea&gt;</code>. Then, the text of the textarea up to the caret is copied into the div and a <code>&lt;span&gt;</code> is inserted right after it. Then, the text content of the span is set to the remainder of the text in the textarea, in order to faithfully reproduce the wrapping in the faux div.</p>\n\n<p>This is the only method guaranteed to handle all the edge cases pertaining to wrapping long lines. It's also used by GitHub to determine the position of its <strong>@</strong> user dropdown.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19990/" ]
For a project of mine I would love to provide auto completion for a specific textarea. Similar to how intellisense/omnicomplete works. For that however I have to find out the absolute cursor position so that I know where the DIV should appear. Turns out: that's (nearly I hope) impossible to achieve. Does anyone has some neat ideas how to solve that problem?
**Version 2 of My Hacky Experiment** *This new version works with any font, which can be adjusted on demand, and any textarea size.* After noticing that some of you are still trying to get this to work, I decided to try a new approach. My results are FAR better this time around - at least on google chrome on linux. I no longer have a windows PC available to me, so I can only test on chrome / firefox on Ubuntu. My results work 100% consistently on Chrome, and let's say somewhere around 70 - 80% on Firefox, but I don't imagine it would be incredibly difficult to find the inconsistencies. This new version relies on a Canvas object. In my [example](http://enobrev.info/cursor2/), I actually show that very canvas - just so you can see it in action, but it could very easily be done with a hidden canvas object. This is most certainly a hack, and I apologize ahead of time for my rather thrown together code. At the very least, in google chrome, it works consistently, no matter what font I set it to, or size of textarea. I used [Sam Saffron](https://stackoverflow.com/users/17174/sam-saffron)'s example to show cursor coordinates (a gray-background div). I also added a "Randomize" link, so you can see it work in different font / texarea sizes and styles, and watch the cursor position update on the fly. I recommend looking at [the full page demo](http://enobrev.info/cursor2/) so you can better see the companion canvas play along. *I'll summarize how it works*... The underlying idea is that we're trying to redraw the textarea on a canvas, as closely as possible. Since the browser uses the same font engine for both and texarea, we can use canvas's font measurement functionality to figure out where things are. From there, we can use the canvas methods available to us to figure out our coordinates. First and foremost, we adjust our canvas to match the dimensions of the textarea. This is entirely for visual purposes since the canvas size doesn't really make a difference in our outcome. Since Canvas doesn't actually provide a means of word wrap, I had to conjure (steal / borrow / munge together) a means of breaking up lines to as-best-as-possible match the textarea. This is where you'll likely find you need to do the most cross-browser tweaking. After word wrap, everything else is basic math. We split the lines into an array to mimic the word wrap, and now we want to loop through those lines and go all the way down until the point where our current selection ends. In order to do that, we're just counting characters and once we surpass `selection.end`, we know we have gone down far enough. Multiply the line count up until that point with the line-height and you have a `y` coordinate. The `x` coordinate is very similar, except we're using `context.measureText`. As long as we're printing out the right number of characters, that will give us the width of the line that's being drawn to Canvas, which happens to end after the last character written out, which is the character before the currentl `selection.end` position. When trying to debug this for other browsers, the thing to look for is where the lines don't break properly. You'll see in some places that the last word on a line in canvas may have wrapped over on the textarea or vice-versa. This has to do with how the browser handles word wraps. As long as you get the wrapping in the canvas to match the textarea, your cursor should be correct. I'll paste the source below. You should be able to copy and paste it, but if you do, I ask that you download your own copy of jquery-fieldselection instead of hitting the one on my server. I've also upped [a new demo](http://enobrev.info/cursor2/) as well as [a fiddle](http://jsfiddle.net/9QAtz/). Good luck! ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Tooltip 2</title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="http://enobrev.info/cursor/js/jquery-fieldselection.js"></script> <style type="text/css"> form { float: left; margin: 20px; } #textariffic { height: 400px; width: 300px; font-size: 12px; font-family: 'Arial'; line-height: 12px; } #tip { width:5px; height:30px; background-color: #777; position: absolute; z-index:10000 } #mock-text { float: left; margin: 20px; border: 1px inset #ccc; } /* way the hell off screen */ .scrollbar-measure { width: 100px; height: 100px; overflow: scroll; position: absolute; top: -9999px; } #randomize { float: left; display: block; } </style> <script type="text/javascript"> var oCanvas; var oTextArea; var $oTextArea; var iScrollWidth; $(function() { iScrollWidth = scrollMeasure(); oCanvas = document.getElementById('mock-text'); oTextArea = document.getElementById('textariffic'); $oTextArea = $(oTextArea); $oTextArea .keyup(update) .mouseup(update) .scroll(update); $('#randomize').bind('click', randomize); update(); }); function randomize() { var aFonts = ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Impact', 'Times New Roman', 'Verdana', 'Webdings']; var iFont = Math.floor(Math.random() * aFonts.length); var iWidth = Math.floor(Math.random() * 500) + 300; var iHeight = Math.floor(Math.random() * 500) + 300; var iFontSize = Math.floor(Math.random() * 18) + 10; var iLineHeight = Math.floor(Math.random() * 18) + 10; var oCSS = { 'font-family': aFonts[iFont], width: iWidth + 'px', height: iHeight + 'px', 'font-size': iFontSize + 'px', 'line-height': iLineHeight + 'px' }; console.log(oCSS); $oTextArea.css(oCSS); update(); return false; } function showTip(x, y) { $('#tip').css({ left: x + 'px', top: y + 'px' }); } // https://stackoverflow.com/a/11124580/14651 // https://stackoverflow.com/a/3960916/14651 function wordWrap(oContext, text, maxWidth) { var aSplit = text.split(' '); var aLines = []; var sLine = ""; // Split words by newlines var aWords = []; for (var i in aSplit) { var aWord = aSplit[i].split('\n'); if (aWord.length > 1) { for (var j in aWord) { aWords.push(aWord[j]); aWords.push("\n"); } aWords.pop(); } else { aWords.push(aSplit[i]); } } while (aWords.length > 0) { var sWord = aWords[0]; if (sWord == "\n") { aLines.push(sLine); aWords.shift(); sLine = ""; } else { // Break up work longer than max width var iItemWidth = oContext.measureText(sWord).width; if (iItemWidth > maxWidth) { var sContinuous = ''; var iWidth = 0; while (iWidth <= maxWidth) { var sNextLetter = sWord.substring(0, 1); var iNextWidth = oContext.measureText(sContinuous + sNextLetter).width; if (iNextWidth <= maxWidth) { sContinuous += sNextLetter; sWord = sWord.substring(1); } iWidth = iNextWidth; } aWords.unshift(sContinuous); } // Extra space after word for mozilla and ie var sWithSpace = (jQuery.browser.mozilla || jQuery.browser.msie) ? ' ' : ''; var iNewLineWidth = oContext.measureText(sLine + sWord + sWithSpace).width; if (iNewLineWidth <= maxWidth) { // word fits on current line to add it and carry on sLine += aWords.shift() + " "; } else { aLines.push(sLine); sLine = ""; } if (aWords.length === 0) { aLines.push(sLine); } } } return aLines; } // http://davidwalsh.name/detect-scrollbar-width function scrollMeasure() { // Create the measurement node var scrollDiv = document.createElement("div"); scrollDiv.className = "scrollbar-measure"; document.body.appendChild(scrollDiv); // Get the scrollbar width var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; // Delete the DIV document.body.removeChild(scrollDiv); return scrollbarWidth; } function update() { var oPosition = $oTextArea.position(); var sContent = $oTextArea.val(); var oSelection = $oTextArea.getSelection(); oCanvas.width = $oTextArea.width(); oCanvas.height = $oTextArea.height(); var oContext = oCanvas.getContext("2d"); var sFontSize = $oTextArea.css('font-size'); var sLineHeight = $oTextArea.css('line-height'); var fontSize = parseFloat(sFontSize.replace(/[^0-9.]/g, '')); var lineHeight = parseFloat(sLineHeight.replace(/[^0-9.]/g, '')); var sFont = [$oTextArea.css('font-weight'), sFontSize + '/' + sLineHeight, $oTextArea.css('font-family')].join(' '); var iSubtractScrollWidth = oTextArea.clientHeight < oTextArea.scrollHeight ? iScrollWidth : 0; oContext.save(); oContext.clearRect(0, 0, oCanvas.width, oCanvas.height); oContext.font = sFont; var aLines = wordWrap(oContext, sContent, oCanvas.width - iSubtractScrollWidth); var x = 0; var y = 0; var iGoal = oSelection.end; aLines.forEach(function(sLine, i) { if (iGoal > 0) { oContext.fillText(sLine.substring(0, iGoal), 0, (i + 1) * lineHeight); x = oContext.measureText(sLine.substring(0, iGoal + 1)).width; y = i * lineHeight - oTextArea.scrollTop; var iLineLength = sLine.length; if (iLineLength == 0) { iLineLength = 1; } iGoal -= iLineLength; } else { // after } }); oContext.restore(); showTip(oPosition.left + x, oPosition.top + y); } </script> </head> <body> <a href="#" id="randomize">Randomize</a> <form id="tipper"> <textarea id="textariffic">Aliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi. Phasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus. Sed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus.</textarea> </form> <div id="tip"></div> <canvas id="mock-text"></canvas> </body> </html> ``` **Bug** *There's one bug I do recall. If you put the cursor before the first letter on a line, it shows the "position" as the last letter on the previous line. This has to do with how selection.end work. I don't think it should be too difficult to look for that case and fix it accordingly.* --- **Version 1** *Leaving this here so you can see the progress without having to dig through the edit history.* It's not perfect and it's most Definitely a hack, but I got it to work pretty well on WinXP IE, FF, Safari, Chrome and Opera. As far as I can tell there's no way to directly find out the x/y of a cursor on any browser. The [IE method](http://weblogs.asp.net/skillet/archive/2005/03/24/395838.aspx), [mentioned](https://stackoverflow.com/questions/128342/display-div-at-cursor-position-in-textarea#128461) by [Adam Bellaire](https://stackoverflow.com/users/21632/adam-bellaire) is interesting, but unfortunately not cross-browser. I figured the next best thing would be to use the characters as a grid. Unfortunately there's no font metric information built into any of the browsers, which means a monospace font is the only font type that's going to have a consistent measurement. Also, there's no reliable means of figuring out a font-width from the font-height. At first I'd tried using a percentage of the height, which worked great. Then I changed the font-size and everything went to hell. I tried one method to figure out character width, which was to create a temporary textarea and keep adding characters until the scrollHeight (or scrollWidth) changed. It seems plausable, but about halfway down that road, I realized I could just use the cols attribute on the textarea and figured there are enough hacks in this ordeal to add another one. This means you can't set the width of the textarea via css. You HAVE to use the cols for this to work. The next problem I ran into is that, even when you set the font via css, the browsers report the font differently. When you don't set a font, mozilla uses `monospace` by default, IE uses `Courier New`, Opera `"Courier New"` (with quotes), Safari, `'Lucida Grand'` (with single quotes). When you do set the font to `monospace`, mozilla and ie take what you give them, Safari comes out as `-webkit-monospace` and Opera stays with `"Courier New"`. So now we initialize some vars. Make sure to set your line height in the css as well. Firefox reports the correct line height, but IE was reporting "normal" and I didn't bother with the other browsers. I just set the line height in my css and that resolved the difference. I haven't tested with using ems instead of pixels. Char height is just font size. Should probably pre-set that in your css as well. Also, one more pre-setting before we start placing characters - which really had me scratching my head. For ie and mozilla, texarea chars are < cols, everything else is <= chars. So Chrome can fit 50 chars across, but mozilla and ie would break the last word off the line. Now we're going to create an array of first-character positions for every line. We loop through every char in the textarea. If it's a newline, we add a new position to our line array. If it's a space, we try to figure out if the current "word" will fit on the line we're on or if it's going to get pushed to the next line. Punctuation counts as a part of the "word". I haven't tested with tabs, but there's a line there for adding 4 chars for a tab char. Once we have an array of line positions, we loop through and try to find which line the cursor is on. We're using hte "End" of the selection as our cursor. x = (cursor position - first character position of cursor line) \* character width y = ((cursor line + 1) \* line height) - scroll position I'm using [jquery 1.2.6](http://docs.jquery.com/Downloading_jQuery), [jquery-fieldselection](http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html), and [jquery-dimensions](http://plugins.jquery.com/project/dimensions) The Demo: <http://enobrev.info/cursor/> And the code: ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Tooltip</title> <script type="text/javascript" src="js/jquery-1.2.6.js"></script> <script type="text/javascript" src="js/jquery-fieldselection.js"></script> <script type="text/javascript" src="js/jquery.dimensions.js"></script> <style type="text/css"> form { margin: 20px auto; width: 500px; } #textariffic { height: 400px; font-size: 12px; font-family: monospace; line-height: 15px; } #tip { position: absolute; z-index: 2; padding: 20px; border: 1px solid #000; background-color: #FFF; } </style> <script type="text/javascript"> $(function() { $('textarea') .keyup(update) .mouseup(update) .scroll(update); }); function showTip(x, y) { y = y + $('#tip').height(); $('#tip').css({ left: x + 'px', top: y + 'px' }); } function update() { var oPosition = $(this).position(); var sContent = $(this).val(); var bGTE = jQuery.browser.mozilla || jQuery.browser.msie; if ($(this).css('font-family') == 'monospace' // mozilla || $(this).css('font-family') == '-webkit-monospace' // Safari || $(this).css('font-family') == '"Courier New"') { // Opera var lineHeight = $(this).css('line-height').replace(/[^0-9]/g, ''); lineHeight = parseFloat(lineHeight); var charsPerLine = this.cols; var charWidth = parseFloat($(this).innerWidth() / charsPerLine); var iChar = 0; var iLines = 1; var sWord = ''; var oSelection = $(this).getSelection(); var aLetters = sContent.split(""); var aLines = []; for (var w in aLetters) { if (aLetters[w] == "\n") { iChar = 0; aLines.push(w); sWord = ''; } else if (aLetters[w] == " ") { var wordLength = parseInt(sWord.length); if ((bGTE && iChar + wordLength >= charsPerLine) || (!bGTE && iChar + wordLength > charsPerLine)) { iChar = wordLength + 1; aLines.push(w - wordLength); } else { iChar += wordLength + 1; // 1 more char for the space } sWord = ''; } else if (aLetters[w] == "\t") { iChar += 4; } else { sWord += aLetters[w]; } } var iLine = 1; for(var i in aLines) { if (oSelection.end < aLines[i]) { iLine = parseInt(i) - 1; break; } } if (iLine > -1) { var x = parseInt(oSelection.end - aLines[iLine]) * charWidth; } else { var x = parseInt(oSelection.end) * charWidth; } var y = (iLine + 1) * lineHeight - this.scrollTop; // below line showTip(oPosition.left + x, oPosition.top + y); } } </script> </head> <body> <form id="tipper"> <textarea id="textariffic" cols="50"> Aliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi. Phasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus. Sed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus. </textarea> </form> <p id="tip">Here I Am!!</p> </body> </html> ```
128,343
<p>I am currently initializing a Hashtable in the following way:</p> <pre><code>Hashtable filter = new Hashtable(); filter.Add("building", "A-51"); filter.Add("apartment", "210"); </code></pre> <p>I am looking for a nicer way to do this.</p> <p>I tried something like </p> <pre><code>Hashtable filter2 = new Hashtable() { {"building", "A-51"}, {"apartment", "210"} }; </code></pre> <p>However the above code does not compile.</p>
[ { "answer_id": 128367, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 3, "selected": false, "text": "<p>In C# 3 it should compile fine like this:</p>\n\n<pre><code>Hashtable table = new Hashtable {{1, 1}, {2, 2}};\n</code></pre>\n" }, { "answer_id": 128380, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>(Not a C# expert)</p>\n\n<p>This is syntactic sugar, and if it's syntactic sugar I'd want to have the mapping (in a Hashtable) nice and obvious:</p>\n\n<pre>\n\nHashtable filter2 = new Hashtable() { \"building\" => \"A-51\", \"apartment\" => \"210\"};\n\n</pre>\n\n<p>However I don't see a real need for this, there isn't much wrong with just having to call add after initialisation.</p>\n\n<p>(I've known people to hack around with the Java compiler to achieve similar things in the past for Java (which caused major issues moving to Java 5 a few years later), I expect this isn't an option for C# though!)</p>\n" }, { "answer_id": 128409, "author": "Paul Batum", "author_id": 48281, "author_profile": "https://Stackoverflow.com/users/48281", "pm_score": 6, "selected": true, "text": "<p>The exact code you posted:</p>\n\n<pre><code> Hashtable filter2 = new Hashtable()\n {\n {\"building\", \"A-51\"},\n {\"apartment\", \"210\"}\n };\n</code></pre>\n\n<p>Compiles perfectly in C# 3. Given you reported compilation problems, I'm guessing you are using C# 2? In this case you can at least do this:</p>\n\n<pre><code> Hashtable filter2 = new Hashtable();\n filter2[\"building\"] = \"A-51\";\n filter2[\"apartment\"] = \"210\";\n</code></pre>\n" }, { "answer_id": 128479, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": -1, "selected": false, "text": "<p>I think the real question being asked may be about imaginable constructors such as:</p>\n\n<p>HashTable ht = new HashTable(MyArray) ; // fill from array</p>\n\n<p>HashTable ht = new HashTable(MyDataTable) ; // fill from datatable</p>\n\n<p>AFAIK, the answer is \"no\", but you could write it yourself. I assume the reason that such methods are not in the library is that the Array or DataTable has to be properly formed. It's not such a big loss since any implementation of these methods would probably be using the Add method in a loop anyway.</p>\n" }, { "answer_id": 128484, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 0, "selected": false, "text": "<p>I had no idea in C# 3.0 <code>Hashtable table = new Hashtable {{1, 1}, {2, 2}};</code> would compile.</p>\n\n<p>Anyway, poor man's implementation:</p>\n\n<p>Meh, you could extend the Hashtable class:</p>\n\n<pre><code>class MyHashTable : System.Collections.Hashtable \n{\n public MyHashTable(string [,] values)\n {\n for (int i = 0; i &lt; (values.Length)/2; i++)\n {\n this.Add(values[i,0], values[i,1]);\n }\n }\n}\n</code></pre>\n\n<p>And then from a Console App:</p>\n\n<pre><code> class Program\n{\n static void Main(string[] args)\n {\n string[,] initialize = { { \"building\", \"A-51\" }, { \"apartment\", \"210\" }, {\"wow\", \"nerf Druids\"}};\n\n\n\n MyHashTable myhashTable = new MyHashTable(initialize);\n Console.WriteLine(myhashTable[\"building\"].ToString());\n Console.WriteLine(myhashTable[\"apartment\"].ToString());\n Console.WriteLine(myhashTable[\"wow\"].ToString());\n Console.ReadKey();\n\n\n }\n}\n</code></pre>\n\n<p>will result in:<br/>\nA-51<br/>\n210<br/>\nnerf Druids</p>\n\n<p>this was done quick so it may bomb in certain situations but then again..</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
I am currently initializing a Hashtable in the following way: ``` Hashtable filter = new Hashtable(); filter.Add("building", "A-51"); filter.Add("apartment", "210"); ``` I am looking for a nicer way to do this. I tried something like ``` Hashtable filter2 = new Hashtable() { {"building", "A-51"}, {"apartment", "210"} }; ``` However the above code does not compile.
The exact code you posted: ``` Hashtable filter2 = new Hashtable() { {"building", "A-51"}, {"apartment", "210"} }; ``` Compiles perfectly in C# 3. Given you reported compilation problems, I'm guessing you are using C# 2? In this case you can at least do this: ``` Hashtable filter2 = new Hashtable(); filter2["building"] = "A-51"; filter2["apartment"] = "210"; ```
128,349
<p>Date coming out of a database, need to format as "mm/dd/yy"</p> <pre><code>For Each dr as DataRow in ds.Tables(0).Rows Response.Write(dr("CreateDate")) Next </code></pre>
[ { "answer_id": 128356, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 0, "selected": false, "text": "<pre><code>Response.Write(DateTime.Parse(dr(\"CreateDate\").ToString()).ToString(\"MM/dd/yyyy\"))\n</code></pre>\n" }, { "answer_id": 128359, "author": "Clyde", "author_id": 945, "author_profile": "https://Stackoverflow.com/users/945", "pm_score": 2, "selected": false, "text": "<p>Convert.ToDateTime(dr(\"CreateDate\")).ToShortDate()</p>\n\n<p>See the MSDN docs for other functions available from the DateTime datatype, including custom formats available through the 'ToString' function.</p>\n" }, { "answer_id": 128364, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 0, "selected": false, "text": "<p>Easy:</p>\n\n<pre><code>((DateTime)dr[\"CreateDate\"]).ToString(\"MM/dd/yyyy\")\n</code></pre>\n\n<p>// I would also check that it isn't dbnull before doing it though</p>\n\n<pre><code>if (! DBNull.Value.Equals(dr[\"CreateDate\"])) // blah blah\n</code></pre>\n" }, { "answer_id": 128370, "author": "Greg", "author_id": 12601, "author_profile": "https://Stackoverflow.com/users/12601", "pm_score": 5, "selected": true, "text": "<pre><code>string.Format( \"{0:MM/dd/yy}\", dr(\"CreateDate\") )\n</code></pre>\n\n<p>Edit: If dr(\"CreateDate\") is DBNull, this returns \"\".</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70/" ]
Date coming out of a database, need to format as "mm/dd/yy" ``` For Each dr as DataRow in ds.Tables(0).Rows Response.Write(dr("CreateDate")) Next ```
``` string.Format( "{0:MM/dd/yy}", dr("CreateDate") ) ``` Edit: If dr("CreateDate") is DBNull, this returns "".
128,350
<p>I'm writing an <code>RSS</code> to <code>JSON parser</code> and as a part of that, I need to use <code>htmlentities()</code> on any tag found inside the description tag. Currently, I'm trying to use <code>preg_replace()</code>, but I'm struggling a little with it. My current (non-working) code looks like:</p> <pre><code>$pattern[0] = "/\&lt;description\&gt;(.*?)\&lt;\/description\&gt;/is"; $replace[0] = '&lt;description&gt;'.htmlentities("$1").'&lt;/description&gt;'; $rawFeed = preg_replace($pattern, $replace, $rawFeed); </code></pre> <p>If you have a more elegant solution to this as well, please share. Thanks.</p>
[ { "answer_id": 128373, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": true, "text": "<p>Simple. Use <code>preg_replace_callback</code>:</p>\n\n<pre><code>function _handle_match($match)\n{\n return '&lt;description&gt;' . htmlentities($match[1]) . '&lt;/description&gt;';\n}\n\n$pattern = \"/\\&lt;description\\&gt;(.*?)\\&lt;\\/description\\&gt;/is\";\n$rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed);\n</code></pre>\n\n<p>It accepts any callback type, so also methods in classes.</p>\n" }, { "answer_id": 128418, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<p>The more elegant solution would be to employ <a href=\"http://php.net/simplexml\" rel=\"nofollow noreferrer\">SimpleXML</a>. Or a third party library such as <a href=\"http://pear.php.net/package/XML_Feed_Parser\" rel=\"nofollow noreferrer\">XML_Feed_Parser</a> or <a href=\"http://framework.zend.com/manual/en/zend.feed.html\" rel=\"nofollow noreferrer\">Zend_Feed</a> to parse the feed.</p>\n\n<p>Here is a SimpleXML example:</p>\n\n<pre><code>&lt;?php\n$rss = file_get_contents('http://rss.slashdot.org/Slashdot/slashdot');\n$xml = simplexml_load_string($rss);\n\nforeach ($xml-&gt;item as $item) {\n echo \"{$item-&gt;description}\\n\\n\";\n}\n?&gt;\n</code></pre>\n\n<p>Keep in mind that RSS and RDF and Atom look different, which is why it can make sense to employ one of the above libraries I mentioned.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
I'm writing an `RSS` to `JSON parser` and as a part of that, I need to use `htmlentities()` on any tag found inside the description tag. Currently, I'm trying to use `preg_replace()`, but I'm struggling a little with it. My current (non-working) code looks like: ``` $pattern[0] = "/\<description\>(.*?)\<\/description\>/is"; $replace[0] = '<description>'.htmlentities("$1").'</description>'; $rawFeed = preg_replace($pattern, $replace, $rawFeed); ``` If you have a more elegant solution to this as well, please share. Thanks.
Simple. Use `preg_replace_callback`: ``` function _handle_match($match) { return '<description>' . htmlentities($match[1]) . '</description>'; } $pattern = "/\<description\>(.*?)\<\/description\>/is"; $rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed); ``` It accepts any callback type, so also methods in classes.
128,365
<p>I have a server access log, with timestamps of each http request, I'd like to obtain a count of the number of requests at each second. Using <code>sed</code>, and <code>cut -c</code>, so far I've managed to cut the file down to just the timestamps, such as:</p> <blockquote> <p>22-Sep-2008 20:00:21 +0000<br> 22-Sep-2008 20:00:22 +0000<br> 22-Sep-2008 20:00:22 +0000<br> 22-Sep-2008 20:00:22 +0000<br> 22-Sep-2008 20:00:24 +0000<br> 22-Sep-2008 20:00:24 +0000</p> </blockquote> <p>What I'd love to get is the number of times each unique timestamp appears in the file. For example, with the above example, I'd like to get output that looks like:</p> <blockquote> <p>22-Sep-2008 20:00:21 +0000: 1<br> 22-Sep-2008 20:00:22 +0000: 3<br> 22-Sep-2008 20:00:24 +0000: 2</p> </blockquote> <p>I've used <code>sort -u</code> to filter the list of timestamps down to a list of unique tokens, hoping that I could use grep like</p> <pre><code>grep -c -f &lt;file containing patterns&gt; &lt;file&gt; </code></pre> <p>but this just produces a single line of a grand total of matching lines.</p> <p>I know this can be done in a single line, stringing a few utilities together ... but I can't think of which. Anyone know?</p>
[ { "answer_id": 128394, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 6, "selected": true, "text": "<p>I think you're looking for</p>\n\n<pre><code>uniq --count\n</code></pre>\n\n<blockquote>\n <p>-c, --count\n prefix lines by the number of occurrences</p>\n</blockquote>\n" }, { "answer_id": 128397, "author": "Clyde", "author_id": 945, "author_profile": "https://Stackoverflow.com/users/945", "pm_score": -1, "selected": false, "text": "<p>maybe use xargs? Can't put it all together in my head on the spot here, but use xargs on your sort -u so that for each unique second you can grep the original file and do a wc -l to get the number. </p>\n" }, { "answer_id": 128411, "author": "David", "author_id": 9908, "author_profile": "https://Stackoverflow.com/users/9908", "pm_score": 1, "selected": false, "text": "<p>Using AWK with associative arrays might be another solution to something like this.</p>\n" }, { "answer_id": 128446, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 1, "selected": false, "text": "<p>Just in case you want the output in the format you originally specified (with the number of occurences at the end):</p>\n\n<pre><code>uniq -c logfile | sed 's/\\([0-9]+\\)\\(.*\\)/\\2: \\1/'\n</code></pre>\n" }, { "answer_id": 161306, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 0, "selected": false, "text": "<p>Using <a href=\"http://www.gnu.org/software/gawk/manual/gawk.html\" rel=\"nofollow noreferrer\">awk</a>:</p>\n\n<pre><code>cat file.txt | awk '{count[$1 \" \" $2]++;} \\\n END {for(w in count){print w \": \" count[w]};}'\n</code></pre>\n" }, { "answer_id": 32888355, "author": "Bity", "author_id": 3797933, "author_profile": "https://Stackoverflow.com/users/3797933", "pm_score": 0, "selected": false, "text": "<p>Tom's solution:</p>\n\n<pre><code>awk '{count[$1 \" \" $2]++;} END {for(w in count){print w \": \" count[w]};}' file.txt\n</code></pre>\n\n<p>works more generally.</p>\n\n<p>My file was not sorted :</p>\n\n<pre><code>name1 \nname2 \nname3 \nname2 \nname2 \nname3 \nname1\n</code></pre>\n\n<p>Therefore the occurrences weren't following each other, and <code>uniq</code> does not work as it gives :</p>\n\n<pre><code>1 name1 \n1 name2 \n1 name3 \n2 name2 \n1 name3 \n1 name1\n</code></pre>\n\n<p>With the awk script however:</p>\n\n<pre><code>name1:2 \nname2:3 \nname3:2\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I have a server access log, with timestamps of each http request, I'd like to obtain a count of the number of requests at each second. Using `sed`, and `cut -c`, so far I've managed to cut the file down to just the timestamps, such as: > > 22-Sep-2008 20:00:21 +0000 > > 22-Sep-2008 20:00:22 +0000 > > 22-Sep-2008 20:00:22 +0000 > > 22-Sep-2008 20:00:22 +0000 > > 22-Sep-2008 20:00:24 +0000 > > 22-Sep-2008 20:00:24 +0000 > > > What I'd love to get is the number of times each unique timestamp appears in the file. For example, with the above example, I'd like to get output that looks like: > > 22-Sep-2008 20:00:21 +0000: 1 > > 22-Sep-2008 20:00:22 +0000: 3 > > 22-Sep-2008 20:00:24 +0000: 2 > > > I've used `sort -u` to filter the list of timestamps down to a list of unique tokens, hoping that I could use grep like ``` grep -c -f <file containing patterns> <file> ``` but this just produces a single line of a grand total of matching lines. I know this can be done in a single line, stringing a few utilities together ... but I can't think of which. Anyone know?
I think you're looking for ``` uniq --count ``` > > -c, --count > prefix lines by the number of occurrences > > >
128,412
<p>We are using SQL Server 2005, but this question can be for any <a href="http://en.wikipedia.org/wiki/Relational_database_management_system" rel="noreferrer">RDBMS</a>.</p> <p>Which of the following is more efficient, when selecting all columns from a view?</p> <pre><code>Select * from view </code></pre> <p>or </p> <pre><code>Select col1, col2, ..., colN from view </code></pre>
[ { "answer_id": 128422, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>If you're really selecting all columns, it shouldn't make any noticeable difference whether you ask for * or if you are explicit. The SQL server will parse the request the same way in pretty much the same amount of time.</p>\n" }, { "answer_id": 128424, "author": "Gthompson83", "author_id": 20483, "author_profile": "https://Stackoverflow.com/users/20483", "pm_score": 4, "selected": false, "text": "<p>It is best practice to select each column by name. In the future your DB schema might change to add columns that you would then not need for a particular query. I would recommend selecting each column by name.</p>\n" }, { "answer_id": 128429, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>Always do select col1, col2 etc from view. There's no efficieny difference between the two methods that I know of, but using \"select *\" can be dangerous. If you modify your view definition adding new columns, you can break a program using \"select *\", whereas selecting a predefined set of columns (even all of them, named), will still work.</p>\n" }, { "answer_id": 128432, "author": "Ken Ray", "author_id": 12253, "author_profile": "https://Stackoverflow.com/users/12253", "pm_score": 0, "selected": false, "text": "<p>I guess it all depends on what the query optimizer does.</p>\n\n<p>If I want to get every record in the row, I will generally use the \"SELECT *...\" option, since I then don't have to worry should I change the underlying table structure. As well, for someone maintaining the code, seeing \"SELECT *\" tells them that this query is intended to return every column, whereas listing the columns individually does not convey the same intention.</p>\n" }, { "answer_id": 128433, "author": "devlord", "author_id": 16454, "author_profile": "https://Stackoverflow.com/users/16454", "pm_score": 6, "selected": true, "text": "<p>NEVER, EVER USE \"SELECT *\"!!!!</p>\n\n<p>This is the cardinal rule of query design!</p>\n\n<p>There are multiple reasons for this. One of which is, that if your table only has three fields on it and you use all three fields in the code that calls the query, there's a great possibility that you will be adding more fields to that table as the application grows, and if your select * query was only meant to return those 3 fields for the calling code, then you're pulling much more data from the database than you need.</p>\n\n<p>Another reason is performance. In query design, don't think about reusability as much as this mantra:</p>\n\n<p>TAKE ALL YOU CAN EAT, BUT EAT ALL YOU TAKE.</p>\n" }, { "answer_id": 128617, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>Select * is a poor programming practice. It is as likely to cause things to break as it is to save things from breaking. If you are only querying one table or view, then the efficiency gain may not be there (although it is possible if you are not intending to actually use every field). If you have an inner join, then you have at least two fields returning the same data (the join fields) and thus you are wasting network resources to send redundant data back to the application. You won't notice this at first, but as the result sets get larger and larger, you will soon have a network pipeline that is full and doesn't need to be. I can think of no instance where select * gains you anything. If a new column is added and you don't need to go to the code to do something with it, then the column shouldn't be returned by your query by definition. If someone drops and recreates the table with the columns in a different order, then all your queries will have information displaying wrong or will be giving bad results, such as putting the price into the part number field in a new record.</p>\n\n<p>Plus it is quick to drag the column names over from the object browser, so that is just pure laziness not efficiency in coding.</p>\n" }, { "answer_id": 128664, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>For performance - look at the query plan (should be no difference).</p>\n\n<p>For maintainability. - always supply a fieldlist (that goes for INSERT INTO too).</p>\n" }, { "answer_id": 132395, "author": "CJM", "author_id": 6898, "author_profile": "https://Stackoverflow.com/users/6898", "pm_score": 2, "selected": false, "text": "<p>Just to clarify a point that several people have already made, the reason Select * is inefficient is because there has to be an initial call to the DB to find out exactly what fields are available, and then a second call where the query is made using explicit columns.</p>\n\n<p>Feel free to use Select * when you are debugging, running casual queries or are in the early stages of developing a query, but as soon as you know your required columns, state them explicitly.</p>\n" }, { "answer_id": 4202807, "author": "Simon", "author_id": 510552, "author_profile": "https://Stackoverflow.com/users/510552", "pm_score": 1, "selected": false, "text": "<p>It depends. Inheritance of views can be a handy thing and easy to maintain (SQL Anywhere): </p>\n\n<pre><code>create view v_fruit as select F.id, S.strain from F key join S; \ncreate view v_apples as select v_fruit.*, C.colour from v_fruit key join C;\n</code></pre>\n" }, { "answer_id": 11009381, "author": "Alireza Masali", "author_id": 1450585, "author_profile": "https://Stackoverflow.com/users/1450585", "pm_score": 0, "selected": false, "text": "<pre><code>select \ncolumn1\n,column2\n,column3\n.\n.\n.\nfrom Your-View\n</code></pre>\n\n<p>this one is more optimizer than Using the </p>\n\n<pre><code>select *\nfrom Your View \n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2539/" ]
We are using SQL Server 2005, but this question can be for any [RDBMS](http://en.wikipedia.org/wiki/Relational_database_management_system). Which of the following is more efficient, when selecting all columns from a view? ``` Select * from view ``` or ``` Select col1, col2, ..., colN from view ```
NEVER, EVER USE "SELECT \*"!!!! This is the cardinal rule of query design! There are multiple reasons for this. One of which is, that if your table only has three fields on it and you use all three fields in the code that calls the query, there's a great possibility that you will be adding more fields to that table as the application grows, and if your select \* query was only meant to return those 3 fields for the calling code, then you're pulling much more data from the database than you need. Another reason is performance. In query design, don't think about reusability as much as this mantra: TAKE ALL YOU CAN EAT, BUT EAT ALL YOU TAKE.
128,443
<p>Does anyone know how I can get a format string to use <a href="http://en.wikipedia.org/wiki/Rounding#Round-to-even_method" rel="nofollow noreferrer">bankers rounding</a>? I have been using "{0:c}" but that doesn't round the same way that bankers rounding does. The <a href="http://msdn.microsoft.com/en-us/library/system.math.round.aspx" rel="nofollow noreferrer"><code>Math.Round()</code></a> method does bankers rounding. I just need to be able to duplicate how it rounds using a format string.</p> <hr> <p> <strong>Note:</strong> the original question was rather misleading, and answers mentioning regex derive from that. </p>
[ { "answer_id": 128453, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "<p><strike>Regexp is a pattern matching language. You can't do arithmetic operations in Regexp.</strike></p>\n\n<p>Do some experiements with IFormatProvider and ICustomFormatter. Here is a link might point you in the right direction. <a href=\"http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx</a></p>\n" }, { "answer_id": 128455, "author": "viggity", "author_id": 4572, "author_profile": "https://Stackoverflow.com/users/4572", "pm_score": 0, "selected": false, "text": "<p>Its not possible, a regular expression doesn't have any concept of \"numbers\". You could use a <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator(VS.71).aspx\" rel=\"nofollow noreferrer\">match evaluator</a> but you'd be adding imperative c# code, and would stray from your regex only requirement.</p>\n" }, { "answer_id": 128539, "author": "Zach Lute", "author_id": 21374, "author_profile": "https://Stackoverflow.com/users/21374", "pm_score": 3, "selected": true, "text": "<p>Can't you simply call Math.Round() on the string input to get the behavior you want?</p>\n\n<p>Instead of:</p>\n\n<pre><code>string s = string.Format(\"{0:c}\", 12345.6789);\n</code></pre>\n\n<p>Do:</p>\n\n<pre><code>string s = string.Format(\"{0:c}\", Math.Round(12345.6789));\n</code></pre>\n" }, { "answer_id": 129470, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>.Net has built in support for both Arithmetic and Bankers' rounding:</p>\n\n<pre><code>//midpoint always goes 'up': 2.5 -&gt; 3\nMath.Round( input, MidpointRounding.AwayFromZero );\n\n//midpoint always goes to nearest even: 2.5 -&gt; 2, 5.5 -&gt; 6\n//aka bankers' rounding\nMath.Round( input, MidpointRounding.ToEven );\n</code></pre>\n\n<p>\"To even\" rounding is actually the default, even though \"away from zero\" is what you learnt at school.</p>\n\n<p>This is because under the hood computer processors also do bankers' rounding.</p>\n\n<pre><code>//defaults to banker's\nMath.Round( input );\n</code></pre>\n\n<p>I would have thought that any rounding format string would default to bankers' rounding, is this not the case?</p>\n" }, { "answer_id": 129587, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 0, "selected": false, "text": "<p>If you are using .NET 3.5, you can define an extension method to help you do this:</p>\n\n<pre><code>public static class DoubleExtensions\n{\n public static string Format(this double d)\n {\n return String.Format(\"{0:c}\", Math.Round(d));\n }\n}\n</code></pre>\n\n<p>Then, when you call it, you can do:</p>\n\n<pre><code>12345.6789.Format();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21767/" ]
Does anyone know how I can get a format string to use [bankers rounding](http://en.wikipedia.org/wiki/Rounding#Round-to-even_method)? I have been using "{0:c}" but that doesn't round the same way that bankers rounding does. The [`Math.Round()`](http://msdn.microsoft.com/en-us/library/system.math.round.aspx) method does bankers rounding. I just need to be able to duplicate how it rounds using a format string. --- **Note:** the original question was rather misleading, and answers mentioning regex derive from that.
Can't you simply call Math.Round() on the string input to get the behavior you want? Instead of: ``` string s = string.Format("{0:c}", 12345.6789); ``` Do: ``` string s = string.Format("{0:c}", Math.Round(12345.6789)); ```
128,450
<p>I have some controller methods I'd like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, or should I create module and add it in to each controller? Below are the controller methods I want to share:</p> <pre><code>def driving_directions @address_to = params[:address_to] @address_from = params[:address_from] @map_center = params[:map_center_start] # if we were not given a center point to start our map on # let's create one. if !@map_center &amp;&amp; @address_to @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_to).ll elsif !@map_center &amp;&amp; @address_from @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_from).ll end end def printer_friendly starting_point = params[:starting_point].split(',').collect{|e|e.to_f} ne = params[:ne].split(',').collect{|e|e.to_f} sw = params[:sw].split(',').collect{|e|e.to_f} size = params[:size].split(',').collect{|e|e.to_f} address = params[:address] @markers = retrieve_points(ne,sw,size,false) @map = initialize_map([[sw[0],sw[1]],[ne[0],ne[1]]],[starting_point[0],starting_point[1]],false,@markers,true) @address_string = address end </code></pre>
[ { "answer_id": 128771, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 4, "selected": false, "text": "<p>I actually think a module is the best way to share code amongst controllers. Helpers are good if you want to share code amongst views. Helpers are basically glorified modules, so if you don't need view level access, I suggest placing a module in your lib folder.</p>\n\n<p>Once you create the module, you'll have to use the include statement to include it in the desired controllers.</p>\n\n<p><a href=\"http://www.rubyist.net/~slagell/ruby/modules.html\" rel=\"noreferrer\">http://www.rubyist.net/~slagell/ruby/modules.html</a></p>\n" }, { "answer_id": 129020, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 1, "selected": false, "text": "<p>I agree with the module approach. Create a separate Ruby file in your lib directory and put the module in the new file.</p>\n\n<p>The most obvious way would be to add the methods to your ApplicationController, but I am sure you know that already.</p>\n" }, { "answer_id": 130821, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 8, "selected": true, "text": "<p>In my opinion, normal OO design principles apply:</p>\n\n<ul>\n<li>If the code is really a set of utilities that doesn't need access to object state, I would consider putting it in a module to be called separately. For instance, if the code is all mapping utilities, create a module <code>Maps</code>, and access the methods like: <code>Maps::driving_directions</code>.</li>\n<li>If the code needs state and is used or could be used in every controller, put the code in ApplicationController.</li>\n<li>If the code needs state and is used in a subset of all controllers that are closely and logically related (i.e. all about maps) then create a base class (<code>class MapController &lt; ApplicationController</code>) and put the shared code there.</li>\n<li>If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers.</li>\n</ul>\n\n<p>In your case, the methods need state (<code>params</code>), so the choice depends on the logical relationship between the controllers that need it.\nIn addition:</p>\n\n<p>Also:</p>\n\n<ul>\n<li>Use partials when possible for repeated code and either place in a common 'partials' directory or include via a specific path.</li>\n<li>Stick to a RESTful approach when possible (for methods) and if you find yourself creating a lot of non-RESTful methods consider extracting them to their own controller.</li>\n</ul>\n" }, { "answer_id": 136426, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "<p>Another possibility:</p>\n\n<p>If your common code needs state and you want to share the behavior amongst controllers, you could put it in a plain old ruby class in either your <code>model</code> or <code>lib</code> directory. Remember that <code>model</code> classes don't have to be persistent even though all ActiveRecord classes are persistent. In other words, it's acceptable to have transient <code>model</code> classes. </p>\n" }, { "answer_id": 2957801, "author": "Shanison", "author_id": 321882, "author_profile": "https://Stackoverflow.com/users/321882", "pm_score": 1, "selected": false, "text": "<p>if you want to share codes between controller and helpers, then you should try creating a module in library. You can use @template and @controller for accessing method in controller and helper as well.\nCheck this for more details <a href=\"http://www.shanison.com/?p=305\" rel=\"nofollow noreferrer\">http://www.shanison.com/?p=305</a></p>\n" }, { "answer_id": 23722926, "author": "Sam G", "author_id": 3642908, "author_profile": "https://Stackoverflow.com/users/3642908", "pm_score": 5, "selected": false, "text": "<p>I know this question was asked 6 years ago. Just want to point out that in Rails 4, there're now Controller Concerns that're a more out of the box solution.</p>\n" }, { "answer_id": 29528340, "author": "Daniel Bonnell", "author_id": 4139179, "author_profile": "https://Stackoverflow.com/users/4139179", "pm_score": 0, "selected": false, "text": "<p>I found that one effective way to share identical code across controllers is to have one controller inherit from the other (where the code lives). I used this approach to share identical methods defined in my controllers with another set of namespaced controllers.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
I have some controller methods I'd like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, or should I create module and add it in to each controller? Below are the controller methods I want to share: ``` def driving_directions @address_to = params[:address_to] @address_from = params[:address_from] @map_center = params[:map_center_start] # if we were not given a center point to start our map on # let's create one. if !@map_center && @address_to @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_to).ll elsif !@map_center && @address_from @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_from).ll end end def printer_friendly starting_point = params[:starting_point].split(',').collect{|e|e.to_f} ne = params[:ne].split(',').collect{|e|e.to_f} sw = params[:sw].split(',').collect{|e|e.to_f} size = params[:size].split(',').collect{|e|e.to_f} address = params[:address] @markers = retrieve_points(ne,sw,size,false) @map = initialize_map([[sw[0],sw[1]],[ne[0],ne[1]]],[starting_point[0],starting_point[1]],false,@markers,true) @address_string = address end ```
In my opinion, normal OO design principles apply: * If the code is really a set of utilities that doesn't need access to object state, I would consider putting it in a module to be called separately. For instance, if the code is all mapping utilities, create a module `Maps`, and access the methods like: `Maps::driving_directions`. * If the code needs state and is used or could be used in every controller, put the code in ApplicationController. * If the code needs state and is used in a subset of all controllers that are closely and logically related (i.e. all about maps) then create a base class (`class MapController < ApplicationController`) and put the shared code there. * If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers. In your case, the methods need state (`params`), so the choice depends on the logical relationship between the controllers that need it. In addition: Also: * Use partials when possible for repeated code and either place in a common 'partials' directory or include via a specific path. * Stick to a RESTful approach when possible (for methods) and if you find yourself creating a lot of non-RESTful methods consider extracting them to their own controller.
128,456
<p>I have a data warehouse containing typical star schemas, and a whole bunch of code which does stuff like this (obviously a lot bigger, but this is illustrative):</p> <pre><code>SELECT cdim.x ,SUM(fact.y) AS y ,dim.z FROM fact INNER JOIN conformed_dim AS cdim ON cdim.cdim_dim_id = fact.cdim_dim_id INNER JOIN nonconformed_dim AS dim ON dim.ncdim_dim_id = fact.ncdim_dim_id INNER JOIN date_dim AS ddim ON ddim.date_id = fact.date_id WHERE fact.date_id = @date_id GROUP BY cdim.x ,dim.z </code></pre> <p>I'm thinking of replacing it with a view (<code>MODEL_SYSTEM_1</code>, say), so that it becomes:</p> <pre><code>SELECT m.x ,SUM(m.y) AS y ,m.z FROM MODEL_SYSTEM_1 AS m WHERE m.date_id = @date_id GROUP BY m.x ,m.z </code></pre> <p>But the view <code>MODEL_SYSTEM_1</code> would have to contain unique column names, and I'm also concerned about performance with the optimizer if I go ahead and do this, because I'm concerned that all the items in the WHERE clause across different facts and dimensions get optimized, since the view would be across a whole star, and views cannot be parametrized (boy, wouldn't that be cool!)</p> <p>So my questions are -</p> <ol> <li><p>Is this approach OK, or is it just going to be an abstraction which hurts performance and doesn't give my anything but a lot nicer syntax?</p></li> <li><p>What's the best way to code-gen these views, eliminating duplicate column names (even if the view later needs to be tweaked by hand), given that all the appropriate PK and FKs are in place? Should I just write some SQL to pull it out of the <code>INFORMATION_SCHEMA</code> or is there a good example already available.</p></li> </ol> <p><strong>Edit:</strong> I have tested it, and the performance seems the same, even on the bigger processes - even joining multiple stars which each use these views.</p> <p>The automation is mainly because there are a number of these stars in the data warehouse, and the FK/PK has been done properly by the designers, but I don't want to have to pick through all the tables or the documentation. I wrote a script to generate the view (it also generates abbreviations for the tables), and it works well to generate the skeleton automagically from <code>INFORMATION_SCHEMA</code>, and then it can be tweaked before committing the creation of the view.</p> <p>If anyone wants the code, I could probably publish it here.</p>
[ { "answer_id": 128486, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "<p>Make the view or views into into one or more summary fact tables and materialize it. These only need to be refreshed when the main fact table is refreshed. The materialized views will be faster to query and this can be a win if you have a lot of queries that can be satisfied by the summary. </p>\n\n<p>You can use the data dictionary or information schema views to generate SQL to create the tables if you have a large number of these summaries or wish to change them about frequently.</p>\n\n<p>However, I would guess that it's not likely that you would change these very often so auto-generating the view definitions might not be worth the trouble.</p>\n" }, { "answer_id": 135127, "author": "Brad_Z", "author_id": 22273, "author_profile": "https://Stackoverflow.com/users/22273", "pm_score": 3, "selected": true, "text": "<ol>\n<li><p>I’ve used this technique on several data warehouses I look after. I have not noticed any performance degradation when running reports based off of the views versus a table direct approach but have never performed a detailed analysis.</p></li>\n<li><p>I created the views using the designer in SQL Server management studio and did not use any automated approach. I can’t imagine the schema changing often enough that automating it would be worthwhile anyhow. You might spend as long tweaking the results as it would have taken to drag all the tables onto the view in the first place! </p></li>\n</ol>\n\n<p>To remove ambiguity a good approach is to preface the column names with the name of the dimension it belongs to. This is helpful to the report writers and to anyone running ad hoc queries.</p>\n" }, { "answer_id": 1625565, "author": "Damir Sudarevic", "author_id": 196713, "author_profile": "https://Stackoverflow.com/users/196713", "pm_score": 1, "selected": false, "text": "<p>If you happen to use MS SQL Server, you could try an Inline UDF which is as close to a <a href=\"http://msdn.microsoft.com/en-us/library/ms189294.aspx\" rel=\"nofollow noreferrer\">parameterized view</a> as it gets.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18255/" ]
I have a data warehouse containing typical star schemas, and a whole bunch of code which does stuff like this (obviously a lot bigger, but this is illustrative): ``` SELECT cdim.x ,SUM(fact.y) AS y ,dim.z FROM fact INNER JOIN conformed_dim AS cdim ON cdim.cdim_dim_id = fact.cdim_dim_id INNER JOIN nonconformed_dim AS dim ON dim.ncdim_dim_id = fact.ncdim_dim_id INNER JOIN date_dim AS ddim ON ddim.date_id = fact.date_id WHERE fact.date_id = @date_id GROUP BY cdim.x ,dim.z ``` I'm thinking of replacing it with a view (`MODEL_SYSTEM_1`, say), so that it becomes: ``` SELECT m.x ,SUM(m.y) AS y ,m.z FROM MODEL_SYSTEM_1 AS m WHERE m.date_id = @date_id GROUP BY m.x ,m.z ``` But the view `MODEL_SYSTEM_1` would have to contain unique column names, and I'm also concerned about performance with the optimizer if I go ahead and do this, because I'm concerned that all the items in the WHERE clause across different facts and dimensions get optimized, since the view would be across a whole star, and views cannot be parametrized (boy, wouldn't that be cool!) So my questions are - 1. Is this approach OK, or is it just going to be an abstraction which hurts performance and doesn't give my anything but a lot nicer syntax? 2. What's the best way to code-gen these views, eliminating duplicate column names (even if the view later needs to be tweaked by hand), given that all the appropriate PK and FKs are in place? Should I just write some SQL to pull it out of the `INFORMATION_SCHEMA` or is there a good example already available. **Edit:** I have tested it, and the performance seems the same, even on the bigger processes - even joining multiple stars which each use these views. The automation is mainly because there are a number of these stars in the data warehouse, and the FK/PK has been done properly by the designers, but I don't want to have to pick through all the tables or the documentation. I wrote a script to generate the view (it also generates abbreviations for the tables), and it works well to generate the skeleton automagically from `INFORMATION_SCHEMA`, and then it can be tweaked before committing the creation of the view. If anyone wants the code, I could probably publish it here.
1. I’ve used this technique on several data warehouses I look after. I have not noticed any performance degradation when running reports based off of the views versus a table direct approach but have never performed a detailed analysis. 2. I created the views using the designer in SQL Server management studio and did not use any automated approach. I can’t imagine the schema changing often enough that automating it would be worthwhile anyhow. You might spend as long tweaking the results as it would have taken to drag all the tables onto the view in the first place! To remove ambiguity a good approach is to preface the column names with the name of the dimension it belongs to. This is helpful to the report writers and to anyone running ad hoc queries.
128,478
<p><a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?</p> <p>Isn't this:</p> <pre><code>class SomeClass(object): def not_often_called(self) from datetime import datetime self.datetime = datetime.now() </code></pre> <p>more efficient than this?</p> <pre><code>from datetime import datetime class SomeClass(object): def not_often_called(self) self.datetime = datetime.now() </code></pre>
[ { "answer_id": 128522, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 4, "selected": false, "text": "<p>The first variant is indeed more efficient than the second when the function is called either zero or one times. With the second and subsequent invocations, however, the \"import every call\" approach is actually less efficient. See <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips#head-c849d5d5d94bc3eacbff9d5746af4083443cf2ca\" rel=\"noreferrer\">this link</a> for a lazy-loading technique that combines the best of both approaches by doing a \"lazy import\".</p>\n\n<p>But there are reasons other than efficiency why you might prefer one over the other. One approach is makes it much more clear to someone reading the code as to the dependencies that this module has. They also have very different failure characteristics -- the first will fail at load time if there's no \"datetime\" module while the second won't fail until the method is called.</p>\n\n<p><strong>Added Note:</strong> In IronPython, imports can be quite a bit more expensive than in CPython because the code is basically being compiled as it's being imported.</p>\n" }, { "answer_id": 128525, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 3, "selected": false, "text": "<p>I wouldn't worry about the efficiency of loading the module up front too much. The memory taken up by the module won't be very big (assuming it's modular enough) and the startup cost will be negligible.</p>\n\n<p>In most cases you want to load the modules at the top of the source file. For somebody reading your code, it makes it much easier to tell what function or object came from what module.</p>\n\n<p>One good reason to import a module elsewhere in the code is if it's used in a debugging statement.</p>\n\n<p>For example:</p>\n\n<pre><code>do_something_with_x(x)\n</code></pre>\n\n<p>I could debug this with:</p>\n\n<pre><code>from pprint import pprint\npprint(x)\ndo_something_with_x(x)\n</code></pre>\n\n<p>Of course, the other reason to import modules elsewhere in the code is if you need to dynamically import them. This is because you pretty much don't have any choice.</p>\n\n<p>I wouldn't worry about the efficiency of loading the module up front too much. The memory taken up by the module won't be very big (assuming it's modular enough) and the startup cost will be negligible.</p>\n" }, { "answer_id": 128532, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 6, "selected": false, "text": "<p>Most of the time this would be useful for clarity and sensible to do but it's not always the case. Below are a couple of examples of circumstances where module imports might live elsewhere.</p>\n\n<p>Firstly, you could have a module with a unit test of the form:</p>\n\n<pre><code>if __name__ == '__main__':\n import foo\n aa = foo.xyz() # initiate something for the test\n</code></pre>\n\n<p>Secondly, you might have a requirement to conditionally import some different module at runtime.</p>\n\n<pre><code>if [condition]:\n import foo as plugin_api\nelse:\n import bar as plugin_api\nxx = plugin_api.Plugin()\n[...]\n</code></pre>\n\n<p>There are probably other situations where you might place imports in other parts in the code.</p>\n" }, { "answer_id": 128534, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 3, "selected": false, "text": "<p>It's a tradeoff, that only the programmer can decide to make. </p>\n\n<p>Case 1 saves some memory and startup time by not importing the datetime module (and doing whatever initialization it might require) until needed. Note that doing the import 'only when called' also means doing it 'every time when called', so each call after the first one is still incurring the additional overhead of doing the import. </p>\n\n<p>Case 2 save some execution time and latency by importing datetime beforehand so that not_often_called() will return more quickly when it <em>is</em> called, and also by not incurring the overhead of an import on every call.</p>\n\n<p>Besides efficiency, it's easier to see module dependencies up front if the import statements are ... up front. Hiding them down in the code can make it more difficult to easily find what modules something depends on.</p>\n\n<p>Personally I generally follow the PEP except for things like unit tests and such that I don't want always loaded because I <em>know</em> they aren't going to be used except for test code.</p>\n" }, { "answer_id": 128549, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.</p>\n\n<p>Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.</p>\n\n<p>If you have to load heavyweight modules at unexpected times, it probably makes more sense to load them dynamically with the <code>__import__</code> function, and be <b>sure</b> to catch <code>ImportError</code> exceptions, and handle them in a reasonable manner.</p>\n" }, { "answer_id": 128577, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 10, "selected": true, "text": "<p>Module importing is quite fast, but not instant. This means that:</p>\n\n<ul>\n<li>Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once.</li>\n<li>Putting the imports within a function will cause calls to that function to take longer.</li>\n</ul>\n\n<p>So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you <strong>did</strong> profile to see where best to improve performance, right??)</p>\n\n<hr>\n\n<p>The best reasons I've seen to perform lazy imports are:</p>\n\n<ul>\n<li>Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed.</li>\n<li>In the <code>__init__.py</code> of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use <code>bzrlib</code>'s lazy-loading framework.</li>\n</ul>\n" }, { "answer_id": 128641, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 3, "selected": false, "text": "<p>Here's an example where all the imports are at the very top (this is the only time I've needed to do this). I want to be able to terminate a subprocess on both Un*x and Windows.</p>\n\n<pre><code>import os\n# ...\ntry:\n kill = os.kill # will raise AttributeError on Windows\n from signal import SIGTERM\n def terminate(process):\n kill(process.pid, SIGTERM)\nexcept (AttributeError, ImportError):\n try:\n from win32api import TerminateProcess # use win32api if available\n def terminate(process):\n TerminateProcess(int(process._handle), -1)\n except ImportError:\n def terminate(process):\n raise NotImplementedError # define a dummy function\n</code></pre>\n\n<p>(On review: what <a href=\"https://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module#128577\">John Millikin</a> said.)</p>\n" }, { "answer_id": 128655, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 3, "selected": false, "text": "<p>This is like many other optimizations - you sacrifice some readability for speed. As John mentioned, if you've done your profiling homework and found this to be a significantly useful enough change <strong>and</strong> you need the extra speed, then go for it. It'd probably be good to put a note up with all the other imports:</p>\n\n<pre><code>from foo import bar\nfrom baz import qux\n# Note: datetime is imported in SomeClass below\n</code></pre>\n" }, { "answer_id": 128684, "author": "Jeremy Brown", "author_id": 21776, "author_profile": "https://Stackoverflow.com/users/21776", "pm_score": 3, "selected": false, "text": "<p>Module initialization only occurs once - on the first import. If the module in question is from the standard library, then you will likely import it from other modules in your program as well. For a module as prevalent as datetime, it is also likely a dependency for a slew of other standard libraries. The import statement would cost very little then since the module intialization would have happened already. All it is doing at this point is binding the existing module object to the local scope.</p>\n\n<p>Couple that information with the argument for readability and I would say that it is best to have the import statement at module scope. </p>\n" }, { "answer_id": 128859, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>I have adopted the practice of putting all imports in the functions that use them, rather than at the top of the module.</p>\n\n<p>The benefit I get is the ability to refactor more reliably. When I move a function from one module to another, I know that the function will continue to work with all of its legacy of testing intact. If I have my imports at the top of the module, when I move a function, I find that I end up spending a lot of time getting the new module's imports complete and minimal. A refactoring IDE might make this irrelevant.</p>\n\n<p>There is a speed penalty as mentioned elsewhere. I have measured this in my application and found it to be insignificant for my purposes. </p>\n\n<p>It is also nice to be able to see all module dependencies up front without resorting to search (e.g. grep). However, the reason I care about module dependencies is generally because I'm installing, refactoring, or moving an entire system comprising multiple files, not just a single module. In that case, I'm going to perform a global search anyway to make sure I have the system-level dependencies. So I have not found global imports to aid my understanding of a system in practice.</p>\n\n<p>I usually put the import of <code>sys</code> inside the <code>if __name__=='__main__'</code> check and then pass arguments (like <code>sys.argv[1:]</code>) to a <code>main()</code> function. This allows me to use <code>main</code> in a context where <code>sys</code> has not been imported.</p>\n" }, { "answer_id": 129810, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 7, "selected": false, "text": "<p>Putting the import statement inside of a function can prevent circular dependencies.\nFor example, if you have 2 modules, X.py and Y.py, and they both need to import each other, this will cause a circular dependency when you import one of the modules causing an infinite loop. If you move the import statement in one of the modules then it won't try to import the other module till the function is called, and that module will already be imported, so no infinite loop. Read here for more - <a href=\"http://effbot.org/zone/import-confusion.htm\" rel=\"noreferrer\">effbot.org/zone/import-confusion.htm</a></p>\n" }, { "answer_id": 17407169, "author": "Caumons", "author_id": 955619, "author_profile": "https://Stackoverflow.com/users/955619", "pm_score": 2, "selected": false, "text": "<p>Just to complete <a href=\"https://stackoverflow.com/a/129810/955619\">Moe's answer</a> and the original question:</p>\n\n<p><strong>When we have to deal with circular dependences we can do some \"tricks\".</strong> Assuming we're working with modules <code>a.py</code> and <code>b.py</code> that contain <code>x()</code> and b <code>y()</code>, respectively. Then:</p>\n\n<ol>\n<li>We can move one of the <code>from imports</code> at the bottom of the module.</li>\n<li>We can move one of the <code>from imports</code> inside the function or method that is actually requiring the import (this isn't always possible, as you may use it from several places).</li>\n<li>We can change one of the two <code>from imports</code> to be an import that looks like: <code>import a</code></li>\n</ol>\n\n<p>So, to conclude. If you aren't dealing with circular dependencies and doing some kind of trick to avoid them, then it's better to put all your imports at the top because of the reasons already explained in other answers to this question. And please, when doing this \"tricks\" include a comment, it's always welcome! :)</p>\n" }, { "answer_id": 36406101, "author": "Paul", "author_id": 845800, "author_profile": "https://Stackoverflow.com/users/845800", "pm_score": 2, "selected": false, "text": "<p>In addition to the excellent answers already given, it's worth noting that the placement of imports is not merely a matter of style. Sometimes a module has implicit dependencies that need to be imported or initialized first, and a top-level import could lead to violations of the required order of execution. </p>\n\n<p>This issue often comes up in Apache Spark's Python API, where you need to initialize the SparkContext before importing any pyspark packages or modules. It's best to place pyspark imports in a scope where the SparkContext is guaranteed to be available.</p>\n" }, { "answer_id": 40862317, "author": "HiFile.app - best file manager", "author_id": 2757925, "author_profile": "https://Stackoverflow.com/users/2757925", "pm_score": 2, "selected": false, "text": "<p>I do not aspire to provide complete answer, because others have already done this very well. I just want to mention one use case when I find especially useful to import modules inside functions. My application uses python packages and modules stored in certain location as plugins. During application startup, the application walks through all the modules in the location and imports them, then it looks inside the modules and if it finds some mounting points for the plugins (in my case it is a subclass of a certain base class having a unique ID) it registers them. The number of plugins is large (now dozens, but maybe hundreds in the future) and each of them is used quite rarely. Having imports of third party libraries at the top of my plugin modules was a bit penalty during application startup. Especially some thirdparty libraries are heavy to import (e.g. import of plotly even tries to connect to internet and download something which was adding about one second to startup). By optimizing imports (calling them only in the functions where they are used) in the plugins I managed to shrink the startup from 10 seconds to some 2 seconds. That is a big difference for my users.</p>\n\n<p>So my answer is no, do not always put the imports at the top of your modules.</p>\n" }, { "answer_id": 49743276, "author": "K.-Michael Aye", "author_id": 680232, "author_profile": "https://Stackoverflow.com/users/680232", "pm_score": 2, "selected": false, "text": "<p>It's interesting that not a single answer mentioned parallel processing so far, where it might be REQUIRED that the imports are in the function, when the serialized function code is what is being pushed around to other cores, e.g. like in the case of ipyparallel.</p>\n" }, { "answer_id": 50282333, "author": "TextGeek", "author_id": 266371, "author_profile": "https://Stackoverflow.com/users/266371", "pm_score": 3, "selected": false, "text": "<p>I was surprised not to see actual cost numbers for the repeated load-checks posted already, although there are many good explanations of what to expect.</p>\n\n<p>If you import at the top, you take the load hit no matter what. That's pretty small, but commonly in the milliseconds, not nanoseconds.</p>\n\n<p>If you import within a function(s), then you only take the hit for loading <em>if</em> and <em>when</em> one of those functions is first called. As many have pointed out, if that doesn't happen at all, you save the load time. But if the function(s) get called a lot, you take a repeated though much smaller hit (for checking that it <em>has</em> been loaded; not for actually re-loading). On the other hand, as @aaronasterling pointed out you also save a little because importing within a function lets the function use slightly-faster <em>local variable</em> lookups to identify the name later (<a href=\"http://stackoverflow.com/questions/477096/python-import-coding-style/4789963#4789963\">http://stackoverflow.com/questions/477096/python-import-coding-style/4789963#4789963</a>).</p>\n\n<p>Here are the results of a simple test that imports a few things from inside a function. The times reported (in Python 2.7.14 on a 2.3 GHz Intel Core i7) are shown below (the 2nd call taking more than later calls seems consistent, though I don't know why).</p>\n\n<pre><code> 0 foo: 14429.0924 µs\n 1 foo: 63.8962 µs\n 2 foo: 10.0136 µs\n 3 foo: 7.1526 µs\n 4 foo: 7.8678 µs\n 0 bar: 9.0599 µs\n 1 bar: 6.9141 µs\n 2 bar: 7.1526 µs\n 3 bar: 7.8678 µs\n 4 bar: 7.1526 µs\n</code></pre>\n\n<p>The code:</p>\n\n<pre><code>from __future__ import print_function\nfrom time import time\n\ndef foo():\n import collections\n import re\n import string\n import math\n import subprocess\n return\n\ndef bar():\n import collections\n import re\n import string\n import math\n import subprocess\n return\n\nt0 = time()\nfor i in xrange(5):\n foo()\n t1 = time()\n print(\" %2d foo: %12.4f \\xC2\\xB5s\" % (i, (t1-t0)*1E6))\n t0 = t1\nfor i in xrange(5):\n bar()\n t1 = time()\n print(\" %2d bar: %12.4f \\xC2\\xB5s\" % (i, (t1-t0)*1E6))\n t0 = t1\n</code></pre>\n" }, { "answer_id": 51198720, "author": "Cedar", "author_id": 5810747, "author_profile": "https://Stackoverflow.com/users/5810747", "pm_score": 0, "selected": false, "text": "<p>I would like to mention a usecase of mine, very similar to those mentioned by @John Millikin and @V.K.:</p>\n<h1>Optional Imports</h1>\n<p>I do data analysis with Jupyter Notebook, and I use the same IPython notebook as a template for all analyses. In some occasions, I need to import Tensorflow to do some quick model runs, but sometimes I work in places where tensorflow isn't set up / is slow to import. In those cases, I encapsulate my Tensorflow-dependent operations in a helper function, import tensorflow inside that function, and bind it to a button.</p>\n<p>This way, I could do &quot;restart-and-run-all&quot; without having to wait for the import, or having to resume the rest of the cells when it fails.</p>\n" }, { "answer_id": 53168846, "author": "quiet_penguin", "author_id": 1086143, "author_profile": "https://Stackoverflow.com/users/1086143", "pm_score": 1, "selected": false, "text": "<p>There can be a performance gain by importing variables/local scoping inside of a function. This depends on the usage of the imported thing inside the function. If you are looping many times and accessing a module global object, importing it as local can help. </p>\n\n<h1>test.py</h1>\n\n<pre><code>X=10\nY=11\nZ=12\ndef add(i):\n i = i + 10\n</code></pre>\n\n<h1>runlocal.py</h1>\n\n<pre><code>from test import add, X, Y, Z\n\n def callme():\n x=X\n y=Y\n z=Z\n ladd=add \n for i in range(100000000):\n ladd(i)\n x+y+z\n\n callme()\n</code></pre>\n\n<h1>run.py</h1>\n\n<pre><code>from test import add, X, Y, Z\n\ndef callme():\n for i in range(100000000):\n add(i)\n X+Y+Z\n\ncallme()\n</code></pre>\n\n<p>A time on Linux shows a small gain</p>\n\n<pre><code>/usr/bin/time -f \"\\t%E real,\\t%U user,\\t%S sys\" python run.py \n 0:17.80 real, 17.77 user, 0.01 sys\n/tmp/test$ /usr/bin/time -f \"\\t%E real,\\t%U user,\\t%S sys\" python runlocal.py \n 0:14.23 real, 14.22 user, 0.01 sys\n</code></pre>\n\n<p>real is wall clock. user is time in program. sys is time for system calls.</p>\n\n<p><a href=\"https://docs.python.org/3.5/reference/executionmodel.html#resolution-of-names\" rel=\"nofollow noreferrer\">https://docs.python.org/3.5/reference/executionmodel.html#resolution-of-names</a></p>\n" }, { "answer_id": 57953097, "author": "LJHW", "author_id": 8502603, "author_profile": "https://Stackoverflow.com/users/8502603", "pm_score": 0, "selected": false, "text": "<p>This is a fascinating discussion. Like many others I had never even considered this topic. I got cornered into having to have the imports in the functions because of wanting to use the Django ORM in one of my libraries. I was having to call <code>django.setup()</code> before importing my model classes and because this was at the top of the file it was being dragged into completely non-Django library code because of the IoC injector construction.</p>\n\n<p>I kind of hacked around a bit and ended up putting the <code>django.setup()</code> in the singleton constructor and the relevant import at the top of each class method. Now this worked fine but made me uneasy because the imports weren't at the top and also I started worrying about the extra time hit of the imports. Then I came here and read with great interest everybody's take on this.</p>\n\n<p>I have a long C++ background and now use Python/Cython. My take on this is that why not put the imports in the function unless it causes you a profiled bottleneck. It's only like declaring space for variables just before you need them. The trouble is I have thousands of lines of code with all the imports at the top! So I think I will do it from now on and change the odd file here and there when I'm passing through and have the time.</p>\n" }, { "answer_id": 59812974, "author": "WinEunuuchs2Unix", "author_id": 6929343, "author_profile": "https://Stackoverflow.com/users/6929343", "pm_score": 2, "selected": false, "text": "<h1>Readability</h1>\n<p>In addition to startup performance, there is a readability argument to be made for localizing <code>import</code> statements. For example take python line numbers 1283 through 1296 in my current first python project:</p>\n<pre><code>listdata.append(['tk font version', font_version])\nlistdata.append(['Gtk version', str(Gtk.get_major_version())+&quot;.&quot;+\n str(Gtk.get_minor_version())+&quot;.&quot;+\n str(Gtk.get_micro_version())])\n\nimport xml.etree.ElementTree as ET\n\nxmltree = ET.parse('/usr/share/gnome/gnome-version.xml')\nxmlroot = xmltree.getroot()\nresult = []\nfor child in xmlroot:\n result.append(child.text)\nlistdata.append(['Gnome version', result[0]+&quot;.&quot;+result[1]+&quot;.&quot;+\n result[2]+&quot; &quot;+result[3]])\n</code></pre>\n<p>If the <code>import</code> statement was at the top of file I would have to scroll up a long way, or press <kbd>Home</kbd>, to find out what <code>ET</code> was. Then I would have to navigate back to line 1283 to continue reading code.</p>\n<p>Indeed even if the <code>import</code> statement was at the top of the function (or class) as many would place it, paging up and back down would be required.</p>\n<p>Displaying the Gnome version number will rarely be done so the <code>import</code> at top of file introduces unnecessary startup lag.</p>\n" }, { "answer_id": 69171198, "author": "None", "author_id": 1038726, "author_profile": "https://Stackoverflow.com/users/1038726", "pm_score": 1, "selected": false, "text": "<p>While <a href=\"https://pep8.org/#imports\" rel=\"nofollow noreferrer\">PEP</a> encourages importing at the top of a module, it isn't an error to import at other levels. That indicates imports should be at the top, however there are exceptions.</p>\n<p>It is a micro-optimization to load modules when they are used. Code that is sluggish importing can be optimized later if it makes a sizable difference.</p>\n<p>Still, you might introduce flags to conditionally import at as near to the top as possible, allowing a user to use configuration to import the modules they need while still importing everything immediately.</p>\n<p>Importing as soon as possible means the program will fail if any imports (or imports of imports) are missing or have syntax errors. If all imports occur at the top of all modules then python works in two steps. Compile. Run.</p>\n<p>Built in modules work anywhere they are imported because they are well designed. Modules you write should be the same. Moving around your imports to the top or to their first use can help ensure there are no side effects and the code is injecting dependencies.</p>\n<p>Whether you put imports at the top or not, your code should still work when the imports are at the top. So start by importing immediately then optimize as needed.</p>\n" }, { "answer_id": 69928434, "author": "Patrick", "author_id": 38281, "author_profile": "https://Stackoverflow.com/users/38281", "pm_score": 3, "selected": false, "text": "<p>Here's an updated <strong>summary</strong> of the answers to this\n<a href=\"https://stackoverflow.com/questions/1188640\">and</a>\n<a href=\"https://stackoverflow.com/questions/1024049\">related</a>\nquestions.</p>\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\"><strong>PEP 8</strong></a>\nrecommends putting imports at the top.</li>\n<li>It's often more convenient to get\n<a href=\"https://stackoverflow.com/a/128522/38281\"><code>ImportError</code>s</a>\nwhen you first run your program\nrather than when your program first calls your function.</li>\n<li>Putting imports in the function scope\ncan help avoid issues with <a href=\"https://stackoverflow.com/a/129810/\">circular imports</a>.</li>\n<li>Putting imports in the function scope\nhelps keep maintain a <em>clean module namespace</em>,\nso that it does not appear among tab-completion suggestions.</li>\n<li><a href=\"https://stackoverflow.com/a/40862317/\">Start-up time</a>:\nimports in a function won't run until (if) that function is called.\nMight get significant with heavy-weight libraries.</li>\n<li>Even though import statements are super fast on subsequent runs,\nthey still incur a <a href=\"https://stackoverflow.com/a/1189199/\">speed penalty</a>\nwhich can be significant if the function is trivial but frequently in use.</li>\n<li>Imports under the <code>__name__ == &quot;__main__&quot;</code> guard <a href=\"https://stackoverflow.com/a/128532/\">seem very reasonable</a>.</li>\n<li><a href=\"https://stackoverflow.com/a/128859/38281\">Refactoring</a>\nmight be easier if the imports are located in the function\n<em>where they're used</em> (facilitates moving it to another module).\nIt can also be argued that this is good for <em>readability</em>.\nHowever, most would argue the contrary, i.e.</li>\n<li>Imports at the top enhance <em>readability</em>,\nsince you can see all your <em>dependencies</em> at a glance.</li>\n<li>It seems unclear if <em>dynamic</em> or <em>conditional</em> imports favour one style over another.</li>\n</ul>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15676/" ]
[PEP 8](http://www.python.org/dev/peps/pep-0008/) states: > > Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. > > > However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed? Isn't this: ``` class SomeClass(object): def not_often_called(self) from datetime import datetime self.datetime = datetime.now() ``` more efficient than this? ``` from datetime import datetime class SomeClass(object): def not_often_called(self) self.datetime = datetime.now() ```
Module importing is quite fast, but not instant. This means that: * Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once. * Putting the imports within a function will cause calls to that function to take longer. So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you **did** profile to see where best to improve performance, right??) --- The best reasons I've seen to perform lazy imports are: * Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed. * In the `__init__.py` of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use `bzrlib`'s lazy-loading framework.
128,502
<p>I've just updated my ruby installation on my gentoo server to ruby 1.8.6 patchlevel 287 and have started getting an error on one of my eRuby apps. The error given in the apache error_log file is:</p> <pre><code>[error] mod_ruby: /usr/lib/ruby/1.8/cgi.rb:774: superclass mismatch for class Cookie (TypeError) </code></pre> <p>The strange thing is that it seems to work sometimes - but other times I get that error. Anyone any ideas?</p>
[ { "answer_id": 129051, "author": "Ben Stiglitz", "author_id": 6298, "author_profile": "https://Stackoverflow.com/users/6298", "pm_score": 3, "selected": true, "text": "<p>That error shows up when you redeclare a class that’s already been declared, most likely because you’re loading two different copies of cgi.rb. See a <a href=\"http://209.85.173.104/search?q=cache:wbXLBotEIvUJ:railsforum.com/viewtopic.php%3Fid%3D10993+superclass+mismatch+for&amp;hl=en&amp;ct=clnk&amp;cd=3&amp;gl=us&amp;client=safari\" rel=\"nofollow noreferrer\">similar issue in Rails</a>.</p>\n" }, { "answer_id": 211049, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 3, "selected": false, "text": "<p>As the error message says, there is an opening of the Cookie class somewhere in the code that is using a different superclass than the one used in a prior definition or opening of the Cookie class.</p>\n\n<p>Even a class definition that does not explicitly specify a superclass still has a superclass:</p>\n\n<pre><code>class Cookie\nend\n</code></pre>\n\n<p>This defines the Cookie class with the superclass of Object.</p>\n\n<p>I've encountered this error before, and it will occur when you have some code trying to reopen a class without specifying the superclass, and the programmer's assumption is that the class (in this case, Cookie) has already been defined, and that he is simply reopening it to add some functionality. But if the reopening and the definition are in reverse order, you'll get that error because the class will already have been defined as a subclass of Object, but is trying to be redefined or reopened with a different superclass. Try this in irb:</p>\n\n<pre><code>% irb\nirb(main):001:0&gt; class C &lt; String; end\n=&gt; nil\nirb(main):002:0&gt; class C; end\n=&gt; nil\nirb(main):003:0&gt; exit\n% irb\nirb(main):001:0&gt; class C; end\n=&gt; nil\nirb(main):002:0&gt; class C &lt; String; end\nTypeError: superclass mismatch for class C\n from (irb):2\n</code></pre>\n\n<p>So, you probably just have to grep for definitions of the Cookie class and try to ensure files are always being require-d in the correct order. This may or may not be easy. :)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
I've just updated my ruby installation on my gentoo server to ruby 1.8.6 patchlevel 287 and have started getting an error on one of my eRuby apps. The error given in the apache error\_log file is: ``` [error] mod_ruby: /usr/lib/ruby/1.8/cgi.rb:774: superclass mismatch for class Cookie (TypeError) ``` The strange thing is that it seems to work sometimes - but other times I get that error. Anyone any ideas?
That error shows up when you redeclare a class that’s already been declared, most likely because you’re loading two different copies of cgi.rb. See a [similar issue in Rails](http://209.85.173.104/search?q=cache:wbXLBotEIvUJ:railsforum.com/viewtopic.php%3Fid%3D10993+superclass+mismatch+for&hl=en&ct=clnk&cd=3&gl=us&client=safari).
128,527
<p>We have our JBoss and Oracle on separate servers. The connections seem to be dropped and is causing issues with JBoss. How can I have the JBoss reconnect to Oracle if the connection is bad while we figure out why the connections are being dropped in the first place?</p>
[ { "answer_id": 129333, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 6, "selected": true, "text": "<p>There is usually a configuration option on the pool to enable a validation query to be executed on borrow. If the validation query executes successfully, the pool will return that connection. If the query does not execute successfully, the pool will create a new connection. </p>\n\n<p>The <a href=\"http://community.jboss.org/wiki/ConfigDataSources\" rel=\"noreferrer\">JBoss Wiki</a> documents the various attributes of the pool. </p>\n\n<pre><code>&lt;check-valid-connection-sql&gt;select 1 from dual&lt;/check-valid-connection-sql&gt;\n</code></pre>\n\n<p>Seems like it should do the trick.</p>\n" }, { "answer_id": 145889, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 5, "selected": false, "text": "<p>Whilst you can use the old \"select 1 from dual\" trick, the downside with this is that it issues an extra query each and every time you borrow a connection from the pool. For high volumes, this is wasteful.</p>\n\n<p>JBoss provides a special connection validator which should be used for Oracle:</p>\n\n<pre><code>&lt;valid-connection-checker-class-name&gt;\n org.jboss.resource.adapter.jdbc.vendor.OracleValidConnectionChecker\n&lt;/valid-connection-checker-class-name&gt;\n</code></pre>\n\n<p>This makes use of the proprietary ping() method on the Oracle JDBC Connection class, and uses the driver's underlying networking code to determine if the connection is still alive. </p>\n\n<p>However, it's still wasteful to run this each and every time a connection is borrowed, so you may want to use the facility where a background thread checks the connections in the pool, and silently discards the dead ones. This is much more efficient, but means that if the connections <em>do</em> go dead, any attempt to use them before the background thread runs its check will fail.</p>\n\n<p>See the <a href=\"http://community.jboss.org/wiki/configdatasources\" rel=\"noreferrer\">wiki docs</a> for how to configure the background checking (look for <code>background-validation-millis</code>).</p>\n" }, { "answer_id": 11164723, "author": "arviarya", "author_id": 409410, "author_profile": "https://Stackoverflow.com/users/409410", "pm_score": 3, "selected": false, "text": "<p>JBoss provides 2 ways to Validate connection:\n- Ping based AND \n- Query based</p>\n\n<p>You can use as per requirement. This is scheduled by separate thread as per duration defined in datasource configuration file.</p>\n\n<pre><code>&lt;background-validation&gt;true&lt;/background-validation&gt; &lt;background-validation-minutes&gt;1&lt;/background-validation-minutes&gt;\n</code></pre>\n\n<p>Some time if you are not having right oracle driver at Jboss, you may get classcast or related error and for that connection may start dropout from connection pool. You can try creating your own ConnectionValidator class by implementing <code>org.jboss.resource.adapter.jdbc.ValidConnectionChecker</code> interface. This interface provides only single method '<code>isValidConnection()</code>' and expecting 'NULL' in return for valid connection.</p>\n\n<p>Ex:</p>\n\n<pre><code>public class OracleValidConnectionChecker implements ValidConnectionChecker, Serializable {\n\n private Method ping;\n\n // The timeout (apparently the timeout is ignored?)\n private static Object[] params = new Object[] { new Integer(5000) };\n\n public SQLException isValidConnection(Connection c) {\n\n try {\n Integer status = (Integer) ping.invoke(c, params);\n\n if (status.intValue() &lt; 0) {\n return new SQLException(\"pingDatabase failed status=\" + status);\n }\n\n }\n catch (Exception e) {\n log.warn(\"Unexpected error in pingDatabase\", e);\n }\n\n // OK\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 24332194, "author": "abh", "author_id": 311003, "author_profile": "https://Stackoverflow.com/users/311003", "pm_score": 3, "selected": false, "text": "<p>Not enough rep for a comment, so it's in a form of an answer. The <code>'Select 1 from dual'</code> and skaffman's <code>org.jboss.resource.adapter.jdbc.vendor.OracleValidConnectionChecker</code> method are equivalent , although the connection check does provide a level of abstraction. We had to decompile the oracle jdbc drivers for a troubleshooting exercise and Oracle's internal implementation of the ping is to perform a <code>'Select 'x' from dual'</code>. Natch. </p>\n" }, { "answer_id": 27361193, "author": "Jakub Godoniuk", "author_id": 995623, "author_profile": "https://Stackoverflow.com/users/995623", "pm_score": 2, "selected": false, "text": "<p>A little update to @skaffman's answer. In JBoss 7 you have to use \"class-name\" attribute when setting valid connection checker and also package is different:</p>\n\n<p><code>&lt;valid-connection-checker class-name=\"org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker\" /&gt;</code></p>\n" }, { "answer_id": 32844258, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 2, "selected": false, "text": "<p>We've recently had some floating request handling failures caused by orphaned oracle <code>DBMS_LOCK</code> session locks that retained indefinitely in client-side connection pool. </p>\n\n<p>So here is a solution that forces session expiry in 30 minutes but doesn't affect application's operation:</p>\n\n<pre><code>&lt;check-valid-connection-sql&gt;select case when 30/60/24 &gt; sysdate-LOGON_TIME then 1 else 1/0 end \nfrom V$SESSION where AUDSID = userenv('SESSIONID')&lt;/check-valid-connection-sql&gt;\n</code></pre>\n\n<p>This may involve some slow down in process of obtaining connections from pool. Make sure to test this under load.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
We have our JBoss and Oracle on separate servers. The connections seem to be dropped and is causing issues with JBoss. How can I have the JBoss reconnect to Oracle if the connection is bad while we figure out why the connections are being dropped in the first place?
There is usually a configuration option on the pool to enable a validation query to be executed on borrow. If the validation query executes successfully, the pool will return that connection. If the query does not execute successfully, the pool will create a new connection. The [JBoss Wiki](http://community.jboss.org/wiki/ConfigDataSources) documents the various attributes of the pool. ``` <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql> ``` Seems like it should do the trick.
128,561
<p>I have a new application written in WPF that needs to support an old API that allows it to receive a message that has been posted to a hidden window. Typically another application uses FindWindow to identify the hidden window using the name of its custom window class.</p> <p><strong>1) I assume to implement a custom window class I need to use old school win32 calls?</strong></p> <p>My old c++ application used RegisterClass and CreateWindow to make the simplest possible invisible window.</p> <p>I believe I should be able to do the same all within c#. I don't want my project to have to compile any unmanaged code.</p> <p>I have tried inheriting from System.Windows.Interop.HwndHost and using System.Runtime.InteropServices.DllImport to pull in the above API methods.</p> <p>Doing this I can successfully host a standard win32 window e.g. "listbox" inside WPF. However when I call CreateWindowEx for my custom window it always returns null.</p> <p>My call to RegisterClass succeeds but I am not sure what I should be setting the WNDCLASS.lpfnWndProc member to.</p> <p><strong>2) Does anyone know how to do this successfully?</strong></p>
[ { "answer_id": 128622, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p><strong>1)</strong> You can just subclass a normal Windows Forms class... no need for all those win32 calls, you just need to parse the WndProc message manually... is all.</p>\n\n<p><strong>2)</strong> You can import the System.Windows.Forms namespace and use it alongside WPF, I believe there won't be any problems as long as you don't intertwine too much windows forms into your WPF application. You just want to instantiate your custom hidden form to receieve a message is that right?</p>\n\n<p>example of WndProc subclassing:</p>\n\n<pre><code>protected override void WndProc(ref System.Windows.Forms.Message m)\n{\n // *always* let the base class process the message\n base.WndProc(ref m);\n\n const int WM_NCHITTEST = 0x84;\n const int HTCAPTION = 2;\n const int HTCLIENT = 1;\n\n // if Windows is querying where the mouse is and the base form class said\n // it's on the client area, let's cheat and say it's on the title bar instead\n if ( m.Msg == WM_NCHITTEST &amp;&amp; m.Result.ToInt32() == HTCLIENT )\n m.Result = new IntPtr(HTCAPTION);\n}\n</code></pre>\n\n<p>Since you already know RegisterClass and all those Win32 calls, I assume the WndProc message wouldn't be a problem for you...</p>\n" }, { "answer_id": 138468, "author": "morechilli", "author_id": 5427, "author_profile": "https://Stackoverflow.com/users/5427", "pm_score": 6, "selected": true, "text": "<p>For the record I finally got this to work.\nTurned out the difficulties I had were down to string marshalling problems.\nI had to be more precise in my importing of win32 functions.</p>\n\n<p>Below is the code that will create a custom window class in c# - useful for supporting old APIs you might have that rely on custom window classes.</p>\n\n<p>It should work in either WPF or Winforms as long as a message pump is running on the thread.</p>\n\n<p>EDIT:\nUpdated to fix the reported crash due to early collection of the delegate that wraps the callback. The delegate is now held as a member and the delegate explicitly marshaled as a function pointer. This fixes the issue and makes it easier to understand the behaviour.</p>\n\n<pre><code>class CustomWindow : IDisposable\n{\n delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);\n\n [System.Runtime.InteropServices.StructLayout(\n System.Runtime.InteropServices.LayoutKind.Sequential,\n CharSet = System.Runtime.InteropServices.CharSet.Unicode\n )]\n struct WNDCLASS\n {\n public uint style;\n public IntPtr lpfnWndProc;\n public int cbClsExtra;\n public int cbWndExtra;\n public IntPtr hInstance;\n public IntPtr hIcon;\n public IntPtr hCursor;\n public IntPtr hbrBackground;\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n public string lpszMenuName;\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n public string lpszClassName;\n }\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern System.UInt16 RegisterClassW(\n [System.Runtime.InteropServices.In] ref WNDCLASS lpWndClass\n );\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr CreateWindowExW(\n UInt32 dwExStyle,\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n string lpClassName,\n [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]\n string lpWindowName,\n UInt32 dwStyle,\n Int32 x,\n Int32 y,\n Int32 nWidth,\n Int32 nHeight,\n IntPtr hWndParent,\n IntPtr hMenu,\n IntPtr hInstance,\n IntPtr lpParam\n );\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern System.IntPtr DefWindowProcW(\n IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam\n );\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\", SetLastError = true)]\n static extern bool DestroyWindow(\n IntPtr hWnd\n );\n\n private const int ERROR_CLASS_ALREADY_EXISTS = 1410;\n\n private bool m_disposed;\n private IntPtr m_hwnd;\n\n public void Dispose() \n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing) \n {\n if (!m_disposed) {\n if (disposing) {\n // Dispose managed resources\n }\n\n // Dispose unmanaged resources\n if (m_hwnd != IntPtr.Zero) {\n DestroyWindow(m_hwnd);\n m_hwnd = IntPtr.Zero;\n }\n\n }\n }\n\n public CustomWindow(string class_name){\n\n if (class_name == null) throw new System.Exception(\"class_name is null\");\n if (class_name == String.Empty) throw new System.Exception(\"class_name is empty\");\n\n m_wnd_proc_delegate = CustomWndProc;\n\n // Create WNDCLASS\n WNDCLASS wind_class = new WNDCLASS();\n wind_class.lpszClassName = class_name;\n wind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate);\n\n UInt16 class_atom = RegisterClassW(ref wind_class);\n\n int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();\n\n if (class_atom == 0 &amp;&amp; last_error != ERROR_CLASS_ALREADY_EXISTS) {\n throw new System.Exception(\"Could not register window class\");\n }\n\n // Create window\n m_hwnd = CreateWindowExW(\n 0,\n class_name,\n String.Empty,\n 0,\n 0,\n 0,\n 0,\n 0,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero\n );\n }\n\n private static IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) \n {\n return DefWindowProcW(hWnd, msg, wParam, lParam);\n }\n\n private WndProc m_wnd_proc_delegate;\n}\n</code></pre>\n" }, { "answer_id": 14162921, "author": "Paul", "author_id": 1122375, "author_profile": "https://Stackoverflow.com/users/1122375", "pm_score": -1, "selected": false, "text": "<p>WNDCLASS wind_class;\nput the definition in the class, not the function, and the crash will be fixed.</p>\n" }, { "answer_id": 18056924, "author": "Martini Bianco", "author_id": 2062574, "author_profile": "https://Stackoverflow.com/users/2062574", "pm_score": 1, "selected": false, "text": "<p>I'd like to comment the answer of morechilli:</p>\n\n<pre><code>public CustomWindow(string class_name){\n\n if (class_name == null) throw new System.Exception(\"class_name is null\");\n if (class_name == String.Empty) throw new System.Exception(\"class_name is empty\");\n\n // Create WNDCLASS\n WNDCLASS wind_class = new WNDCLASS();\n wind_class.lpszClassName = class_name;\n wind_class.lpfnWndProc = CustomWndProc;\n\n UInt16 class_atom = RegisterClassW(ref wind_class);\n\n int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();\n\n if (class_atom == 0 &amp;&amp; last_error != ERROR_CLASS_ALREADY_EXISTS) {\n throw new System.Exception(\"Could not register window class\");\n }\n\n // Create window\n m_hwnd = CreateWindowExW(\n 0,\n class_name,\n String.Empty,\n 0,\n 0,\n 0,\n 0,\n 0,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero,\n IntPtr.Zero\n );\n}\n</code></pre>\n\n<p>In the constructor I copied above is slight error: The WNDCLASS instance is created, but not saved. It will eventually be garbage collected. But the WNDCLASS holds the WndProc delegate. This results in an error as soon as WNDCLASS is garbage collected. The instance of WNDCLASS should be hold in a member variable until the window is destroyed.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5427/" ]
I have a new application written in WPF that needs to support an old API that allows it to receive a message that has been posted to a hidden window. Typically another application uses FindWindow to identify the hidden window using the name of its custom window class. **1) I assume to implement a custom window class I need to use old school win32 calls?** My old c++ application used RegisterClass and CreateWindow to make the simplest possible invisible window. I believe I should be able to do the same all within c#. I don't want my project to have to compile any unmanaged code. I have tried inheriting from System.Windows.Interop.HwndHost and using System.Runtime.InteropServices.DllImport to pull in the above API methods. Doing this I can successfully host a standard win32 window e.g. "listbox" inside WPF. However when I call CreateWindowEx for my custom window it always returns null. My call to RegisterClass succeeds but I am not sure what I should be setting the WNDCLASS.lpfnWndProc member to. **2) Does anyone know how to do this successfully?**
For the record I finally got this to work. Turned out the difficulties I had were down to string marshalling problems. I had to be more precise in my importing of win32 functions. Below is the code that will create a custom window class in c# - useful for supporting old APIs you might have that rely on custom window classes. It should work in either WPF or Winforms as long as a message pump is running on the thread. EDIT: Updated to fix the reported crash due to early collection of the delegate that wraps the callback. The delegate is now held as a member and the delegate explicitly marshaled as a function pointer. This fixes the issue and makes it easier to understand the behaviour. ``` class CustomWindow : IDisposable { delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [System.Runtime.InteropServices.StructLayout( System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Unicode )] struct WNDCLASS { public uint style; public IntPtr lpfnWndProc; public int cbClsExtra; public int cbWndExtra; public IntPtr hInstance; public IntPtr hIcon; public IntPtr hCursor; public IntPtr hbrBackground; [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string lpszMenuName; [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string lpszClassName; } [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern System.UInt16 RegisterClassW( [System.Runtime.InteropServices.In] ref WNDCLASS lpWndClass ); [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern IntPtr CreateWindowExW( UInt32 dwExStyle, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string lpClassName, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string lpWindowName, UInt32 dwStyle, Int32 x, Int32 y, Int32 nWidth, Int32 nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam ); [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern System.IntPtr DefWindowProcW( IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam ); [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern bool DestroyWindow( IntPtr hWnd ); private const int ERROR_CLASS_ALREADY_EXISTS = 1410; private bool m_disposed; private IntPtr m_hwnd; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!m_disposed) { if (disposing) { // Dispose managed resources } // Dispose unmanaged resources if (m_hwnd != IntPtr.Zero) { DestroyWindow(m_hwnd); m_hwnd = IntPtr.Zero; } } } public CustomWindow(string class_name){ if (class_name == null) throw new System.Exception("class_name is null"); if (class_name == String.Empty) throw new System.Exception("class_name is empty"); m_wnd_proc_delegate = CustomWndProc; // Create WNDCLASS WNDCLASS wind_class = new WNDCLASS(); wind_class.lpszClassName = class_name; wind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate); UInt16 class_atom = RegisterClassW(ref wind_class); int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) { throw new System.Exception("Could not register window class"); } // Create window m_hwnd = CreateWindowExW( 0, class_name, String.Empty, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero ); } private static IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { return DefWindowProcW(hWnd, msg, wParam, lParam); } private WndProc m_wnd_proc_delegate; } ```
128,573
<p>I have a class with two class methods (using the <code>classmethod()</code> function) for getting and setting what is essentially a static variable. I tried to use the <code>property()</code> function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter:</p> <pre><code>class Foo(object): _var = 5 @classmethod def getvar(cls): return cls._var @classmethod def setvar(cls, value): cls._var = value var = property(getvar, setvar) </code></pre> <p>I can demonstrate the class methods, but they don't work as properties:</p> <pre><code>&gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.getvar() 5 &gt;&gt;&gt; f.setvar(4) &gt;&gt;&gt; f.getvar() 4 &gt;&gt;&gt; f.var Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in ? TypeError: 'classmethod' object is not callable &gt;&gt;&gt; f.var=5 Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in ? TypeError: 'classmethod' object is not callable </code></pre> <p>Is it possible to use the <code>property()</code> function with <code>@classmethod</code> decorated functions?</p>
[ { "answer_id": 128624, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": -1, "selected": false, "text": "<p>Here's my suggestion. Don't use class methods. </p>\n\n<p>Seriously. </p>\n\n<p>What's the reason for using class methods in this case? Why not have an ordinary object of an ordinary class?</p>\n\n<hr>\n\n<p>If you simply want to change the value, a property isn't really very helpful is it? Just set the attribute value and be done with it.</p>\n\n<p>A property should only be used if there's something to conceal -- something that might change in a future implementation. </p>\n\n<p>Maybe your example is way stripped down, and there is some hellish calculation you've left off. But it doesn't look like the property adds significant value.</p>\n\n<p>The Java-influenced \"privacy\" techniques (in Python, attribute names that begin with _) aren't really very helpful. Private from whom? The point of private is a little nebulous when you have the source (as you do in Python.)</p>\n\n<p>The Java-influenced EJB-style getters and setters (often done as properties in Python) are there to facilitate Java's primitive introspection as well as to pass muster with the static language compiler. All those getters and setters aren't as helpful in Python.</p>\n" }, { "answer_id": 128812, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 2, "selected": false, "text": "<p>Half a solution, __set__ on the class does not work, still. The solution is a custom property class implementing both a property and a staticmethod</p>\n\n<pre><code>class ClassProperty(object):\n def __init__(self, fget, fset):\n self.fget = fget\n self.fset = fset\n\n def __get__(self, instance, owner):\n return self.fget()\n\n def __set__(self, instance, value):\n self.fset(value)\n\nclass Foo(object):\n _bar = 1\n def get_bar():\n print 'getting'\n return Foo._bar\n\n def set_bar(value):\n print 'setting'\n Foo._bar = value\n\n bar = ClassProperty(get_bar, set_bar)\n\nf = Foo()\n#__get__ works\nf.bar\nFoo.bar\n\nf.bar = 2\nFoo.bar = 3 #__set__ does not\n</code></pre>\n" }, { "answer_id": 129819, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 4, "selected": false, "text": "<p>There is no reasonable way to make this \"class property\" system to work in Python.</p>\n\n<p>Here is one unreasonable way to make it work. You can certainly make it more seamless with increasing amounts of metaclass magic.</p>\n\n<pre><code>class ClassProperty(object):\n def __init__(self, getter, setter):\n self.getter = getter\n self.setter = setter\n def __get__(self, cls, owner):\n return getattr(cls, self.getter)()\n def __set__(self, cls, value):\n getattr(cls, self.setter)(value)\n\nclass MetaFoo(type):\n var = ClassProperty('getvar', 'setvar')\n\nclass Foo(object):\n __metaclass__ = MetaFoo\n _var = 5\n @classmethod\n def getvar(cls):\n print \"Getting var =\", cls._var\n return cls._var\n @classmethod\n def setvar(cls, value):\n print \"Setting var =\", value\n cls._var = value\n\nx = Foo.var\nprint \"Foo.var = \", x\nFoo.var = 42\nx = Foo.var\nprint \"Foo.var = \", x\n</code></pre>\n\n<p>The knot of the issue is that properties are what Python calls \"descriptors\". There is no short and easy way to explain how this sort of metaprogramming works, so I must point you to the <a href=\"http://users.rcn.com/python/download/Descriptor.htm\" rel=\"noreferrer\">descriptor howto</a>.</p>\n\n<p>You only ever need to understand this sort of things if you are implementing a fairly advanced framework. Like a transparent object persistence or RPC system, or a kind of domain-specific language.</p>\n\n<p>However, in a comment to a previous answer, you say that you </p>\n\n<blockquote>\n <p>need to modify an attribute that in such a way that is seen by all instances of a class, and in the scope from which these class methods are called does not have references to all instances of the class.</p>\n</blockquote>\n\n<p>It seems to me, what you really want is an <a href=\"http://en.wikipedia.org/wiki/Observer_pattern\" rel=\"noreferrer\">Observer</a> design pattern.</p>\n" }, { "answer_id": 129868, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Because I need to modify an attribute that in such a way that is seen by all instances of a class, and in the scope from which these class methods are called does not have references to all instances of the class.</p>\n</blockquote>\n\n<p>Do you have access to at least one instance of the class? I can think of a way to do it then:</p>\n\n<pre><code>class MyClass (object):\n __var = None\n\n def _set_var (self, value):\n type (self).__var = value\n\n def _get_var (self):\n return self.__var\n\n var = property (_get_var, _set_var)\n\na = MyClass ()\nb = MyClass ()\na.var = \"foo\"\nprint b.var\n</code></pre>\n" }, { "answer_id": 130090, "author": "Sufian", "author_id": 9241, "author_profile": "https://Stackoverflow.com/users/9241", "pm_score": 2, "selected": false, "text": "<p>Give this a try, it gets the job done without having to change/add a lot of existing code.</p>\n\n<pre><code>&gt;&gt;&gt; class foo(object):\n... _var = 5\n... def getvar(cls):\n... return cls._var\n... getvar = classmethod(getvar)\n... def setvar(cls, value):\n... cls._var = value\n... setvar = classmethod(setvar)\n... var = property(lambda self: self.getvar(), lambda self, val: self.setvar(val))\n...\n&gt;&gt;&gt; f = foo()\n&gt;&gt;&gt; f.var\n5\n&gt;&gt;&gt; f.var = 3\n&gt;&gt;&gt; f.var\n3\n</code></pre>\n\n<p>The <code>property</code> function needs two <code>callable</code> arguments. give them lambda wrappers (which it passes the instance as its first argument) and all is well.</p>\n" }, { "answer_id": 1383402, "author": "Jason R. Coombs", "author_id": 70170, "author_profile": "https://Stackoverflow.com/users/70170", "pm_score": 6, "selected": false, "text": "<p>Reading the <a href=\"http://www.python.org/download/releases/2.2/descrintro/#property\" rel=\"noreferrer\">Python 2.2 release</a> notes, I find the following.</p>\n\n<blockquote>\n <p>The get method [of a property] won't be called when\n the property is accessed as a class\n attribute (C.x) instead of as an\n instance attribute (C().x). If you\n want to override the __get__ operation\n for properties when used as a class\n attribute, you can subclass property -\n it is a new-style type itself - to\n extend its __get__ method, or you can\n define a descriptor type from scratch\n by creating a new-style class that\n defines __get__, __set__ and\n __delete__ methods.</p>\n</blockquote>\n\n<p><strong>NOTE: The below method doesn't actually work for setters, only getters.</strong></p>\n\n<p>Therefore, I believe the prescribed solution is to create a ClassProperty as a subclass of property.</p>\n\n<pre><code>class ClassProperty(property):\n def __get__(self, cls, owner):\n return self.fget.__get__(None, owner)()\n\nclass foo(object):\n _var=5\n def getvar(cls):\n return cls._var\n getvar=classmethod(getvar)\n def setvar(cls,value):\n cls._var=value\n setvar=classmethod(setvar)\n var=ClassProperty(getvar,setvar)\n\nassert foo.getvar() == 5\nfoo.setvar(4)\nassert foo.getvar() == 4\nassert foo.var == 4\nfoo.var = 3\nassert foo.var == 3\n</code></pre>\n\n<p>However, the setters don't actually work:</p>\n\n<pre><code>foo.var = 4\nassert foo.var == foo._var # raises AssertionError\n</code></pre>\n\n<p><code>foo._var</code> is unchanged, you've simply overwritten the property with a new value.</p>\n\n<p>You can also use <code>ClassProperty</code> as a decorator:</p>\n\n<pre><code>class foo(object):\n _var = 5\n\n @ClassProperty\n @classmethod\n def var(cls):\n return cls._var\n\n @var.setter\n @classmethod\n def var(cls, value):\n cls._var = value\n\nassert foo.var == 5\n</code></pre>\n" }, { "answer_id": 1800999, "author": "A. Coady", "author_id": 36433, "author_profile": "https://Stackoverflow.com/users/36433", "pm_score": 7, "selected": false, "text": "<h3>3.8 &lt; Python &lt; 3.11</h3>\n<p>Can use both decorators together. See <a href=\"https://stackoverflow.com/a/64738850/674039\">this answer</a>.</p>\n<h3>Python &lt; 3.9</h3>\n<p>A property is created on a class but affects an instance. So if you want a <code>classmethod</code> property, create the property on the metaclass.</p>\n<pre><code>&gt;&gt;&gt; class foo(object):\n... _var = 5\n... class __metaclass__(type): # Python 2 syntax for metaclasses\n... pass\n... @classmethod\n... def getvar(cls):\n... return cls._var\n... @classmethod\n... def setvar(cls, value):\n... cls._var = value\n... \n&gt;&gt;&gt; foo.__metaclass__.var = property(foo.getvar.im_func, foo.setvar.im_func)\n&gt;&gt;&gt; foo.var\n5\n&gt;&gt;&gt; foo.var = 3\n&gt;&gt;&gt; foo.var\n3\n</code></pre>\n<p>But since you're using a metaclass anyway, it will read better if you just move the classmethods in there.</p>\n<pre><code>&gt;&gt;&gt; class foo(object):\n... _var = 5\n... class __metaclass__(type): # Python 2 syntax for metaclasses\n... @property\n... def var(cls):\n... return cls._var\n... @var.setter\n... def var(cls, value):\n... cls._var = value\n... \n&gt;&gt;&gt; foo.var\n5\n&gt;&gt;&gt; foo.var = 3\n&gt;&gt;&gt; foo.var\n3\n</code></pre>\n<p>or, using Python 3's <code>metaclass=...</code> syntax, and the metaclass defined outside of the <code>foo</code> class body, and the metaclass responsible for setting the initial value of <code>_var</code>:</p>\n<pre><code>&gt;&gt;&gt; class foo_meta(type):\n... def __init__(cls, *args, **kwargs):\n... cls._var = 5\n... @property\n... def var(cls):\n... return cls._var\n... @var.setter\n... def var(cls, value):\n... cls._var = value\n...\n&gt;&gt;&gt; class foo(metaclass=foo_meta):\n... pass\n...\n&gt;&gt;&gt; foo.var\n5\n&gt;&gt;&gt; foo.var = 3\n&gt;&gt;&gt; foo.var\n3\n</code></pre>\n" }, { "answer_id": 2544313, "author": "Nils Philippsen", "author_id": 304979, "author_profile": "https://Stackoverflow.com/users/304979", "pm_score": 3, "selected": false, "text": "<p>Setting it only on the meta class doesn't help if you want to access the class property via an instantiated object, in this case you need to install a normal property on the object as well (which dispatches to the class property). I think the following is a bit more clear:</p>\n\n<pre><code>#!/usr/bin/python\n\nclass classproperty(property):\n def __get__(self, obj, type_):\n return self.fget.__get__(None, type_)()\n\n def __set__(self, obj, value):\n cls = type(obj)\n return self.fset.__get__(None, cls)(value)\n\nclass A (object):\n\n _foo = 1\n\n @classproperty\n @classmethod\n def foo(cls):\n return cls._foo\n\n @foo.setter\n @classmethod\n def foo(cls, value):\n cls.foo = value\n\na = A()\n\nprint a.foo\n\nb = A()\n\nprint b.foo\n\nb.foo = 5\n\nprint a.foo\n\nA.foo = 10\n\nprint b.foo\n\nprint A.foo\n</code></pre>\n" }, { "answer_id": 13624858, "author": "Denis Ryzhkov", "author_id": 350937, "author_profile": "https://Stackoverflow.com/users/350937", "pm_score": 6, "selected": false, "text": "<p>I hope this dead-simple read-only <code>@classproperty</code> decorator would help somebody looking for classproperties.</p>\n<pre><code>class classproperty(property):\n def __get__(self, owner_self, owner_cls):\n return self.fget(owner_cls)\n\nclass C(object):\n\n @classproperty\n def x(cls):\n return 1\n\nassert C.x == 1\nassert C().x == 1\n</code></pre>\n" }, { "answer_id": 39542816, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "<blockquote>\n<h1>Is it possible to use the property() function with classmethod decorated functions?</h1>\n</blockquote>\n<p>No.</p>\n<p>However, a classmethod is simply a bound method (a partial function) on a class accessible from instances of that class.</p>\n<p>Since the instance is a function of the class and you can derive the class from the instance, you can can get whatever desired behavior you might want from a class-property with <code>property</code>:</p>\n<pre><code>class Example(object):\n _class_property = None\n @property\n def class_property(self):\n return self._class_property\n @class_property.setter\n def class_property(self, value):\n type(self)._class_property = value\n @class_property.deleter\n def class_property(self):\n del type(self)._class_property\n</code></pre>\n<p>This code can be used to test - it should pass without raising any errors:</p>\n<pre><code>ex1 = Example()\nex2 = Example()\nex1.class_property = None\nex2.class_property = 'Example'\nassert ex1.class_property is ex2.class_property\ndel ex2.class_property\nassert not hasattr(ex1, 'class_property')\n</code></pre>\n<p>And note that we didn't need metaclasses at all - and you don't directly access a metaclass through its classes' instances anyways.</p>\n<h2>writing a <code>@classproperty</code> decorator</h2>\n<p>You can actually create a <code>classproperty</code> decorator in just a few lines of code by subclassing <code>property</code> (it's implemented in C, but you can see equivalent Python <a href=\"https://docs.python.org/3/howto/descriptor.html#properties\" rel=\"noreferrer\">here</a>):</p>\n<pre><code>class classproperty(property):\n def __get__(self, obj, objtype=None):\n return super(classproperty, self).__get__(objtype)\n def __set__(self, obj, value):\n super(classproperty, self).__set__(type(obj), value)\n def __delete__(self, obj):\n super(classproperty, self).__delete__(type(obj))\n</code></pre>\n<p>Then treat the decorator as if it were a classmethod combined with property:</p>\n<pre><code>class Foo(object):\n _bar = 5\n @classproperty\n def bar(cls):\n &quot;&quot;&quot;this is the bar attribute - each subclass of Foo gets its own.\n Lookups should follow the method resolution order.\n &quot;&quot;&quot;\n return cls._bar\n @bar.setter\n def bar(cls, value):\n cls._bar = value\n @bar.deleter\n def bar(cls):\n del cls._bar\n</code></pre>\n<p>And this code should work without errors:</p>\n<pre><code>def main():\n f = Foo()\n print(f.bar)\n f.bar = 4\n print(f.bar)\n del f.bar\n try:\n f.bar\n except AttributeError:\n pass\n else:\n raise RuntimeError('f.bar must have worked - inconceivable!')\n help(f) # includes the Foo.bar help.\n f.bar = 5\n\n class Bar(Foo):\n &quot;a subclass of Foo, nothing more&quot;\n help(Bar) # includes the Foo.bar help!\n b = Bar()\n b.bar = 'baz'\n print(b.bar) # prints baz\n del b.bar\n print(b.bar) # prints 5 - looked up from Foo!\n\n \nif __name__ == '__main__':\n main()\n</code></pre>\n<p>But I'm not sure how well-advised this would be. An old mailing list <a href=\"https://mail.python.org/pipermail/python-ideas/2011-January/008959.html\" rel=\"noreferrer\">article</a> suggests it shouldn't work.</p>\n<h2>Getting the property to work on the class:</h2>\n<p>The downside of the above is that the &quot;class property&quot; isn't accessible from the class, because it would simply overwrite the data descriptor from the class <code>__dict__</code>.</p>\n<p>However, we can override this with a property defined in the metaclass <code>__dict__</code>. For example:</p>\n<pre><code>class MetaWithFooClassProperty(type):\n @property\n def foo(cls):\n &quot;&quot;&quot;The foo property is a function of the class -\n in this case, the trivial case of the identity function.\n &quot;&quot;&quot;\n return cls\n</code></pre>\n<p>And then a class instance of the metaclass could have a property that accesses the class's property using the principle already demonstrated in the prior sections:</p>\n<pre><code>class FooClassProperty(metaclass=MetaWithFooClassProperty):\n @property\n def foo(self):\n &quot;&quot;&quot;access the class's property&quot;&quot;&quot;\n return type(self).foo\n</code></pre>\n<p>And now we see both the instance</p>\n<pre><code>&gt;&gt;&gt; FooClassProperty().foo\n&lt;class '__main__.FooClassProperty'&gt;\n</code></pre>\n<p>and the class</p>\n<pre><code>&gt;&gt;&gt; FooClassProperty.foo\n&lt;class '__main__.FooClassProperty'&gt;\n</code></pre>\n<p>have access to the class property.</p>\n" }, { "answer_id": 44811984, "author": "papercrane", "author_id": 892621, "author_profile": "https://Stackoverflow.com/users/892621", "pm_score": 2, "selected": false, "text": "<p>Here's a solution which should work for both access via the class and access via an instance which uses a metaclass.</p>\n\n<pre><code>In [1]: class ClassPropertyMeta(type):\n ...: @property\n ...: def prop(cls):\n ...: return cls._prop\n ...: def __new__(cls, name, parents, dct):\n ...: # This makes overriding __getattr__ and __setattr__ in the class impossible, but should be fixable\n ...: dct['__getattr__'] = classmethod(lambda cls, attr: getattr(cls, attr))\n ...: dct['__setattr__'] = classmethod(lambda cls, attr, val: setattr(cls, attr, val))\n ...: return super(ClassPropertyMeta, cls).__new__(cls, name, parents, dct)\n ...:\n\nIn [2]: class ClassProperty(object):\n ...: __metaclass__ = ClassPropertyMeta\n ...: _prop = 42\n ...: def __getattr__(self, attr):\n ...: raise Exception('Never gets called')\n ...:\n\nIn [3]: ClassProperty.prop\nOut[3]: 42\n\nIn [4]: ClassProperty.prop = 1\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n&lt;ipython-input-4-e2e8b423818a&gt; in &lt;module&gt;()\n----&gt; 1 ClassProperty.prop = 1\n\nAttributeError: can't set attribute\n\nIn [5]: cp = ClassProperty()\n\nIn [6]: cp.prop\nOut[6]: 42\n\nIn [7]: cp.prop = 1\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n&lt;ipython-input-7-e8284a3ee950&gt; in &lt;module&gt;()\n----&gt; 1 cp.prop = 1\n\n&lt;ipython-input-1-16b7c320d521&gt; in &lt;lambda&gt;(cls, attr, val)\n 6 # This makes overriding __getattr__ and __setattr__ in the class impossible, but should be fixable\n 7 dct['__getattr__'] = classmethod(lambda cls, attr: getattr(cls, attr))\n----&gt; 8 dct['__setattr__'] = classmethod(lambda cls, attr, val: setattr(cls, attr, val))\n 9 return super(ClassPropertyMeta, cls).__new__(cls, name, parents, dct)\n\nAttributeError: can't set attribute\n</code></pre>\n\n<p>This also works with a setter defined in the metaclass.</p>\n" }, { "answer_id": 46818912, "author": "alex", "author_id": 4444742, "author_profile": "https://Stackoverflow.com/users/4444742", "pm_score": 0, "selected": false, "text": "<p>After searching different places, I found a method to define a classproperty\nvalid with Python 2 and 3.</p>\n\n<pre><code>from future.utils import with_metaclass\n\nclass BuilderMetaClass(type):\n @property\n def load_namespaces(self):\n return (self.__sourcepath__)\n\nclass BuilderMixin(with_metaclass(BuilderMetaClass, object)):\n __sourcepath__ = 'sp' \n\nprint(BuilderMixin.load_namespaces)\n</code></pre>\n\n<p>Hope this can help somebody :)</p>\n" }, { "answer_id": 47334224, "author": "OJFord", "author_id": 1446048, "author_profile": "https://Stackoverflow.com/users/1446048", "pm_score": 5, "selected": false, "text": "<h1>Python 3!</h1>\n<p>See <a href=\"https://stackoverflow.com/a/64738850/1446048\">@Amit Portnoy's answer</a> for an even cleaner method in python &gt;= 3.9</p>\n<hr />\n<p>Old question, lots of views, sorely in need of a one-true Python 3 way.</p>\n<p>Luckily, it's easy with the <code>metaclass</code> kwarg:</p>\n<pre><code>class FooProperties(type):\n \n @property\n def var(cls):\n return cls._var\n\nclass Foo(object, metaclass=FooProperties):\n _var = 'FOO!'\n</code></pre>\n<p>Then, <code>&gt;&gt;&gt; Foo.var</code></p>\n<blockquote>\n<p>'FOO!'</p>\n</blockquote>\n" }, { "answer_id": 64510457, "author": "spacether", "author_id": 4175822, "author_profile": "https://Stackoverflow.com/users/4175822", "pm_score": -1, "selected": false, "text": "<p>Here is my solution that also caches the class property</p>\n<pre><code>class class_property(object):\n # this caches the result of the function call for fn with cls input\n # use this as a decorator on function methods that you want converted\n # into cached properties\n\n def __init__(self, fn):\n self._fn_name = fn.__name__\n if not isinstance(fn, (classmethod, staticmethod)):\n fn = classmethod(fn)\n self._fn = fn\n\n def __get__(self, obj, cls=None):\n if cls is None:\n cls = type(obj)\n if (\n self._fn_name in vars(cls) and\n type(vars(cls)[self._fn_name]).__name__ != &quot;class_property&quot;\n ):\n return vars(cls)[self._fn_name]\n else:\n value = self._fn.__get__(obj, cls)()\n setattr(cls, self._fn_name, value)\n return value\n</code></pre>\n" }, { "answer_id": 64738850, "author": "Amit Portnoy", "author_id": 990421, "author_profile": "https://Stackoverflow.com/users/990421", "pm_score": 7, "selected": false, "text": "<p>In <em>Python 3.9</em> You could use them together, but (as noted in @xgt's <a href=\"https://stackoverflow.com/questions/128573/using-property-on-classmethods/64738850#comment127939742_64738850\">comment</a>) it was <strong>removed</strong> in <em>Python 3.11</em>, so <strong>it is not recommended to use it</strong>.</p>\n<p>Check the version remarks here:</p>\n<p><a href=\"https://docs.python.org/3.11/library/functions.html#classmethod\" rel=\"noreferrer\">https://docs.python.org/3.11/library/functions.html#classmethod</a></p>\n<p>However, it used to work like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class G:\n @classmethod\n @property\n def __doc__(cls):\n return f'A doc for {cls.__name__!r}'\n</code></pre>\n<p>Order matters - due to how the descriptors interact, <code>@classmethod</code> has to be on top.</p>\n" }, { "answer_id": 68349052, "author": "Emma Brown", "author_id": 13649935, "author_profile": "https://Stackoverflow.com/users/13649935", "pm_score": 2, "selected": false, "text": "<p>I found one clean solution to this problem. It's a package called <strong>classutilities</strong> (<code>pip install classutilities</code>), see the documentation <a href=\"https://pypi.org/project/classutilities/\" rel=\"nofollow noreferrer\">here on PyPi</a>.</p>\n<p>Consider example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import classutilities\n\nclass SomeClass(classutilities.ClassPropertiesMixin):\n _some_variable = 8 # Some encapsulated class variable\n\n @classutilities.classproperty\n def some_variable(cls): # class property getter\n return cls._some_variable\n\n @some_variable.setter\n def some_variable(cls, value): # class property setter\n cls._some_variable = value\n</code></pre>\n<p>You can use it on both class level and instance level:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Getter on class level:\nvalue = SomeClass.some_variable\nprint(value) # &gt;&gt;&gt; 8\n# Getter on instance level\ninst = SomeClass()\nvalue = inst.some_variable\nprint(value) # &gt;&gt;&gt; 8\n\n# Setter on class level:\nnew_value = 9\nSomeClass.some_variable = new_value\nprint(SomeClass.some_variable) # &gt;&gt;&gt; 9\nprint(SomeClass._some_variable) # &gt;&gt;&gt; 9\n# Setter on instance level\ninst = SomeClass()\ninst.some_variable = new_value\nprint(SomeClass.some_variable) # &gt;&gt;&gt; 9\nprint(SomeClass._some_variable) # &gt;&gt;&gt; 9\nprint(inst.some_variable) # &gt;&gt;&gt; 9\nprint(inst._some_variable) # &gt;&gt;&gt; 9\n</code></pre>\n<p>As you can see, it works correctly under all circumstances.</p>\n" }, { "answer_id": 69936409, "author": "user2290820", "author_id": 2290820, "author_profile": "https://Stackoverflow.com/users/2290820", "pm_score": 1, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/a/1800999/2290820\">https://stackoverflow.com/a/1800999/2290820</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>\nclass MetaProperty(type):\n\n def __init__(cls, *args, **kwargs):\n super()\n\n @property\n def praparty(cls):\n return cls._var\n\n @praparty.setter\n def praparty(cls, val):\n cls._var = val\n\n\nclass A(metaclass=MetaProperty):\n _var = 5\n\n\nprint(A.praparty)\nA.praparty = 6\nprint(A.praparty)\n</code></pre>\n" }, { "answer_id": 70311457, "author": "Shawn Martin", "author_id": 17648663, "author_profile": "https://Stackoverflow.com/users/17648663", "pm_score": 1, "selected": false, "text": "<p>For a functional approach pre Python 3.9 you can use this:</p>\n<pre><code>def classproperty(fget):\n return type(\n 'classproperty',\n (),\n {'__get__': lambda self, _, cls: fget(cls), '__module__': None}\n )()\n \nclass Item:\n a = 47\n\n @classproperty\n def x(cls):\n return cls.a\n\nItem.x\n</code></pre>\n" }, { "answer_id": 71479873, "author": "eugene-bright", "author_id": 2657676, "author_profile": "https://Stackoverflow.com/users/2657676", "pm_score": 0, "selected": false, "text": "<p>A code completion friendly solution for Python &lt; 3.9</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import (\n Callable,\n Generic,\n TypeVar,\n)\n\n\nT = TypeVar('T')\n\n\nclass classproperty(Generic[T]):\n &quot;&quot;&quot;Converts a method to a class property.\n &quot;&quot;&quot;\n\n def __init__(self, f: Callable[..., T]):\n self.fget = f\n\n def __get__(self, instance, owner) -&gt; T:\n return self.fget(owner)\n\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I have a class with two class methods (using the `classmethod()` function) for getting and setting what is essentially a static variable. I tried to use the `property()` function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter: ``` class Foo(object): _var = 5 @classmethod def getvar(cls): return cls._var @classmethod def setvar(cls, value): cls._var = value var = property(getvar, setvar) ``` I can demonstrate the class methods, but they don't work as properties: ``` >>> f = Foo() >>> f.getvar() 5 >>> f.setvar(4) >>> f.getvar() 4 >>> f.var Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'classmethod' object is not callable >>> f.var=5 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'classmethod' object is not callable ``` Is it possible to use the `property()` function with `@classmethod` decorated functions?
### 3.8 < Python < 3.11 Can use both decorators together. See [this answer](https://stackoverflow.com/a/64738850/674039). ### Python < 3.9 A property is created on a class but affects an instance. So if you want a `classmethod` property, create the property on the metaclass. ``` >>> class foo(object): ... _var = 5 ... class __metaclass__(type): # Python 2 syntax for metaclasses ... pass ... @classmethod ... def getvar(cls): ... return cls._var ... @classmethod ... def setvar(cls, value): ... cls._var = value ... >>> foo.__metaclass__.var = property(foo.getvar.im_func, foo.setvar.im_func) >>> foo.var 5 >>> foo.var = 3 >>> foo.var 3 ``` But since you're using a metaclass anyway, it will read better if you just move the classmethods in there. ``` >>> class foo(object): ... _var = 5 ... class __metaclass__(type): # Python 2 syntax for metaclasses ... @property ... def var(cls): ... return cls._var ... @var.setter ... def var(cls, value): ... cls._var = value ... >>> foo.var 5 >>> foo.var = 3 >>> foo.var 3 ``` or, using Python 3's `metaclass=...` syntax, and the metaclass defined outside of the `foo` class body, and the metaclass responsible for setting the initial value of `_var`: ``` >>> class foo_meta(type): ... def __init__(cls, *args, **kwargs): ... cls._var = 5 ... @property ... def var(cls): ... return cls._var ... @var.setter ... def var(cls, value): ... cls._var = value ... >>> class foo(metaclass=foo_meta): ... pass ... >>> foo.var 5 >>> foo.var = 3 >>> foo.var 3 ```
128,579
<p>When developing a module (device driver, middleware, etc...) that will run in the kernel space, we would like to have some way to capture the reason an operation might fail. </p> <p>In VxWorks, The errno mechanism seems to be a good way to do this.</p> <p>Is it possible to define my own errno values?</p>
[ { "answer_id": 128628, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 1, "selected": false, "text": "<p>Errno is just a number and functions like strerror() return a describing text. If you want to extend it just provide an own function similar to strerror() that looks into your error list or delegates to strerror().</p>\n" }, { "answer_id": 128645, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 3, "selected": true, "text": "<p>In the context of VxWorks errno is defined as two 16-bit: </p>\n\n<ul>\n<li>The upper 16-bit identifies the \"module\" where the error occured.</li>\n<li>The lower 16-bit represent the particular error for that module.</li>\n</ul>\n\n<p>The official vxWorks module values (for errno) are located in the ../h/vwModNum.h file.\nThey are currently using a few hundred numbers.\nThese module numbers all have the form </p>\n\n<pre>\n#define M_something (nn &lt&lt 16)\n</pre>\n\n<p>It is <strong>strongly</strong> discouraged to modify this (or any) vxWorks header file. </p>\n\n<p>What you could do is create your own module header file and start at a large enough number to not cause conflicts.</p>\n\n<pre>\n/* myModNum.h */\n#define M_MyModule (10000 &lt&lt 16)\n#define M_MyNextModule (10001 &lt&lt 16)\n...\n</pre>\n\n<p>The in the individual module header files, create the individual errno values.</p>\n\n<pre>\n/* myModule.h */\n#define S_MyModule_OutOfResources (M_MyModule | 1)\n#define S_MyModule_InvalidHandle (M_MyModule | 2)\n...\n</pre>\n\n<p>In your code, you can then set errno to your defined macro.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
When developing a module (device driver, middleware, etc...) that will run in the kernel space, we would like to have some way to capture the reason an operation might fail. In VxWorks, The errno mechanism seems to be a good way to do this. Is it possible to define my own errno values?
In the context of VxWorks errno is defined as two 16-bit: * The upper 16-bit identifies the "module" where the error occured. * The lower 16-bit represent the particular error for that module. The official vxWorks module values (for errno) are located in the ../h/vwModNum.h file. They are currently using a few hundred numbers. These module numbers all have the form ``` #define M_something (nn << 16) ``` It is **strongly** discouraged to modify this (or any) vxWorks header file. What you could do is create your own module header file and start at a large enough number to not cause conflicts. ``` /* myModNum.h */ #define M_MyModule (10000 << 16) #define M_MyNextModule (10001 << 16) ... ``` The in the individual module header files, create the individual errno values. ``` /* myModule.h */ #define S_MyModule_OutOfResources (M_MyModule | 1) #define S_MyModule_InvalidHandle (M_MyModule | 2) ... ``` In your code, you can then set errno to your defined macro.
128,580
<p>I'm trying to get the contents of a XML document element, but the element has a colon in it's name.</p> <p>This line works for every element but the ones with a colon in the name:</p> <pre><code>$(this).find("geo:lat").text(); </code></pre> <p>I assume that the colon needs escaping. How do I fix this?</p>
[ { "answer_id": 128598, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 6, "selected": true, "text": "<p>Use a backslash, which itself should be escaped so JavaScript doesn't eat it:</p>\n\n<pre><code>$(this).find(\"geo\\\\:lat\").text();\n</code></pre>\n" }, { "answer_id": 128640, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 4, "selected": false, "text": "<p>That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.</p>\n\n<p>Right now, jQuery can't deal with namespaces very well, see <a href=\"http://dev.jquery.com/ticket/155\" rel=\"noreferrer\">bug 155</a> for details.</p>\n\n<p>Right now, as a workaround, you should be able to select these elements with just the local name:</p>\n\n<pre><code>$(this).find(\"lat\").text();\n</code></pre>\n\n<p>If you have to distinguish between element types with the same local name, then you can use <code>filter()</code>:</p>\n\n<pre><code>var NS = \"http://example.com/whatever-the-namespace-is-for-geo\";\n$(this).find(\"lat\").filter(function() { return this.namespaceURI == NS; }).text();\n</code></pre>\n\n<p><strong>Edit:</strong> my mistake, I was under the impression that patch had already landed. Use Adam's suggestion for the selector, and <code>filter()</code> if you need the namespacing too:</p>\n\n<pre><code>var NS = \"http://example.com/whatever-the-namespace-is-for-geo\";\n$(this).find(\"geo\\\\:lat\").filter(function() { return this.namespaceURI == NS; }).text();\n</code></pre>\n" }, { "answer_id": 2478484, "author": "simon", "author_id": 297453, "author_profile": "https://Stackoverflow.com/users/297453", "pm_score": 2, "selected": false, "text": "<p>if you have a <strong>jquery selector problem with chrome or webkit</strong> not selecting it try </p>\n\n<pre><code>$(this).find('[nodeName=geo:lat]').text();\n</code></pre>\n\n<p>this way it works in all browsers</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399/" ]
I'm trying to get the contents of a XML document element, but the element has a colon in it's name. This line works for every element but the ones with a colon in the name: ``` $(this).find("geo:lat").text(); ``` I assume that the colon needs escaping. How do I fix this?
Use a backslash, which itself should be escaped so JavaScript doesn't eat it: ``` $(this).find("geo\\:lat").text(); ```
128,584
<p>The following simple "calculator expression" grammar (BNF) can be easily parsed with the a trivial recursive-descent parser, which is predictive LL(1):</p> <pre><code>&lt;expr&gt; := &lt;term&gt; + &lt;term&gt; | &lt;term&gt; - &lt;term&gt; | &lt;term&gt; &lt;term&gt; := &lt;factor&gt; * &lt;factor&gt; &lt;factor&gt; / &lt;factor&gt; &lt;factor&gt; &lt;factor&gt; := &lt;number&gt; | &lt;id&gt; | ( &lt;expr&gt; ) &lt;number&gt; := \d+ &lt;id&gt; := [a-zA-Z_]\w+ </code></pre> <p>Because it is always enough to see the next token in order to know the rule to pick. However, suppose that I add the following rule:</p> <pre><code>&lt;command&gt; := &lt;expr&gt; | &lt;id&gt; = &lt;expr&gt; </code></pre> <p>For the purpose of interacting with the calculator on the command line, with variables, like this:</p> <pre><code>calc&gt; 5+5 =&gt; 10 calc&gt; x = 8 calc&gt; 6 * x + 1 =&gt; 49 </code></pre> <p>Is it true that I can not use a simple LL(1) predictive parser to parse <code>&lt;command&gt;</code> rules ? I tried to write the parser for it, but it seems that I need to know more tokens forward. Is the solution to use backtracking, or can I just implement LL(2) and always look two tokens forward ?</p> <p>How to RD parser generators handle this problem (ANTLR, for instance)?</p>
[ { "answer_id": 128661, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "<p>The problem is that the grammar:</p>\n\n<pre>\n<code>\n&lt;command> := &lt;expr>\n | &lt;id> = &lt;expr>\n</code>\n</pre>\n\n<p>is not a mutually-recursive procedure. For a recursive decent parser you will need to determine a non-recursive equivalent.</p>\n\n<p>rdentato post's shows how to fix this, assuming you can play with the grammar. This powerpoint spells out the problem in a bit more detail and shows how to correct it: \n<a href=\"http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=7&amp;url=http%3A%2F%2Fxml.cs.nccu.edu.tw%2Fcourses%2Fcompiler%2Fcp2006%2Fslides%2Flec3-Parsing%26TopDownParsing.ppt&amp;ei=-YLaSPrWGaPwhAK5ydCqBQ&amp;usg=AFQjCNGAFrODJxoxkgJEwDMQ8A8594vn0Q&amp;sig2=nlYKQVfakmqy_57137XzrQ\" rel=\"nofollow noreferrer\">http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=7&amp;url=http%3A%2F%2Fxml.cs.nccu.edu.tw%2Fcourses%2Fcompiler%2Fcp2006%2Fslides%2Flec3-Parsing%26TopDownParsing.ppt&amp;ei=-YLaSPrWGaPwhAK5ydCqBQ&amp;usg=AFQjCNGAFrODJxoxkgJEwDMQ8A8594vn0Q&amp;sig2=nlYKQVfakmqy_57137XzrQ</a></p>\n" }, { "answer_id": 128724, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 4, "selected": true, "text": "<p>THe problem with </p>\n\n<pre><code>&lt;command&gt; := &lt;expr&gt;\n | &lt;id&gt; = &lt;expr&gt;\n</code></pre>\n\n<p>is that when you \"see\" <code>&lt;id&gt;</code> you can't tell if it's the beginning of an assignement (second rule) or it's a \"<code>&lt;factor&gt;</code>\". You will only know when you'll read the next token.</p>\n\n<p>AFAIK ANTLR is LL(*) (and is also able to generate rat-pack parsers if I'm not mistaken) so it will probably handle this grammare considering two tokens at once.</p>\n\n<p>If you can play with the grammar I would suggest to either add a keyword for the assignment (e.g. <code>let x = 8</code>) :</p>\n\n<pre><code>&lt;command&gt; := &lt;expr&gt;\n | \"let\" &lt;id&gt; \"=\" &lt;expr&gt;\n</code></pre>\n\n<p>or use the <code>=</code> to signify evaluation:</p>\n\n<pre><code>&lt;command&gt; := \"=\" &lt;expr&gt;\n | &lt;id&gt; \"=\" &lt;expr&gt;\n</code></pre>\n" }, { "answer_id": 128792, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.artima.com/lejava/articles/antlr_3.html\" rel=\"nofollow noreferrer\">ANTLR 3</a> uses a \"LL(*)\" parser as opposed to a LL(k) parser, so it will look ahead until it reaches the end of the input if it has to, without backtracking, using a specially optimized determinstic finite automata (DFA).</p>\n" }, { "answer_id": 3922949, "author": "Sven", "author_id": 431526, "author_profile": "https://Stackoverflow.com/users/431526", "pm_score": 3, "selected": false, "text": "<p>I think there are two ways to solve this with a recursive descent parser: either by using (more) lookahead or by backtracking.</p>\n\n<h3>Lookahead</h3>\n\n<pre><code>command() {\n if (currentToken() == id &amp;&amp; lookaheadToken() == '=') {\n return assignment();\n } else {\n return expr();\n }\n}\n</code></pre>\n\n<h3>Backtracking</h3>\n\n<pre><code>command() {\n savedLocation = scanLocation();\n if (accept( id )) {\n identifier = acceptedTokenValue();\n if (!accept( '=' )) {\n setScanLocation( savedLocation );\n return expr();\n }\n return new assignment( identifier, expr() );\n } else {\n return expr();\n }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
The following simple "calculator expression" grammar (BNF) can be easily parsed with the a trivial recursive-descent parser, which is predictive LL(1): ``` <expr> := <term> + <term> | <term> - <term> | <term> <term> := <factor> * <factor> <factor> / <factor> <factor> <factor> := <number> | <id> | ( <expr> ) <number> := \d+ <id> := [a-zA-Z_]\w+ ``` Because it is always enough to see the next token in order to know the rule to pick. However, suppose that I add the following rule: ``` <command> := <expr> | <id> = <expr> ``` For the purpose of interacting with the calculator on the command line, with variables, like this: ``` calc> 5+5 => 10 calc> x = 8 calc> 6 * x + 1 => 49 ``` Is it true that I can not use a simple LL(1) predictive parser to parse `<command>` rules ? I tried to write the parser for it, but it seems that I need to know more tokens forward. Is the solution to use backtracking, or can I just implement LL(2) and always look two tokens forward ? How to RD parser generators handle this problem (ANTLR, for instance)?
THe problem with ``` <command> := <expr> | <id> = <expr> ``` is that when you "see" `<id>` you can't tell if it's the beginning of an assignement (second rule) or it's a "`<factor>`". You will only know when you'll read the next token. AFAIK ANTLR is LL(\*) (and is also able to generate rat-pack parsers if I'm not mistaken) so it will probably handle this grammare considering two tokens at once. If you can play with the grammar I would suggest to either add a keyword for the assignment (e.g. `let x = 8`) : ``` <command> := <expr> | "let" <id> "=" <expr> ``` or use the `=` to signify evaluation: ``` <command> := "=" <expr> | <id> "=" <expr> ```
128,618
<p>Is there any easy way to create a class that uses <strong>IFormatProvider</strong> that writes out a user-friendly file-size?</p> <pre><code>public static string GetFileSizeString(string filePath) { FileInfo info = new FileInfo(@"c:\windows\notepad.exe"); long size = info.Length; string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic... } </code></pre> <p>It should result in strings formatted something like "<em>2,5 MB</em>", "<em>3,9 GB</em>", "<em>670 bytes</em>" and so on.</p>
[ { "answer_id": 128683, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 8, "selected": true, "text": "<p>I use this one, I get it from the web</p>\n\n<pre><code>public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter\n{\n public object GetFormat(Type formatType)\n {\n if (formatType == typeof(ICustomFormatter)) return this;\n return null;\n }\n\n private const string fileSizeFormat = \"fs\";\n private const Decimal OneKiloByte = 1024M;\n private const Decimal OneMegaByte = OneKiloByte * 1024M;\n private const Decimal OneGigaByte = OneMegaByte * 1024M;\n\n public string Format(string format, object arg, IFormatProvider formatProvider)\n { \n if (format == null || !format.StartsWith(fileSizeFormat)) \n { \n return defaultFormat(format, arg, formatProvider); \n }\n\n if (arg is string) \n { \n return defaultFormat(format, arg, formatProvider); \n }\n\n Decimal size;\n\n try \n { \n size = Convert.ToDecimal(arg); \n } \n catch (InvalidCastException) \n { \n return defaultFormat(format, arg, formatProvider); \n }\n\n string suffix;\n if (size &gt; OneGigaByte)\n {\n size /= OneGigaByte;\n suffix = \"GB\";\n }\n else if (size &gt; OneMegaByte)\n {\n size /= OneMegaByte;\n suffix = \"MB\";\n }\n else if (size &gt; OneKiloByte)\n {\n size /= OneKiloByte;\n suffix = \"kB\";\n }\n else\n {\n suffix = \" B\";\n }\n\n string precision = format.Substring(2);\n if (String.IsNullOrEmpty(precision)) precision = \"2\";\n return String.Format(\"{0:N\" + precision + \"}{1}\", size, suffix);\n\n }\n\n private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)\n {\n IFormattable formattableArg = arg as IFormattable;\n if (formattableArg != null)\n {\n return formattableArg.ToString(format, formatProvider);\n }\n return arg.ToString();\n }\n\n}\n</code></pre>\n\n<p>an example of use would be:</p>\n\n<pre><code>Console.WriteLine(String.Format(new FileSizeFormatProvider(), \"File size: {0:fs}\", 100));\nConsole.WriteLine(String.Format(new FileSizeFormatProvider(), \"File size: {0:fs}\", 10000));\n</code></pre>\n\n<p>Credits for <a href=\"http://flimflan.com/blog/FileSizeFormatProvider.aspx\" rel=\"noreferrer\">http://flimflan.com/blog/FileSizeFormatProvider.aspx</a></p>\n\n<p>There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :( </p>\n\n<p>If you're using C# 3.0 you can use an extension method to get the result you want:</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static string ToFileSize(this long l)\n {\n return String.Format(new FileSizeFormatProvider(), \"{0:fs}\", l);\n }\n}\n</code></pre>\n\n<p>You can use it like this.</p>\n\n<pre><code>long l = 100000000;\nConsole.WriteLine(l.ToFileSize());\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 129110, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 6, "selected": false, "text": "<p>OK I'm not going to wrap it up as a Format provider but rather than reinventing the wheel there's a Win32 api call to format a size string based on supplied bytes that I've used many times in various applications.</p>\n\n<pre><code>[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Auto)]\npublic static extern long StrFormatByteSize( long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize );\n</code></pre>\n\n<p>So I imagine you should be able to put together a provider using that as the core conversion code.</p>\n\n<p>Here's a <a href=\"http://msdn.microsoft.com/en-us/library/bb759974(VS.85).aspx\" rel=\"noreferrer\">link</a> to the MSDN spec for StrFormatByteSize.</p>\n" }, { "answer_id": 1756525, "author": "ariso", "author_id": 97775, "author_profile": "https://Stackoverflow.com/users/97775", "pm_score": 3, "selected": false, "text": "<p>My code... thanks for Shaun Austin.</p>\n\n<pre><code>[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Auto)]\npublic static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize);\n\npublic void getFileInfo(string filename)\n{\n System.IO.FileInfo fileinfo = new FileInfo(filename);\n this.FileName.Text = fileinfo.Name;\n StringBuilder buffer = new StringBuilder();\n StrFormatByteSize(fileinfo.Length, buffer, 100);\n this.FileSize.Text = buffer.ToString();\n}\n</code></pre>\n" }, { "answer_id": 2467447, "author": "Tyler Durden", "author_id": 296147, "author_profile": "https://Stackoverflow.com/users/296147", "pm_score": 1, "selected": false, "text": "<p>I have taken Eduardo's answer and combined it with a similar example from elsewhere to provide additional options for the formatting.</p>\n\n<pre><code>public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter\n{\n public object GetFormat(Type formatType)\n {\n if (formatType == typeof(ICustomFormatter))\n {\n return this;\n }\n\n return null;\n }\n\n private const string fileSizeFormat = \"FS\";\n private const string kiloByteFormat = \"KB\";\n private const string megaByteFormat = \"MB\";\n private const string gigaByteFormat = \"GB\";\n private const string byteFormat = \"B\";\n private const Decimal oneKiloByte = 1024M;\n private const Decimal oneMegaByte = oneKiloByte * 1024M;\n private const Decimal oneGigaByte = oneMegaByte * 1024M;\n\n public string Format(string format, object arg, IFormatProvider formatProvider)\n {\n //\n // Ensure the format provided is supported\n //\n if (String.IsNullOrEmpty(format) || !(format.StartsWith(fileSizeFormat, StringComparison.OrdinalIgnoreCase) ||\n format.StartsWith(kiloByteFormat, StringComparison.OrdinalIgnoreCase) ||\n format.StartsWith(megaByteFormat, StringComparison.OrdinalIgnoreCase) ||\n format.StartsWith(gigaByteFormat, StringComparison.OrdinalIgnoreCase)))\n {\n return DefaultFormat(format, arg, formatProvider);\n }\n\n //\n // Ensure the argument type is supported\n //\n if (!(arg is long || arg is decimal || arg is int))\n {\n return DefaultFormat(format, arg, formatProvider);\n }\n\n //\n // Try and convert the argument to decimal\n //\n Decimal size;\n\n try\n {\n size = Convert.ToDecimal(arg);\n }\n catch (InvalidCastException)\n {\n return DefaultFormat(format, arg, formatProvider);\n }\n\n //\n // Determine the suffix to use and convert the argument to the requested size\n //\n string suffix;\n\n switch (format.Substring(0, 2).ToUpper())\n {\n case kiloByteFormat:\n size = size / oneKiloByte;\n suffix = kiloByteFormat;\n break;\n case megaByteFormat:\n size = size / oneMegaByte;\n suffix = megaByteFormat;\n break;\n case gigaByteFormat:\n size = size / oneGigaByte;\n suffix = gigaByteFormat;\n break;\n case fileSizeFormat:\n if (size &gt; oneGigaByte)\n {\n size /= oneGigaByte;\n suffix = gigaByteFormat;\n }\n else if (size &gt; oneMegaByte)\n {\n size /= oneMegaByte;\n suffix = megaByteFormat;\n }\n else if (size &gt; oneKiloByte)\n {\n size /= oneKiloByte;\n suffix = kiloByteFormat;\n }\n else\n {\n suffix = byteFormat;\n }\n break;\n default:\n suffix = byteFormat;\n break;\n }\n\n //\n // Determine the precision to use\n //\n string precision = format.Substring(2);\n\n if (String.IsNullOrEmpty(precision))\n {\n precision = \"2\";\n }\n\n return String.Format(\"{0:N\" + precision + \"}{1}\", size, suffix);\n }\n\n private static string DefaultFormat(string format, object arg, IFormatProvider formatProvider)\n {\n IFormattable formattableArg = arg as IFormattable;\n\n if (formattableArg != null)\n {\n return formattableArg.ToString(format, formatProvider);\n }\n\n return arg.ToString();\n }\n}\n</code></pre>\n" }, { "answer_id": 3968504, "author": "mindplay.dk", "author_id": 283851, "author_profile": "https://Stackoverflow.com/users/283851", "pm_score": 5, "selected": false, "text": "<p>I realize now that you were actually asking for something that would work with String.Format() - I guess I should have read the question twice before posting ;-)</p>\n\n<p>I don't like the solution where you have to explicitly pass in a format provider every time - from what I could gather from <a href=\"http://msdn.microsoft.com/en-us/library/26etazsy.aspx\" rel=\"noreferrer\">this article</a>, the best way to approach this, is to implement a FileSize type, implementing the IFormattable interface.</p>\n\n<p>I went ahead and implemented a struct that supports this interface, and which can be cast from an integer. In my own file-related APIs, I will have my .FileSize properties return a FileSize instance.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>using System.Globalization;\n\npublic struct FileSize : IFormattable\n{\n private ulong _value;\n\n private const int DEFAULT_PRECISION = 2;\n\n private static IList&lt;string&gt; Units;\n\n static FileSize()\n {\n Units = new List&lt;string&gt;(){\n \"B\", \"KB\", \"MB\", \"GB\", \"TB\"\n };\n }\n\n public FileSize(ulong value)\n {\n _value = value;\n }\n\n public static explicit operator FileSize(ulong value)\n {\n return new FileSize(value);\n }\n\n override public string ToString()\n {\n return ToString(null, null);\n }\n\n public string ToString(string format)\n {\n return ToString(format, null);\n }\n\n public string ToString(string format, IFormatProvider formatProvider)\n {\n int precision;\n\n if (String.IsNullOrEmpty(format))\n return ToString(DEFAULT_PRECISION);\n else if (int.TryParse(format, out precision))\n return ToString(precision);\n else\n return _value.ToString(format, formatProvider);\n }\n\n /// &lt;summary&gt;\n /// Formats the FileSize using the given number of decimals.\n /// &lt;/summary&gt;\n public string ToString(int precision)\n {\n double pow = Math.Floor((_value &gt; 0 ? Math.Log(_value) : 0) / Math.Log(1024));\n pow = Math.Min(pow, Units.Count - 1);\n double value = (double)_value / Math.Pow(1024, pow);\n return value.ToString(pow == 0 ? \"F0\" : \"F\" + precision.ToString()) + \" \" + Units[(int)pow];\n }\n}\n</code></pre>\n\n<p>And a simple Unit Test that demonstrates how this works:</p>\n\n<pre><code> [Test]\n public void CanUseFileSizeFormatProvider()\n {\n Assert.AreEqual(String.Format(\"{0}\", (FileSize)128), \"128 B\");\n Assert.AreEqual(String.Format(\"{0}\", (FileSize)1024), \"1.00 KB\");\n Assert.AreEqual(String.Format(\"{0:0}\", (FileSize)10240), \"10 KB\");\n Assert.AreEqual(String.Format(\"{0:1}\", (FileSize)102400), \"100.0 KB\");\n Assert.AreEqual(String.Format(\"{0}\", (FileSize)1048576), \"1.00 MB\");\n Assert.AreEqual(String.Format(\"{0:D}\", (FileSize)123456), \"123456\");\n\n // You can also manually invoke ToString(), optionally with the precision specified as an integer:\n Assert.AreEqual(((FileSize)111111).ToString(2), \"108.51 KB\");\n }\n</code></pre>\n\n<p>As you can see, the FileSize type can now be formatted correctly, and it is also possible to specify the number of decimals, as well as applying regular numeric formatting if required.</p>\n\n<p>I guess you could take this much further, for example allowing explicit format selection, e.g. \"{0:KB}\" to force formatting in kilobytes. But I'm going to leave it at this.</p>\n\n<p>I'm also leaving my initial post below for those two prefer not to use the formatting API...</p>\n\n<hr>\n\n<p>100 ways to skin a cat, but here's my approach - adding an extension method to the int type:</p>\n\n<pre><code>public static class IntToBytesExtension\n{\n private const int PRECISION = 2;\n\n private static IList&lt;string&gt; Units;\n\n static IntToBytesExtension()\n {\n Units = new List&lt;string&gt;(){\n \"B\", \"KB\", \"MB\", \"GB\", \"TB\"\n };\n }\n\n /// &lt;summary&gt;\n /// Formats the value as a filesize in bytes (KB, MB, etc.)\n /// &lt;/summary&gt;\n /// &lt;param name=\"bytes\"&gt;This value.&lt;/param&gt;\n /// &lt;returns&gt;Filesize and quantifier formatted as a string.&lt;/returns&gt;\n public static string ToBytes(this int bytes)\n {\n double pow = Math.Floor((bytes&gt;0 ? Math.Log(bytes) : 0) / Math.Log(1024));\n pow = Math.Min(pow, Units.Count-1);\n double value = (double)bytes / Math.Pow(1024, pow);\n return value.ToString(pow==0 ? \"F0\" : \"F\" + PRECISION.ToString()) + \" \" + Units[(int)pow];\n }\n}\n</code></pre>\n\n<p>With this extension in your assembly, to format a filesize, simply use a statement like (1234567).ToBytes()</p>\n\n<p>The following MbUnit test clarifies precisely what the output looks like:</p>\n\n<pre><code> [Test]\n public void CanFormatFileSizes()\n {\n Assert.AreEqual(\"128 B\", (128).ToBytes());\n Assert.AreEqual(\"1.00 KB\", (1024).ToBytes());\n Assert.AreEqual(\"10.00 KB\", (10240).ToBytes());\n Assert.AreEqual(\"100.00 KB\", (102400).ToBytes());\n Assert.AreEqual(\"1.00 MB\", (1048576).ToBytes());\n }\n</code></pre>\n\n<p>And you can easily change the units and precision to whatever suits your needs :-)</p>\n" }, { "answer_id": 13777868, "author": "wvd_vegt", "author_id": 1034074, "author_profile": "https://Stackoverflow.com/users/1034074", "pm_score": 1, "selected": false, "text": "<p>If you change: </p>\n\n<pre><code> if (String.IsNullOrEmpty(precision))\n {\n precision = \"2\";\n }\n</code></pre>\n\n<p>into </p>\n\n<pre><code> if (String.IsNullOrEmpty(precision))\n {\n if (size &lt; 10)\n {\n precision = \"2\";\n }\n else if (size &lt; 100)\n {\n precision = \"1\";\n }\n else\n {\n precision = \"0\";\n }\n }\n</code></pre>\n\n<p>the results without additional precision specifier (so just 0:fs instead of 0:fs3) will start to mimic Win32's StrFormatByteSize() by adjusting precision to size.</p>\n" }, { "answer_id": 15340481, "author": "fubo", "author_id": 1315444, "author_profile": "https://Stackoverflow.com/users/1315444", "pm_score": 2, "selected": false, "text": "<p>since shifting is a very cheap operation</p>\n\n<pre><code>public static string ToFileSize(this long size)\n{\n if (size &lt; 1024)\n {\n return (size).ToString(\"F0\") + \" bytes\";\n }\n else if ((size &gt;&gt; 10) &lt; 1024)\n {\n return (size/(float)1024).ToString(\"F1\") + \" KB\";\n }\n else if ((size &gt;&gt; 20) &lt; 1024)\n {\n return ((size &gt;&gt; 10) / (float)1024).ToString(\"F1\") + \" MB\";\n }\n else if ((size &gt;&gt; 30) &lt; 1024)\n {\n return ((size &gt;&gt; 20) / (float)1024).ToString(\"F1\") + \" GB\";\n }\n else if ((size &gt;&gt; 40) &lt; 1024)\n {\n return ((size &gt;&gt; 30) / (float)1024).ToString(\"F1\") + \" TB\";\n }\n else if ((size &gt;&gt; 50) &lt; 1024)\n {\n return ((size &gt;&gt; 40) / (float)1024).ToString(\"F1\") + \" PB\";\n }\n else\n {\n return ((size &gt;&gt; 50) / (float)1024).ToString(\"F0\") + \" EB\";\n }\n}\n</code></pre>\n" }, { "answer_id": 18331628, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 2, "selected": false, "text": "<p>I needed a version that can be localized for different cultures (decimal separator, \"byte\" translation) and support for all possible <a href=\"http://en.wikipedia.org/wiki/Binary_prefix\" rel=\"nofollow\">binary prefixes</a> (up to Exa). Here is an example that demonstrates how to use it:</p>\n\n<pre><code>// force \"en-US\" culture for tests\nThread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(1033); \n\n// Displays \"8.00 EB\"\nConsole.WriteLine(FormatFileSize(long.MaxValue)); \n\n// Use \"fr-FR\" culture. Displays \"20,74 ko\", o is for \"octet\"\nConsole.WriteLine(FormatFileSize(21234, \"o\", null, CultureInfo.GetCultureInfo(1036)));\n</code></pre>\n\n<p>And here is the code:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes or exabytes, depending on the size\n /// &lt;/summary&gt;\n /// &lt;param name=\"size\"&gt;The size.&lt;/param&gt;\n /// &lt;returns&gt;\n /// The number converted.\n /// &lt;/returns&gt;\n public static string FormatFileSize(long size)\n {\n return FormatFileSize(size, null, null, null);\n }\n\n /// &lt;summary&gt;\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes or exabytes, depending on the size\n /// &lt;/summary&gt;\n /// &lt;param name=\"size\"&gt;The size.&lt;/param&gt;\n /// &lt;param name=\"byteName\"&gt;The string used for the byte name. If null is passed, \"B\" will be used.&lt;/param&gt;\n /// &lt;param name=\"numberFormat\"&gt;The number format. If null is passed, \"N2\" will be used.&lt;/param&gt;\n /// &lt;param name=\"formatProvider\"&gt;The format provider. May be null to use current culture.&lt;/param&gt;\n /// &lt;returns&gt;The number converted.&lt;/returns&gt;\n public static string FormatFileSize(long size, string byteName, string numberFormat, IFormatProvider formatProvider)\n {\n if (size &lt; 0)\n throw new ArgumentException(null, \"size\");\n\n if (byteName == null)\n {\n byteName = \"B\";\n }\n\n if (string.IsNullOrEmpty(numberFormat))\n {\n numberFormat = \"N2\";\n }\n\n const decimal K = 1024;\n const decimal M = K * K;\n const decimal G = M * K;\n const decimal T = G * K;\n const decimal P = T * K;\n const decimal E = P * K;\n\n decimal dsize = size;\n\n string suffix = null;\n if (dsize &gt;= E)\n {\n dsize /= E;\n suffix = \"E\";\n }\n else if (dsize &gt;= P)\n {\n dsize /= P;\n suffix = \"P\";\n }\n else if (dsize &gt;= T)\n {\n dsize /= T;\n suffix = \"T\";\n }\n else if (dsize &gt;= G)\n {\n dsize /= G;\n suffix = \"G\";\n }\n else if (dsize &gt;= M)\n {\n dsize /= M;\n suffix = \"M\";\n }\n else if (dsize &gt;= K)\n {\n dsize /= K;\n suffix = \"k\";\n }\n if (suffix != null)\n {\n suffix = \" \" + suffix;\n }\n return string.Format(formatProvider, \"{0:\" + numberFormat + \"}\" + suffix + byteName, dsize);\n }\n</code></pre>\n" }, { "answer_id": 21175211, "author": "Christian Moser", "author_id": 1452507, "author_profile": "https://Stackoverflow.com/users/1452507", "pm_score": 4, "selected": false, "text": "<p>this is the simplest implementation I know to format file sizes:</p>\n\n<pre><code>public string SizeText\n{\n get\n {\n var units = new[] { \"B\", \"KB\", \"MB\", \"GB\", \"TB\" };\n var index = 0;\n double size = Size;\n while (size &gt; 1024)\n {\n size /= 1024;\n index++;\n }\n return string.Format(\"{0:2} {1}\", size, units[index]);\n }\n}\n</code></pre>\n\n<p>Whereas Size is the unformatted file size in bytes.</p>\n\n<p>Greetings\nChristian</p>\n\n<p><a href=\"http://www.wpftutorial.net\" rel=\"noreferrer\">http://www.wpftutorial.net</a> </p>\n" }, { "answer_id": 27162235, "author": "Michel Tomassini", "author_id": 4298319, "author_profile": "https://Stackoverflow.com/users/4298319", "pm_score": 2, "selected": false, "text": "<p>Here is an extension with more precision:</p>\n\n<pre><code> public static string FileSizeFormat(this long lSize)\n {\n double size = lSize;\n int index = 0;\n for(; size &gt; 1024; index++)\n size /= 1024;\n return size.ToString(\"0.000 \" + new[] { \"B\", \"KB\", \"MB\", \"GB\", \"TB\" }[index]); \n }\n</code></pre>\n" }, { "answer_id": 34063957, "author": "Corniel Nobel", "author_id": 2266405, "author_profile": "https://Stackoverflow.com/users/2266405", "pm_score": 2, "selected": false, "text": "<p>A Domain Driven Approach can be found here: <a href=\"https://github.com/Corniel/Qowaiv/blob/master/src/Qowaiv/IO/StreamSize.cs\" rel=\"nofollow\">https://github.com/Corniel/Qowaiv/blob/master/src/Qowaiv/IO/StreamSize.cs</a></p>\n\n<p>The StreamSize struct is a representation of a stream size, allows you both to format automatic with the proper extension, but also to specify that you want it in KB/MB or whatever. This has a lot of advantages, not only because you get the formatting out of the box, it also helps you to make better models, as it is obvious than, that the property or the result of a method represents a stream size. It also has an extension on file size: GetStreamSize(this FileInfo file).</p>\n\n<h2>Short notation</h2>\n\n<ul>\n<li>new StreamSize(8900).ToString(\"s\") => 8900b</li>\n<li>new StreamSize(238900).ToString(\"s\") => 238.9kb</li>\n<li>new StreamSize(238900).ToString(\" S\") => 238.9 kB</li>\n<li>new StreamSize(238900).ToString(\"0000.00 S\") => 0238.90 kB</li>\n</ul>\n\n<h2>Full notation</h2>\n\n<ul>\n<li>new StreamSize(8900).ToString(\"0.0 f\") => 8900.0 byte</li>\n<li>new StreamSize(238900).ToString(\"0 f\") => 234 kilobyte</li>\n<li>new StreamSize(1238900).ToString(\"0.00 F\") => 1.24 Megabyte</li>\n</ul>\n\n<h2>Custom</h2>\n\n<ul>\n<li>new StreamSize(8900).ToString(\"0.0 kb\") => 8.9 kb</li>\n<li>new StreamSize(238900).ToString(\"0.0 MB\") => 0.2 MB</li>\n<li>new StreamSize(1238900).ToString(\"#,##0.00 Kilobyte\") => 1,239.00 Kilobyte</li>\n<li>new StreamSize(1238900).ToString(\"#,##0\") => 1,238,900</li>\n</ul>\n\n<p>There is a NuGet-package, so you just can use that one: <a href=\"https://www.nuget.org/packages/Qowaiv\" rel=\"nofollow\">https://www.nuget.org/packages/Qowaiv</a></p>\n" }, { "answer_id": 67771566, "author": "JRoger", "author_id": 3670782, "author_profile": "https://Stackoverflow.com/users/3670782", "pm_score": 0, "selected": false, "text": "<p>using C# 9.0 syntax can be written like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string ToFormatSize(ulong size)\n{\n return size switch\n {\n ulong s when s &lt; 1024 =&gt; $&quot;{size} bytes&quot;,\n ulong s when s &lt; (1024 &lt;&lt; 10) =&gt; $&quot;{Math.Round(size / 1024D, 2)} KB&quot;,\n ulong s when s &lt; (1024 &lt;&lt; 20) =&gt; $&quot;{Math.Round(size * 1D / (1024 &lt;&lt; 10), 2)} MB&quot;,\n ulong s when s &lt; (1024 &lt;&lt; 30) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 20), 2)} GB&quot;,\n ulong s when s &lt; (1024 &lt;&lt; 40) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 30), 2)} TB&quot;,\n ulong s when s &lt; (1024 &lt;&lt; 50) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 40), 2)} PB&quot;,\n ulong s when s &lt; (1024 &lt;&lt; 60) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 50), 2)} EB&quot;,\n _ =&gt; $&quot;{size} bytes&quot;\n };\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
Is there any easy way to create a class that uses **IFormatProvider** that writes out a user-friendly file-size? ``` public static string GetFileSizeString(string filePath) { FileInfo info = new FileInfo(@"c:\windows\notepad.exe"); long size = info.Length; string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic... } ``` It should result in strings formatted something like "*2,5 MB*", "*3,9 GB*", "*670 bytes*" and so on.
I use this one, I get it from the web ``` public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; return null; } private const string fileSizeFormat = "fs"; private const Decimal OneKiloByte = 1024M; private const Decimal OneMegaByte = OneKiloByte * 1024M; private const Decimal OneGigaByte = OneMegaByte * 1024M; public string Format(string format, object arg, IFormatProvider formatProvider) { if (format == null || !format.StartsWith(fileSizeFormat)) { return defaultFormat(format, arg, formatProvider); } if (arg is string) { return defaultFormat(format, arg, formatProvider); } Decimal size; try { size = Convert.ToDecimal(arg); } catch (InvalidCastException) { return defaultFormat(format, arg, formatProvider); } string suffix; if (size > OneGigaByte) { size /= OneGigaByte; suffix = "GB"; } else if (size > OneMegaByte) { size /= OneMegaByte; suffix = "MB"; } else if (size > OneKiloByte) { size /= OneKiloByte; suffix = "kB"; } else { suffix = " B"; } string precision = format.Substring(2); if (String.IsNullOrEmpty(precision)) precision = "2"; return String.Format("{0:N" + precision + "}{1}", size, suffix); } private static string defaultFormat(string format, object arg, IFormatProvider formatProvider) { IFormattable formattableArg = arg as IFormattable; if (formattableArg != null) { return formattableArg.ToString(format, formatProvider); } return arg.ToString(); } } ``` an example of use would be: ``` Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100)); Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000)); ``` Credits for <http://flimflan.com/blog/FileSizeFormatProvider.aspx> There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :( If you're using C# 3.0 you can use an extension method to get the result you want: ``` public static class ExtensionMethods { public static string ToFileSize(this long l) { return String.Format(new FileSizeFormatProvider(), "{0:fs}", l); } } ``` You can use it like this. ``` long l = 100000000; Console.WriteLine(l.ToFileSize()); ``` Hope this helps.
128,623
<p>How can I disable all table constrains in Oracle with a single command? This can be either for a single table, a list of tables, or for all tables.</p>
[ { "answer_id": 128663, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>It doesn't look like you can do this with a single command, but <a href=\"http://oracle.ittoolbox.com/documents/popular-q-and-a/how-to-disable-all-constraints-via-single-sql-command-1948\" rel=\"nofollow noreferrer\">here'</a>s the closest thing to it that I could find.</p>\n" }, { "answer_id": 128786, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 3, "selected": false, "text": "<p>It's not a single command, but here's how I do it. The following script has been designed to run in SQL*Plus. Note, I've purposely written this to only work within the current schema.</p>\n\n<pre><code>set heading off\n\nspool drop_constraints.out\n\nselect\n 'alter table ' || \n owner || '.' || \n table_name || \n ' disable constraint ' || -- or 'drop' if you want to permanently remove\n constraint_name || ';'\nfrom\n user_constraints;\n\nspool off\n\nset heading on\n\n@drop_constraints.out\n</code></pre>\n\n<p>To restrict what you drop, filter add a where clause to the select statement:-</p>\n\n<ul>\n<li>filter on constraint_type to drop only particular types of constraints</li>\n<li>filter on table_name to do it only for one or a few tables.</li>\n</ul>\n\n<p>To run on more than the current schema, modify the select statement to select from all_constraints rather than user_constraints.</p>\n\n<p><strong>Note</strong> - for some reason I can't get the underscore to NOT act like an italicization in the previous paragraph. If someone knows how to fix it, please feel free to edit this answer.</p>\n" }, { "answer_id": 128813, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>This can be scripted in PL/SQL pretty simply based on the DBA/ALL/USER_CONSTRAINTS system view, but various details make not as trivial as it sounds. You have to be careful about the order in which it is done and you also have to take account of the presence of unique indexes.</p>\n\n<p>The order is important because you cannot drop a unique or primary key that is referenced by a foreign key, and there could be foreign keys on tables in other schemas that reference primary keys in your own, so unless you have ALTER ANY TABLE privilege then you cannot drop those PKs and UKs. Also you cannot switch a unique index to being a non-unique index so you have to drop it in order to drop the constraint (for this reason it's almost always better to implement unique constraints as a \"real\" constraint that is supported by a non-unique index).</p>\n" }, { "answer_id": 131595, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 8, "selected": true, "text": "<p>It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.</p>\n\n<p>It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.</p>\n\n<pre><code>BEGIN\n FOR c IN\n (SELECT c.owner, c.table_name, c.constraint_name\n FROM user_constraints c, user_tables t\n WHERE c.table_name = t.table_name\n AND c.status = 'ENABLED'\n AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')\n ORDER BY c.constraint_type DESC)\n LOOP\n dbms_utility.exec_ddl_statement('alter table \"' || c.owner || '\".\"' || c.table_name || '\" disable constraint ' || c.constraint_name);\n END LOOP;\nEND;\n/\n</code></pre>\n\n<p>Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.</p>\n\n<pre><code>BEGIN\n FOR c IN\n (SELECT c.owner, c.table_name, c.constraint_name\n FROM user_constraints c, user_tables t\n WHERE c.table_name = t.table_name\n AND c.status = 'DISABLED'\n ORDER BY c.constraint_type)\n LOOP\n dbms_utility.exec_ddl_statement('alter table \"' || c.owner || '\".\"' || c.table_name || '\" enable constraint ' || c.constraint_name);\n END LOOP;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 1101073, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In the \"disable\" script, the order by clause should be that:</p>\n\n<pre><code>ORDER BY c.constraint_type DESC, c.last_change DESC\n</code></pre>\n\n<p>The goal of this clause is disable the constraints in the right order.</p>\n" }, { "answer_id": 4014154, "author": "user486360", "author_id": 486360, "author_profile": "https://Stackoverflow.com/users/486360", "pm_score": 3, "selected": false, "text": "<p>Use following cursor to disable all constraint.. And alter query for enable constraints...</p>\n\n<pre><code>DECLARE\n\ncursor r1 is select * from user_constraints;\ncursor r2 is select * from user_tables;\n\nBEGIN\n FOR c1 IN r1\n loop\n for c2 in r2\n loop\n if c1.table_name = c2.table_name and c1.status = 'ENABLED' THEN\n dbms_utility.exec_ddl_statement('alter table ' || c1.owner || '.' || c1.table_name || ' disable constraint ' || c1.constraint_name);\n end if;\n end loop;\n END LOOP;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 5075815, "author": "Cyryl1972", "author_id": 627962, "author_profile": "https://Stackoverflow.com/users/627962", "pm_score": 4, "selected": false, "text": "<p>To take in count the dependencies between the constraints: </p>\n\n<pre><code>SET Serveroutput ON\nBEGIN\n FOR c IN\n (SELECT c.owner,c.table_name,c.constraint_name\n FROM user_constraints c,user_tables t\n WHERE c.table_name=t.table_name\n AND c.status='ENABLED'\n ORDER BY c.constraint_type DESC,c.last_change DESC\n )\n LOOP\n FOR D IN\n (SELECT P.Table_Name Parent_Table,C1.Table_Name Child_Table,C1.Owner,P.Constraint_Name Parent_Constraint,\n c1.constraint_name Child_Constraint\n FROM user_constraints p\n JOIN user_constraints c1 ON(p.constraint_name=c1.r_constraint_name)\n WHERE(p.constraint_type='P'\n OR p.constraint_type='U')\n AND c1.constraint_type='R'\n AND p.table_name=UPPER(c.table_name)\n )\n LOOP\n dbms_output.put_line('. Disable the constraint ' || d.Child_Constraint ||' (on table '||d.owner || '.' ||\n d.Child_Table || ')') ;\n dbms_utility.exec_ddl_statement('alter table ' || d.owner || '.' ||d.Child_Table || ' disable constraint ' ||\n d.Child_Constraint) ;\n END LOOP;\n END LOOP;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 28367033, "author": "Ankireddy Polu", "author_id": 950212, "author_profile": "https://Stackoverflow.com/users/950212", "pm_score": 1, "selected": false, "text": "<pre class=\"lang-sql prettyprint-override\"><code>SELECT 'ALTER TABLE '||substr(c.table_name,1,35)|| \n' DISABLE CONSTRAINT '||constraint_name||' ;' \nFROM user_constraints c, user_tables u \nWHERE c.table_name = u.table_name; \n</code></pre>\n\n<p>This statement returns the commands which turn off all the constraints including primary key, foreign keys, and another constraints.</p>\n" }, { "answer_id": 40281408, "author": "Cyryl1972", "author_id": 627962, "author_profile": "https://Stackoverflow.com/users/627962", "pm_score": 0, "selected": false, "text": "<p>This is another way for disabling constraints (it came from <a href=\"https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817\" rel=\"nofollow\">https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817</a>)</p>\n\n<pre><code>WITH qry0 AS\n (SELECT 'ALTER TABLE '\n || child_tname\n || ' DISABLE CONSTRAINT '\n || child_cons_name\n disable_fk\n , 'ALTER TABLE '\n || parent_tname\n || ' DISABLE CONSTRAINT '\n || parent.parent_cons_name\n disable_pk\n FROM (SELECT a.table_name child_tname\n ,a.constraint_name child_cons_name\n ,b.r_constraint_name parent_cons_name\n ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns\n FROM user_cons_columns a\n ,user_constraints b\n WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'\n GROUP BY a.table_name, a.constraint_name\n ,b.r_constraint_name) child\n ,(SELECT a.constraint_name parent_cons_name\n ,a.table_name parent_tname\n ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns\n FROM user_cons_columns a\n ,user_constraints b\n WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')\n GROUP BY a.table_name, a.constraint_name) parent\n WHERE child.parent_cons_name = parent.parent_cons_name\n AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))\nSELECT DISTINCT disable_pk\n FROM qry0\nUNION\nSELECT DISTINCT disable_fk\n FROM qry0;\n</code></pre>\n\n<p>works like a charm</p>\n" }, { "answer_id": 51173286, "author": "diaphol", "author_id": 9654615, "author_profile": "https://Stackoverflow.com/users/9654615", "pm_score": 0, "selected": false, "text": "<p>with cursor for loop (user = 'TRANEE', table = 'D')</p>\n\n<pre><code>declare\n constr all_constraints.constraint_name%TYPE;\nbegin\n for constr in\n (select constraint_name from all_constraints\n where table_name = 'D'\n and owner = 'TRANEE')\n loop\n execute immediate 'alter table D disable constraint '||constr.constraint_name;\n end loop;\nend;\n/\n</code></pre>\n\n<p>(If you change disable to enable, you can make all constraints enable)</p>\n" }, { "answer_id": 52968518, "author": "Cristina Bazar", "author_id": 10551854, "author_profile": "https://Stackoverflow.com/users/10551854", "pm_score": 0, "selected": false, "text": "<p>You can execute all the commands returned by the following query :</p>\n<pre><code>select 'ALTER TABLE '||substr(c.table_name,1,35)|| \n' DISABLE CONSTRAINT '||constraint_name||' ;' \nfrom user_constraints c\n--where c.table_name = 'TABLE_NAME' ;\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9435/" ]
How can I disable all table constrains in Oracle with a single command? This can be either for a single table, a list of tables, or for all tables.
It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL\*Plus or put this thing into a package or procedure. The join to USER\_TABLES is there to avoid view constraints. It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint\_type in the WHERE clause. ``` BEGIN FOR c IN (SELECT c.owner, c.table_name, c.constraint_name FROM user_constraints c, user_tables t WHERE c.table_name = t.table_name AND c.status = 'ENABLED' AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P') ORDER BY c.constraint_type DESC) LOOP dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name); END LOOP; END; / ``` Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint\_type. 'P' = primary key, 'R' = foreign key. ``` BEGIN FOR c IN (SELECT c.owner, c.table_name, c.constraint_name FROM user_constraints c, user_tables t WHERE c.table_name = t.table_name AND c.status = 'DISABLED' ORDER BY c.constraint_type) LOOP dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name); END LOOP; END; / ```
128,783
<p>Is it possible to use AIX's mksysb and savevg to create a bootable tape with the rootvg and then append all the other VGs?</p>
[ { "answer_id": 129951, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>First, use savevg to backup any extra volume groups to a file system on the rootvg:</p>\n\n<pre><code>savevg -f /tmp/vgname\n</code></pre>\n\n<p>Compress it if it will be too large, or use the -i option to exclude files. The easiest way is to exclude all files on the volume group and restore those off of the regular backup device. Once that is done, create your normal mksysb.</p>\n\n<p>For DR purposes, restore the system using the mksysb, then use restvg to restore the volume groups out of your backup files. Restore any extra files that may have been excluded, and you're running again.</p>\n" }, { "answer_id": 234211, "author": "Guy Gervais", "author_id": 31226, "author_profile": "https://Stackoverflow.com/users/31226", "pm_score": 2, "selected": false, "text": "<p>Answering my own question:</p>\n\n<p>To backup, use a script similar to this one:</p>\n\n<pre>\ntctl -f/dev/rmt0 rewind\n/usr/bin/mksysb -p -v /dev/rmt0.1\n/usr/bin/savevg -p -v -f/dev/rmt0.1 vg01\n/usr/bin/savevg -p -v -f/dev/rmt0.1 vg02\n/usr/bin/savevg -p -v -f/dev/rmt0.1 vg03\n ...etc...\ntctl -f/dev/rmt0 rewind\n</pre>\n\n<p>Notes:<br>\n- mksysb backs up rootvg and creates a bootable tape.<br>\n- using \"rmt0.1\" prevents auto-rewind after operations.</p>\n\n<p>Also, mkszfile and mkvgdata were used previously to create the \"image.data\" and various \"vgdata\" and map files. I did this because my system runs all disks mirrored and I wanted the possibility of restoring with only half the number of disks present. All my image.dat, vgdata and map files were done unmirrored to allow more flexibility during restore.</p>\n\n<p>To restore, the procedures are:</p>\n\n<p>For rootvg, boot from tape and follow the on-screen prompt (a normal mksysb restore).</p>\n\n<p>For the other volume groups, it goes like this:</p>\n\n<pre>\ntctl -f/dev/rmt0.1 rewind\ntctl -f/dev/rmt0.1 fsf 4\nrestvg -f/dev/rmt0.1 hdisk[n]\n</pre>\n\n<p>\"fsf 4\" will place the tape at the first saved VG following the mksysb backup. Use \"fsf 5\" for the 2nd, \"fsf 6\" for the 3rd, and so on.</p>\n\n<p>If restvg complains about missing disks, you can add the \"-n\" flag to forego the \"exact map\" default parameter.</p>\n\n<p>If you need to recuperate single files, you can do it like this:</p>\n\n<pre>\ntctl -f/dev/rmt0 rewind\nrestore -x -d -v -s4 -f/dev/rmt0.1 ./[path]/[file]\n</pre>\n\n<p>\"-s4\" is rootvg, replace with \"-s5\" for 1st VG following, \"-s6\" for 2nd, etc. The files are restored in your current folder.</p>\n\n<p>This technique gives you a single tape that can be used to restore any single file or folder; and also be used to completely rebuild your system from scratch.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to use AIX's mksysb and savevg to create a bootable tape with the rootvg and then append all the other VGs?
Answering my own question: To backup, use a script similar to this one: ``` tctl -f/dev/rmt0 rewind /usr/bin/mksysb -p -v /dev/rmt0.1 /usr/bin/savevg -p -v -f/dev/rmt0.1 vg01 /usr/bin/savevg -p -v -f/dev/rmt0.1 vg02 /usr/bin/savevg -p -v -f/dev/rmt0.1 vg03 ...etc... tctl -f/dev/rmt0 rewind ``` Notes: - mksysb backs up rootvg and creates a bootable tape. - using "rmt0.1" prevents auto-rewind after operations. Also, mkszfile and mkvgdata were used previously to create the "image.data" and various "vgdata" and map files. I did this because my system runs all disks mirrored and I wanted the possibility of restoring with only half the number of disks present. All my image.dat, vgdata and map files were done unmirrored to allow more flexibility during restore. To restore, the procedures are: For rootvg, boot from tape and follow the on-screen prompt (a normal mksysb restore). For the other volume groups, it goes like this: ``` tctl -f/dev/rmt0.1 rewind tctl -f/dev/rmt0.1 fsf 4 restvg -f/dev/rmt0.1 hdisk[n] ``` "fsf 4" will place the tape at the first saved VG following the mksysb backup. Use "fsf 5" for the 2nd, "fsf 6" for the 3rd, and so on. If restvg complains about missing disks, you can add the "-n" flag to forego the "exact map" default parameter. If you need to recuperate single files, you can do it like this: ``` tctl -f/dev/rmt0 rewind restore -x -d -v -s4 -f/dev/rmt0.1 ./[path]/[file] ``` "-s4" is rootvg, replace with "-s5" for 1st VG following, "-s6" for 2nd, etc. The files are restored in your current folder. This technique gives you a single tape that can be used to restore any single file or folder; and also be used to completely rebuild your system from scratch.
128,796
<p>I really enjoy having "pretty" URLs (e.g. <code>/Products/Edit/1</code> instead of <code>/products.aspx?productID=1</code>) but I'm at a loss on how to do this for pages that let you search by a large number of variables.</p> <p>For instance, let's say you have a page that lets a user search for all products of a particular type with a certain name and near a specific address. Would you do this with really long "pretty" URLs</p> <pre><code>/Products/Search/Type/{producttype}/Name/{name}/Address/{address} </code></pre> <p>or just resort to using url params</p> <pre><code>/Products/Search?productType={producttype}&amp;name={name}&amp;address={address} </code></pre>
[ { "answer_id": 128846, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 1, "selected": false, "text": "<p>The MVC (Model View Controller) framework is designed specifically to tackle this issue. It uses a form of url rewriting to redirect actions to pages and provides just the functionality you're looking for. It makes handling pretty urls a breeze.</p>\n\n<p>With regard to the length of URLs, id still use pretty urls but a particularly long URL may be an indication that you may want to reconsider your grouping of the items, alter the classification if you will so Products/{NAME}/{Address} without intermediary url parts. </p>\n\n<p>Examples of the MVC framework can be found at: </p>\n\n<p>.Net - <a href=\"http://www.asp.net/mvc/\" rel=\"nofollow noreferrer\">http://www.asp.net/mvc/</a></p>\n\n<p>PHP - <a href=\"http://www.phpmvc.net/\" rel=\"nofollow noreferrer\">http://www.phpmvc.net/</a></p>\n\n<p>Java - <a href=\"http://struts.apache.org/\" rel=\"nofollow noreferrer\">http://struts.apache.org/</a></p>\n" }, { "answer_id": 128864, "author": "Ken Ray", "author_id": 12253, "author_profile": "https://Stackoverflow.com/users/12253", "pm_score": 1, "selected": false, "text": "<p>We have a similar url rewriting, and using IIS 6, we have the redirect defined as:</p>\n\n<p>/content.aspx?url=$S&amp;$P</p>\n\n<p>This takes a url of the form </p>\n\n<p>/content/page/press_room and makes it in the format</p>\n\n<p>/content.aspx/url=/page/pressroom&amp;</p>\n\n<p>I'm not sure of the complete synyax options IIS has, but I'm sure what you want can be done in a similar way.</p>\n" }, { "answer_id": 128874, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 0, "selected": false, "text": "<p>You can find an answer about <strong>Routing in .NET</strong> here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/125826/what-is-the-best-method-to-achieve-dynamic-url-rewriting-in-aspnet#126426\">What is the best method to achieve dynamic URL Rewriting in ASP.Net?</a></p>\n\n<p>There you can find different resources on the subject.</p>\n" }, { "answer_id": 128881, "author": "chrisntr", "author_id": 4455, "author_profile": "https://Stackoverflow.com/users/4455", "pm_score": 1, "selected": false, "text": "<p>As mentioned before - using HTTP Post would be best but then you lose the ability for people to send the link to people/bookmark it. Leaving the query string in the URL isn't going to be too bad. I have it set up so that the url string is like this:</p>\n\n<p><code>http://example.com/search/?productType={producttype}&amp;name={name}&amp;address={address}</code></p>\n\n<p>And then for paginating the search results add in the page number before the query string (so the query string is customizable if needed.</p>\n\n<ul>\n<li>Page 1:\n<a href=\"http://example.com/search/?productType=\" rel=\"nofollow noreferrer\">http://example.com/search/?productType=</a>{producttype}&amp;name={name}</li>\n<li>Page 2:\n<a href=\"http://example.com/search/2/?productType=\" rel=\"nofollow noreferrer\">http://example.com/search/2/?productType=</a>{producttype}&amp;name={name}</li>\n<li>Page 3:\n<a href=\"http://example.com/search/3/?productType=\" rel=\"nofollow noreferrer\">http://example.com/search/3/?productType=</a>{producttype}&amp;name={name}</li>\n</ul>\n\n<p>etc...</p>\n\n<p>At the end of the day - the king of search 'Google' don't mind leaving the query string in the URL so it can't be too bad :)</p>\n" }, { "answer_id": 128882, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p>You can get the \"pretty\" urls, but not through the prettiest of means..</p>\n\n<p>You can set up your url to be something like:</p>\n\n<pre><code>/Products/Search/Type/{producttype}/Name_{name}/Address_{address}\n</code></pre>\n\n<p>Then a <a href=\"http://www.workingwith.me.uk/articles/scripting/mod_rewrite\" rel=\"nofollow noreferrer\">mod_rewrite</a> rule something like:</p>\n\n<pre><code>RewriteRule ^Products/Search/Type/([a-z]+)(.*)?$ product_lookup.php?type=$1&amp;params=$2 [NC,L]\n</code></pre>\n\n<p>This will give you 2 parameters in your <code>product_lookup</code> file:</p>\n\n<pre><code>$type = {producttype}\n$params = \"/Name_{name}/Address_{address}\"\n</code></pre>\n\n<p>You can then implement some logic in your <code>product_lookup.php</code> file to loop through <code>$params</code>, splitting it up on the \"/\", tokenising it according to whatever is before the \"_\", and then using the resulting parameters in your search as normal, e.g.</p>\n\n<pre><code>// Split request params first on /, then figure out key-&gt;val pairs\n$query_parts = explode(\"/\", $params);\nforeach($params as $param)\n{\n $param_parts = explode(\"_\", $param);\n // Build up associative array of params\n $query[$param_parts[0]] = $param_parts[1];\n}\n// $query should now contain the search parameters in an assoc. array, e.g.\n// $query['Name'] = {name};\n</code></pre>\n\n<p>Having the parameters as \"pretty\" urls rather than POSTs enables users to bookmark particular searches more easily.</p>\n\n<p>An example of this in action is \n<code><a href=\"http://www.property.ie/property-for-sale/dublin/ashington/price_200000-550000/beds_1/\" rel=\"nofollow noreferrer\">http://www.property.ie/property-for-sale/dublin/ashington/price_200000-550000/beds_1/</a></code>\n - the user's selected params are denoted by the \"_\" (price range and beds) which can be translated internally into whichever param format you need, whilst keeping a nice readable url.</p>\n\n<p>The code above is a trivial example without error checking (rogue delimiters etc in input) but should give you an idea of where to start. </p>\n\n<p>It also assumes a LAMP stack (Apache for mod_rewrite and PHP) but could be done along the same lines using asp.net and <a href=\"https://stackoverflow.com/questions/60857/modrewrite-equivalent-for-iis-70\">an IIS mod_rewrite equivalent</a>.</p>\n" }, { "answer_id": 128912, "author": "Nick", "author_id": 5222, "author_profile": "https://Stackoverflow.com/users/5222", "pm_score": 3, "selected": false, "text": "<p>This question is primarily about URL design and only incidentally about rewriting. Once you've designed your URLs to be <a href=\"http://www.w3.org/Provider/Style/URI\" rel=\"noreferrer\">cool</a>, there are lots of ways to make them work including rewriting at the server level or using a web framework that does URL-based dispatch (I think most modern web frameworks do this these days). </p>\n\n<p>Beauty is in the eye of the beholder, but I do agree with you that a lot of search urls are ugly. What makes them so? I think the primary thing that makes URLs ugly is cruft in the URL that doesn't add semantic meaning but is the result of an implementation detail, like (.aspx) or other extensions. My rule is that if a URL returns (X)HTML than it shouldn't have an extension, otherwise it ought to. </p>\n\n<p>In the case of a search, the fact is that the standard search syntax does add meaning: it indicates that the page is a search, it indicates that the arguments are named and reorderable. The ugliness primarily comes from the ?&amp;= characters, but really anything else you do will be to replace these same characters with more attractive characters like |-/, but at the cost of making the URL opaque to any software that wishes to parse it like a spider, a caching proxy server, or something else.</p>\n\n<p>So think carefully about not using the standard syntax and be sure you have a good reason for doing it. I think in the case where your arguments have a natural order <em>and</em> must all be defined for the search to make sense <em>and</em> are compact, you could push it into the URL. For example, in a blog URL you might have:</p>\n\n<pre><code>/weblog/entries/2008\n/weblog/entries/2008/11\n/weblog/entries/2008/11/22\n</code></pre>\n\n<p>For a search defining the entries from 2008, nov 2008, and 22th of november 2008, respectively. Your URLs should be unique and unambiguous; sometimes people put in /-/ for missing search parameters, which I think is pretty compact. However, I would avoid pushing potentially long parameters, like a free-form text query, into the the URL.\n/weblog/entries/containing/here%20is%20some%20freeform%20text%20blah%20blah is not any more attractive that using the query syntax.</p>\n\n<p>If you are going to use the standard query syntax, then picking argument names that are meaningful <em>might</em> improve the attractiveness, somewhat. products/search?description=\"blah\", though longer, is probably better than products/search?q=\"blah\". At this point it's diminishing returns, I think.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
I really enjoy having "pretty" URLs (e.g. `/Products/Edit/1` instead of `/products.aspx?productID=1`) but I'm at a loss on how to do this for pages that let you search by a large number of variables. For instance, let's say you have a page that lets a user search for all products of a particular type with a certain name and near a specific address. Would you do this with really long "pretty" URLs ``` /Products/Search/Type/{producttype}/Name/{name}/Address/{address} ``` or just resort to using url params ``` /Products/Search?productType={producttype}&name={name}&address={address} ```
You can get the "pretty" urls, but not through the prettiest of means.. You can set up your url to be something like: ``` /Products/Search/Type/{producttype}/Name_{name}/Address_{address} ``` Then a [mod\_rewrite](http://www.workingwith.me.uk/articles/scripting/mod_rewrite) rule something like: ``` RewriteRule ^Products/Search/Type/([a-z]+)(.*)?$ product_lookup.php?type=$1&params=$2 [NC,L] ``` This will give you 2 parameters in your `product_lookup` file: ``` $type = {producttype} $params = "/Name_{name}/Address_{address}" ``` You can then implement some logic in your `product_lookup.php` file to loop through `$params`, splitting it up on the "/", tokenising it according to whatever is before the "\_", and then using the resulting parameters in your search as normal, e.g. ``` // Split request params first on /, then figure out key->val pairs $query_parts = explode("/", $params); foreach($params as $param) { $param_parts = explode("_", $param); // Build up associative array of params $query[$param_parts[0]] = $param_parts[1]; } // $query should now contain the search parameters in an assoc. array, e.g. // $query['Name'] = {name}; ``` Having the parameters as "pretty" urls rather than POSTs enables users to bookmark particular searches more easily. An example of this in action is `<http://www.property.ie/property-for-sale/dublin/ashington/price_200000-550000/beds_1/>` - the user's selected params are denoted by the "\_" (price range and beds) which can be translated internally into whichever param format you need, whilst keeping a nice readable url. The code above is a trivial example without error checking (rogue delimiters etc in input) but should give you an idea of where to start. It also assumes a LAMP stack (Apache for mod\_rewrite and PHP) but could be done along the same lines using asp.net and [an IIS mod\_rewrite equivalent](https://stackoverflow.com/questions/60857/modrewrite-equivalent-for-iis-70).
128,818
<p>I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything:</p> <pre><code>StreamReader reader=new StreamReader("myfile.txt"); try { int i = 5 / 0; } catch // No args, so it will catch any exception {} reader.Close(); </code></pre> <p>However, this is considered good form:</p> <pre><code>StreamReader reader=new StreamReader("myfile.txt"); try { int i = 5 / 0; } finally // Will execute despite any exception { reader.Close(); } </code></pre> <p>As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not).</p> <p>Otherwise, what's so special about finally?</p>
[ { "answer_id": 128827, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 6, "selected": false, "text": "<p>\"Finally\" is a statement of \"Something you must always do to make sure program state is sane\". As such, it's always good form to have one, if there's any possibility that exceptions may throw off the program state. The compiler also goes to great lengths to ensure that your Finally code is run.</p>\n\n<p>\"Catch\" is a statement of \"I can recover from this exception\". You should only recover from exceptions you really can correct - catch without arguments says \"Hey, I can recover from anything!\", which is nearly always untrue.</p>\n\n<p><em>If</em> it were possible to recover from every exception, then it would really be a semantic quibble, about what you're declaring your intent to be. However, it's not, and almost certainly frames above yours will be better equipped to handle certain exceptions. As such, use finally, get your cleanup code run for free, but still let more knowledgeable handlers deal with the issue.</p>\n" }, { "answer_id": 128829, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 10, "selected": true, "text": "<p>The big difference is that <code>try...catch</code> will swallow the exception, hiding the fact that an error occurred. <code>try..finally</code> will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.</p>\n" }, { "answer_id": 128832, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>If you don't know what exception type to catch or what to do with it, there's no point in having a catch statement. You should just leave it for a higher-up caller that may have more information about the situation to know what to do.</p>\n\n<p>You should still have a finally statement in there in case there is an exception, so that you can clean up resources before that exception is thrown to the caller. </p>\n" }, { "answer_id": 128841, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 2, "selected": false, "text": "<p>From a readability perspective, it's more explicitly telling future code-readers \"this stuff in here is important, it needs to be done no matter what happens.\" This is good. </p>\n\n<p>Also, empty catch statements tend to have a certain \"smell\" to them. They might be a sign that developers aren't thinking through the various exceptions that can occur and how to handle them. </p>\n" }, { "answer_id": 128843, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "<p>With finally, you can clean up resources, even if your catch statement throws the exception up to the calling program. With your example containing the empty catch statement, there is little difference. However, if in your catch, you do some processing and throw the error, or even just don't even have a catch at all, the finally will still get run.</p>\n" }, { "answer_id": 128845, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 5, "selected": false, "text": "<p>Because when that one single line throws an exception, you wouldn't know it.</p>\n\n<p>With the first block of code, the exception will simply be <strong>absorbed</strong>, the program will continue to execute even when the state of the program might be wrong.</p>\n\n<p>With the second block, the exception will be <strong>thrown</strong> and bubbles up <em>but</em> the <code>reader.Close()</code> is still guaranteed to run.</p>\n\n<p>If an exception is not expected, then don't put a try..catch block just so, it'll be hard to debug later when the program went into a bad state and you don't have an idea why.</p>\n" }, { "answer_id": 128848, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 2, "selected": false, "text": "<p>Finally is optional -- there's no reason to have a \"Finally\" block if there are no resources to clean up.</p>\n" }, { "answer_id": 128849, "author": "lotsoffreetime", "author_id": 18248, "author_profile": "https://Stackoverflow.com/users/18248", "pm_score": 0, "selected": false, "text": "<p>Amongst probably many reasons, exceptions are very slow to execute. You can easily cripple your execution times if this happens a lot.</p>\n" }, { "answer_id": 128850, "author": "SpoiledTechie.com", "author_id": 7644, "author_profile": "https://Stackoverflow.com/users/7644", "pm_score": 2, "selected": false, "text": "<p>Taken from: <a href=\"http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_21336581.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Raising and catching exceptions should not routinely occur as part of the successful execution of a method. When developing class libraries, client code must be given the opportunity to test for an error condition before undertaking an operation that can result in an exception being raised. For example, System.IO.FileStream provides a CanRead property that can be checked prior to calling the Read method, preventing a potential exception being raised, as illustrated in the following code snippet:</p>\n\n<p>Dim str As Stream = GetStream()\nIf (str.CanRead) Then\n 'code to read stream\nEnd If</p>\n\n<p>The decision of whether to check the state of an object prior to invoking a particular method that may raise an exception depends on the expected state of the object. If a FileStream object is created using a file path that should exist and a constructor that should return a file in read mode, checking the CanRead property is not necessary; the inability to read the FileStream would be a violation of the expected behavior of the method calls made, and an exception should be raised. In contrast, if a method is documented as returning a FileStream reference that may or may not be readable, checking the CanRead property before attempting to read data is advisable.</p>\n\n<p>To illustrate the performance impact that using a \"run until exception\" coding technique can cause, the performance of a cast, which throws an InvalidCastException if the cast fails, is compared to the C# as operator, which returns nulls if a cast fails. The performance of the two techniques is identical for the case where the cast is valid (see Test 8.05), but for the case where the cast is invalid, and using a cast causes an exception, using a cast is 600 times slower than using the as operator (see Test 8.06). The high-performance impact of the exception-throwing technique includes the cost of allocating, throwing, and catching the exception and the cost of subsequent garbage collection of the exception object, which means the instantaneous impact of throwing an exception is not this high. As more exceptions are thrown, frequent garbage collection becomes an issue, so the overall impact of the frequent use of an exception- throwing coding technique will be similar to Test 8.05.</p>\n" }, { "answer_id": 128851, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 0, "selected": false, "text": "<p>The problem with try/catch blocks that catch all exceptions is that your program is now in an indeterminate state if an unknown exception occurs. This goes completely against the fail fast rule - you don't want your program to continue if an exception occurs. The above try/catch would even catch OutOfMemoryExceptions, but that is definitely a state that your program will not run in.</p>\n\n<p>Try/finally blocks allow you to execute clean up code while still failing fast. For most circumstances, you only want to catch all exceptions at the global level, so that you can log them, and then exit out.</p>\n" }, { "answer_id": 128852, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": false, "text": "<p>Finally is executed no matter what. So, if your try block was successful it will execute, if your try block fails, it will then execute the catch block, and then the finally block.</p>\n\n<p>Also, it's better to try to use the following construct:</p>\n\n<pre><code>using (StreamReader reader=new StreamReader(\"myfile.txt\"))\n{\n}\n</code></pre>\n\n<p>As the using statement is automatically wrapped in a try / finally and the stream will be automatically closed. (You will need to put a try / catch around the using statement if you want to actually catch the exception).</p>\n" }, { "answer_id": 128858, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "<p>The try..finally block will still throw any exceptions that are raised. All <code>finally</code> does is ensure that the cleanup code is run before the exception is thrown.</p>\n\n<p>The try..catch with an empty catch will completely consume any exception and hide the fact that it happened. The reader will be closed, but there's no telling if the correct thing happened. What if your intent was to write <em>i</em> to the file? In this case, you won't make it to that part of the code and <em>myfile.txt</em> will be empty. Do all of the downstream methods handle this properly? When you see the empty file, will you be able to correctly guess that it's empty because an exception was thrown? Better to throw the exception and let it be known that you're doing something wrong.</p>\n\n<p>Another reason is the try..catch done like this is completely incorrect. What you are saying by doing this is, \"No matter what happens, I can handle it.\" What about <code>StackOverflowException</code>, can you clean up after that? What about <code>OutOfMemoryException</code>? In general, you should only handle exceptions that you expect and know how to handle.</p>\n" }, { "answer_id": 128873, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 1, "selected": false, "text": "<p>Well for one, it's bad practice to catch exceptions you don't bother to handle. Check out <a href=\"http://msdn.microsoft.com/en-us/library/ms998547.aspx\" rel=\"nofollow noreferrer\">Chapter 5 about .Net Performance</a> from <em>Improving .NET Application Performance and Scalability</em>. Side note, you should probably be loading the stream inside the try block, that way, you can catch the pertinent exception if it fails. Creating the stream outside the try block defeats its purpose.</p>\n" }, { "answer_id": 128916, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 0, "selected": false, "text": "<p>The effective difference between your examples is negligible as long as no exceptions are thrown.</p>\n\n<p>If, however, an exception is thrown while in the 'try' clause, the first example will swallow it completely. The second example will raise the exception to the next step up the call stack, so the difference in the stated examples is that one completely obscures any exceptions (first example), and the other (second example) retains exception information for potential later handling while still executing the content in the 'finally' clause.</p>\n\n<p>If, for example, you were to put code in the 'catch' clause of the first example that threw an exception (either the one that was initially raised, or a new one), the reader cleanup code would never execute. Finally executes <em>regardless</em> of what happens in the 'catch' clause.</p>\n\n<p>So, the main difference between 'catch' and 'finally' is that the contents of the 'finally' block (with a few rare exceptions) can be considered <em>guaranteed</em> to execute, even in the face of an unexpected exception, while any code following a 'catch' clause (but outside a 'finally' clause) would not carry such a guaranty.</p>\n\n<p>Incidentally, Stream and StreamReader both implement IDisposable, and can be wrapped in a 'using' block. 'Using' blocks are the semantic equivalent of try/finally (no 'catch'), so your example could be more tersely expressed as:</p>\n\n<pre><code>using (StreamReader reader = new StreamReader(\"myfile.txt\"))\n{\n int i = 5 / 0;\n}\n</code></pre>\n\n<p>...which will close and dispose of the StreamReader instance when it goes out of scope.\nHope this helps.</p>\n" }, { "answer_id": 128917, "author": "Chris Lawlor", "author_id": 21245, "author_profile": "https://Stackoverflow.com/users/21245", "pm_score": 3, "selected": false, "text": "<p>I agree with what seems to be the consensus here - an empty 'catch' is bad because it masks whatever exception might have occurred in the try block.</p>\n\n<p>Also, from a readability standpoint, when I see a 'try' block I assume there will be a corresponding 'catch' statement. If you are only using a 'try' in order to ensure resources are de-allocated in the 'finally' block, you might consider the <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"noreferrer\">'using' statement</a> instead:</p>\n\n<pre><code>using (StreamReader reader = new StreamReader('myfile.txt'))\n{\n // do stuff here\n} // reader.dispose() is called automatically\n</code></pre>\n\n<p>You can use the 'using' statement with any object that implements IDisposable. The object's dispose() method gets called automatically at the end of the block.</p>\n" }, { "answer_id": 129916, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": false, "text": "<p>While the following 2 code blocks are equivalent, they are not equal.</p>\n\n<pre><code>try\n{\n int i = 1/0; \n}\ncatch\n{\n reader.Close();\n throw;\n}\n\ntry\n{\n int i = 1/0;\n}\nfinally\n{\n reader.Close();\n}\n</code></pre>\n\n<ol>\n<li>'finally' is intention-revealing code. You declare to the compiler and to other programmers that this code needs to run no matter what.</li>\n<li>if you have multiple catch blocks and you have cleanup code, you need finally. Without finally, you would be duplicating your cleanup code in each catch block. (DRY principle)</li>\n</ol>\n\n<p>finally blocks are special. The CLR recognizes and treats code withing a finally block separately from catch blocks, and the CLR goes to great lengths to guarantee that a finally block will always execute. It's not just syntactic sugar from the compiler.</p>\n" }, { "answer_id": 130315, "author": "Martin Liesén", "author_id": 20715, "author_profile": "https://Stackoverflow.com/users/20715", "pm_score": 0, "selected": false, "text": "<p>try {…} catch{} is not always bad. It's not a common pattern, but I do tend to use it when I need to shutdown resources no matter what, like closing a (possibly) open sockets at the end of a thread. </p>\n" }, { "answer_id": 12621762, "author": "Bastien Vandamme", "author_id": 196526, "author_profile": "https://Stackoverflow.com/users/196526", "pm_score": 2, "selected": false, "text": "<p>It's bad practice to add a catch clause just to rethrow the exception.</p>\n" }, { "answer_id": 36936022, "author": "dr.Crow", "author_id": 2530448, "author_profile": "https://Stackoverflow.com/users/2530448", "pm_score": 2, "selected": false, "text": "<p>If you'll read <a href=\"https://books.google.com.ph/books?id=euV7e2f-RzsC&amp;pg=PA443&amp;lpg=PA443&amp;dq=throwing%20exception%20memory%20leak%20C%23&amp;source=bl&amp;ots=LEya1iGiLH&amp;sig=G6ALwAG6X8WrJ4EIOpJD8en8EKc&amp;hl=en&amp;sa=X&amp;ved=0ahUKEwjc17H_u_vLAhWHGpQKHSZqAhcQ6AEISTAH#v=onepage&amp;q=throwing%20exception%20memory%20leak%20C%23&amp;f=false\" rel=\"nofollow\">C# for programmers</a> you will understand, that the finally block was design to optimize an application and prevent memory leak.</p>\n\n<blockquote>\n <p>The CLR does not completely eliminate leaks... memory leaks can occur if program inadvertently keep references to unwanted objects </p>\n</blockquote>\n\n<p>For example when you open a file or database connection, your machine will allocate memory to cater that transaction, and that memory will be kept not unless the disposed or close command was executed. but if during transaction, an error was occurred, the proceeding command will be terminated not unless it was inside the <code>try.. finally..</code> block.</p>\n\n<p><code>catch</code> was different from <code>finally</code> in the sense that, catch was design to give you way to handle/manage or interpret the error it self. Think of it as person who tells you \"hey i caught some bad guys, what do you want me to do to them?\" \nwhile <code>finally</code> was designed to make sure that your resources was properly placed. Think of it of someone that whether or not there is some bad guys he will make sure that your property was still safe. </p>\n\n<p>And you should allow those two to work together for good.</p>\n\n<p>for example:</p>\n\n<pre><code>try\n{\n StreamReader reader=new StreamReader(\"myfile.txt\");\n //do other stuff\n}\ncatch(Exception ex){\n // Create log, or show notification\n generic.Createlog(\"Error\", ex.message);\n}\nfinally // Will execute despite any exception\n{\n reader.Close();\n}\n</code></pre>\n" }, { "answer_id": 39586676, "author": "manjuv", "author_id": 3509222, "author_profile": "https://Stackoverflow.com/users/3509222", "pm_score": 3, "selected": false, "text": "<p>Use <code>Try..Catch..Finally</code>, if your method knows how to handle the exception locally. The Exception occurs in Try, Handled in Catch and after that clean up is done in Finally.</p>\n\n<p>In case if your method doesn't know how to handle the exception but needs a cleanup once it has occurred use <code>Try..Finally</code></p>\n\n<p>By this the exception is propagated to the calling methods and handled if there are any suitable Catch statements in the calling methods.If there are no exception handlers in the current method or any of the calling methods then the application crashes. </p>\n\n<p>By <code>Try..Finally</code> it is ensured that the local clean up is done before propagating the exception to the calling methods.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21727/" ]
I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything: ``` StreamReader reader=new StreamReader("myfile.txt"); try { int i = 5 / 0; } catch // No args, so it will catch any exception {} reader.Close(); ``` However, this is considered good form: ``` StreamReader reader=new StreamReader("myfile.txt"); try { int i = 5 / 0; } finally // Will execute despite any exception { reader.Close(); } ``` As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not). Otherwise, what's so special about finally?
The big difference is that `try...catch` will swallow the exception, hiding the fact that an error occurred. `try..finally` will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.
128,853
<p>I'm sure there's some trivial one-liner with perl, ruby, bash whatever that would let me run a command in a loop until I observe some string in stdout, then stop. Ideally, I'd like to capture stdout as well, but if it's going to console, that might be enough. </p> <p>The particular environment in question at the moment is RedHat Linux but need same thing on Mac sometimes too. So something, generic and *nixy would be best. Don't care about Windows - presumably a *nixy thing would work under cygwin.</p> <p>UPDATE: Note that by "observe some string" I mean "stdout contains some string" not "stdout IS some string". </p>
[ { "answer_id": 128872, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p>There's a bunch of ways to do this, the first that came to mind was: </p>\n\n<pre><code>OUTPUT=\"\"; \nwhile [ `echo $OUTPUT | grep -c somestring` = 0 ]; do \n OUTPUT=`$cmd`; \ndone\n</code></pre>\n\n<p>Where $cmd is your command to execute.</p>\n\n<p>For the heck of it, here's a BASH function version, so you can call this more easily if it's something you're wanting to invoke from an interactive shell on a regular basis: </p>\n\n<pre><code>function run_until () {\n OUTPUT=\"\";\n while [ `echo $OUTPUT | grep -c $2` = 0 ]; do\n OUTPUT=`$1`;\n echo $OUTPUT;\n done\n}\n</code></pre>\n\n<p><em>Disclaimer: only lightly tested, may need to do some additional escaping etc. if your commands have lots of arguments or the string contains special chars.</em></p>\n\n<p><strong>EDIT</strong>: Based on feedback from Adam's comment - if you <em>don't</em> need the output for any reason (i.e. don't want to display the output), then you can use this shorter version, with less usage of backticks and therefore less overhead: </p>\n\n<pre><code>OUTPUT=0; \nwhile [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$cmd | grep -c somestring`;\ndone\n</code></pre>\n\n<p>BASH function version also: </p>\n\n<pre><code>function run_until () {\n OUTPUT=0; \n while [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$1 | grep -c $2`; \n done\n}\n</code></pre>\n" }, { "answer_id": 128875, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<pre><code>while (/bin/true); do\n OUTPUT=`/some/command`\n if [[ \"x$OUTPUT\" != \"x\" ]]; then\n echo $OUTPUT\n break\n fi\n\n sleep 1\ndone\n</code></pre>\n" }, { "answer_id": 128886, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 1, "selected": false, "text": "<p>EDIT:\nMy original answer was assuming that \"some string\" means \"any string\". If you need to look for a specific one, Perl is probably your best option, since almost nothing can beat Perl when it comes to REGEX matching.</p>\n\n<p>However, if you can't use Perl for any reason (you can expect Perl to be present in most Linux distros, but nobody forces a user to install it, though Perl may not be available), you can do it with the help of grep. However, some of the grep solutions I have seen so far are suboptimal (they are slower than would be necessary). In that case I would rather do the following:</p>\n\n<pre><code>MATCH=''; while [[ \"e$MATCH\" == \"e\" ]]; do MATCH=`COMMAND | grep \"SOME_STRING\"`; done; echo $MATCH\n</code></pre>\n\n<p>Replace <em>COMMAND</em> with the actually command to run and <em>SOME_STRING</em> with the string to search. If SOME_STRING is found in the output of COMMAND, the loop will stop and print the output where SOME_STRING was found.</p>\n\n<p>ORIGINAL ANSWER:</p>\n\n<p>Probably not the best solution (I'm no good bash programmer), but it will work :-P</p>\n\n<pre><code>RUN=''; while [[ \"e$RUN\" == \"e\" ]]; do RUN=`XXXX`; done ; echo $RUN\n</code></pre>\n\n<p>Just replace XXXX with your command call, e.g. try using \"<em>echo</em>\" and it will never return (as echo never prints anything to stdout), however if you use \"<em>echo test</em>\" it will terminate at once and finally print out test.</p>\n" }, { "answer_id": 128905, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 5, "selected": true, "text": "<p>In Perl:</p>\n\n<pre><code>#!/usr/local/bin/perl -w\n\nif (@ARGV != 2)\n{\n print \"Usage: watchit.pl &lt;cmd&gt; &lt;str&gt;\\n\";\n exit(1);\n}\n\n$cmd = $ARGV[0];\n$str = $ARGV[1];\n\nwhile (1)\n{\n my $output = `$cmd`;\n print $output; # or dump to file if desired\n if ($output =~ /$str/)\n {\n exit(0);\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>[bash$] ./watchit.pl ls stop\nwatchit.pl\nwatchit.pl~\nwatchit.pl\nwatchit.pl~\n... # from another terminal type \"touch stop\"\nstop \nwatchit.pl\nwatchit.pl~\n</code></pre>\n\n<p>You might want to add a sleep in there, though.</p>\n" }, { "answer_id": 130406, "author": "skoob", "author_id": 20708, "author_profile": "https://Stackoverflow.com/users/20708", "pm_score": 1, "selected": false, "text": "<pre><code>CONT=1; while [ $CONT -gt 0 ]; do $CMD | tee -a $FILE | grep -q $REGEXP; CONT=$? ; done\n</code></pre>\n\n<p>The tee command can capture stdout in a pipe while still passing the data on, and <code>-a</code> makes it append to the file instead of overwriting it every time. <code>grep -q</code> will <code>return 0</code> if there was a match, <code>1</code> otherwise and doesn't write anything to stdout. <code>$?</code> is the return value of the previous command, so <code>$CONT</code> will be the return value of grep in this case.</p>\n" }, { "answer_id": 130521, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 1, "selected": false, "text": "<p>A simple way to do this would be</p>\n\n<pre><code>until `/some/command`\ndo\n sleep 1\ndone\n</code></pre>\n\n<p>The backticks around the command make the <code>until</code> test for some output to be returned rather than testing the exit value of the command.</p>\n" }, { "answer_id": 133040, "author": "ordnungswidrig", "author_id": 9069, "author_profile": "https://Stackoverflow.com/users/9069", "pm_score": 3, "selected": false, "text": "<p><code>grep -c 99999</code> will print 99999 lines of context for the match (I assume this will be enough):</p>\n\n<pre><code>while true; do /some/command | grep expected -C 99999 &amp;&amp; break; done\n</code></pre>\n\n<p>or</p>\n\n<pre><code>until /some/command | grep expected -C 9999; do echo -n .; done\n</code></pre>\n\n<p>...this will print some nice dots to indicate progress.</p>\n" }, { "answer_id": 160803, "author": "markets", "author_id": 4662, "author_profile": "https://Stackoverflow.com/users/4662", "pm_score": 3, "selected": false, "text": "<p>I'm surprised I haven't seen a brief Perl one-liner mentioned here:</p>\n\n<pre><code>perl -e 'do { sleep(1); $_ = `command`; print $_; } until (m/search/);'\n</code></pre>\n\n<p>Perl is a really nice language for stuff like this. Replace \"command\" with the command you want to repeatedly run. Replace \"search\" with what you want to search for. If you want to search for something with a slash in it, then replace <code>m/search/</code> with <code>m#search</code> string with <code>/es#</code>.</p>\n\n<p>Also, Perl runs on lots of different platforms, including Win32, and this will work wherever you have a Perl installation. Just change your command appropriately.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671/" ]
I'm sure there's some trivial one-liner with perl, ruby, bash whatever that would let me run a command in a loop until I observe some string in stdout, then stop. Ideally, I'd like to capture stdout as well, but if it's going to console, that might be enough. The particular environment in question at the moment is RedHat Linux but need same thing on Mac sometimes too. So something, generic and \*nixy would be best. Don't care about Windows - presumably a \*nixy thing would work under cygwin. UPDATE: Note that by "observe some string" I mean "stdout contains some string" not "stdout IS some string".
In Perl: ``` #!/usr/local/bin/perl -w if (@ARGV != 2) { print "Usage: watchit.pl <cmd> <str>\n"; exit(1); } $cmd = $ARGV[0]; $str = $ARGV[1]; while (1) { my $output = `$cmd`; print $output; # or dump to file if desired if ($output =~ /$str/) { exit(0); } } ``` Example: ``` [bash$] ./watchit.pl ls stop watchit.pl watchit.pl~ watchit.pl watchit.pl~ ... # from another terminal type "touch stop" stop watchit.pl watchit.pl~ ``` You might want to add a sleep in there, though.
128,857
<p>I have a user reporting that when they use the back button to return to a web page that they come back as a different person. It seems like they may be accessing a different users profile.</p> <p>Here are the important parts of the code:</p> <pre><code>//here's the code on the web page public static WebProfile p = null; protected void Page_Load(object sender, EventArgs e) { p = ProfileController.GetWebProfile(); if (!this.IsPostBack) { PopulateForm(); } } //here's the code in the "ProfileController" (probably misnamed) public static WebProfile GetWebProfile() { //get shopperID from cookie string mscsShopperID = GetShopperID(); string userName = new tpw.Shopper(Shopper.Columns.ShopperId, mscsShopperID).Email; p = WebProfile.GetProfile(userName); return p; } </code></pre> <p>I'm using static methods and a <code>static WebProfile</code> because I need to use the profile object in a <code>static WebMethod</code> (ajax <code>pageMethod</code>). </p> <ul> <li>Could this lead to the profile object being "shared" by different users? </li> <li>Am I not using static methods and objects correctly?</li> </ul> <hr> <p>The reason I changed <code>WebProfile</code> object to a <code>static</code> object was because I need to access the profile object within a <code>[WebMethod]</code> (called from javascript on the page). </p> <ul> <li>Is there a way to access a profile object within a <code>[WebMethod]</code>? </li> <li>If not, what choices do I have?</li> </ul>
[ { "answer_id": 128872, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p>There's a bunch of ways to do this, the first that came to mind was: </p>\n\n<pre><code>OUTPUT=\"\"; \nwhile [ `echo $OUTPUT | grep -c somestring` = 0 ]; do \n OUTPUT=`$cmd`; \ndone\n</code></pre>\n\n<p>Where $cmd is your command to execute.</p>\n\n<p>For the heck of it, here's a BASH function version, so you can call this more easily if it's something you're wanting to invoke from an interactive shell on a regular basis: </p>\n\n<pre><code>function run_until () {\n OUTPUT=\"\";\n while [ `echo $OUTPUT | grep -c $2` = 0 ]; do\n OUTPUT=`$1`;\n echo $OUTPUT;\n done\n}\n</code></pre>\n\n<p><em>Disclaimer: only lightly tested, may need to do some additional escaping etc. if your commands have lots of arguments or the string contains special chars.</em></p>\n\n<p><strong>EDIT</strong>: Based on feedback from Adam's comment - if you <em>don't</em> need the output for any reason (i.e. don't want to display the output), then you can use this shorter version, with less usage of backticks and therefore less overhead: </p>\n\n<pre><code>OUTPUT=0; \nwhile [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$cmd | grep -c somestring`;\ndone\n</code></pre>\n\n<p>BASH function version also: </p>\n\n<pre><code>function run_until () {\n OUTPUT=0; \n while [ \"$OUTPUT\" = 0 ]; do \n OUTPUT=`$1 | grep -c $2`; \n done\n}\n</code></pre>\n" }, { "answer_id": 128875, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<pre><code>while (/bin/true); do\n OUTPUT=`/some/command`\n if [[ \"x$OUTPUT\" != \"x\" ]]; then\n echo $OUTPUT\n break\n fi\n\n sleep 1\ndone\n</code></pre>\n" }, { "answer_id": 128886, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 1, "selected": false, "text": "<p>EDIT:\nMy original answer was assuming that \"some string\" means \"any string\". If you need to look for a specific one, Perl is probably your best option, since almost nothing can beat Perl when it comes to REGEX matching.</p>\n\n<p>However, if you can't use Perl for any reason (you can expect Perl to be present in most Linux distros, but nobody forces a user to install it, though Perl may not be available), you can do it with the help of grep. However, some of the grep solutions I have seen so far are suboptimal (they are slower than would be necessary). In that case I would rather do the following:</p>\n\n<pre><code>MATCH=''; while [[ \"e$MATCH\" == \"e\" ]]; do MATCH=`COMMAND | grep \"SOME_STRING\"`; done; echo $MATCH\n</code></pre>\n\n<p>Replace <em>COMMAND</em> with the actually command to run and <em>SOME_STRING</em> with the string to search. If SOME_STRING is found in the output of COMMAND, the loop will stop and print the output where SOME_STRING was found.</p>\n\n<p>ORIGINAL ANSWER:</p>\n\n<p>Probably not the best solution (I'm no good bash programmer), but it will work :-P</p>\n\n<pre><code>RUN=''; while [[ \"e$RUN\" == \"e\" ]]; do RUN=`XXXX`; done ; echo $RUN\n</code></pre>\n\n<p>Just replace XXXX with your command call, e.g. try using \"<em>echo</em>\" and it will never return (as echo never prints anything to stdout), however if you use \"<em>echo test</em>\" it will terminate at once and finally print out test.</p>\n" }, { "answer_id": 128905, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 5, "selected": true, "text": "<p>In Perl:</p>\n\n<pre><code>#!/usr/local/bin/perl -w\n\nif (@ARGV != 2)\n{\n print \"Usage: watchit.pl &lt;cmd&gt; &lt;str&gt;\\n\";\n exit(1);\n}\n\n$cmd = $ARGV[0];\n$str = $ARGV[1];\n\nwhile (1)\n{\n my $output = `$cmd`;\n print $output; # or dump to file if desired\n if ($output =~ /$str/)\n {\n exit(0);\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>[bash$] ./watchit.pl ls stop\nwatchit.pl\nwatchit.pl~\nwatchit.pl\nwatchit.pl~\n... # from another terminal type \"touch stop\"\nstop \nwatchit.pl\nwatchit.pl~\n</code></pre>\n\n<p>You might want to add a sleep in there, though.</p>\n" }, { "answer_id": 130406, "author": "skoob", "author_id": 20708, "author_profile": "https://Stackoverflow.com/users/20708", "pm_score": 1, "selected": false, "text": "<pre><code>CONT=1; while [ $CONT -gt 0 ]; do $CMD | tee -a $FILE | grep -q $REGEXP; CONT=$? ; done\n</code></pre>\n\n<p>The tee command can capture stdout in a pipe while still passing the data on, and <code>-a</code> makes it append to the file instead of overwriting it every time. <code>grep -q</code> will <code>return 0</code> if there was a match, <code>1</code> otherwise and doesn't write anything to stdout. <code>$?</code> is the return value of the previous command, so <code>$CONT</code> will be the return value of grep in this case.</p>\n" }, { "answer_id": 130521, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 1, "selected": false, "text": "<p>A simple way to do this would be</p>\n\n<pre><code>until `/some/command`\ndo\n sleep 1\ndone\n</code></pre>\n\n<p>The backticks around the command make the <code>until</code> test for some output to be returned rather than testing the exit value of the command.</p>\n" }, { "answer_id": 133040, "author": "ordnungswidrig", "author_id": 9069, "author_profile": "https://Stackoverflow.com/users/9069", "pm_score": 3, "selected": false, "text": "<p><code>grep -c 99999</code> will print 99999 lines of context for the match (I assume this will be enough):</p>\n\n<pre><code>while true; do /some/command | grep expected -C 99999 &amp;&amp; break; done\n</code></pre>\n\n<p>or</p>\n\n<pre><code>until /some/command | grep expected -C 9999; do echo -n .; done\n</code></pre>\n\n<p>...this will print some nice dots to indicate progress.</p>\n" }, { "answer_id": 160803, "author": "markets", "author_id": 4662, "author_profile": "https://Stackoverflow.com/users/4662", "pm_score": 3, "selected": false, "text": "<p>I'm surprised I haven't seen a brief Perl one-liner mentioned here:</p>\n\n<pre><code>perl -e 'do { sleep(1); $_ = `command`; print $_; } until (m/search/);'\n</code></pre>\n\n<p>Perl is a really nice language for stuff like this. Replace \"command\" with the command you want to repeatedly run. Replace \"search\" with what you want to search for. If you want to search for something with a slash in it, then replace <code>m/search/</code> with <code>m#search</code> string with <code>/es#</code>.</p>\n\n<p>Also, Perl runs on lots of different platforms, including Win32, and this will work wherever you have a Perl installation. Just change your command appropriately.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4888/" ]
I have a user reporting that when they use the back button to return to a web page that they come back as a different person. It seems like they may be accessing a different users profile. Here are the important parts of the code: ``` //here's the code on the web page public static WebProfile p = null; protected void Page_Load(object sender, EventArgs e) { p = ProfileController.GetWebProfile(); if (!this.IsPostBack) { PopulateForm(); } } //here's the code in the "ProfileController" (probably misnamed) public static WebProfile GetWebProfile() { //get shopperID from cookie string mscsShopperID = GetShopperID(); string userName = new tpw.Shopper(Shopper.Columns.ShopperId, mscsShopperID).Email; p = WebProfile.GetProfile(userName); return p; } ``` I'm using static methods and a `static WebProfile` because I need to use the profile object in a `static WebMethod` (ajax `pageMethod`). * Could this lead to the profile object being "shared" by different users? * Am I not using static methods and objects correctly? --- The reason I changed `WebProfile` object to a `static` object was because I need to access the profile object within a `[WebMethod]` (called from javascript on the page). * Is there a way to access a profile object within a `[WebMethod]`? * If not, what choices do I have?
In Perl: ``` #!/usr/local/bin/perl -w if (@ARGV != 2) { print "Usage: watchit.pl <cmd> <str>\n"; exit(1); } $cmd = $ARGV[0]; $str = $ARGV[1]; while (1) { my $output = `$cmd`; print $output; # or dump to file if desired if ($output =~ /$str/) { exit(0); } } ``` Example: ``` [bash$] ./watchit.pl ls stop watchit.pl watchit.pl~ watchit.pl watchit.pl~ ... # from another terminal type "touch stop" stop watchit.pl watchit.pl~ ``` You might want to add a sleep in there, though.
128,888
<p>In Java, I have a subclass <code>Vertex</code> of the Java3D class <code>Point3f</code>. Now <code>Point3f</code> computes <code>equals()</code> based on the values of its coordinates, but for my <code>Vertex</code> class I want to be stricter: two vertices are only equal if they are the same object. So far, so good:</p> <pre><code>class Vertex extends Point3f { // ... public boolean equals(Object other) { return this == other; } } </code></pre> <p>I know this violates the contract of <code>equals()</code>, but since I'll only compare vertices to other vertices this is not a problem.</p> <p>Now, to be able to put vertices into a <code>HashMap</code>, the <code>hashCode()</code> method must return results consistent with <code>equals()</code>. It currently does that, but probably bases its return value on the fields of the <code>Point3f</code>, and therefore will give hash collisions for different <code>Vertex</code> objects with the same coordinates.</p> <p>Therefore I would like to base the <code>hashCode()</code> on the object's address, instead of computing it from the <code>Vertex</code>'s fields. I know that the <code>Object</code> class does this, but I cannot call its <code>hashCode()</code> method because <code>Point3f</code> overrides it.</p> <p>So, actually my question is twofold:</p> <ul> <li>Should I even want such a shallow <code>equals()</code>?</li> <li>If yes, then, how do I get the object's address to compute the hash code from?</li> </ul> <p>Edit: I just thought of something... I could generate a random <code>int</code> value on object creation, and use that for the hash code. Is that a good idea? Why (not)?</p>
[ { "answer_id": 128910, "author": "Christian P.", "author_id": 9479, "author_profile": "https://Stackoverflow.com/users/9479", "pm_score": -1, "selected": false, "text": "<p>The function hashCode() is inherited from Object and works exactly as you intend (on object level, not coordinate-level). There should be no need to change it.</p>\n\n<p>As for your equals-method, there is no reason to even use it, since you can just do obj1 == obj2 in your code instead of using equals, since it's meant for sorting and similar, where comparing coordinates makes a lot more sense.</p>\n" }, { "answer_id": 128926, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": true, "text": "<p>Either use System.identityHashCode() or use an IdentityHashMap.</p>\n" }, { "answer_id": 128940, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#identityHashCode(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>System.identityHashCode()</code></a> returns the same hash code for the given object as would be returned by the default method <code>hashCode()</code>, whether or not the given object's class overrides <code>hashCode()</code>.</p>\n" }, { "answer_id": 128982, "author": "Jay R.", "author_id": 5074, "author_profile": "https://Stackoverflow.com/users/5074", "pm_score": 0, "selected": false, "text": "<p>You use a delegate even though this <a href=\"https://stackoverflow.com/questions/128888/how-to-compute-the-hashcode-from-the-objects-address#128926\">answer</a> is probably better.</p>\n\n<pre><code>\nclass Vertex extends Point3f{\n private final Object equalsDelegate = new Object();\n public boolean equals(Object vertex){\n if(vertex instanceof Vertex){\n return this.equalsDelegate.equals(((Vertex)vertex).equalsDelegate);\n }\n else{\n return super.equals(vertex);\n }\n }\n public int hashCode(){\n return this.equalsDelegate.hashCode();\n }\n}\n</code></pre>\n" }, { "answer_id": 129021, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "<p>Just FYI, your equals method does NOT violate the equals contract (for the base Object's contract that is)... that is basically the equals method for the base Object method, so if you want identity equals instead of the Vertex equals, that is fine.</p>\n\n<p>As for the hash code, you really don't need to change it, though the accepted answer is a good option and will be a lot more efficient if your hash table contains a lot of vertex keys that have the same values.</p>\n\n<p>The reason you don't need to change it is because it is completely fine that the hash code will return the same value for objects that equals returns false... it is even a valid hash code to just return 0 all the time for EVERY instance. Whether this is efficient for hash tables is completely different issue... you will get a lot more collisions if a lot of your objects have the same hash code (which may be the case if you left hash code alone and had a lot of vertices with the same values).</p>\n\n<p>Please don't accept this as the answer though of course (what you chose is much more practical), I just wanted to give you a little more background info about hash codes and equals ;-)</p>\n" }, { "answer_id": 129411, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 0, "selected": false, "text": "<p>Why do you want to override hashCode() in the first place? You'd want to do it if you want to work with some other definition of equality. For example</p>\n\n<p>public class A {\n int id;</p>\n\n<p>public boolean equals(A other) { return other.id==id}\n public int hashCode() {return id;}</p>\n\n<p>}\nwhere you want to be clear that if the id's are the same then the objects are the same, and you override hashcode so that you can't do this:</p>\n\n<p>HashSet hash= new HashSet();\nhash.add(new A(1));\nhash.add(new A(1));\nand get 2 identical(from the point of view of your definition of equality) A's.\nThe correct behavior would then be that you'd only have 1 object in the hash, the second write would overwrite.</p>\n" }, { "answer_id": 130389, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 0, "selected": false, "text": "<p>Since you are not using equals as a logical comparison, but a physical one (i.e. it is the same object), the only way you will guarantee that the hashcode will return a unique value, is to implement a variation of your own suggestion. Instead of generating a random number, use UUID to generate an actual unique value for each object.</p>\n\n<p>The System.identityHashCode() will work, <strong>most</strong> of the time, but is not guaranteed as the Object.hashCode() method is <strong>not</strong> guaranteed to return a unique value for every object. I have seen the marginal case happen, and it will probably be dependent on the VM implementation, which is not something you will want your code be dependent on.</p>\n\n<p>Excerpt from the javadocs for Object.hashCode():\nAs much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.) </p>\n\n<p>The problem this addresses, is the case of having two separate point objects from overwriting each other when inserted into the hashmap because they both have the same hash. Since there is no logical equals, with the accompanying override of hashCode(), the identityHashCode method can actually cause this scenario to occur. Where the logical case would only replace hash entries for the same logical point, using the system based hash can cause it to occur with any two objects, equality (and even class) is no longer a factor.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14637/" ]
In Java, I have a subclass `Vertex` of the Java3D class `Point3f`. Now `Point3f` computes `equals()` based on the values of its coordinates, but for my `Vertex` class I want to be stricter: two vertices are only equal if they are the same object. So far, so good: ``` class Vertex extends Point3f { // ... public boolean equals(Object other) { return this == other; } } ``` I know this violates the contract of `equals()`, but since I'll only compare vertices to other vertices this is not a problem. Now, to be able to put vertices into a `HashMap`, the `hashCode()` method must return results consistent with `equals()`. It currently does that, but probably bases its return value on the fields of the `Point3f`, and therefore will give hash collisions for different `Vertex` objects with the same coordinates. Therefore I would like to base the `hashCode()` on the object's address, instead of computing it from the `Vertex`'s fields. I know that the `Object` class does this, but I cannot call its `hashCode()` method because `Point3f` overrides it. So, actually my question is twofold: * Should I even want such a shallow `equals()`? * If yes, then, how do I get the object's address to compute the hash code from? Edit: I just thought of something... I could generate a random `int` value on object creation, and use that for the hash code. Is that a good idea? Why (not)?
Either use System.identityHashCode() or use an IdentityHashMap.
128,914
<p>Several months ago my work deployed an in-house function that wraps the standard, php, mysql_query() function with additional options and abilities. A sample feature would be some handy debugging tools we can turn on/off. </p> <p>I was wondering how popular query handlers are and what features people like to build into them.</p>
[ { "answer_id": 128962, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "<p>I use a DBAL like <a href=\"http://pear.php.net/package/MDB2\" rel=\"nofollow noreferrer\">MDB2</a>, <a href=\"http://framework.zend.com/manual/en/zend.db.html\" rel=\"nofollow noreferrer\">Zend_Db</a> or <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine</a> for similar reason. Primarily to be able to utilize all the shortcuts it offers, not so much for the fact that it supports different databases.</p>\n\n<p>E.g., old:</p>\n\n<pre><code>&lt;?php\n$query = \"SELECT * FROM table\";\n$result = mysql_query($query);\nif (!$result) {\n echo mysql_error();\n} else {\n if (mysql_num_rows($result) &gt; 0) {\n while ($row = mysql_fetch_obj($result)) {\n ...\n }\n }\n}\n?&gt;\n</code></pre>\n\n<p>Versus (Zend_Db):</p>\n\n<pre><code>&lt;?php\ntry {\n $result = $db-&gt;fetchAll(\"SELECT * FROM table\");\n foreach($result as $row) {\n ...\n }\n} catch (Zend_Exception $e) {\n echo $e-&gt;getMessage();\n}\n?&gt;\n</code></pre>\n\n<p>IMHO, more intuitive.</p>\n" }, { "answer_id": 695940, "author": "jerebear", "author_id": 42979, "author_profile": "https://Stackoverflow.com/users/42979", "pm_score": 0, "selected": false, "text": "<p>We implemented something similar at my office too. It's proven to be an invaluable to tool for the associated handling features it offers. Error tracking, pre-formatted output and it also works as an 'AL' between MsSQL and MySQL.</p>\n\n<p>Aside from the above features I think it'd be cool to have some low-resource intensive performance monitoring or tracking. For larger or more complicated data sets the queries can be quite weighty and being able to monitor that real-time (or post) would be helpful for any optimization needed on larger-scale websites.</p>\n\n<p>Just my two cents.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14959/" ]
Several months ago my work deployed an in-house function that wraps the standard, php, mysql\_query() function with additional options and abilities. A sample feature would be some handy debugging tools we can turn on/off. I was wondering how popular query handlers are and what features people like to build into them.
I use a DBAL like [MDB2](http://pear.php.net/package/MDB2), [Zend\_Db](http://framework.zend.com/manual/en/zend.db.html) or [Doctrine](http://www.doctrine-project.org/) for similar reason. Primarily to be able to utilize all the shortcuts it offers, not so much for the fact that it supports different databases. E.g., old: ``` <?php $query = "SELECT * FROM table"; $result = mysql_query($query); if (!$result) { echo mysql_error(); } else { if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_obj($result)) { ... } } } ?> ``` Versus (Zend\_Db): ``` <?php try { $result = $db->fetchAll("SELECT * FROM table"); foreach($result as $row) { ... } } catch (Zend_Exception $e) { echo $e->getMessage(); } ?> ``` IMHO, more intuitive.
128,923
<p>Many times I've seen links like these in HTML pages:</p> <pre><code>&lt;a href='#' onclick='someFunc(3.1415926); return false;'&gt;Click here !&lt;/a&gt; </code></pre> <p>What's the effect of the <code>return false</code> in there?</p> <p>Also, I don't usually see that in buttons.</p> <p>Is this specified anywhere? In some spec in w3.org?</p>
[ { "answer_id": 128928, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": false, "text": "<p>I believe it causes the standard event to not happen.</p>\n\n<p>In your example the browser will not attempt to go to #.</p>\n" }, { "answer_id": 128931, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 4, "selected": false, "text": "<p>Retuning false from a JavaScript event usually cancels the \"default\" behavior - in the case of links, it tells the browser to not follow the link.</p>\n" }, { "answer_id": 128935, "author": "ncgz", "author_id": 12905, "author_profile": "https://Stackoverflow.com/users/12905", "pm_score": 2, "selected": false, "text": "<p>Return false will prevent navigation. Otherwise, the location would become the return value of someFunc</p>\n" }, { "answer_id": 128939, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 3, "selected": false, "text": "<p>The return false is saying not to take the default action, which in the case of an <code>&lt;a href&gt;</code> is to follow the link. When you return false to the onclick, then the href will be ignored. </p>\n" }, { "answer_id": 128942, "author": "pixel", "author_id": 21804, "author_profile": "https://Stackoverflow.com/users/21804", "pm_score": 3, "selected": false, "text": "<p>using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.</p>\n\n<p>In other words, adding return false stops the href from working. In your example, this is exactly what you want.</p>\n\n<p>In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.</p>\n" }, { "answer_id": 128947, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 3, "selected": false, "text": "<p>Browser hack:\n<a href=\"http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html\" rel=\"noreferrer\">http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html</a></p>\n" }, { "answer_id": 128952, "author": "HoboBen", "author_id": 840, "author_profile": "https://Stackoverflow.com/users/840", "pm_score": 4, "selected": false, "text": "<p>Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.</p>\n\n<p>If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.</p>\n" }, { "answer_id": 128966, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 9, "selected": true, "text": "<p>The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.</p>\n\n<p>I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname \"DOM 0\", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.</p>\n\n<p>The modern way of achieving this effect is to call <code>event.preventDefault()</code>, and this is specified in <a href=\"http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation\" rel=\"noreferrer\">the DOM 2 Events specification</a>.</p>\n" }, { "answer_id": 129500, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 5, "selected": false, "text": "<p>Here's a more robust routine to cancel default behavior and event bubbling in all browsers:</p>\n<pre><code>// Prevents event bubble up or any usage after this is called.\neventCancel = function (e)\n{\n if (!e)\n if (window.event) e = window.event;\n else return;\n if (e.cancelBubble != null) e.cancelBubble = true;\n if (e.stopPropagation) e.stopPropagation();\n if (e.preventDefault) e.preventDefault();\n if (window.event) e.returnValue = false;\n if (e.cancel != null) e.cancel = true;\n}\n</code></pre>\n<p>An example of how this would be used in an event handler:</p>\n<pre><code>// Handles the click event for each tab\nTabstrip.tabstripLinkElement_click = function (evt, context) \n{\n // Find the tabStrip element (we know it's the parent element of this link)\n var tabstripElement = this.parentNode;\n Tabstrip.showTabByLink(tabstripElement, this);\n return eventCancel(evt);\n}\n</code></pre>\n" }, { "answer_id": 132396, "author": "HoboBen", "author_id": 840, "author_profile": "https://Stackoverflow.com/users/840", "pm_score": 8, "selected": false, "text": "<p>You can see the difference with the following example:</p>\n\n<pre><code>&lt;a href=\"http://www.google.co.uk/\" onclick=\"return (confirm('Follow this link?'))\"&gt;Google&lt;/a&gt;\n</code></pre>\n\n<p>Clicking \"Okay\" returns true, and the link is followed. Clicking \"Cancel\" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.</p>\n" }, { "answer_id": 22270882, "author": "Dmitri Zaitsev", "author_id": 1614973, "author_profile": "https://Stackoverflow.com/users/1614973", "pm_score": 2, "selected": false, "text": "<p>I am surprised that no one mentioned <code>onmousedown</code> instead of <code>onclick</code>. The </p>\n\n<p><code>onclick='return false'</code> </p>\n\n<p>does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for <code>mousedown</code> but </p>\n\n<p><code>onmousedown='return false'</code> </p>\n\n<p>does.</p>\n\n<p>In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the <code>mousedown</code> event is registered before <code>click</code>, so if you only prevent that behaviour inside your <code>click</code> handler, it will not affect the unwanted selection arising from the <code>mousedown</code> event. So the text still gets selected. However, preventing default for the <code>mousedown</code> event will do the job.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false\">event.preventDefault() vs. return false</a></p>\n" }, { "answer_id": 25377783, "author": "kamesh", "author_id": 3007335, "author_profile": "https://Stackoverflow.com/users/3007335", "pm_score": 5, "selected": false, "text": "<h2>WHAT <strong><em>\"return false\"</em></strong> IS REALLY DOING?</h2>\n\n<p>return false is actually doing three very separate things when you call it:</p>\n\n<ol>\n<li>event.preventDefault();</li>\n<li>event.stopPropagation();</li>\n<li>Stops callback execution and returns immediately when called.</li>\n</ol>\n\n<p>See <a href=\"http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/\">jquery-events-stop-misusing-return-false</a> for more information.</p>\n\n<p><em>For example :</em></p>\n\n<p>while clicking this link, return false will <strong><em>cancel the default behaviour of the browser</em></strong>. </p>\n\n<pre><code>&lt;a href='#' onclick='someFunc(3.1415926); return false;'&gt;Click here !&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 36315459, "author": "Shivakrishna", "author_id": 5485645, "author_profile": "https://Stackoverflow.com/users/5485645", "pm_score": 2, "selected": false, "text": "<p>The <code>return false</code> prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.</p>\n\n<pre><code>onclick=\"return false\"\n</code></pre>\n" }, { "answer_id": 59011450, "author": "Panu Logic", "author_id": 1639918, "author_profile": "https://Stackoverflow.com/users/1639918", "pm_score": 2, "selected": false, "text": "<p>I have this link on my HTML-page:</p>\n\n<pre><code>&lt;a href = \"\" \nonclick = \"setBodyHtml ('new content'); return false; \"\n&gt; click here &lt;/a&gt;\n</code></pre>\n\n<p>The function setBodyHtml() is defined as:</p>\n\n<pre><code>function setBodyHtml (s)\n{ document.body.innerHTML = s;\n}\n</code></pre>\n\n<p>When I click the link the link disappears and the text shown in the browser\nchanges to \"new content\".</p>\n\n<p>But if I remove the \"false\" from my link, clicking the link does (seemingly) nothing. Why is that?</p>\n\n<p>It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is \"\" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens. </p>\n\n<p>In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.</p>\n\n<p>This example shows why it is sometimes USEFUL to use \"return false\". </p>\n\n<p>I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must \"return false\".</p>\n\n<p>The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the \"return false\" above does the trick. </p>\n" }, { "answer_id": 59419315, "author": "Allan", "author_id": 2952113, "author_profile": "https://Stackoverflow.com/users/2952113", "pm_score": 1, "selected": false, "text": "<p>When using forms,we can use 'return false' to prevent submitting.</p>\n\n<pre><code>function checkForm() {\n // return true to submit, return false to prevent submitting\n}\n&lt;form onsubmit=\"return checkForm()\"&gt;\n ...\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 64905141, "author": "jason", "author_id": 5489036, "author_profile": "https://Stackoverflow.com/users/5489036", "pm_score": 1, "selected": false, "text": "<p>By default, when you click on the button, the form would be sent to server no matter what value you have input.</p>\n<p>However, this behavior is not quite appropriate for most cases because we may want to do some checking before sending it to server.</p>\n<p>So, when the listener received &quot;false&quot;, the submitting would be cancelled. Basically, it is for the purpose to do some checking on front end.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
Many times I've seen links like these in HTML pages: ``` <a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a> ``` What's the effect of the `return false` in there? Also, I don't usually see that in buttons. Is this specified anywhere? In some spec in w3.org?
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information. I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation. The modern way of achieving this effect is to call `event.preventDefault()`, and this is specified in [the DOM 2 Events specification](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation).
128,933
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears that the usermod easily allows me to add a user to a supplementary group with this command:</p> <pre><code>usermod -a -G supgroup1,supgroup2 username </code></pre> <p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p> <p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p> <pre><code>#!/usr/bin/perl # # Usage: removegroup.pl login group # Purpose: Removes a user from a group while retaining current primary and # supplementary groups. # Notes: There is a Debian specific utility that can do this called deluser, # but I did not want any cross-distribution dependencies # # Date: 25 September 2008 # Validate Arguments (correct number, format etc.) if ( ($#ARGV &lt; 1) || (2 &lt; $#ARGV) ) { print "\nUsage: removegroup.pl login group\n\n"; print "EXIT VALUES\n"; print " The removeuser.pl script exits with the following values:\n\n"; print " 0 success\n\n"; print " 1 Invalid number of arguments\n\n"; print " 2 Login or Group name supplied greater than 16 characters\n\n"; print " 3 Login and/or Group name contains invalid characters\n\n"; exit 1; } # Check for well formed group and login names if ((16 &lt; length($ARGV[0])) ||(16 &lt; length($ARGV[1]))) { print "Usage: removegroup.pl login group\n"; print "ERROR: Login and Group names must be less than 16 Characters\n"; exit 2; } if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) ) { print "Usage: removegroup.pl login group\n"; print "ERROR: Login and/or Group name contains invalid characters\n"; exit 3; } # Set some variables for readability $login=$ARGV[0]; $group=$ARGV[1]; # Requires the GroupFile interface from perl-Unix-Configfile use Unix::GroupFile; $grp = new Unix::GroupFile "/etc/group"; $grp-&gt;remove_user("$group", "$login"); $grp-&gt;commit(); undef $grp; exit 0; </code></pre>
[ { "answer_id": 129012, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "<p>It looks like <em>deluser --group [groupname]</em> should do it.</p>\n\n<p>If not, the <em>groups</em> command lists the groups that a user belongs to. It should be fairly straightforward to come up with some Perl to capture that list into an array (or <em>map</em> it into a hash), delete the unwanted group(s), and feed that back to <em>usermod</em>.</p>\n" }, { "answer_id": 129245, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "<p>I found <a href=\"http://search.cpan.org/~ssnodgra/Unix-ConfigFile-0.06/GroupFile.pm\" rel=\"nofollow noreferrer\">This</a> for you. It should do what you need. As far as I can tell Perl does not have any built in functions for removing users from a group. It has several for seeing the group id of a user or process.</p>\n" }, { "answer_id": 129468, "author": "innaM", "author_id": 7498, "author_profile": "https://Stackoverflow.com/users/7498", "pm_score": 1, "selected": false, "text": "<p>Here's a very simple little Perl script that should give you the list of groups you need:</p>\n\n<pre><code>my $user = 'user';\nmy $groupNoMore = 'somegroup';\nmy $groups = join ',', grep { $_ ne $groupNoMore } split /\\s/, `groups $user`;\n</code></pre>\n\n<p>Getting and sanitizing the required arguments is left as an execrcise for the reader.</p>\n" }, { "answer_id": 462545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Web Link: <a href=\"http://www.ibm.com/developerworks/linux/library/l-roadmap4/\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/linux/library/l-roadmap4/</a></p>\n\n<p>To add members to the group, use the gpasswd command with the -a switch and the user id you wish to add:</p>\n\n<p>gpasswd -a userid mygroup</p>\n\n<p>Remove users from a group with the same command, but a -d switch rather than -a:</p>\n\n<p>gpasswd -d userid mygroup </p>\n\n<p>\"man gpasswd\" for more info...</p>\n\n<p>I looked for ages to find this. Sometimes it takes too much effort not to reinvent the wheel...</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346/" ]
I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears that the usermod easily allows me to add a user to a supplementary group with this command: ``` usermod -a -G supgroup1,supgroup2 username ``` Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance! Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure. ``` #!/usr/bin/perl # # Usage: removegroup.pl login group # Purpose: Removes a user from a group while retaining current primary and # supplementary groups. # Notes: There is a Debian specific utility that can do this called deluser, # but I did not want any cross-distribution dependencies # # Date: 25 September 2008 # Validate Arguments (correct number, format etc.) if ( ($#ARGV < 1) || (2 < $#ARGV) ) { print "\nUsage: removegroup.pl login group\n\n"; print "EXIT VALUES\n"; print " The removeuser.pl script exits with the following values:\n\n"; print " 0 success\n\n"; print " 1 Invalid number of arguments\n\n"; print " 2 Login or Group name supplied greater than 16 characters\n\n"; print " 3 Login and/or Group name contains invalid characters\n\n"; exit 1; } # Check for well formed group and login names if ((16 < length($ARGV[0])) ||(16 < length($ARGV[1]))) { print "Usage: removegroup.pl login group\n"; print "ERROR: Login and Group names must be less than 16 Characters\n"; exit 2; } if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) ) { print "Usage: removegroup.pl login group\n"; print "ERROR: Login and/or Group name contains invalid characters\n"; exit 3; } # Set some variables for readability $login=$ARGV[0]; $group=$ARGV[1]; # Requires the GroupFile interface from perl-Unix-Configfile use Unix::GroupFile; $grp = new Unix::GroupFile "/etc/group"; $grp->remove_user("$group", "$login"); $grp->commit(); undef $grp; exit 0; ```
Web Link: <http://www.ibm.com/developerworks/linux/library/l-roadmap4/> To add members to the group, use the gpasswd command with the -a switch and the user id you wish to add: gpasswd -a userid mygroup Remove users from a group with the same command, but a -d switch rather than -a: gpasswd -d userid mygroup "man gpasswd" for more info... I looked for ages to find this. Sometimes it takes too much effort not to reinvent the wheel...
128,949
<p>Templates are a pretty healthy business in established programming languages, but are there any good ones that can be processed in JavaScript?</p> <p>By "template" I mean a document that accepts a data object as input, inserts the data into some kind of serialized markup language, and outputs the markup. Well-known examples are <a href="http://en.wikipedia.org/wiki/JavaServer_Pages" rel="nofollow noreferrer">JSP</a>, the original PHP, <a href="http://en.wikipedia.org/wiki/XSLT" rel="nofollow noreferrer">XSLT</a>.</p> <p>By "good" I mean that it's declarative and easy for an HTML author to write, that it's robust, and that it's supported in other languages too. Something better than the options I know about. Some examples of "not good":</p> <hr> <p>String math:</p> <pre><code>element.innerHTML = "&lt;p&gt;Name: " + data.name + "&lt;/p&gt;&lt;p&gt;Email: " + data.email + "&lt;/p&gt;"; </code></pre> <p>clearly too unwieldy, HTML structure not apparent.</p> <hr> <p>XSLT:</p> <pre><code>&lt;p&gt;&lt;xsl:text&gt;Name: &lt;/xsl:text&gt;&lt;xsl:value-of select="//data/name"&gt;&lt;/p&gt; &lt;p&gt;&lt;xsl:text&gt;Email: &lt;/xsl:text&gt;&lt;xsl:value-of select="//data/email"&gt;&lt;/p&gt; </code></pre> <p>// Structurally this works well, but let's face it, XSLT confuses HTML developers.</p> <hr> <p>Trimpath:</p> <pre><code>&lt;p&gt;Name: ${data.name}&lt;/p&gt;&lt;p&gt;Email: ${data.email}&lt;/p&gt; </code></pre> <p>// This is nice, but the processor is only supported in JavaScript, and the language is sort of primitive (<a href="http://code.google.com/p/trimpath/wiki/JavaScriptTemplateSyntax" rel="nofollow noreferrer">http://code.google.com/p/trimpath/wiki/JavaScriptTemplateSyntax</a>).</p> <hr> <p>I'd love to see a subset of JSP or ASP or PHP ported to the browser, but I haven't found that.</p> <p>What are people using these days in JavaScript for their templating?</p> <h2>Addendum 1 (2008)</h2> <p>After a few months there have been plenty of workable template languages posted here, but most of them aren't usable in any other language. Most of these templates couldn't be used outside a JavaScript engine.</p> <p>The exception is Microsoft's -- you can process the same ASP either in the browser or in any other ASP engine. That has its own set of portability problems, since you're bound to Microsoft systems. I marked that as the answer, but am still interested in more portable solutions.</p> <h2>Addendum 2 (2020)</h2> <p>Dusting off this old question, it's ten years later, and Mustache is widely supported in dozens of languages. It is now the current answer, in case anyone is still reading this.</p>
[ { "answer_id": 128980, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://ejohn.org/\" rel=\"noreferrer\">John Resig</a> has a mini javascript templating engine at <a href=\"http://ejohn.org/blog/javascript-micro-templating/\" rel=\"noreferrer\">http://ejohn.org/blog/javascript-micro-templating/</a></p>\n" }, { "answer_id": 128986, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>Tenjin <a href=\"http://www.kuwata-lab.com/tenjin/\" rel=\"nofollow noreferrer\">http://www.kuwata-lab.com/tenjin/</a> Might be what you're looking for. Haven't used it, but looks good. </p>\n" }, { "answer_id": 129062, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 1, "selected": false, "text": "<p>I wrote <a href=\"http://google-caja.googlecode.com/svn/changes/mikesamuel/string-interpolation-29-Jan-2008/trunk/src/js/com/google/caja/interp/index.html\" rel=\"nofollow noreferrer\">http://google-caja.googlecode.com/svn/changes/mikesamuel/string-interpolation-29-Jan-2008/trunk/src/js/com/google/caja/interp/index.html</a> which describes a templating system that bolts string interpolation onto javascript in a way that prevents XSS attacks by choosing the correct escaping scheme based on the preceding context.</p>\n" }, { "answer_id": 131215, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 1, "selected": false, "text": "<p>There is Client-Side Template functionality coming to the coming ASP.NET AJAX 4.0.</p>\n\n<p><a href=\"http://encosia.com/2008/07/23/sneak-peak-aspnet-ajax-4-client-side-templating/\" rel=\"nofollow noreferrer\">http://encosia.com/2008/07/23/sneak-peak-aspnet-ajax-4-client-side-templating/</a></p>\n\n<p>Also, you can use the Microsoft AJAX Library (which is the JavaScript part of ASP.NET AJAX) by itself, without using ASP.NET.</p>\n\n<p><a href=\"http://www.asp.net/ajax/downloads/\" rel=\"nofollow noreferrer\">http://www.asp.net/ajax/downloads/</a></p>\n" }, { "answer_id": 135952, "author": "big lep", "author_id": 16318, "author_profile": "https://Stackoverflow.com/users/16318", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://extjs.com\" rel=\"nofollow noreferrer\">ExtJS</a> has an exceptional templating class called Ext.XTemplate: <a href=\"http://extjs.com/deploy/dev/docs/?class=Ext.XTemplate\" rel=\"nofollow noreferrer\">http://extjs.com/deploy/dev/docs/?class=Ext.XTemplate</a> </p>\n" }, { "answer_id": 167442, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 1, "selected": false, "text": "<p>I've enjoyed <a href=\"http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/\" rel=\"nofollow noreferrer\">using jTemplates</a>: </p>\n\n<p><a href=\"http://jtemplates.tpython.com/\" rel=\"nofollow noreferrer\">http://jtemplates.tpython.com/</a></p>\n" }, { "answer_id": 220569, "author": "ckarbass", "author_id": 67719, "author_profile": "https://Stackoverflow.com/users/67719", "pm_score": 3, "selected": false, "text": "<p>I came across this today, I haven't tried it though...</p>\n\n<p><a href=\"http://beebole.com/pure/\" rel=\"noreferrer\">http://beebole.com/pure/</a></p>\n" }, { "answer_id": 598639, "author": "Tobias Cudnik", "author_id": 48002, "author_profile": "https://Stackoverflow.com/users/48002", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://code.google.com/p/querytemplates/\" rel=\"nofollow noreferrer\">QueryTemplates</a>\nDemo: <a href=\"http://sandbox.meta20.net/querytemplates-js/demo.html\" rel=\"nofollow noreferrer\">http://sandbox.meta20.net/querytemplates-js/demo.html</a></p>\n" }, { "answer_id": 2079687, "author": "Shiva", "author_id": 51570, "author_profile": "https://Stackoverflow.com/users/51570", "pm_score": 0, "selected": false, "text": "<p>If you are using <a href=\"http://projects.nikhilk.net/ScriptSharp\" rel=\"nofollow noreferrer\">Script#</a> you may want to consider <a href=\"http://xtreemgeek.net/projects/sharptemplate/\" rel=\"nofollow noreferrer\">SharpTemplate</a>, a strongly typed, super efficient HTML templating engine.</p>\n" }, { "answer_id": 2687348, "author": "Mike Hordecki", "author_id": 19082, "author_profile": "https://Stackoverflow.com/users/19082", "pm_score": 4, "selected": true, "text": "<p>You might want to check out <a href=\"https://mustache.github.io/\" rel=\"nofollow noreferrer\">Mustache</a> - it's really portable and simple template language with javascript support among other languages.</p>\n" }, { "answer_id": 3170446, "author": "nas", "author_id": 375867, "author_profile": "https://Stackoverflow.com/users/375867", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://code.google.com/closure/templates/\" rel=\"noreferrer\">Closure templates</a> are a fairly robust templating system from Google, and they work for both Javascript and Java. I've had good experiences using them.</p>\n" }, { "answer_id": 3185367, "author": "balupton", "author_id": 130638, "author_profile": "https://Stackoverflow.com/users/130638", "pm_score": 1, "selected": false, "text": "<p>Here is one implemented in jQuery for the Smarty templating language. <a href=\"http://www.balupton.com/sandbox/jquery-smarty/demo/\" rel=\"nofollow noreferrer\">http://www.balupton.com/sandbox/jquery-smarty/demo/</a></p>\n\n<p>One impressive feature is the support for dynamic updates. So if you update a template variable, it will update anywhere in the template where that variable is used. Pretty nifty.</p>\n\n<p>You can also hook into variable changes using a onchange event. So that is useful for say performing effects or AJAX when say the variable \"page\" changes ;-)</p>\n" }, { "answer_id": 4801606, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 2, "selected": false, "text": "<p>I use <a href=\"http://en.wikipedia.org/wiki/Google_Closure_Tools\" rel=\"nofollow\">Google Closure</a> templates. <a href=\"http://code.google.com/closure/templates/docs/helloworld_js.html\" rel=\"nofollow\">http://code.google.com/closure/templates/docs/helloworld_js.html</a></p>\n\n<p>Simple templating, <a href=\"http://en.wikipedia.org/wiki/Bi-directional_text#Unicode_support\" rel=\"nofollow\">BiDi</a> support, auto-escaping, optimized for speed. Also, the template parsing happens as a build step, so it doesn't slow down the client. Another benefit is that you can use the same templates from Java, in case you need to generate your HTML on the server for users with JavaScript disabled.</p>\n" }, { "answer_id": 7171526, "author": "KajMagnus", "author_id": 694469, "author_profile": "https://Stackoverflow.com/users/694469", "pm_score": 0, "selected": false, "text": "<p>If you use <a href=\"http://www.mozilla.org/rhino/\" rel=\"nofollow\">Rhino</a> (a Java implementation of JavaScript) you can run the JavaScript template language of your choice on the server too.</p>\n\n<p>You also know for sure that the server and browser template results are identical. (If the template is implemented in 2 languages, there might be some subtle differences between the implementations.)</p>\n\n<p>... But now 5 years later (that is, year 2016), with Java 8, you'd be using Nashorn instead, not Rhino. Here is an intro to Nashorn, and if you scroll down a bit, you'll find an example of Nashorn + the Mustahce template language:\n<a href=\"http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html\" rel=\"nofollow\">http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html</a></p>\n\n<p>(Personally I use React.js server side, via Nashorn (but React isn't a templating language). )</p>\n" }, { "answer_id": 11573000, "author": "Kernel James", "author_id": 1203580, "author_profile": "https://Stackoverflow.com/users/1203580", "pm_score": 0, "selected": false, "text": "<p>Distal templates <a href=\"http://code.google.com/p/distal\" rel=\"nofollow\">http://code.google.com/p/distal</a>\nis a little like your XSLT demo but simpler:</p>\n\n<pre><code>&lt;p&gt;Name: &lt;span data-qtext=\"data.name\"&gt;&lt;/span&gt;&lt;/p&gt;\n&lt;p&gt;Email: &lt;span data-qtext=\"data.email\"&gt;&lt;/span&gt;&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 47505044, "author": "Tod Harter", "author_id": 7186177, "author_profile": "https://Stackoverflow.com/users/7186177", "pm_score": 0, "selected": false, "text": "<p>One possibly interesting choice is <a href=\"https://github.com/rexxars/react-markdown\" rel=\"nofollow noreferrer\">https://github.com/rexxars/react-markdown</a> which is a rather interesting way to include markdown in your React-based web UI. I've tested it, works reasonably well, although the docs lead me to understand that HTML rendering has acquired some issues in the 3.x branch. Still, seems like a viable option for certain uses.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8735/" ]
Templates are a pretty healthy business in established programming languages, but are there any good ones that can be processed in JavaScript? By "template" I mean a document that accepts a data object as input, inserts the data into some kind of serialized markup language, and outputs the markup. Well-known examples are [JSP](http://en.wikipedia.org/wiki/JavaServer_Pages), the original PHP, [XSLT](http://en.wikipedia.org/wiki/XSLT). By "good" I mean that it's declarative and easy for an HTML author to write, that it's robust, and that it's supported in other languages too. Something better than the options I know about. Some examples of "not good": --- String math: ``` element.innerHTML = "<p>Name: " + data.name + "</p><p>Email: " + data.email + "</p>"; ``` clearly too unwieldy, HTML structure not apparent. --- XSLT: ``` <p><xsl:text>Name: </xsl:text><xsl:value-of select="//data/name"></p> <p><xsl:text>Email: </xsl:text><xsl:value-of select="//data/email"></p> ``` // Structurally this works well, but let's face it, XSLT confuses HTML developers. --- Trimpath: ``` <p>Name: ${data.name}</p><p>Email: ${data.email}</p> ``` // This is nice, but the processor is only supported in JavaScript, and the language is sort of primitive (<http://code.google.com/p/trimpath/wiki/JavaScriptTemplateSyntax>). --- I'd love to see a subset of JSP or ASP or PHP ported to the browser, but I haven't found that. What are people using these days in JavaScript for their templating? Addendum 1 (2008) ----------------- After a few months there have been plenty of workable template languages posted here, but most of them aren't usable in any other language. Most of these templates couldn't be used outside a JavaScript engine. The exception is Microsoft's -- you can process the same ASP either in the browser or in any other ASP engine. That has its own set of portability problems, since you're bound to Microsoft systems. I marked that as the answer, but am still interested in more portable solutions. Addendum 2 (2020) ----------------- Dusting off this old question, it's ten years later, and Mustache is widely supported in dozens of languages. It is now the current answer, in case anyone is still reading this.
You might want to check out [Mustache](https://mustache.github.io/) - it's really portable and simple template language with javascript support among other languages.
128,954
<p>I have code to create another "row" (div with inputs) on a button click. I am creating new input elements and everything works fine, however, I can't find a way to access these new elements.</p> <p>Example: I have input element (name_1 below). Then I create another input element (name_2 below), by using the javascript's <code>createElement</code> function.</p> <pre><code>&lt;input type='text' id='name_1' name="name_1" /&gt; &lt;input type='text' id='name_2' name="name_2" /&gt; </code></pre> <p>Again, I create the element fine, but I want to be able to access the value of name_2 after it has been created and modified by the user. Example: <code>document.getElementById('name_2');</code></p> <p>This doesn't work. How do I make the DOM recognize the new element? Is it possible?</p> <p>My code sample (utilizing jQuery):</p> <pre><code>function addName(){ var parentDiv = document.createElement("div"); $(parentDiv).attr( "id", "lp_" + id ); var col1 = document.createElement("div"); var input1 = $( 'input[name="lp_name_1"]').clone(true); $(input1).attr( "name", "lp_name_" + id ); $(col1).attr( "class", "span-4" ); $(col1).append( input1 ); $(parentDiv).append( col1 ); $('#main_div').append(parentDiv); } </code></pre> <p>I have used both jQuery and JavaScript selectors. Example: <code>$('#lp_2').html()</code> returns null. So does <code>document.getElementById('lp_2');</code></p>
[ { "answer_id": 128967, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 3, "selected": true, "text": "<p>You have to create the element AND add it to the DOM using functions such as appendChild. See <a href=\"http://www.w3schools.com/htmldom/dom_methods.asp\" rel=\"nofollow noreferrer\">here</a> for details.</p>\n\n<p>My guess is that you called createElement() but never added it to your DOM hierarchy.</p>\n" }, { "answer_id": 128972, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "<p>If it's properly added to the dom tree you will be able to query it with document.getElementById. However browser bugs may cause troubles, so use a JavaScript toolkit like jQuery that works around browser bugs.</p>\n" }, { "answer_id": 129186, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>var input1 = $( 'input[name=\"lp_name_1\"]').clone(true);</p>\n</blockquote>\n\n<p>The code you have posted does not indicate any element with that name attribute. Immediately before this part, you create an element with an <strong>id</strong> attribute that is similar, but you would use <code>$(\"#lp_1\")</code> to select that, and even that will fail to work until you insert it into the document, which you do not do until afterwards.</p>\n" }, { "answer_id": 129199, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 0, "selected": false, "text": "<pre><code>var input1 = $( 'input[name=\"lp_name_1\"]').clone(true);\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>var input1 = $( 'input[@name=\"lp_name_1\"]').clone(true);\n</code></pre>\n\n<p>Try that first, check that input1 actually returns something (maybe a debug statement of a sort), to make sure that's not the problem.</p>\n\n<p>Edit: just been told that this is only true for older versions of JQuery, so please disregard my advice.</p>\n" }, { "answer_id": 129392, "author": "brostbeef", "author_id": 16437, "author_profile": "https://Stackoverflow.com/users/16437", "pm_score": 0, "selected": false, "text": "<p>Thank you so much for your answers. After walking away and coming back to my code, I noticed that I had made a mistake. I had two functions which added the line in different ways. I was \"100% sure\" that I was calling the right one (the code example I posted), but alas, I was not.</p>\n\n<p>For those also experiencing problems, I would say all the answers I received are a great start and I had used them for debugging, they will ensure the correctness of your code.</p>\n\n<p>My code example was 100% correct for what I was needing, I just needed to call it. (Duh!)</p>\n\n<p>Thanks again for all your help,</p>\n\n<p>-Jamie</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16437/" ]
I have code to create another "row" (div with inputs) on a button click. I am creating new input elements and everything works fine, however, I can't find a way to access these new elements. Example: I have input element (name\_1 below). Then I create another input element (name\_2 below), by using the javascript's `createElement` function. ``` <input type='text' id='name_1' name="name_1" /> <input type='text' id='name_2' name="name_2" /> ``` Again, I create the element fine, but I want to be able to access the value of name\_2 after it has been created and modified by the user. Example: `document.getElementById('name_2');` This doesn't work. How do I make the DOM recognize the new element? Is it possible? My code sample (utilizing jQuery): ``` function addName(){ var parentDiv = document.createElement("div"); $(parentDiv).attr( "id", "lp_" + id ); var col1 = document.createElement("div"); var input1 = $( 'input[name="lp_name_1"]').clone(true); $(input1).attr( "name", "lp_name_" + id ); $(col1).attr( "class", "span-4" ); $(col1).append( input1 ); $(parentDiv).append( col1 ); $('#main_div').append(parentDiv); } ``` I have used both jQuery and JavaScript selectors. Example: `$('#lp_2').html()` returns null. So does `document.getElementById('lp_2');`
You have to create the element AND add it to the DOM using functions such as appendChild. See [here](http://www.w3schools.com/htmldom/dom_methods.asp) for details. My guess is that you called createElement() but never added it to your DOM hierarchy.
128,965
<p>When I started writing database queries I didn't know the JOIN keyword yet and naturally I just extended what I already knew and wrote queries like this:</p> <pre><code>SELECT a.someRow, b.someRow FROM tableA AS a, tableB AS b WHERE a.ID=b.ID AND b.ID= $someVar </code></pre> <p>Now that I know that this is the same as an INNER JOIN I find all these queries in my code and ask myself if I should rewrite them. Is there something smelly about them or are they just fine?</p> <hr /> <p><strong>My answer summary</strong>: There is nothing wrong with this query BUT using the keywords will most probably make the code more readable/maintainable.</p> <p><strong>My conclusion</strong>: I will not change my old queries but I will correct my writing style and use the keywords in the future.</p>
[ { "answer_id": 128995, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 2, "selected": false, "text": "<p>Nothing is wrong with the syntax in your example. The 'INNER JOIN' syntax is generally termed 'ANSI' syntax, and came after the style illustrated in your example. It exists to clarify the type/direction/constituents of the join, but is not generally functionally different than what you have.</p>\n\n<p>Support for 'ANSI' joins is per-database platform, but it's more or less universal these days.</p>\n\n<p>As a side note, one addition with the 'ANSI' syntax was the 'FULL OUTER JOIN' or 'FULL JOIN'.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 129000, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>I avoid implicit joins; when the query is really large, they make the code hard to decipher</p>\n\n<p>With explicit joins, and good formatting, the code is more readable and understandable without need for comments.</p>\n" }, { "answer_id": 129005, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 3, "selected": false, "text": "<p>It's more of a syntax choice. I prefer grouping my join conditions with my joins, hence I use the INNER JOIN syntax</p>\n\n<pre><code>SELECT a.someRow, b.someRow\nFROM tableA AS a\nINNER JOIN tableB AS b\n ON a.ID = b.ID\nWHERE b.ID = ?\n</code></pre>\n\n<p>(? being a placeholder)</p>\n" }, { "answer_id": 129006, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 3, "selected": false, "text": "<p>The more verbose <code>INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN</code> are from the ANSI SQL/92 syntax for joining. For me, this verbosity makes the join more clear to the developer/DBA of what the intent is with the join.</p>\n" }, { "answer_id": 129076, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 3, "selected": false, "text": "<p>In SQL Server there are always query plans to check, a text output can be made as follows:</p>\n\n<pre><code>SET SHOWPLAN_ALL ON\nGO\n\nDECLARE @TABLE_A TABLE\n(\n ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n Data VARCHAR(10) NOT NULL\n)\nINSERT INTO @TABLE_A\nSELECT 'ABC' UNION \nSELECT 'DEF' UNION\nSELECT 'GHI' UNION\nSELECT 'JKL' \n\nDECLARE @TABLE_B TABLE\n(\n ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n Data VARCHAR(10) NOT NULL\n)\nINSERT INTO @TABLE_B\nSELECT 'ABC' UNION \nSELECT 'DEF' UNION\nSELECT 'GHI' UNION\nSELECT 'JKL' \n\nSELECT A.Data, B.Data\nFROM\n @TABLE_A AS A, @TABLE_B AS B\nWHERE\n A.ID = B.ID\n\nSELECT A.Data, B.Data\nFROM\n @TABLE_A AS A\n INNER JOIN @TABLE_B AS B ON A.ID = B.ID\n</code></pre>\n\n<p>Now I'll omit the plan for the table variable creates, the plan for both queries is identical though:</p>\n\n<pre><code> SELECT A.Data, B.Data FROM @TABLE_A AS A, @TABLE_B AS B WHERE A.ID = B.ID\n |--Nested Loops(Inner Join, OUTER REFERENCES:([A].[ID]))\n |--Clustered Index Scan(OBJECT:(@TABLE_A AS [A]))\n |--Clustered Index Seek(OBJECT:(@TABLE_B AS [B]), SEEK:([B].[ID]=@TABLE_A.[ID] as [A].[ID]) ORDERED FORWARD)\n SELECT A.Data, B.Data FROM @TABLE_A AS A INNER JOIN @TABLE_B AS B ON A.ID = B.ID\n |--Nested Loops(Inner Join, OUTER REFERENCES:([A].[ID]))\n |--Clustered Index Scan(OBJECT:(@TABLE_A AS [A]))\n |--Clustered Index Seek(OBJECT:(@TABLE_B AS [B]), SEEK:([B].[ID]=@TABLE_A.[ID] as [A].[ID]) ORDERED FORWARD)\n</code></pre>\n\n<p>So, short answer - No need to rewrite, unless you spend a long time trying to read them each time you maintain them?</p>\n" }, { "answer_id": 129134, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 2, "selected": false, "text": "<p>It also depends on whether you are just doing inner joins this way or outer joins as well. For instance, the MS SQL Server syntax for outer joins in the WHERE clause (=* and *=) can give different results than the OUTER JOIN syntax and is no longer supported (<a href=\"http://msdn.microsoft.com/en-us/library/ms178653(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms178653(SQL.90).aspx</a>) in SQL Server 2005.</p>\n" }, { "answer_id": 129410, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 6, "selected": true, "text": "<p>Filtering joins solely using <code>WHERE</code> can be extremely inefficient in some common scenarios. For example:</p>\n\n<pre><code>SELECT * FROM people p, companies c \n WHERE p.companyID = c.id AND p.firstName = 'Daniel'\n</code></pre>\n\n<p>Most databases will execute this query quite literally, first taking the <a href=\"http://en.wikipedia.org/wiki/Cartesian_product\" rel=\"noreferrer\">Cartesian product</a> of the <code>people</code> and <code>companies</code> tables and <em>then</em> filtering by those which have matching <code>companyID</code> and <code>id</code> fields. While the fully-unconstrained product does not exist anywhere but in memory and then only for a moment, its calculation does take some time.</p>\n\n<p>A better approach is to group the constraints with the <code>JOIN</code>s where relevant. This is not only subjectively easier to read but also far more efficient. Thusly:</p>\n\n<pre><code>SELECT * FROM people p JOIN companies c ON p.companyID = c.id\n WHERE p.firstName = 'Daniel'\n</code></pre>\n\n<p>It's a little longer, but the database is able to look at the <code>ON</code> clause and use it to compute the fully-constrained <code>JOIN</code> directly, rather than starting with <em>everything</em> and then limiting down. This is faster to compute (especially with large data sets and/or many-table joins) and requires less memory.</p>\n\n<p>I change every query I see which uses the \"comma <code>JOIN</code>\" syntax. In my opinion, the only purpose for its existence is conciseness. Considering the performance impact, I don't think this is a compelling reason.</p>\n" }, { "answer_id": 129424, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": false, "text": "<p>In general: </p>\n\n<p>Use the JOIN keyword to link (ie. \"join\") primary keys and foreign keys.</p>\n\n<p>Use the WHERE clause to limit your result set to only the records you are interested in. </p>\n" }, { "answer_id": 129443, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>The one problem that can arise is when you try to mix the old \"comma-style\" join with SQL-92 joins in the same query, for example if you need one inner join and another outer join.</p>\n\n<pre><code>SELECT *\nFROM table1 AS a, table2 AS b\n LEFT OUTER JOIN table3 AS c ON a.column1 = c.column1\nWHERE a.column2 = b.column2;\n</code></pre>\n\n<p>The problem is that recent SQL standards say that the JOIN is evaluated before the comma-join. So the reference to \"a\" in the ON clause gives an error, because the correlation name hasn't been defined yet as that ON clause is being evaluated. This is a very confusing error to get.</p>\n\n<p>The solution is to not mix the two styles of joins. You can continue to use comma-style in your old code, but if you write a new query, convert all the joins to SQL-92 style.</p>\n\n<pre><code>SELECT *\nFROM table1 AS a\n INNER JOIN table2 AS b ON a.column2 = b.column2\n LEFT OUTER JOIN table3 AS c ON a.column1 = c.column1;\n</code></pre>\n" }, { "answer_id": 558908, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>Another thing to consider in the old join syntax is that is is very easy to get a cartesion join by accident since there is no on clause. If the Distinct keyword is in the query and it uses the old style joins, convert it to an ANSI standard join and see if you still need the distinct. If you are fixing accidental cartesion joins this way, you can improve performance tremendously by rewriting to specify the join and the join fields.</p>\n" }, { "answer_id": 69911033, "author": "SQLpro", "author_id": 12659872, "author_profile": "https://Stackoverflow.com/users/12659872", "pm_score": 1, "selected": false, "text": "<p><strong>And what about performances ???</strong></p>\n<p>As a matter of fact, performances is a very important problem in RDBMS.</p>\n<p>So the question is <em>what is the most performant... Using JOIN or having joined table in the WHERE clause ?</em></p>\n<p>Because optimizer (or planer as they said in PG...) ordinary does a good job, the two execution plans are the same, so the performances while excuting the query will be the same...</p>\n<p><strong>But devil are hidden in some details....</strong></p>\n<p>All optimizers have a limited time or a limited amount of work to find the best plan... And when the limit is reached, the result is the best plan among all computed plans, and not the better of all possible plans !</p>\n<p>Now the question is <em>do I loose time when I use WHERE clause instead of JOINs for joining tables ?</em></p>\n<p>And the answer is <strong>YES</strong> !</p>\n<p>YES, because the relational engine use relational algebrae that knows only JOIN operator, not pseudo joins made in the WHERE clause. So the first thing that the optimizer do (in fact the parser or the algrebriser) is to rewrite the query... and this loose some chances to have the best of all plans !</p>\n<p>I have seen this problem twice, in my long RDBMS career (40 years...)</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995/" ]
When I started writing database queries I didn't know the JOIN keyword yet and naturally I just extended what I already knew and wrote queries like this: ``` SELECT a.someRow, b.someRow FROM tableA AS a, tableB AS b WHERE a.ID=b.ID AND b.ID= $someVar ``` Now that I know that this is the same as an INNER JOIN I find all these queries in my code and ask myself if I should rewrite them. Is there something smelly about them or are they just fine? --- **My answer summary**: There is nothing wrong with this query BUT using the keywords will most probably make the code more readable/maintainable. **My conclusion**: I will not change my old queries but I will correct my writing style and use the keywords in the future.
Filtering joins solely using `WHERE` can be extremely inefficient in some common scenarios. For example: ``` SELECT * FROM people p, companies c WHERE p.companyID = c.id AND p.firstName = 'Daniel' ``` Most databases will execute this query quite literally, first taking the [Cartesian product](http://en.wikipedia.org/wiki/Cartesian_product) of the `people` and `companies` tables and *then* filtering by those which have matching `companyID` and `id` fields. While the fully-unconstrained product does not exist anywhere but in memory and then only for a moment, its calculation does take some time. A better approach is to group the constraints with the `JOIN`s where relevant. This is not only subjectively easier to read but also far more efficient. Thusly: ``` SELECT * FROM people p JOIN companies c ON p.companyID = c.id WHERE p.firstName = 'Daniel' ``` It's a little longer, but the database is able to look at the `ON` clause and use it to compute the fully-constrained `JOIN` directly, rather than starting with *everything* and then limiting down. This is faster to compute (especially with large data sets and/or many-table joins) and requires less memory. I change every query I see which uses the "comma `JOIN`" syntax. In my opinion, the only purpose for its existence is conciseness. Considering the performance impact, I don't think this is a compelling reason.
128,981
<p>I'm writing a program and am having trouble using the scanf and fopen working together.</p> <p>From what I can tell my erroneous lines seems to be:</p> <pre><code>FiLE * DataFile DataFile = fopen("StcWx.txt","r"); scanf(DataFile, "%i %i %i %.2f %i %i", &amp;Year, &amp;Month, &amp;Day, &amp;Precip, &amp;High, &amp;Low); </code></pre> <p>The file it opens from has a list of weather data that looks like this:</p> <pre><code>1944 4 12 0 58 24 1944 4 13 0.4 58 29 1944 4 14 0.54 42 29 1944 4 15 0 43 27 </code></pre> <p>(Those spaces are tabs)</p> <p>The error that is displayed is "[Warning] passing arg 1 of `scanf' from incompatible pointer type"</p> <p>Can anyone help me?</p>
[ { "answer_id": 128991, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 4, "selected": false, "text": "<p>I think you want <a href=\"http://en.wikipedia.org/wiki/Scanf#fscanf\" rel=\"nofollow noreferrer\"><strong>fscanf</strong></a> not <a href=\"http://en.wikipedia.org/wiki/Scanf\" rel=\"nofollow noreferrer\"><strong>scanf</strong></a>.</p>\n" }, { "answer_id": 128993, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 1, "selected": false, "text": "<p>You're using the wrong function. You should be using <code>fscanf</code>.</p>\n" }, { "answer_id": 138089, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>Your code looks like it should be using fscanf, not scanf.</p>\n\n<p>I would strongly suggest using fgets and sscanf rather than directly calling fscanf.</p>\n\n<p>The fscanf can fail in ways that leave in doubt where your file pointer is. Using fgets to get whole lines and sscanf to scan the strings means you always know the state of the file pointer and it's very easy to back up to the start of the line (the string is still in memory).</p>\n" }, { "answer_id": 54590680, "author": "Vừng Nhỏ ", "author_id": 5137968, "author_profile": "https://Stackoverflow.com/users/5137968", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<p><code>freopen (\"StcWx.txt\",\"r\",stdin);</code></p>\n\n<p><code>scanf(\"%i %i %i %.2f %i %i\", &amp;Year, &amp;Month, &amp;Day, &amp;Precip, &amp;High, &amp;Low);</code></p>\n\n<p><a href=\"http://www.cplusplus.com/reference/cstdio/freopen/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/cstdio/freopen/</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a program and am having trouble using the scanf and fopen working together. From what I can tell my erroneous lines seems to be: ``` FiLE * DataFile DataFile = fopen("StcWx.txt","r"); scanf(DataFile, "%i %i %i %.2f %i %i", &Year, &Month, &Day, &Precip, &High, &Low); ``` The file it opens from has a list of weather data that looks like this: ``` 1944 4 12 0 58 24 1944 4 13 0.4 58 29 1944 4 14 0.54 42 29 1944 4 15 0 43 27 ``` (Those spaces are tabs) The error that is displayed is "[Warning] passing arg 1 of `scanf' from incompatible pointer type" Can anyone help me?
I think you want [**fscanf**](http://en.wikipedia.org/wiki/Scanf#fscanf) not [**scanf**](http://en.wikipedia.org/wiki/Scanf).
128,990
<p>I have a base URL :</p> <pre><code>http://my.server.com/folder/directory/sample </code></pre> <p>And a relative one :</p> <pre><code>../../other/path </code></pre> <p>How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the <code>Uri</code> class or something similar.</p> <p>It's for a standard a C# app, not an ASP.NET one.</p>
[ { "answer_id": 129003, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": true, "text": "<pre><code>var baseUri = new Uri(\"http://my.server.com/folder/directory/sample\");\nvar absoluteUri = new Uri(baseUri,\"../../other/path\");\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>Uri uri;\nif ( Uri.TryCreate(\"http://base/\",\"../relative\", out uri) ) doSomething(uri);\n</code></pre>\n" }, { "answer_id": 38462625, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 0, "selected": false, "text": "<p>Some might be looking for Javascript solution that would allow conversion of urls 'on the fly' when debugging </p>\n\n<pre><code>var absoluteUrl = function(href) {\n var link = document.createElement(\"a\");\n link.href = href;\n return link.href;\n} \n</code></pre>\n\n<p>use like: </p>\n\n<p><code>absoluteUrl(\"http://google.com\")</code></p>\n\n<blockquote>\n <p><code>http://google.com/</code></p>\n</blockquote>\n\n<p>or</p>\n\n<p><code>absoluteUrl(\"../../absolute\")</code></p>\n\n<blockquote>\n <p><code>http://stackoverflow.com/absolute</code></p>\n</blockquote>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/128990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
I have a base URL : ``` http://my.server.com/folder/directory/sample ``` And a relative one : ``` ../../other/path ``` How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the `Uri` class or something similar. It's for a standard a C# app, not an ASP.NET one.
``` var baseUri = new Uri("http://my.server.com/folder/directory/sample"); var absoluteUri = new Uri(baseUri,"../../other/path"); ``` OR ``` Uri uri; if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri); ```
129,013
<p>This is only happening on the live server. On multiply development servers the image is being created as expected.</p> <p>LIVE: Red Hat</p> <pre><code>$ php --version PHP 5.2.6 (cli) (built: May 16 2008 21:56:34) Copyright (c) 1997-2008 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies </code></pre> <p>GD Support => enabled GD Version => bundled (2.0.34 compatible)</p> <p>DEV: Ubuntu 8</p> <pre><code>$ php --version PHP 5.2.4-2ubuntu5.3 with Suhosin-Patch 0.9.6.2 (cli) (built: Jul 23 2008 06:44:49) Copyright (c) 1997-2007 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies </code></pre> <p>GD Support => enabled GD Version => 2.0 or higher</p> <pre><code>&lt;?php $image = imagecreatetruecolor($width, $height); // Colors in RGB $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0); imagefilledrectangle($image, 0, 0, $width, $height, $white); imagettftext($image, $fontSize, 0, 0, 50, $black, $font, $text); imagegif($image, $file_path); ?&gt; </code></pre> <p>In a perfect world I would like the live server and the dev server to be running the same distro, but the live server must be Red Hat. </p> <p>My question is does anyone know the specific differences that would cause the right most part of an image to be cut off using the bundled version of GD?</p> <p>EDIT: I am not running out of memory. There are no errors being generated in the logs files. As far as php is concerned the image is being generated correctly. That is why I believe it to be a GD specific problem with the bundled version.</p>
[ { "answer_id": 129030, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>Maybe you are running out of memory or something similar? Did you double check all logfiles, etc.? </p>\n" }, { "answer_id": 129041, "author": "Devin Ceartas", "author_id": 14897, "author_profile": "https://Stackoverflow.com/users/14897", "pm_score": 0, "selected": false, "text": "<p>Is it 100% consistent and always at the same place? If not, it might be a resource issue -- time to execute the script or memory limitation. Try tweaking the php.ini settings, rebooting web server, testing. </p>\n" }, { "answer_id": 159611, "author": "William Macdonald", "author_id": 2725, "author_profile": "https://Stackoverflow.com/users/2725", "pm_score": 0, "selected": false, "text": "<p>Does it depend on the image ?</p>\n\n<p>Recently I discovered a strange bug/feature in PHP &amp; GD.</p>\n\n<p>When trying to resize and edit JPEGs that had an all white background (c. 3MB), it would fail. It DID work with other images that were larger (c. 4MB), and more complicated backgrounds.</p>\n\n<p>I worked out that when GD opened the images to edit, the white back ground images grew by a greater ratio than the more complex images. This ratio for some images caused PHP/GD to fail and cut of images halfway.</p>\n\n<p>William</p>\n" }, { "answer_id": 850170, "author": "NineBerry", "author_id": 101087, "author_profile": "https://Stackoverflow.com/users/101087", "pm_score": 0, "selected": false, "text": "<p>Have you had the value of $width output to see whether it is correct?</p>\n" }, { "answer_id": 851769, "author": "Darkerstar", "author_id": 73565, "author_profile": "https://Stackoverflow.com/users/73565", "pm_score": 0, "selected": false, "text": "<p>It might not be the image is being cut off. It might be the text being cut off.</p>\n\n<pre><code>imagettftext($image, $fontSize, 0, 0, 50, $black, $font, $text);\n</code></pre>\n\n<p>TTF font has overhead and paddings. Try a larger canvas see if the you get the same result.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
This is only happening on the live server. On multiply development servers the image is being created as expected. LIVE: Red Hat ``` $ php --version PHP 5.2.6 (cli) (built: May 16 2008 21:56:34) Copyright (c) 1997-2008 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies ``` GD Support => enabled GD Version => bundled (2.0.34 compatible) DEV: Ubuntu 8 ``` $ php --version PHP 5.2.4-2ubuntu5.3 with Suhosin-Patch 0.9.6.2 (cli) (built: Jul 23 2008 06:44:49) Copyright (c) 1997-2007 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies ``` GD Support => enabled GD Version => 2.0 or higher ``` <?php $image = imagecreatetruecolor($width, $height); // Colors in RGB $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0); imagefilledrectangle($image, 0, 0, $width, $height, $white); imagettftext($image, $fontSize, 0, 0, 50, $black, $font, $text); imagegif($image, $file_path); ?> ``` In a perfect world I would like the live server and the dev server to be running the same distro, but the live server must be Red Hat. My question is does anyone know the specific differences that would cause the right most part of an image to be cut off using the bundled version of GD? EDIT: I am not running out of memory. There are no errors being generated in the logs files. As far as php is concerned the image is being generated correctly. That is why I believe it to be a GD specific problem with the bundled version.
Maybe you are running out of memory or something similar? Did you double check all logfiles, etc.?
129,019
<p>I would like something that I can use as follows</p> <pre><code>var msg = new NonStaticMessageBox(); if(msg.Show("MyMessage", "MyCaption", MessageBoxButtons.OkCancel) == DialogResult.Ok) {....} </code></pre> <p>But specifically non-static (I need to pass a reference to it around) does anyone know if/where such an object exists?</p>
[ { "answer_id": 129025, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 3, "selected": true, "text": "<p>Such an object does not exist in the .net framework. You'll need to roll your own.</p>\n" }, { "answer_id": 132642, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Looking at the comments. Encapsulation is your answer :)</p>\n" }, { "answer_id": 132654, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>why do you need to pass a reference of it? you could just use MessageBox.Show and that's all? if you really need it you could make your own MessageBox class, something like:</p>\n\n<pre><code>public class MessageBox\n{\n private Form _messageForm = null;\n\n public void Show(string title,...) {...}\n}\n</code></pre>\n\n<p>or you could inherit MessageBox class and implement your own instance members... however I don't see any sense in this...</p>\n" }, { "answer_id": 132701, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>Bear in mind that, at the end of the day, the S.W.F.MessageBox.Show() methods are all basically wrappers around the core Win32 MessageBox() API call. (Run mscorlib through Reflector; you'll see the \"real\" code in the private methods called ShowCore.)</p>\n\n<p>There is no provision (as far as I know) for caching the called MessageBox in Win32, therefore there is no way to do so in .NET.</p>\n\n<p>I do have my own custom-built MessageBox class which I use -- although I did so not to cache it (in my usage scenarios in WinForms, the same MB is rarely used twice), but rather to provide a more detailed error message and information -- a header, a description, an ability to copy the message to the clipboard (it's usually the tool which notifies the user of an unhandled exception) and then the buttons.</p>\n\n<p>Your mileage may vary.</p>\n" }, { "answer_id": 132816, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 0, "selected": false, "text": "<p>You might want to have a look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms166340(SQL.90).aspx\" rel=\"nofollow noreferrer\">ExceptionMessageBox</a> class that comes with SQL Server. It is in a self-contained assembly, but I'm not sure if you are allowed to redistribute it without SQL Server - you might need to check on this.</p>\n" }, { "answer_id": 594890, "author": "Tristan Warner-Smith", "author_id": 29553, "author_profile": "https://Stackoverflow.com/users/29553", "pm_score": 0, "selected": false, "text": "<p>You say </p>\n\n<blockquote>\n <p>\"This is obviously a simplification of\n my problem.\"</p>\n</blockquote>\n\n<p>However your question doesn't reveal a problem we can solve without more information about intent.</p>\n\n<p>Given that any form can be shown modally by calling ShowDialog and in the form returning DialogResult. I'm not seeing an issue here. You can pass whatever parameters you like into it, define the contents as you like, then call:</p>\n\n<pre><code>MyFactory.GetMyCustomDialogWithInterfacesOrSomesuch myDialog = new ...\nmyDialog.ShowDialog() == DialogResult.Ok;\n</code></pre>\n\n<p>Because you're dealing with form and not MessageBox, it's not static so it's not an issue.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I would like something that I can use as follows ``` var msg = new NonStaticMessageBox(); if(msg.Show("MyMessage", "MyCaption", MessageBoxButtons.OkCancel) == DialogResult.Ok) {....} ``` But specifically non-static (I need to pass a reference to it around) does anyone know if/where such an object exists?
Such an object does not exist in the .net framework. You'll need to roll your own.
129,036
<p>I am writing a component that, given a ZIP file, needs to:</p> <ol> <li>Unzip the file.</li> <li>Find a specific dll among the unzipped files.</li> <li>Load that dll through reflection and invoke a method on it.</li> </ol> <p>I'd like to unit test this component.</p> <p>I'm tempted to write code that deals directly with the file system:</p> <pre class="lang-cs prettyprint-override"><code>void DoIt() { Zip.Unzip(theZipFile, "C:\\foo\\Unzipped"); System.IO.File myDll = File.Open("C:\\foo\\Unzipped\\SuperSecret.bar"); myDll.InvokeSomeSpecialMethod(); } </code></pre> <p>But folks often say, "Don't write unit tests that rely on the file system, database, network, etc."</p> <p>If I were to write this in a unit-test friendly way, I suppose it would look like this:</p> <pre class="lang-cs prettyprint-override"><code>void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner) { string path = zipper.Unzip(theZipFile); IFakeFile file = fileSystem.Open(path); runner.Run(file); } </code></pre> <p>Yay! Now it's testable; I can feed in test doubles (mocks) to the DoIt method. But at what cost? I've now had to define 3 new interfaces just to make this testable. And what, exactly, am I testing? I'm testing that my DoIt function properly interacts with its dependencies. It doesn't test that the zip file was unzipped properly, etc.</p> <p>It doesn't feel like I'm testing functionality anymore. It feels like I'm just testing class interactions.</p> <p><strong>My question is this</strong>: what's the proper way to unit test something that is dependent on the file system?</p> <p><em>edit</em> I'm using .NET, but the concept could apply Java or native code too.</p>
[ { "answer_id": 129061, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 3, "selected": false, "text": "<p>One way would be to write the unzip method to take InputStreams. Then the unit test could construct such an InputStream from a byte array using ByteArrayInputStream. The contents of that byte array could be a constant in the unit test code.</p>\n" }, { "answer_id": 129067, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 2, "selected": false, "text": "<p>Assuming that \"file system interactions\" are well tested in the framework itself, create your method to work with streams, and test this. Opening a FileStream and passing it to the method can be left out of your tests, as FileStream.Open is well tested by the framework creators.</p>\n" }, { "answer_id": 129079, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": false, "text": "<p>I am reticent to pollute my code with types and concepts that exist only to facilitate unit testing. Sure, if it makes the design cleaner and better then great, but I think that is often not the case.</p>\n\n<p>My take on this is that your unit tests would do as much as they can which may not be 100% coverage. In fact, it may only be 10%. The point is, your unit tests should be fast and have no external dependencies. They might test cases like \"this method throws an ArgumentNullException when you pass in null for this parameter\".</p>\n\n<p>I would then add integration tests (also automated and probably using the same unit testing framework) that can have external dependencies and test end-to-end scenarios such as these.</p>\n\n<p>When measuring code coverage, I measure both unit and integration tests.</p>\n" }, { "answer_id": 129080, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 1, "selected": false, "text": "<p>You should not test class interaction and function calling. instead you should consider integration testing. Test the required result and not the file loading operation.</p>\n" }, { "answer_id": 129119, "author": "JC.", "author_id": 3615, "author_profile": "https://Stackoverflow.com/users/3615", "pm_score": 3, "selected": false, "text": "<p>There's nothing wrong with hitting the file system, just consider it an integration test rather than a unit test. I'd swap the hard coded path with a relative path and create a TestData subfolder to contain the zips for the unit tests.</p>\n\n<p>If your integration tests take too long to run then separate them out so they aren't running as often as your quick unit tests.</p>\n\n<p>I agree, sometimes I think interaction based testing can cause too much coupling and often ends up not providing enough value. You really want to test unzipping the file here not just verify you are calling the right methods.</p>\n" }, { "answer_id": 129142, "author": "tap", "author_id": 21830, "author_profile": "https://Stackoverflow.com/users/21830", "pm_score": 2, "selected": false, "text": "<p>This seems to be more of an integration test as you are depending on a specific detail (the file system) that could change, in theory.</p>\n\n<p>I would abstract the code that deals with the OS into it's own module (class, assembly, jar, whatever). In your case you want to load a specific DLL if found, so make an IDllLoader interface and DllLoader class. Have your app acquire the DLL from the DllLoader using the interface and test that .. you're not responsible for the unzip code afterall right?</p>\n" }, { "answer_id": 129204, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 7, "selected": true, "text": "<p>There's really nothing wrong with this, it's just a question of whether you call it a unit test or an integration test. You just have to make sure that if you do interact with the file system, there are no unintended side effects. Specifically, make sure that you clean up after youself -- delete any temporary files you created -- and that you don't accidentally overwrite an existing file that happened to have the same filename as a temporary file you were using. Always use relative paths and not absolute paths.</p>\n\n<p>It would also be a good idea to <code>chdir()</code> into a temporary directory before running your test, and <code>chdir()</code> back afterwards.</p>\n" }, { "answer_id": 371359, "author": "David Sykes", "author_id": 259, "author_profile": "https://Stackoverflow.com/users/259", "pm_score": 1, "selected": false, "text": "<p>As others have said, the first is fine as an integration test. The second tests only what the function is supposed to actually do, which is all a unit test should do.</p>\n\n<p>As shown, the second example looks a little pointless, but it does give you the opportunity to test how the function responds to errors in any of the steps. You don't have any error checking in the example, but in the real system you may have, and the dependency injection would let you test all the responses to any errors. Then the cost will have been worth it.</p>\n" }, { "answer_id": 371373, "author": "James Anderson", "author_id": 38207, "author_profile": "https://Stackoverflow.com/users/38207", "pm_score": 1, "selected": false, "text": "<p>For unit test I would suggest that you include the test file in your project(EAR file or equivalent) then use a relative path in the unit tests i.e. \"../testdata/testfile\".</p>\n\n<p>As long as your project is correctly exported/imported than your unit test should work.</p>\n" }, { "answer_id": 4075614, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 6, "selected": false, "text": "<blockquote>\n <p>Yay! Now it's testable; I can feed in test doubles (mocks) to the DoIt method. But at what cost? I've now had to define 3 new interfaces just to make this testable. And what, exactly, am I testing? I'm testing that my DoIt function properly interacts with its dependencies. It doesn't test that the zip file was unzipped properly, etc.</p>\n</blockquote>\n\n<p>You have hit the nail right on its head. What you want to test is the logic of your method, not necessarily whether a true file can be addressed. You don´t need to test (in this unit test) whether a file is correctly unzipped, your method takes that for granted. The interfaces are valuable by itself because they provide abstractions that you can program against, rather than implicitly or explicitly relying on one concrete implementation.</p>\n" }, { "answer_id": 23124879, "author": "Christopher Perry", "author_id": 413414, "author_profile": "https://Stackoverflow.com/users/413414", "pm_score": 6, "selected": false, "text": "\n\n<p>Your question exposes one of the hardest parts of testing for developers just getting into it: </p>\n\n<p><strong>\"What the hell do I test?\"</strong></p>\n\n<p>Your example isn't very interesting because it just glues some API calls together so if you were to write a unit test for it you would end up just asserting that methods were called. Tests like this tightly couple your implementation details to the test. This is bad because now you have to change the test every time you change the implementation details of your method because changing the implementation details breaks your test(s)!</p>\n\n<p><strong>Having bad tests is actually worse than having no tests at all.</strong></p>\n\n<p>In your example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner)\n{\n string path = zipper.Unzip(theZipFile);\n IFakeFile file = fileSystem.Open(path);\n runner.Run(file);\n}\n</code></pre>\n\n<p>While you can pass in mocks, there's no logic in the method to test. If you were to attempt a unit test for this it might look something like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// Assuming that zipper, fileSystem, and runner are mocks\nvoid testDoIt()\n{\n // mock behavior of the mock objects\n when(zipper.Unzip(any(File.class)).thenReturn(\"some path\");\n when(fileSystem.Open(\"some path\")).thenReturn(mock(IFakeFile.class));\n\n // run the test\n someObject.DoIt(zipper, fileSystem, runner);\n\n // verify things were called\n verify(zipper).Unzip(any(File.class));\n verify(fileSystem).Open(\"some path\"));\n verify(runner).Run(file);\n}\n</code></pre>\n\n<p>Congratulations, you basically copy-pasted the implementation details of your <code>DoIt()</code> method into a test. Happy maintaining.</p>\n\n<p><strong>When you write tests you want to test the <em>WHAT</em> and not the <em>HOW</em>.</strong> \nSee <a href=\"http://en.wikipedia.org/wiki/Black_box_testing\" rel=\"noreferrer\">Black Box Testing</a> for more.</p>\n\n<p>The <strong>WHAT</strong> is the name of your method (or at least it should be). The <strong>HOW</strong> are all the little implementation details that live inside your method. Good tests allow you to swap out the <strong>HOW</strong> without breaking the <strong>WHAT</strong>. </p>\n\n<p>Think about it this way, ask yourself:</p>\n\n<p><strong>\"If I change the implementation details of this method (without altering the public contract) will it break my test(s)?\"</strong> </p>\n\n<p>If the answer is yes, you are testing the <strong>HOW</strong> and not the <strong>WHAT</strong>.</p>\n\n<p>To answer your specific question about testing code with file system dependencies, let's say you had something a bit more interesting going on with a file and you wanted to save the Base64 encoded contents of a <code>byte[]</code> to a file. You can use streams for this to test that your code does the right thing without having to check <strong>how</strong> it does it. One example might be something like this (in Java):</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>interface StreamFactory {\n OutputStream outStream();\n InputStream inStream();\n}\n\nclass Base64FileWriter {\n public void write(byte[] contents, StreamFactory streamFactory) {\n OutputStream outputStream = streamFactory.outStream();\n outputStream.write(Base64.encodeBase64(contents));\n }\n}\n\n@Test\npublic void save_shouldBase64EncodeContents() {\n OutputStream outputStream = new ByteArrayOutputStream();\n StreamFactory streamFactory = mock(StreamFactory.class);\n when(streamFactory.outStream()).thenReturn(outputStream);\n\n // Run the method under test\n Base64FileWriter fileWriter = new Base64FileWriter();\n fileWriter.write(\"Man\".getBytes(), streamFactory);\n\n // Assert we saved the base64 encoded contents\n assertThat(outputStream.toString()).isEqualTo(\"TWFu\");\n}\n</code></pre>\n\n<p>The test uses a <code>ByteArrayOutputStream</code> but in the application (using dependency injection) the real StreamFactory (perhaps called FileStreamFactory) would return <code>FileOutputStream</code> from <code>outputStream()</code> and would write to a <code>File</code>.</p>\n\n<p>What was interesting about the <code>write</code> method here is that it was writing the contents out Base64 encoded, so that's what we tested for. For your <code>DoIt()</code> method, this would be more appropriately tested with an <a href=\"http://en.wikipedia.org/wiki/Integration_testing\" rel=\"noreferrer\">integration test</a>.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
I am writing a component that, given a ZIP file, needs to: 1. Unzip the file. 2. Find a specific dll among the unzipped files. 3. Load that dll through reflection and invoke a method on it. I'd like to unit test this component. I'm tempted to write code that deals directly with the file system: ```cs void DoIt() { Zip.Unzip(theZipFile, "C:\\foo\\Unzipped"); System.IO.File myDll = File.Open("C:\\foo\\Unzipped\\SuperSecret.bar"); myDll.InvokeSomeSpecialMethod(); } ``` But folks often say, "Don't write unit tests that rely on the file system, database, network, etc." If I were to write this in a unit-test friendly way, I suppose it would look like this: ```cs void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner) { string path = zipper.Unzip(theZipFile); IFakeFile file = fileSystem.Open(path); runner.Run(file); } ``` Yay! Now it's testable; I can feed in test doubles (mocks) to the DoIt method. But at what cost? I've now had to define 3 new interfaces just to make this testable. And what, exactly, am I testing? I'm testing that my DoIt function properly interacts with its dependencies. It doesn't test that the zip file was unzipped properly, etc. It doesn't feel like I'm testing functionality anymore. It feels like I'm just testing class interactions. **My question is this**: what's the proper way to unit test something that is dependent on the file system? *edit* I'm using .NET, but the concept could apply Java or native code too.
There's really nothing wrong with this, it's just a question of whether you call it a unit test or an integration test. You just have to make sure that if you do interact with the file system, there are no unintended side effects. Specifically, make sure that you clean up after youself -- delete any temporary files you created -- and that you don't accidentally overwrite an existing file that happened to have the same filename as a temporary file you were using. Always use relative paths and not absolute paths. It would also be a good idea to `chdir()` into a temporary directory before running your test, and `chdir()` back afterwards.
129,043
<p>I have a bash script that creates a Subversion patch file for the current directory. I want to modify it to zip the produced file, if <code>-z</code> is given as an argument to the script.</p> <p>Here's the relevant part:</p> <pre><code>zipped='' zipcommand='&gt;' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip &gt;' fi echo "Creating ${zipped}patch file $filename..." svn diff $zipcommand $filename </code></pre> <p>This doesn't work because it passes the <code>|</code> or <code>></code> contained in <code>$zipcommand</code> as an argument to <code>svn</code>.</p> <p>I can easily work around this, but the question is whether it's ever possible to use these kinds of operators when they're contained in variables.</p> <p>Thanks!</p>
[ { "answer_id": 129132, "author": "Keeth", "author_id": 20588, "author_profile": "https://Stackoverflow.com/users/20588", "pm_score": 4, "selected": true, "text": "<p>I would do something like this (use bash -c or eval):</p>\n\n<pre><code>zipped=''\nzipcommand='&gt;'\n\nif [ \"$1\" = \"-z\" ]\nthen\n zipped='zipped '\n filename=\"${filename}.zip\"\n zipcommand='| zip -@'\nfi\n\necho \"Creating ${zipped}patch file $filename...\"\n\neval \"svn diff $zipcommand $filename\"\n# this also works: \n# bash -c \"svn diff $zipcommand $filename\"\n</code></pre>\n\n<p>This appears to work, but my version of zip (Mac OS X) required that i change the line:</p>\n\n<pre><code>zipcommand='| zip -@'\n</code></pre>\n\n<p>to</p>\n\n<pre><code>zipcommand='| zip - - &gt;'\n</code></pre>\n\n<p>Edit: incorporated @DanielBungert's suggestion to use eval</p>\n" }, { "answer_id": 129149, "author": "Daniel Bungert", "author_id": 21093, "author_profile": "https://Stackoverflow.com/users/21093", "pm_score": 2, "selected": false, "text": "<p>eval is what you are looking for.</p>\n\n<pre><code># eval 'printf \"foo\\nbar\" | grep bar'\nbar\n</code></pre>\n\n<p>Be careful with quote characters on that.</p>\n" }, { "answer_id": 132267, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<p>Or you should try <code>zsh</code> shell whic allows to define global aliases, e.g.:</p>\n\n<pre><code>alias -g L='| less'\nalias -g S='| sort'\nalias -g U='| uniq -c'\n</code></pre>\n\n<p>Then use this command (which is somewhat cryptic for the ones who took a look from behind ;-) )</p>\n\n<pre><code>./somecommand.sh S U L\n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 33428179, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "<p>Open a new file handle on either a process substitution to handle the compression or on the named file. Then redirect the output of <code>svn diff</code> to that file handle.</p>\n\n<pre><code>if [ \"$1\" = \"-z\" ]; then\n zipped='zipped '\n filename=$filename.zip\n exec 3&gt; &gt;(zip &gt; \"$filename\")\nelse\n exec 3&gt; \"$filename\"\nfi\n\necho \"Creating ${zipped}patch file $filename\"\nsvn diff &gt;&amp;3\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
I have a bash script that creates a Subversion patch file for the current directory. I want to modify it to zip the produced file, if `-z` is given as an argument to the script. Here's the relevant part: ``` zipped='' zipcommand='>' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip >' fi echo "Creating ${zipped}patch file $filename..." svn diff $zipcommand $filename ``` This doesn't work because it passes the `|` or `>` contained in `$zipcommand` as an argument to `svn`. I can easily work around this, but the question is whether it's ever possible to use these kinds of operators when they're contained in variables. Thanks!
I would do something like this (use bash -c or eval): ``` zipped='' zipcommand='>' if [ "$1" = "-z" ] then zipped='zipped ' filename="${filename}.zip" zipcommand='| zip -@' fi echo "Creating ${zipped}patch file $filename..." eval "svn diff $zipcommand $filename" # this also works: # bash -c "svn diff $zipcommand $filename" ``` This appears to work, but my version of zip (Mac OS X) required that i change the line: ``` zipcommand='| zip -@' ``` to ``` zipcommand='| zip - - >' ``` Edit: incorporated @DanielBungert's suggestion to use eval
129,046
<p>How would I disable and later enable all indexes in a given schema/database in Oracle?</p> <p>Note: This is to make sqlldr run faster.</p>
[ { "answer_id": 129163, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 2, "selected": false, "text": "<p>From here: <a href=\"http://forums.oracle.com/forums/thread.jspa?messageID=2354075\" rel=\"nofollow noreferrer\">http://forums.oracle.com/forums/thread.jspa?messageID=2354075</a></p>\n\n<p><code>alter session set skip_unusable_indexes = true;</code></p>\n\n<p><code>alter index your_index unusable;</code></p>\n\n<p>do import...</p>\n\n<p><code>alter index your_index rebuild [online];</code></p>\n" }, { "answer_id": 129227, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 2, "selected": false, "text": "<p>You can disable constraints in Oracle but not indexes. There's a command to make an index ununsable but you have to rebuild the index anyway, so I'd probably just write a script to drop and rebuild the indexes. You can use the user_indexes and user_ind_columns to get all the indexes for a schema or use dbms_metadata:</p>\n\n<pre><code>select dbms_metadata.get_ddl('INDEX', u.index_name) from user_indexes u;\n</code></pre>\n" }, { "answer_id": 129313, "author": "oneself", "author_id": 9435, "author_profile": "https://Stackoverflow.com/users/9435", "pm_score": 1, "selected": false, "text": "<p>Combining the two answers:</p>\n\n<p>First create sql to make all index unusable:</p>\n\n<pre><code>alter session set skip_unusable_indexes = true;\nselect 'alter index ' || u.index_name || ' unusable;' from user_indexes u;\n</code></pre>\n\n<p>Do import...</p>\n\n<pre><code>select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;\n</code></pre>\n" }, { "answer_id": 129870, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>If you are using non-parallel direct path loads then consider and benchmark not dropping the indexes at all, particularly if the indexes only cover a minority of the columns. Oracle has a mechanism for efficient maintenance of indexes on direct path loads.</p>\n\n<p>Otherwise, I'd also advise making the indexes unusable instead of dropping them. Less chance of accidentally not recreating an index.</p>\n" }, { "answer_id": 136612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>combining 3 answers together:\n(because a select statement does not execute the DDL)</p>\n\n<pre><code>set pagesize 0\n\nalter session set skip_unusable_indexes = true;\nspool c:\\temp\\disable_indexes.sql\nselect 'alter index ' || u.index_name || ' unusable;' from user_indexes u;\nspool off\n@c:\\temp\\disable_indexes.sql\n</code></pre>\n\n<p>Do import...</p>\n\n<pre><code>select 'alter index ' || u.index_name || \n' rebuild online;' from user_indexes u;\n</code></pre>\n\n<p>Note this assumes that the import is going to happen in the same (sqlplus) session.<br>\nIf you are calling \"imp\" it will run in a separate session so you would need to use \"ALTER SYSTEM\" instead of \"ALTER SESSION\" (and remember to put the parameter back the way you found it.</p>\n" }, { "answer_id": 1357864, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>If you're on Oracle 11g, you may also want to check out <a href=\"http://www.psoug.org/reference/dbms_index_utl.html\" rel=\"nofollow noreferrer\">dbms_index_utl</a>.</p>\n" }, { "answer_id": 1578690, "author": "Karl Bartel", "author_id": 114926, "author_profile": "https://Stackoverflow.com/users/114926", "pm_score": 0, "selected": false, "text": "<p>You should try sqlldr's SKIP_INDEX_MAINTENANCE parameter.</p>\n" }, { "answer_id": 3526027, "author": "jmc", "author_id": 425739, "author_profile": "https://Stackoverflow.com/users/425739", "pm_score": 5, "selected": true, "text": "<p>Here's making the indexes unusable without the file:</p>\n\n<pre><code>DECLARE\n CURSOR usr_idxs IS select * from user_indexes;\n cur_idx usr_idxs% ROWTYPE;\n v_sql VARCHAR2(1024);\n\nBEGIN\n OPEN usr_idxs;\n LOOP\n FETCH usr_idxs INTO cur_idx;\n EXIT WHEN NOT usr_idxs%FOUND;\n\n v_sql:= 'ALTER INDEX ' || cur_idx.index_name || ' UNUSABLE';\n EXECUTE IMMEDIATE v_sql;\n END LOOP;\n CLOSE usr_idxs;\nEND;\n</code></pre>\n\n<p>The rebuild would be similiar.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9435/" ]
How would I disable and later enable all indexes in a given schema/database in Oracle? Note: This is to make sqlldr run faster.
Here's making the indexes unusable without the file: ``` DECLARE CURSOR usr_idxs IS select * from user_indexes; cur_idx usr_idxs% ROWTYPE; v_sql VARCHAR2(1024); BEGIN OPEN usr_idxs; LOOP FETCH usr_idxs INTO cur_idx; EXIT WHEN NOT usr_idxs%FOUND; v_sql:= 'ALTER INDEX ' || cur_idx.index_name || ' UNUSABLE'; EXECUTE IMMEDIATE v_sql; END LOOP; CLOSE usr_idxs; END; ``` The rebuild would be similiar.
129,072
<p>Essentially the only thing I can deploy to my deployment machine is a JAR file. I can't install JRuby, nor can I install Glassfish or Tomcat.</p> <p>Is it possible to package up a Rails application (including Rails, vendored, of course) to a JAR file such that I can do</p> <pre><code>c:\my_server&gt; java rails_app.jar </code></pre> <p>and have it run WEBRick or Mongrel within the JVM?</p>
[ { "answer_id": 129109, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 4, "selected": true, "text": "<p>I'd recommend that you checkout Jetty. The process for <a href=\"http://docs.codehaus.org/display/JETTY/Embedding+Jetty\" rel=\"noreferrer\">Embedding Jetty</a> is surprisingly easy, and it should be possible to give it your servlets from your current jar file. I haven't used Ruby/Rails, though, so I'm not sure if there are any complications there.</p>\n\n<p>Is it normally possible to embed all of your rails templates/models into a jar inside of a war file for deployment on Tomcat? If so, then you should be able to get embedded Jetty to pull it from your single jar as well.</p>\n" }, { "answer_id": 129214, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>I don't think you can run Mongrel within the JVM. Trying to run a webserver of any kind without Tomcat or Jetty is probably way more trouble than it's worth. <a href=\"https://stackoverflow.com/questions/129072/is-it-possible-to-compile-a-rails-app-to-a-java-vm-jar-file#129109\">jsight</a>'s answer looks helpful for that problem. If you can get that far, here's a page on JRuby's site about running <a href=\"http://wiki.jruby.org/wiki/Jruby_on_Rails_on_Tomcat\" rel=\"nofollow noreferrer\">JRuby on Rails in Tomcat</a>.</p>\n" }, { "answer_id": 129307, "author": "Evgeny", "author_id": 11414, "author_profile": "https://Stackoverflow.com/users/11414", "pm_score": 3, "selected": false, "text": "<p>I wrote an article a year ago about how to embed your ruby sources with jruby and everything else you want into one jar file, and then run it with \"java -jar myapp.jar\".</p>\n\n<p>It will need some work to make it boot rails I guess, but it should not be too hard. And with the complimentary jruby documentation on their wiki, i guess you can run a jetty+war thing fairly easily with this technique.</p>\n\n<p>The article is here:\n<a href=\"http://blog.kesor.net/2007/08/14/jruby-in-a-jar/\" rel=\"nofollow noreferrer\">http://blog.kesor.net/2007/08/14/jruby-in-a-jar/</a></p>\n" }, { "answer_id": 129621, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 1, "selected": false, "text": "<p>you might want to try asking this question on the JRuby mailing list/forum(<a href=\"http://xircles.codehaus.org/lists/[email protected]\" rel=\"nofollow noreferrer\">http://xircles.codehaus.org/lists/[email protected]</a>).</p>\n\n<p>Another place someone would have done the same is the glassfish mailing list</p>\n\n<p>Yet another thing you might want to do is to bundle winstone embeddable servlet container AND jruby AND rails and use jarjar to create one big jar. You might be able to build an ant build file to build such a BIG jar that also includes your rails application. One project that used this approach is hudson(<a href=\"https://hudson.dev.java.net/\" rel=\"nofollow noreferrer\">https://hudson.dev.java.net/</a>) -- you may get some info on how to go about doing that.</p>\n\n<p>BR,<br>\n~A</p>\n" }, { "answer_id": 131172, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "<p>It may be a bit dated, but Nick Sieger, one of the JRuby contributors <a href=\"http://blog.nicksieger.com/articles/2007/09/04/warbler-a-little-birdie-to-introduce-your-rails-app-to-java\" rel=\"nofollow noreferrer\">wrote about warbler</a> a while ago.</p>\n\n<p><a href=\"http://caldersphere.rubyforge.org/warbler/\" rel=\"nofollow noreferrer\">Warbler</a> is about packaging a Rails app into a .war file. Now I'm not a big Java guy, so I'm not sure where your .jar restriction comes from. war files are similar to jars but they're for whole websites or something.</p>\n\n<p>Worst case, I'm pretty sure the <a href=\"http://wiki.jruby.org/wiki/Main_Page\" rel=\"nofollow noreferrer\">JRuby wiki</a> has something about the state of packaging Rails apps to be run on Java architectures. It's in their best interest to have info about that.</p>\n" }, { "answer_id": 3878269, "author": "Cognition.Mind", "author_id": 468646, "author_profile": "https://Stackoverflow.com/users/468646", "pm_score": 0, "selected": false, "text": "<p>I just ran across this blog today, and I intend on giving it a try, if anyone else has let me know</p>\n\n<p><a href=\"http://matthewkwilliams.com/index.php/2010/03/02/rails-jruby-in-a-jar/\" rel=\"nofollow\">http://matthewkwilliams.com/index.php/2010/03/02/rails-jruby-in-a-jar/</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
Essentially the only thing I can deploy to my deployment machine is a JAR file. I can't install JRuby, nor can I install Glassfish or Tomcat. Is it possible to package up a Rails application (including Rails, vendored, of course) to a JAR file such that I can do ``` c:\my_server> java rails_app.jar ``` and have it run WEBRick or Mongrel within the JVM?
I'd recommend that you checkout Jetty. The process for [Embedding Jetty](http://docs.codehaus.org/display/JETTY/Embedding+Jetty) is surprisingly easy, and it should be possible to give it your servlets from your current jar file. I haven't used Ruby/Rails, though, so I'm not sure if there are any complications there. Is it normally possible to embed all of your rails templates/models into a jar inside of a war file for deployment on Tomcat? If so, then you should be able to get embedded Jetty to pull it from your single jar as well.
129,077
<p>This issue came up when I got different records counts for what I thought were identical queries one using a <code>not in</code> <code>where</code> constraint and the other a <code>left join</code>. The table in the <code>not in</code> constraint had one null value (bad data) which caused that query to return a count of 0 records. I sort of understand why but I could use some help fully grasping the concept.</p> <p>To state it simply, why does query A return a result but B doesn't?</p> <pre><code>A: select 'true' where 3 in (1, 2, 3, null) B: select 'true' where 3 not in (1, 2, null) </code></pre> <p>This was on SQL Server 2005. I also found that calling <code>set ansi_nulls off</code> causes B to return a result.</p>
[ { "answer_id": 129089, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 4, "selected": false, "text": "<p>Compare to null is undefined, unless you use IS NULL.</p>\n\n<p>So, when comparing 3 to NULL (query A), it returns undefined.</p>\n\n<p>I.e. SELECT 'true' where 3 in (1,2,null)\n and \nSELECT 'true' where 3 not in (1,2,null)</p>\n\n<p>will produce the same result, as NOT (UNDEFINED) is still undefined, but not TRUE</p>\n" }, { "answer_id": 129127, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 3, "selected": false, "text": "<p>In A, 3 is tested for equality against each member of the set, yielding (FALSE, FALSE, TRUE, UNKNOWN). Since one of the elements is TRUE, the condition is TRUE. (It's also possible that some short-circuiting takes place here, so it actually stops as soon as it hits the first TRUE and never evaluates 3=NULL.)</p>\n\n<p>In B, I think it is evaluating the condition as NOT (3 in (1,2,null)). Testing 3 for equality against the set yields (FALSE, FALSE, UNKNOWN), which is aggregated to UNKNOWN. NOT ( UNKNOWN ) yields UNKNOWN. So overall the truth of the condition is unknown, which at the end is essentially treated as FALSE.</p>\n" }, { "answer_id": 129151, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": 6, "selected": false, "text": "<h2><code>NOT IN</code> returns 0 records when compared against an unknown value</h2>\n\n<p>Since <code>NULL</code> is an unknown, a <code>NOT IN</code> query containing a <code>NULL</code> or <code>NULL</code>s in the list of possible values will always return <code>0</code> records since there is no way to be sure that the <code>NULL</code> value is not the value being tested.</p>\n" }, { "answer_id": 129152, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 9, "selected": true, "text": "<p>Query A is the same as:</p>\n\n<pre><code>select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null\n</code></pre>\n\n<p>Since <code>3 = 3</code> is true, you get a result.</p>\n\n<p>Query B is the same as:</p>\n\n<pre><code>select 'true' where 3 &lt;&gt; 1 and 3 &lt;&gt; 2 and 3 &lt;&gt; null\n</code></pre>\n\n<p>When <code>ansi_nulls</code> is on, <code>3 &lt;&gt; null</code> is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.</p>\n\n<p>When <code>ansi_nulls</code> is off, <code>3 &lt;&gt; null</code> is true, so the predicate evaluates to true, and you get a row.</p>\n" }, { "answer_id": 129196, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 3, "selected": false, "text": "<p>Null signifies and absence of data, that is it is unknown, not a data value of nothing. It's very easy for people from a programming background to confuse this because in C type languages when using pointers null is indeed nothing. </p>\n\n<p>Hence in the first case 3 is indeed in the set of (1,2,3,null) so true is returned</p>\n\n<p>In the second however you can reduce it to </p>\n\n<p><em>select 'true' where 3 not in (null)</em></p>\n\n<p>So nothing is returned because the parser knows nothing about the set to which you are comparing it - it's not an empty set but an unknown set. Using (1, 2, null) doesn't help because the (1,2) set is obviously false, but then you're and'ing that against unknown, which is unknown.</p>\n" }, { "answer_id": 130409, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 0, "selected": false, "text": "<p>also this might be of use to know the logical difference between join, exists and in\n<a href=\"http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx\" rel=\"nofollow noreferrer\">http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx</a></p>\n" }, { "answer_id": 132402, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 6, "selected": false, "text": "<p>Whenever you use NULL you are really dealing with a Three-Valued logic.</p>\n\n<p>Your first query returns results as the WHERE clause evaluates to:</p>\n\n<pre><code> 3 = 1 or 3 = 2 or 3 = 3 or 3 = null\nwhich is:\n FALSE or FALSE or TRUE or UNKNOWN\nwhich evaluates to \n TRUE\n</code></pre>\n\n<p>The second one:</p>\n\n<pre><code> 3 &lt;&gt; 1 and 3 &lt;&gt; 2 and 3 &lt;&gt; null\nwhich evaluates to:\n TRUE and TRUE and UNKNOWN\nwhich evaluates to:\n UNKNOWN\n</code></pre>\n\n<p>The UNKNOWN is not the same as FALSE\nyou can easily test it by calling:</p>\n\n<pre><code>select 'true' where 3 &lt;&gt; null\nselect 'true' where not (3 &lt;&gt; null)\n</code></pre>\n\n<p>Both queries will give you no results</p>\n\n<p>If the UNKNOWN was the same as FALSE then assuming that the first query would give you FALSE the second would have to evaluate to TRUE as it would have been the same as NOT(FALSE).<br>\nThat is not the case.</p>\n\n<p>There is a very good <a href=\"http://www.sqlservercentral.com/articles/Advanced+Querying/fourrulesfornulls/1915/\" rel=\"noreferrer\">article on this subject on SqlServerCentral</a>.</p>\n\n<p>The whole issue of NULLs and Three-Valued Logic can be a bit confusing at first but it is essential to understand in order to write correct queries in TSQL </p>\n\n<p>Another article I would recommend is <a href=\"http://www.sqlservercentral.com/articles/Advanced+Querying/gotchasqlaggregatefunctionsandnull/1947/\" rel=\"noreferrer\">SQL Aggregate Functions and NULL</a>.</p>\n" }, { "answer_id": 1031653, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>this is for Boy:</p>\n\n<pre><code>select party_code \nfrom abc as a\nwhere party_code not in (select party_code \n from xyz \n where party_code = a.party_code);\n</code></pre>\n\n<p>this works regardless of ansi settings</p>\n" }, { "answer_id": 7526344, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "<p>The title of this question at the time of writing is </p>\n\n<blockquote>\n <p>SQL NOT IN constraint and NULL values</p>\n</blockquote>\n\n<p>From the text of the question it appears that the problem was occurring in a SQL DML <code>SELECT</code> query, rather than a SQL DDL <code>CONSTRAINT</code>.</p>\n\n<p>However, especially given the wording of the title, I want to point out that some statements made here are potentially misleading statements, those along the lines of (paraphrasing) </p>\n\n<blockquote>\n <p>When the predicate evaluates to UNKNOWN you don't get any rows.</p>\n</blockquote>\n\n<p>Although this is the case for SQL DML, when considering constraints the effect is different.</p>\n\n<p>Consider this very simple table with two constraints taken directly from the predicates in the question (and addressed in an excellent answer by @Brannon):</p>\n\n<pre><code>DECLARE @T TABLE \n(\n true CHAR(4) DEFAULT 'true' NOT NULL, \n CHECK ( 3 IN (1, 2, 3, NULL )), \n CHECK ( 3 NOT IN (1, 2, NULL ))\n);\n\nINSERT INTO @T VALUES ('true');\n\nSELECT COUNT(*) AS tally FROM @T;\n</code></pre>\n\n<p>As per @Brannon's answer, the first constraint (using <code>IN</code>) evaluates to TRUE and the second constraint (using <code>NOT IN</code>) evaluates to UNKNOWN. <strong>However</strong>, the insert succeeds! Therefore, in this case it is not strictly correct to say, \"you don't get any rows\" because we have indeed got a row inserted as a result.</p>\n\n<p>The above effect is indeed the correct one as regards the SQL-92 Standard. Compare and contrast the following section from the SQL-92 spec</p>\n\n<blockquote>\n <p><strong>7.6 where clause</strong></p>\n \n <p>The result of the is a table of those rows of T for\n which the result of the search condition is true.</p>\n \n <p><strong>4.10 Integrity constraints</strong></p>\n \n <p>A table check constraint is satisfied if and only if the specified\n search condition is not false for any row of a table.</p>\n</blockquote>\n\n<p>In other words:</p>\n\n<p>In SQL DML, rows are removed from the result when the <code>WHERE</code> evaluates to UNKNOWN because it <strong>does not</strong> satisfy the condition \"is true\".</p>\n\n<p>In SQL DDL (i.e. constraints), rows are not removed from the result when they evaluate to UNKNOWN because it <strong>does</strong> satisfy the condition \"is not false\".</p>\n\n<p>Although the effects in SQL DML and SQL DDL respectively may seem contradictory, there is practical reason for giving UNKNOWN results the 'benefit of the doubt' by allowing them to satisfy a constraint (more correctly, allowing them to not fail to satisfy a constraint): without this behaviour, every constraints would have to explicitly handle nulls and that would be very unsatisfactory from a language design perspective (not to mention, a right pain for coders!)</p>\n\n<p>p.s. if you are finding it as challenging to follow such logic as \"unknown does not fail to satisfy a constraint\" as I am to write it, then consider you can dispense with all this simply by avoiding nullable columns in SQL DDL and anything in SQL DML that produces nulls (e.g. outer joins)!</p>\n" }, { "answer_id": 7571289, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "<p>It may be concluded from answers here that <code>NOT IN (subquery)</code> doesn't handle nulls correctly and should be avoided in favour of <code>NOT EXISTS</code>. However, such a conclusion may be premature. In the following scenario, credited to Chris Date (Database Programming and Design, Vol 2 No 9, September 1989), it is <code>NOT IN</code> that handles nulls correctly and returns the correct result, rather than <code>NOT EXISTS</code>.</p>\n\n<p>Consider a table <code>sp</code> to represent suppliers (<code>sno</code>) who are known to supply parts (<code>pno</code>) in quantity (<code>qty</code>). The table currently holds the following values:</p>\n\n<pre><code> VALUES ('S1', 'P1', NULL), \n ('S2', 'P1', 200),\n ('S3', 'P1', 1000)\n</code></pre>\n\n<p>Note that quantity is nullable i.e. to be able to record the fact a supplier is known to supply parts even if it is not known in what quantity. </p>\n\n<p>The task is to find the suppliers who are known supply part number 'P1' but not in quantities of 1000.</p>\n\n<p>The following uses <code>NOT IN</code> to correctly identify supplier 'S2' only:</p>\n\n<pre><code>WITH sp AS \n ( SELECT * \n FROM ( VALUES ( 'S1', 'P1', NULL ), \n ( 'S2', 'P1', 200 ),\n ( 'S3', 'P1', 1000 ) )\n AS T ( sno, pno, qty )\n )\nSELECT DISTINCT spx.sno\n FROM sp spx\n WHERE spx.pno = 'P1'\n AND 1000 NOT IN (\n SELECT spy.qty\n FROM sp spy\n WHERE spy.sno = spx.sno\n AND spy.pno = 'P1'\n );\n</code></pre>\n\n<p>However, the below query uses the same general structure but with <code>NOT EXISTS</code> but incorrectly includes supplier 'S1' in the result (i.e. for which the quantity is null):</p>\n\n<pre><code>WITH sp AS \n ( SELECT * \n FROM ( VALUES ( 'S1', 'P1', NULL ), \n ( 'S2', 'P1', 200 ),\n ( 'S3', 'P1', 1000 ) )\n AS T ( sno, pno, qty )\n )\nSELECT DISTINCT spx.sno\n FROM sp spx\n WHERE spx.pno = 'P1'\n AND NOT EXISTS (\n SELECT *\n FROM sp spy\n WHERE spy.sno = spx.sno\n AND spy.pno = 'P1'\n AND spy.qty = 1000\n );\n</code></pre>\n\n<p>So <code>NOT EXISTS</code> is not the silver bullet it may have appeared!</p>\n\n<p>Of course, source of the problem is the presence of nulls, therefore the 'real' solution is to eliminate those nulls.</p>\n\n<p>This can be achieved (among other possible designs) using two tables:</p>\n\n<ul>\n<li><code>sp</code> suppliers known to supply parts</li>\n<li><code>spq</code> suppliers known to supply parts in known quantities</li>\n</ul>\n\n<p>noting there should probably be a foreign key constraint where <code>spq</code> references <code>sp</code>.</p>\n\n<p>The result can then be obtained using the 'minus' relational operator (being the <code>EXCEPT</code> keyword in Standard SQL) e.g. </p>\n\n<pre><code>WITH sp AS \n ( SELECT * \n FROM ( VALUES ( 'S1', 'P1' ), \n ( 'S2', 'P1' ),\n ( 'S3', 'P1' ) )\n AS T ( sno, pno )\n ),\n spq AS \n ( SELECT * \n FROM ( VALUES ( 'S2', 'P1', 200 ),\n ( 'S3', 'P1', 1000 ) )\n AS T ( sno, pno, qty )\n )\nSELECT sno\n FROM spq\n WHERE pno = 'P1'\nEXCEPT \nSELECT sno\n FROM spq\n WHERE pno = 'P1'\n AND qty = 1000;\n</code></pre>\n" }, { "answer_id": 26684098, "author": "Mihai", "author_id": 1745672, "author_profile": "https://Stackoverflow.com/users/1745672", "pm_score": 3, "selected": false, "text": "<p>IF you want to filter with NOT IN for a subquery containg NULLs justcheck for not null</p>\n\n<pre><code>SELECT blah FROM t WHERE blah NOT IN\n (SELECT someotherBlah FROM t2 WHERE someotherBlah IS NOT NULL )\n</code></pre>\n" }, { "answer_id": 59084753, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 3, "selected": false, "text": "<p>SQL uses three-valued logic for truth values. The <code>IN</code> query produces the expected result:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE col IN (NULL, 1)\n-- returns first row\n</code></pre>\n<p><em><strong>But adding a <code>NOT</code> does not invert the results:</strong></em></p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT col IN (NULL, 1)\n-- returns zero rows\n</code></pre>\n<p>This is because the above query is equivalent of the following:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT (col = NULL OR col = 1)\n</code></pre>\n<p>Here is how the where clause is evaluated:</p>\n<pre class=\"lang-none prettyprint-override\"><code>| col | col = NULL⁽¹⁾ | col = 1 | col = NULL OR col = 1 | NOT (col = NULL OR col = 1) |\n|-----|----------------|---------|-----------------------|-----------------------------|\n| 1 | UNKNOWN | TRUE | TRUE | FALSE |\n| 2 | UNKNOWN | FALSE | UNKNOWN⁽²⁾ | UNKNOWN⁽³⁾ |\n</code></pre>\n<p>Notice that:</p>\n<ol>\n<li>The comparison involving <code>NULL</code> yields <code>UNKNOWN</code></li>\n<li>The <code>OR</code> expression where none of the operands are <code>TRUE</code> and at least one operand is <code>UNKNOWN</code> yields <code>UNKNOWN</code> (<a href=\"https://en.wikipedia.org/wiki/Null_(SQL)#Comparisons_with_NULL_and_the_three-valued_logic_(3VL)\" rel=\"noreferrer\">ref</a>)</li>\n<li>The <code>NOT</code> of <code>UNKNOWN</code> yields <code>UNKNOWN</code> (<a href=\"https://en.wikipedia.org/wiki/Null_(SQL)#Comparisons_with_NULL_and_the_three-valued_logic_(3VL)\" rel=\"noreferrer\">ref</a>)</li>\n</ol>\n<p>You can extend the above example to more than two values (e.g. NULL, 1 and 2) but the result will be same: if one of the values is <code>NULL</code> then no row will match.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12752/" ]
This issue came up when I got different records counts for what I thought were identical queries one using a `not in` `where` constraint and the other a `left join`. The table in the `not in` constraint had one null value (bad data) which caused that query to return a count of 0 records. I sort of understand why but I could use some help fully grasping the concept. To state it simply, why does query A return a result but B doesn't? ``` A: select 'true' where 3 in (1, 2, 3, null) B: select 'true' where 3 not in (1, 2, null) ``` This was on SQL Server 2005. I also found that calling `set ansi_nulls off` causes B to return a result.
Query A is the same as: ``` select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null ``` Since `3 = 3` is true, you get a result. Query B is the same as: ``` select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null ``` When `ansi_nulls` is on, `3 <> null` is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows. When `ansi_nulls` is off, `3 <> null` is true, so the predicate evaluates to true, and you get a row.
129,120
<p>I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at all until recently.</p> <p>Our production code contains no asserts whatsoever and my question is this...</p> <p>Should I begin using Asserts in our production code? And if so, When is its use most appropriate? Would it make more sense to do</p> <pre><code>Debug.Assert(val != null); </code></pre> <p>or</p> <pre><code>if ( val == null ) throw new exception(); </code></pre>
[ { "answer_id": 129136, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": false, "text": "<p>Put <code>Debug.Assert()</code> everywhere in the code where you want have sanity checks to ensure invariants. When you compile a Release build (i.e., no <em><code>DEBUG</code></em> compiler constant), the calls to <code>Debug.Assert()</code> will be removed so they won't affect performance.</p>\n\n<p>You should still throw exceptions before calling <code>Debug.Assert()</code>. The assert just makes sure that everything is as expected while you're still developing.</p>\n" }, { "answer_id": 129139, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": -1, "selected": false, "text": "<p>I don't know how it is in C# and .NET, but in C will assert() only work if compiled with -DDEBUG - the enduser will never see an assert() if it's compiled without. It's for developer only. I use it really often, it's sometimes easier to track bugs.</p>\n" }, { "answer_id": 129146, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": -1, "selected": false, "text": "<p>I would not use them in production code. Throw exceptions, catch and log.</p>\n\n<p>Also need to be careful in asp.net, as an assert can show up on the console and freeze the request(s).</p>\n" }, { "answer_id": 129150, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 6, "selected": false, "text": "<p>Use asserts to check developer assumptions and exceptions to check environmental assumptions. </p>\n" }, { "answer_id": 129155, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": false, "text": "<p>If you want Asserts in your production code (i.e. Release builds), you can use Trace.Assert instead of Debug.Assert.</p>\n\n<p>This of course adds overhead to your production executable.</p>\n\n<p>Also if your application is running in user-interface mode, the Assertion dialog will be displayed by default, which may be a bit disconcerting for your users. </p>\n\n<p>You can override this behaviour by removing the DefaultTraceListener: look at the documentation for Trace.Listeners in MSDN.</p>\n\n<p>In summary,</p>\n\n<ul>\n<li><p>Use Debug.Assert liberally to help catch bugs in Debug builds.</p></li>\n<li><p>If you use Trace.Assert in user-interface mode, you probably want to remove the DefaultTraceListener to avoid disconcerting users.</p></li>\n<li><p>If the condition you're testing is something your app can't handle, you're probably better off throwing an exception, to ensure execution doesn't continue. Be aware that a user can choose to ignore an assertion.</p></li>\n</ul>\n" }, { "answer_id": 129162, "author": "orlando calresian", "author_id": 21165, "author_profile": "https://Stackoverflow.com/users/21165", "pm_score": 0, "selected": false, "text": "<p>You should use Debug.Assert to test for logical errors in your programs. The complier can only inform you of syntax errors. So you should definetely use Assert statements to test for logical errors. Like say testing a program that sells cars that only BMWs that are blue should get a 15% discount. The complier could tell you nothing about if your program is logically correct in performing this but an assert statement could.</p>\n" }, { "answer_id": 129166, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 3, "selected": false, "text": "<p>Use assertions only in cases where you want the check removed for release builds. Remember, your assertions will not fire if you don't compile in debug mode.</p>\n\n<p>Given your check-for-null example, if this is in an internal-only API, I might use an assertion. If it's in a public API, I would definitely use the explicit check and throw.</p>\n" }, { "answer_id": 129169, "author": "user19113", "author_id": 19113, "author_profile": "https://Stackoverflow.com/users/19113", "pm_score": 5, "selected": false, "text": "<p>Asserts are used to catch programmer (your) error, not user error. They should be used only when there is no chance a user could cause the assert to fire. If you're writing an API, for example, asserts should not be used to check that an argument is not null in any method an API user could call. But it could be used in a private method not exposed as part of your API to assert that YOUR code never passes a null argument when it isn't supposed to.</p>\n\n<p>I usually favour exceptions over asserts when I'm not sure.</p>\n" }, { "answer_id": 129179, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 5, "selected": false, "text": "<p>If I were you I would do:</p>\n\n<pre><code>Debug.Assert(val != null);\nif ( val == null )\n throw new exception();\n</code></pre>\n\n<p>Or to avoid repeated condition check</p>\n\n<pre><code>if ( val == null )\n{\n Debug.Assert(false,\"breakpoint if val== null\");\n throw new exception();\n}\n</code></pre>\n" }, { "answer_id": 129203, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 2, "selected": false, "text": "<p>You should always use the second approach (throwing exceptions).</p>\n\n<p>Also if you're in production (and have a release-build), it's better to throw an exception (and let the app crash in the worst-case) than working with invalid values and maybe destroy your customer's data (which may cost thousand of dollars).</p>\n" }, { "answer_id": 129223, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 6, "selected": false, "text": "<p>From <a href=\"http://cc2e.com/\" rel=\"noreferrer\">Code Complete</a></p>\n<blockquote>\n<h2>8 Defensive Programming</h2>\n<h3>8.2 Assertions</h3>\n<p>An assertion is code that’s used during development—usually a routine\nor macro—that allows a program to check itself as it runs. When an\nassertion is true, that means everything is operating as expected.\nWhen it’s false, that means it has detected an unexpected error in the\ncode. For example, if the system assumes that a customer-information\nfile will never have more than 50,000 records, the program might\ncontain an assertion that the number of records is lessthan or equal\nto 50,000. As long as the number of records is less than or equal to\n50,000, the assertion will be silent. If it encounters more than\n50,000 records, however, it will loudly “assert” that there is an\nerror in the program.</p>\n<p>Assertions are especially useful in large, complicated programs and\nin high reliability programs. They enable programmers to more quickly\nflush out mismatched interface assumptions, errors that creep in when\ncode is modified, and so on.</p>\n<p>An assertion usually takes two arguments: a boolean expression that\ndescribes the assumption that’s supposed to be true and a message to\ndisplay if it isn’t.</p>\n<p>(…)</p>\n<p>Normally, you don’t want users to see assertion messages in\nproduction code; assertions are primarily for use during development\nand maintenance. Assertions are normally compiled into the code at\ndevelopment time and compiled out of the code for production. During\ndevelopment, assertions flush out contradictory assumptions,\nunexpected conditions, bad values passed to routines, and so on.\nDuring production, they are compiled out of the code so that the\nassertions don’t degrade system performance.</p>\n</blockquote>\n" }, { "answer_id": 129315, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "<p>Mostly never in my book.\nIn the vast majority of occasions if you want to check if everything is sane then throw if it isn't.</p>\n\n<p>What I dislike is the fact that it makes a debug build functionally different to a release build. If a debug assert fails but the functionality works in release then how does that make any sense? It's even better when the asserter has long left the company and no-one knows that part of the code. Then you have to kill some of your time exploring the issue to see if it is really a problem or not. If it is a problem then why isn't the person throwing in the first place? </p>\n\n<p>To me this suggests by using Debug.Asserts you're deferring the problem to someone else, deal with the problem yourself. If something is supposed to be the case and it isn't then throw. </p>\n\n<p>I guess there are possibly performance critical scenarios where you want to optimise away your asserts and they're useful there, however I am yet to encounter such a scenario.</p>\n" }, { "answer_id": 129429, "author": "Rory MacLeod", "author_id": 1016, "author_profile": "https://Stackoverflow.com/users/1016", "pm_score": 9, "selected": true, "text": "<p>In <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735622027\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Debugging Microsoft .NET 2.0 Applications</a> John Robbins has a big section on assertions. His main points are:</p>\n\n<ol>\n<li>Assert liberally. You can never have too many assertions.</li>\n<li>Assertions don't replace exceptions. Exceptions cover the things your code demands; assertions cover the things it assumes.</li>\n<li>A well-written assertion can tell you not just what happened and where (like an exception), but why.</li>\n<li>An exception message can often be cryptic, requiring you to work backwards through the code to recreate the context that caused the error. An assertion can preserve the program's state at the time the error occurred.</li>\n<li>Assertions double as documentation, telling other developers what implied assumptions your code depends on.</li>\n<li>The dialog that appears when an assertion fails lets you attach a debugger to the process, so you can poke around the stack as if you had put a breakpoint there.</li>\n</ol>\n\n<p>PS: If you liked Code Complete, I recommend following it up with this book. I bought it to learn about using WinDBG and dump files, but the first half is packed with tips to help avoid bugs in the first place.</p>\n" }, { "answer_id": 129535, "author": "devlord", "author_id": 16454, "author_profile": "https://Stackoverflow.com/users/16454", "pm_score": 3, "selected": false, "text": "<p>According to the <a href=\"http://www.idesign.net/idesign/DesktopDefault.aspx\" rel=\"noreferrer\">IDesign Standard</a>, you should</p>\n\n<blockquote>\n <p>Assert every assumption. On average, every fifth line is an assertion.</p>\n</blockquote>\n\n<pre><code>using System.Diagnostics;\n\nobject GetObject()\n{...}\n\nobject someObject = GetObject();\nDebug.Assert(someObject != null);\n</code></pre>\n\n<p>As a disclaimer I should mention I have not found it practical to implement this IRL. But this is their standard.</p>\n" }, { "answer_id": 5031211, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 6, "selected": false, "text": "<p>FWIW ... I find that my public methods tend to use the <code>if () { throw; }</code> pattern to ensure that the method is being called correctly. My private methods tend to use <code>Debug.Assert()</code>. </p>\n\n<p>The idea is that with my private methods, I'm the one under control, so if I start calling one of my own private methods with parameters that are incorrect, then I've broken my own assumption somewhere--I should have never gotten into that state. In production, these private asserts should ideally be unnecessary work since I am supposed to be keeping my internal state valid and consistent. Contrast with parameters given to public methods, which could be called by anyone at runtime: I still need to enforce parameter constraints there by throwing exceptions.</p>\n\n<p>Additionally, my private methods can still throw exceptions if something doesn't work at runtime (network error, data access error, bad data retrieved from a third party service, etc.). My asserts are just there to make sure that I haven't broken my own internal assumptions about the state of the object.</p>\n" }, { "answer_id": 20715592, "author": "shannon", "author_id": 608220, "author_profile": "https://Stackoverflow.com/users/608220", "pm_score": 2, "selected": false, "text": "<p>I thought I would add four more cases, where Debug.Assert can be the right choice.</p>\n\n<p><strong>1)</strong> Something I have not seen mentioned here is the <strong>additional conceptual coverage Asserts can provide during automated testing</strong>. As a simple example:</p>\n\n<p>When some higher-level caller is modified by an author who believes they have expanded the scope of the code to handle additional scenarios, ideally (!) they will write unit tests to cover this new condition. It may then be that the fully integrated code appears to work fine.</p>\n\n<p>However, actually a subtle flaw has been introduced, but not detected in test results. The callee has become non-deterministic in this case, and only <em>happens</em> to provide the expected result. Or perhaps it has yielded a rounding error that was unnoticed. Or caused an error that was offset equally elsewhere. Or granted not only the access requested but additional privileges that should not be granted. Etc.</p>\n\n<p>At this point, the Debug.Assert() statements contained in the callee coupled with the new case (or edge case) driven in by unit tests can provide invaluable notification during test that the original author's assumptions have been invalidated, and the code should not be released without additional review. Asserts with unit tests are the perfect partners.</p>\n\n<p><strong>2)</strong> Additionally, <strong>some tests are simple to write, but high-cost and unnecessary given the initial assumptions</strong>. For example:</p>\n\n<p>If an object can only be accessed from a certain secured entry point, should an additional query be made to a network rights database from every object method to ensure the caller has permissions? Surely not. Perhaps the ideal solution includes caching or some other expansion of features, but the design does not require it. A Debug.Assert() will immediately show when the object has been attached to an insecure entry point.</p>\n\n<p><strong>3)</strong> Next, in some cases your <strong>product may have no helpful diagnostic interaction for all or part of its operations when deployed in release mode</strong>. For example:</p>\n\n<p>Suppose it is an embedded real-time device. Throwing exceptions and restarting when it encounters a malformed packet is counter-productive. Instead the device may benefit from best-effort operation, even to the point of rendering noise in its output. It also may not have a human interface, logging device, or even be physically accessible by human at all when deployed in release mode, and awareness of errors is best provided by assessing the same output. In this case, liberal Assertions and thorough pre-release testing are more valuable than exceptions.</p>\n\n<p><strong>4)</strong> Lastly, <strong>some tests are unneccessary only because the callee is perceived as extremely reliable</strong>. In most cases, the more reusable code is, the more effort has been put into making it reliable. Therefore it is common to Exception for unexpected parameters from callers, but Assert for unexpected results from callees. For example:</p>\n\n<p>If a core <code>String.Find</code> operation states it will return a <code>-1</code> when the search criteria is not found, you may be able to safely perform one operation rather than three. However, if it actually returned <code>-2</code>, you may have no reasonable course of action. It would be unhelpful to replace the simpler calculation with one that tests separately for a <code>-1</code> value, and unreasonable in most release environments to litter your code with tests ensuring core libraries are operating as expected. In this case Asserts are ideal.</p>\n" }, { "answer_id": 20830932, "author": "Jon Hanna", "author_id": 400547, "author_profile": "https://Stackoverflow.com/users/400547", "pm_score": 3, "selected": false, "text": "<p>All asserts should be code that could be optimised to:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Debug.Assert(true);\n</code></pre>\n<p>Because it's checking something that you have already assumed is true. E.g.:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static void ConsumeEnumeration&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n if(source != null)\n using(var en = source.GetEnumerator())\n RunThroughEnumerator(en);\n}\npublic static T GetFirstAndConsume&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n if(source == null)\n throw new ArgumentNullException(&quot;source&quot;);\n using(var en = source.GetEnumerator())\n {\n if(!en.MoveNext())\n throw new InvalidOperationException(&quot;Empty sequence&quot;);\n T ret = en.Current;\n RunThroughEnumerator(en);\n return ret;\n }\n}\nprivate static void RunThroughEnumerator&lt;T&gt;(IEnumerator&lt;T&gt; en)\n{\n Debug.Assert(en != null);\n while(en.MoveNext());\n}\n</code></pre>\n<p>In the above, there are three different approaches to null parameters. The first accepts it as allowable (it just does nothing). The second throws an exception for the calling code to handle (or not, resulting in an error message). The third assumes it can't possibly happen, and asserts that it is so.</p>\n<p>In the first case, there's no problem.</p>\n<p>In the second case, there's a problem with the calling code - it shouldn't have called <code>GetFirstAndConsume</code> with null, so it gets an exception back.</p>\n<p>In the third case, there's a problem with this code, because it should already have been checked that <code>en != null</code> before it was ever called, so that it isn't true is a bug. Or in other words, it should be code that could theoretically be optimised to <code>Debug.Assert(true)</code>, sicne <code>en != null</code> should always be <code>true</code>!</p>\n" }, { "answer_id": 26407624, "author": "StuartLC", "author_id": 314291, "author_profile": "https://Stackoverflow.com/users/314291", "pm_score": 4, "selected": false, "text": "<p><strong>In Short</strong></p>\n<p><code>Asserts</code> are used for guards and for checking Design by Contract constraints, i.e. to ensure that the state of your code, objects, variables and parameters is operating <em><strong>within the boundaries and limits</strong></em> of your intended design.</p>\n<ul>\n<li><code>Asserts</code> should be for Debug and non-Production builds only. Asserts are typically ignored by the compiler in Release builds.</li>\n<li><code>Asserts</code> can check for bugs / unexpected conditions which ARE in the control of your system</li>\n<li><code>Asserts</code> are NOT a mechanism for first-line validation of user input or business rules</li>\n<li><code>Asserts</code> should <em>not</em> be used to detect unexpected environmental conditions (which are outside the control of the code) e.g. out of memory, network failure, database failure, etc. Although rare, these conditions are to be expected (and your app code cannot fix issues like hardware failure or resource exhaustion). Typically, exceptions will be thrown - your application can then either take corrective action (e.g. retry a database or network operation, attempt to free up cached memory), or abort gracefully if the exception cannot be handled.</li>\n<li>A failed Assertion should be fatal to your system - i.e. unlike an exception, do not try and catch or handle failed <code>Asserts</code> - your code is operating in unexpected territory. Stack Traces and crash dumps can be used to determine what went wrong.</li>\n</ul>\n<p>Assertions have enormous benefit:</p>\n<ul>\n<li>To assist in finding missing validation of user inputs, or upstream bugs in higher level code.</li>\n<li>Asserts in the code base clearly convey the assumptions made in the code to the reader</li>\n<li>Assert will be checked at runtime in <code>Debug</code> builds.</li>\n<li>Once code has been exhaustively tested, rebuilding the code as Release will remove the performance overhead of verifying the assumption (but with the benefit that a later Debug build will always revert the checks, if needed).</li>\n</ul>\n<p><strong>... More Detail</strong></p>\n<p><code>Debug.Assert</code> expresses a condition which has been assumed about state by the remainder of the code block within the control of the program. This can include the state of the provided parameters, state of members of a class instance, or that the return from a method call is in its contracted / designed range.\nTypically, asserts should crash the thread / process / program with all necessary info (Stack Trace, Crash Dump, etc), as they indicate the presence of a bug or unconsidered condition which has not been designed for (i.e. do not try and catch or handle assertion failures), with one possible exception of when an assertion itself could cause more damage than the bug (e.g. Air Traffic Controllers wouldn't want a YSOD when an aircraft goes submarine, although it is moot whether a debug build should be deployed to production ...)</p>\n<p>When should you use <code>Asserts?</code></p>\n<ul>\n<li>At any point in a system, or library API, or service where the inputs to a function or state of a class are assumed valid (e.g. when validation has already been done on user input in the presentation tier of a system, the business and data tier classes typically assume that null checks, range checks, string length checks etc on input have been already done).</li>\n<li>Common <code>Assert</code> checks include where an invalid assumption would result in a null object dereference, a zero divisor, numerical or date arithmetic overflow, and general out of band / not designed for behaviour (e.g. if a 32 bit int was used to model a human's age, it would be prudent to <code>Assert</code> that the age is actually between 0 and 125 or so - values of -100 and 10^10 were not designed for).</li>\n</ul>\n<p><strong>.Net Code Contracts</strong><br />\nIn the .Net Stack, <a href=\"http://research.microsoft.com/en-us/projects/contracts/\" rel=\"noreferrer\">Code Contracts</a> can be used <a href=\"https://stackoverflow.com/q/20603510/314291\">in addition to, or as an alternative to</a> using <code>Debug.Assert</code>. Code Contracts can further formalize state checking, and can assist in detecting violations of assumptions at ~compile time (or shortly thereafter, if run as a background check in an IDE).</p>\n<p>Design by Contract (DBC) checks available include:</p>\n<ul>\n<li><code>Contract.Requires</code> - Contracted Preconditions</li>\n<li><code>Contract.Ensures</code> - Contracted PostConditions</li>\n<li><code>Invariant</code> - Expresses an assumption about the state of an object at all points in its lifespan.</li>\n<li><code>Contract.Assumes</code> - pacifies the static checker when a call to non-Contract decorated methods is made.</li>\n</ul>\n" }, { "answer_id": 31746164, "author": "AlexDev", "author_id": 733760, "author_profile": "https://Stackoverflow.com/users/733760", "pm_score": 0, "selected": false, "text": "<p>I've read the answers here and I thought I should add an important distinction. There are two very different ways in which asserts are used. One is as a temporary developer shortcut for \"This shouldn't really happen so if it does let me know so I can decide what to do\", sort of like a conditional breakpoint, for cases in which your program is able to continue. The other, is a as a way to put assumptions about valid program states in your code.</p>\n\n<p>In the first case, the assertions don't even need to be in the final code. You should use <code>Debug.Assert</code> during development and you can remove them if/when no longer needed. If you want to leave them or if you forget to remove them no problem, since they won't have any consequence in Release compilations.</p>\n\n<p>But in the second case, the assertions are part of the code. They, well, assert, that your assumptions are true, and also document them. In that case, you really want to leave them in the code. If the program is in an invalid state it should not be allowed to continue. If you couldn't afford the performance hit you wouldn't be using C#. On one hand it might be useful to be able to attach a debugger if it happens. On the other, you don't want the stack trace popping up on your users and perhaps more important you don't want them to be able to ignore it. Besides, if it's in a service it will always be ignored. Therefore in production the correct behavior would be to throw an Exception, and use the normal exception handling of your program, which might show the user a nice message and log the details.</p>\n\n<p><code>Trace.Assert</code> has the perfect way to achieve this. It won't be removed in production, and can be configured with different listeners using app.config.\nSo for development the default handler is fine, and for production you can create a simple TraceListener like below which throws an exception and activate it in the production config file.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Diagnostics;\n\npublic class ExceptionTraceListener : DefaultTraceListener\n{\n [DebuggerStepThrough]\n public override void Fail(string message, string detailMessage)\n {\n throw new AssertException(message);\n }\n}\n\npublic class AssertException : Exception\n{\n public AssertException(string message) : base(message) { }\n}\n</code></pre>\n\n<p>And in the production config file:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;system.diagnostics&gt;\n &lt;trace&gt;\n &lt;listeners&gt;\n &lt;remove name=\"Default\"/&gt;\n &lt;add name=\"ExceptionListener\" type=\"Namespace.ExceptionTraceListener,AssemblyName\"/&gt;\n &lt;/listeners&gt;\n &lt;/trace&gt;\n &lt;/system.diagnostics&gt;\n</code></pre>\n" }, { "answer_id": 33784811, "author": "Teoman shipahi", "author_id": 929902, "author_profile": "https://Stackoverflow.com/users/929902", "pm_score": 2, "selected": false, "text": "<p>Quote Taken from <a href=\"https://rads.stackoverflow.com/amzn/click/com/020161622X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Pragmatic Programmer: From Journeyman to Master</a></p>\n\n<blockquote>\n <p><strong>Leave Assertions Turned On</strong></p>\n \n <p>There is a common misunderstanding about assertions, promulgated by\n the people who write compilers and language environments. It goes\n something like this:</p>\n \n <p>Assertions add some overhead to code. Because they check for things\n that should never happen, they'll get triggered only by a bug in the\n code. Once the code has been tested and shipped, they are no longer\n needed, and should be turned off to make the code run faster.\n Assertions are a debugging facility.</p>\n \n <p>There are two patently wrong assumptions here. First, they assume that\n testing finds all the bugs. In reality, for any complex program you\n are unlikely to test even a miniscule percentage of the permutations\n your code will be put through (see Ruthless Testing).</p>\n \n <p>Second, the optimists are forgetting that your program runs in a\n dangerous world. During testing, rats probably won't gnaw through a\n communications cable, someone playing a game won't exhaust memory, and\n log files won't fill the hard drive. These things might happen when\n your program runs in a production environment. Your first line of\n defense is checking for any possible error, and your second is using\n assertions to try to detect those you've missed.</p>\n \n <p><strong>Turning off assertions when you deliver a program to production is\n like crossing a high wire without a net because you once made it\n across in practice</strong>. There's dramatic value, but it's hard to get life\n insurance.</p>\n \n <p><strong>Even if you do have performance issues, turn off only those\n assertions that really hit you</strong>.</p>\n</blockquote>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at all until recently. Our production code contains no asserts whatsoever and my question is this... Should I begin using Asserts in our production code? And if so, When is its use most appropriate? Would it make more sense to do ``` Debug.Assert(val != null); ``` or ``` if ( val == null ) throw new exception(); ```
In [Debugging Microsoft .NET 2.0 Applications](https://rads.stackoverflow.com/amzn/click/com/0735622027) John Robbins has a big section on assertions. His main points are: 1. Assert liberally. You can never have too many assertions. 2. Assertions don't replace exceptions. Exceptions cover the things your code demands; assertions cover the things it assumes. 3. A well-written assertion can tell you not just what happened and where (like an exception), but why. 4. An exception message can often be cryptic, requiring you to work backwards through the code to recreate the context that caused the error. An assertion can preserve the program's state at the time the error occurred. 5. Assertions double as documentation, telling other developers what implied assumptions your code depends on. 6. The dialog that appears when an assertion fails lets you attach a debugger to the process, so you can poke around the stack as if you had put a breakpoint there. PS: If you liked Code Complete, I recommend following it up with this book. I bought it to learn about using WinDBG and dump files, but the first half is packed with tips to help avoid bugs in the first place.
129,133
<p>How do I view the SQL that is generated by nHibernate? version 1.2</p>
[ { "answer_id": 129138, "author": "Iain Holder", "author_id": 1122, "author_profile": "https://Stackoverflow.com/users/1122", "pm_score": 3, "selected": false, "text": "<p>Use sql server profiler.</p>\n\n<p>EDIT (1 year later): As @Toran Billups states below, the NHibernate profiler Ayende wrote is very very cool.</p>\n" }, { "answer_id": 129153, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 4, "selected": false, "text": "<p>In the configuration settings, set the \"show_sql\" property to true. \nThis will cause the SQL to be output in NHibernate's logfiles courtesy of log4net.</p>\n" }, { "answer_id": 129170, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 2, "selected": false, "text": "<p>There is a good reference for NHibernate logging at: <a href=\"http://www.nhforge.org/blogs/nhibernate/archive/2008/09/06/how-to-configure-log4net-for-use-with-nhibernate.aspx\" rel=\"nofollow noreferrer\">How to configure Log4Net for use with NHibernate</a>. It includes info on logging all NHibernate-generated SQL statements.</p>\n" }, { "answer_id": 129818, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 6, "selected": true, "text": "<p>You can put something like this in your app.config/web.config file :</p>\n\n<p>in the configSections node :</p>\n\n<pre><code>&lt;section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\"/&gt;\n</code></pre>\n\n<p>in the configuration node :</p>\n\n<pre><code>&lt;log4net&gt;\n &lt;appender name=\"NHibernateFileLog\" type=\"log4net.Appender.FileAppender\"&gt;\n &lt;file value=\"logs/nhibernate.txt\" /&gt;\n &lt;appendToFile value=\"false\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n &lt;logger name=\"NHibernate.SQL\" additivity=\"false\"&gt;\n &lt;level value=\"DEBUG\"/&gt;\n &lt;appender-ref ref=\"NHibernateFileLog\"/&gt;\n &lt;/logger&gt;\n&lt;/log4net&gt;\n</code></pre>\n\n<p>And don't forget to call </p>\n\n<pre><code>log4net.Config.XmlConfigurator.Configure();\n</code></pre>\n\n<p>at the startup of your application, or to put </p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(Watch=true)]\n</code></pre>\n\n<p>in the assemblyinfo.cs</p>\n\n<p>In the configuration settings, set the \"show_sql\" property to true.</p>\n" }, { "answer_id": 1555098, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://nhprof.com/\" rel=\"nofollow noreferrer\">Nhibernate Profiler</a> is an option, if you have to do anything serious.</p>\n" }, { "answer_id": 1555114, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 3, "selected": false, "text": "<p>You can also try <a href=\"http://nhprof.com/\" rel=\"noreferrer\">NHibernate Profiler</a> (30 day trial if nothing else). This tool is the best around IMHO.</p>\n\n<p>This will not only show the SQL generated but also warnings/suggestions/etc</p>\n" }, { "answer_id": 25065892, "author": "Big McLargeHuge", "author_id": 1015595, "author_profile": "https://Stackoverflow.com/users/1015595", "pm_score": 1, "selected": false, "text": "<p>If you're using SQL Server (not Express), you can try SQL Server Profiler.</p>\n" }, { "answer_id": 36732969, "author": "Alexander", "author_id": 1456567, "author_profile": "https://Stackoverflow.com/users/1456567", "pm_score": 5, "selected": false, "text": "<p>I am a bit late I know, but this does the trick and it is tool/db/framework independent.\nInstead of those valid options, I use <a href=\"http://nhibernate.info/doc/nhibernate-reference/events.html\" rel=\"noreferrer\">NH Interceptors</a>.</p>\n<p>At first, implement a class which extends <strong>NHibernate.EmptyInterceptor</strong> and implements <strong>NHibernate.IInterceptor</strong>:</p>\n<pre><code>using NHibernate;\n\nnamespace WebApplication2.Infrastructure\n{\n public class SQLDebugOutput : EmptyInterceptor, IInterceptor\n {\n public override NHibernate.SqlCommand.SqlString\n OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)\n {\n System.Diagnostics.Debug.WriteLine(&quot;NH: &quot; + sql);\n\n return base.OnPrepareStatement(sql);\n }\n }\n}\n</code></pre>\n<p>Then, just pass an instance when you open your session. Be sure to do it only when in DEBUG:</p>\n<pre><code>public static void OpenSession() {\n\n#if DEBUG\n HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession(new SQLDebugOutput());\n\n#else\n HttpContext.Current.Items[SessionKey] = _sessionFactory.OpenSession();\n \n#endif\n}\n</code></pre>\n<p>And that's it.</p>\n<p>From now on, your sql commands like these...</p>\n<pre><code> var totalPostsCount = Database.Session.Query&lt;Post&gt;().Count();\n \n var currentPostPage = Database.Session.Query&lt;Post&gt;()\n .OrderByDescending(c =&gt; c.CreatedAt)\n .Skip((page - 1) * PostsPerPage)\n .Take(PostsPerPage)\n .ToList();\n</code></pre>\n<p>.. are shown straight in your Output window:</p>\n<blockquote>\n<p>NH: select cast(count(*) as INT) as col_0_0_ from posts post0_</p>\n<p>NH:select post0_.Id as Id3_, post0_.user_id as user2_3_, post0_.Title as\nTitle3_, post0_.Slug as Slug3_, post0_.Content as Content3_,\npost0_.created_at as created6_3_, post0_.updated_at as updated7_3_,\npost0_.deleted_at as deleted8_3_ from posts post0_ order by\npost0_.created_at desc limit ? offset ?</p>\n</blockquote>\n" }, { "answer_id": 62440063, "author": "Formalist", "author_id": 12154974, "author_profile": "https://Stackoverflow.com/users/12154974", "pm_score": 0, "selected": false, "text": "<p>Or, if you want to show the SQL of a specific query, use the following method (slightly altered version of what suggested <a href=\"https://weblogs.asp.net/ricardoperes/getting-the-sql-from-a-linq-query-in-nhibernate\" rel=\"nofollow noreferrer\">here</a> by <a href=\"https://about.me/rjperes\" rel=\"nofollow noreferrer\">Ricardo Peres</a>) :</p>\n\n<pre><code>private String NHibernateSql(IQueryable queryable)\n{\n var prov = queryable.Provider as DefaultQueryProvider;\n var session = prov.Session as ISession;\n\n var sessionImpl = session.GetSessionImplementation();\n var factory = sessionImpl.Factory;\n var nhLinqExpression = new NhLinqExpression(queryable.Expression, factory);\n var translatorFactory = new NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory();\n var translator = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).First();\n var sql = translator.SQLString;\n\n var parameters = nhLinqExpression.ParameterValuesByName;\n if ( (parameters?.Count ?? 0) &gt; 0)\n {\n sql += \"\\r\\n\\r\\n-- Parameters:\\r\\n\";\n foreach (var par in parameters)\n {\n sql += \"-- \" + par.Key.ToString() + \" - \" + par.Value.ToString() + \"\\r\\n\";\n }\n }\n\n return sql;\n}\n</code></pre>\n\n<p>and pass to it a <code>NHibernate</code> query, i.e.</p>\n\n<pre><code>var query = from a in session.Query&lt;MyRecord&gt;()\n where a.Id == \"123456\" \n orderby a.Name\n select a;\n\nvar sql = NHibernateSql(query);\n</code></pre>\n" }, { "answer_id": 65579330, "author": "Amit Joshi", "author_id": 5779732, "author_profile": "https://Stackoverflow.com/users/5779732", "pm_score": 0, "selected": false, "text": "<p>You are asking only for viewing; but this answer explains how to log it to file. Once logged, you can view it in any text editor.</p>\n<p>Latest versions of NHibernate support enabling logging through code. Following is the sample code that demonstrates this. Please read the comments for better understanding.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Configuration configuration = new Configuration();\n\nconfiguration.SetProperty(NHibernate.Cfg.Environment.Dialect, ......);\n//Set other configuration.SetProperty as per need\nconfiguration.SetProperty(NHibernate.Cfg.Environment.ShowSql, &quot;true&quot;); //Enable ShowSql\nconfiguration.SetProperty(NHibernate.Cfg.Environment.FormatSql, &quot;true&quot;); //Enable FormatSql to make the log readable; optional.\n\nconfiguration.AddMapping(......);\nconfiguration.BuildMappings();\n\nISessionFactory sessionFactory = configuration.BuildSessionFactory();\n\n//ISessionFactory is setup so far. Now, configure logging.\nHierarchy hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly());\nhierarchy.Root.RemoveAllAppenders();\n\nFileAppender fileAppender = new FileAppender();\nfileAppender.Name = &quot;NHFileAppender&quot;;\nfileAppender.File = logFilePath;\nfileAppender.AppendToFile = true;\nfileAppender.LockingModel = new FileAppender.MinimalLock();\nfileAppender.Layout = new PatternLayout(&quot;%d{yyyy-MM-dd HH:mm:ss}:%m%n%n&quot;);\nfileAppender.ActivateOptions();\n\nLogger logger = hierarchy.GetLogger(&quot;NHibernate.SQL&quot;) as Logger;\nlogger.Additivity = false;\nlogger.Level = Level.Debug;\nlogger.AddAppender(fileAppender);\n\nhierarchy.Configured = true;\n</code></pre>\n<p>You can further play with <code>FileAppender</code> and <code>Logger</code> as per your need. Please refer to <a href=\"https://stackoverflow.com/a/54182578/5779732\">this</a> answer and <a href=\"https://nhibernate.info/doc/howto/various/configure-log4net-for-use-with-nhibernate\" rel=\"nofollow noreferrer\">this</a> resource for more details. This explains the same with XML configuration; but the same should equally apply to code.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642688/" ]
How do I view the SQL that is generated by nHibernate? version 1.2
You can put something like this in your app.config/web.config file : in the configSections node : ``` <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> ``` in the configuration node : ``` <log4net> <appender name="NHibernateFileLog" type="log4net.Appender.FileAppender"> <file value="logs/nhibernate.txt" /> <appendToFile value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" /> </layout> </appender> <logger name="NHibernate.SQL" additivity="false"> <level value="DEBUG"/> <appender-ref ref="NHibernateFileLog"/> </logger> </log4net> ``` And don't forget to call ``` log4net.Config.XmlConfigurator.Configure(); ``` at the startup of your application, or to put ``` [assembly: log4net.Config.XmlConfigurator(Watch=true)] ``` in the assemblyinfo.cs In the configuration settings, set the "show\_sql" property to true.
129,144
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> <p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p> <p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p> <p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</p>
[ { "answer_id": 129172, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>If they're simple one-line commands, you can wrap them in <code>lambda</code>s:</p>\n\n<pre><code>for cmd in [\n (lambda: foo (a, b)),\n (lambda: bar (c, d)),\n]:\n try:\n cmd ()\n except StandardError, e:\n baz (e)\n</code></pre>\n\n<p>You could wrap that whole thing up in a function, so it looked like this:</p>\n\n<pre><code>ignore_errors (baz, [\n (lambda: foo (a, b)),\n (lambda: bar (c, d)),\n])\n</code></pre>\n" }, { "answer_id": 129174, "author": "Sufian", "author_id": 9241, "author_profile": "https://Stackoverflow.com/users/9241", "pm_score": 2, "selected": false, "text": "<p>The best approach I have found, is to define a function like such:</p>\n\n<pre><code>def handle_exception(function, reaction, *args, **kwargs):\n try:\n result = function(*args, **kwargs)\n except Exception, e:\n result = reaction(e)\n return result\n</code></pre>\n\n<p>But that just doesn't feel or look right in practice:</p>\n\n<pre><code>handle_exception(foo, baz, a, b)\nhandle_exception(bar, baz, c, d)\n</code></pre>\n" }, { "answer_id": 129176, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": -1, "selected": false, "text": "<p>In your specific case, you can do this:</p>\n\n<pre><code>try:\n foo(a, b)\n bar(c, d)\nexcept Exception, e:\n baz(e)\n</code></pre>\n\n<p>Or, you can catch the exception one step above:</p>\n\n<pre><code>try:\n foo_bar() # This function can throw at several places\nexcept Exception, e:\n baz(e)\n</code></pre>\n" }, { "answer_id": 129177, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 7, "selected": true, "text": "<p>You could use the <a href=\"https://www.python.org/dev/peps/pep-0343/\" rel=\"noreferrer\"><code>with</code> statement</a> if you have python 2.5 or above:</p>\n\n<pre><code>from __future__ import with_statement\nimport contextlib\n\[email protected]\ndef handler():\n try:\n yield\n except Exception, e:\n baz(e)\n</code></pre>\n\n<p>Your example now becomes:</p>\n\n<pre><code>with handler():\n foo(a, b)\nwith handler():\n bar(c, d)\n</code></pre>\n" }, { "answer_id": 129626, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>You could try something like this. This is vaguely C macro-like.</p>\n\n<pre><code>class TryOrBaz( object ):\n def __init__( self, that ):\n self.that= that\n def __call__( self, *args ):\n try:\n return self.that( *args )\n except Exception, e:\n baz( e )\n\nTryOrBaz( foo )( a, b )\nTryOrBaz( bar )( c, d )\n</code></pre>\n" }, { "answer_id": 133336, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "<p>If this is always, <em>always</em> the behaviour you want when a particular function raises an exception, you could use a decorator:</p>\n\n<pre><code>def handle_exception(handler):\n def decorate(func):\n def call_function(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception, e:\n handler(e)\n return call_function\n return decorate\n\ndef baz(e):\n print(e)\n\n@handle_exception(baz)\ndef foo(a, b):\n return a + b\n\n@handle_exception(baz)\ndef bar(c, d):\n return c.index(d)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt;&gt;&gt; foo(1, '2')\nunsupported operand type(s) for +: 'int' and 'str'\n&gt;&gt;&gt; bar('steve', 'cheese')\nsubstring not found\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9241/" ]
Sometimes I find myself in the situation where I want to execute several sequential commands like such: ``` try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... ``` This same pattern occurs when exceptions simply need to be ignored. This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code. In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python. Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?
You could use the [`with` statement](https://www.python.org/dev/peps/pep-0343/) if you have python 2.5 or above: ``` from __future__ import with_statement import contextlib @contextlib.contextmanager def handler(): try: yield except Exception, e: baz(e) ``` Your example now becomes: ``` with handler(): foo(a, b) with handler(): bar(c, d) ```
129,157
<p>I've encountered a problem when retrieving a JSONP response from a server in a different domain using IE6.</p> <p>When I make the same AJAX call using JSONP to a server in the same domain as the web page, all goes well in all browsers (including IE6). However, when I make calls between domains (XSS) using JSONP, Internet Explorer 6 locks up. Specifically, the CPU spikes to 100% and the 'success' callback is never reached. The only time I have had success going between domains is when the response is very short (less than 150 bytes typically). The length of the response seems important.</p> <p>I'm using jQuery 1.2.6. I've tried the $.getJSON() method and the $.ajax(dataType: "jsonp") method without success. This works beautifully in FF3 and IE7. I haven't been able to find anyone else with a similar problem. I thought this type of functionality was fully supported by jQuery in IE6.</p> <p>Any help is very appreciated,</p> <p>Andrew</p> <hr> <p><strong>Here is the code for the html page making the AJAX call</strong>. Make a local copy of this file (and jquery library) and give it a shot using IE6. For me, it always causes the CPU to spike with no response rendered.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head&gt; &lt;title&gt;Untitled Page&lt;/title&gt; &lt;script type="text/javascript" src="Scripts/jquery-1.2.6.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://devhubplus/portal/search.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="javascript:test1(500, 'wikiResults');"&gt;Test&lt;/a&gt; &lt;div id="wikiResults" style="margin-top: 35px;"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; function test1(count, targetId) { var dataSourceUrl = "http://code.katzenbach.com/Default.aspx?callback=?"; $.getJSON(dataSourceUrl, {c: count, test: "true", nt: new Date().getTime()}, function(results) { var response = new String(); response += "&lt;div&gt;"; for(i in results) { response += results[i]; response += " "; } response += "&lt;/div&gt;"; $("#" + targetId).html(response); }); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is the JSON that comes back in the response. According to JSLint, it is valid JSON (once you remove the method call surrounding it). The real results would be different, but this seemed like that simplest example that would cause this to fail. The server is a ASP.Net application returning a response of type 'application/json.' I've tried changing the response type to 'application/javascript' and 'application/x-javascript' but it didn't have any affect. I really appreciate the help.</p> <pre><code>jsonp1222350625589(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18" ,"19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38" ,"39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58" ,"59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78" ,"79","80","81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97","98" ,"99","100","101","102","103","104","105","106","107","108","109","110","111","112","113","114","115" ,"116","117","118","119","120","121","122","123","124","125","126","127","128","129","130","131","132" ,"133","134","135","136","137","138","139","140","141","142","143","144","145","146","147","148","149" ,"150","151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166" ,"167","168","169","170","171","172","173","174","175","176","177","178","179","180","181","182","183" ,"184","185","186","187","188","189","190","191","192","193","194","195","196","197","198","199","200" ,"201","202","203","204","205","206","207","208","209","210","211","212","213","214","215","216","217" ,"218","219","220","221","222","223","224","225","226","227","228","229","230","231","232","233","234" ,"235","236","237","238","239","240","241","242","243","244","245","246","247","248","249","250","251" ,"252","253","254","255","256","257","258","259","260","261","262","263","264","265","266","267","268" ,"269","270","271","272","273","274","275","276","277","278","279","280","281","282","283","284","285" ,"286","287","288","289","290","291","292","293","294","295","296","297","298","299","300","301","302" ,"303","304","305","306","307","308","309","310","311","312","313","314","315","316","317","318","319" ,"320","321","322","323","324","325","326","327","328","329","330","331","332","333","334","335","336" ,"337","338","339","340","341","342","343","344","345","346","347","348","349","350","351","352","353" ,"354","355","356","357","358","359","360","361","362","363","364","365","366","367","368","369","370" ,"371","372","373","374","375","376","377","378","379","380","381","382","383","384","385","386","387" ,"388","389","390","391","392","393","394","395","396","397","398","399","400","401","402","403","404" ,"405","406","407","408","409","410","411","412","413","414","415","416","417","418","419","420","421" ,"422","423","424","425","426","427","428","429","430","431","432","433","434","435","436","437","438" ,"439","440","441","442","443","444","445","446","447","448","449","450","451","452","453","454","455" ,"456","457","458","459","460","461","462","463","464","465","466","467","468","469","470","471","472" ,"473","474","475","476","477","478","479","480","481","482","483","484","485","486","487","488","489" ,"490","491","492","493","494","495","496","497","498","499"]) </code></pre>
[ { "answer_id": 132005, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 0, "selected": false, "text": "<p>Does you json validate at <a href=\"http://www.jslint.com\" rel=\"nofollow noreferrer\">jslint</a>?\nIf you have a ur and include the full jquery lib I can debug it for you or post the json and I can try to recreate the issue. Just from the info given it is quite hard to tell.\nI have seen some odd things before with the actual names of the keys in the json which breaks on ie6.</p>\n" }, { "answer_id": 151813, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>May be completely unrelated but I have just discovered that in IE6, when code is initiated from an onclick event handler, a JSONP callback may never execute.</p>\n\n<p>The fix for this issue is to attach the code via an HREF instead of the click event.</p>\n" }, { "answer_id": 175461, "author": "J5.", "author_id": 25380, "author_profile": "https://Stackoverflow.com/users/25380", "pm_score": 0, "selected": false, "text": "<p>Have you tried mime-type: application/x-javascript?</p>\n" }, { "answer_id": 204281, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 4, "selected": true, "text": "<p>you're not going to like this response so much, but I'm convinced it's on your server side.</p>\n\n<p>Here's why:</p>\n\n<p>I've recreated your scenario and when I run with your JSONP responder I get IE6 hanging, as you've explained.</p>\n\n<p>However, when I change the JSONP responder to my own code (exactly the same output as you've give above) it works without any issue (in all browsers, but particularly IE6).</p>\n\n<p>Here's the example I mocked together:</p>\n\n<p><a href=\"http://jsbin.com/udako\" rel=\"noreferrer\">http://jsbin.com/udako</a> (to edit <a href=\"http://jsbin.com/udako/edit\" rel=\"noreferrer\">http://jsbin.com/udako/edit</a>)</p>\n\n<p>The callback is hitting <a href=\"http://jsbin.com/rs.php?callback=\" rel=\"noreferrer\">http://jsbin.com/rs.php?callback=</a>?</p>\n\n<p>Small note - I initially suspected the string length: I've read that strings in IE have a maxlength of ~1Mb which is what you were hitting (I'm not 100% sure if this is accurate), but I changed the concatenation to an array push - which is generally faster anyway.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21832/" ]
I've encountered a problem when retrieving a JSONP response from a server in a different domain using IE6. When I make the same AJAX call using JSONP to a server in the same domain as the web page, all goes well in all browsers (including IE6). However, when I make calls between domains (XSS) using JSONP, Internet Explorer 6 locks up. Specifically, the CPU spikes to 100% and the 'success' callback is never reached. The only time I have had success going between domains is when the response is very short (less than 150 bytes typically). The length of the response seems important. I'm using jQuery 1.2.6. I've tried the $.getJSON() method and the $.ajax(dataType: "jsonp") method without success. This works beautifully in FF3 and IE7. I haven't been able to find anyone else with a similar problem. I thought this type of functionality was fully supported by jQuery in IE6. Any help is very appreciated, Andrew --- **Here is the code for the html page making the AJAX call**. Make a local copy of this file (and jquery library) and give it a shot using IE6. For me, it always causes the CPU to spike with no response rendered. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type="text/javascript" src="Scripts/jquery-1.2.6.min.js"></script> <script type="text/javascript" src="http://devhubplus/portal/search.js"></script> </head> <body> <a href="javascript:test1(500, 'wikiResults');">Test</a> <div id="wikiResults" style="margin-top: 35px;"></div> <script type="text/javascript"> function test1(count, targetId) { var dataSourceUrl = "http://code.katzenbach.com/Default.aspx?callback=?"; $.getJSON(dataSourceUrl, {c: count, test: "true", nt: new Date().getTime()}, function(results) { var response = new String(); response += "<div>"; for(i in results) { response += results[i]; response += " "; } response += "</div>"; $("#" + targetId).html(response); }); } </script> </body> </html> ``` Here is the JSON that comes back in the response. According to JSLint, it is valid JSON (once you remove the method call surrounding it). The real results would be different, but this seemed like that simplest example that would cause this to fail. The server is a ASP.Net application returning a response of type 'application/json.' I've tried changing the response type to 'application/javascript' and 'application/x-javascript' but it didn't have any affect. I really appreciate the help. ``` jsonp1222350625589(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18" ,"19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38" ,"39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58" ,"59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78" ,"79","80","81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97","98" ,"99","100","101","102","103","104","105","106","107","108","109","110","111","112","113","114","115" ,"116","117","118","119","120","121","122","123","124","125","126","127","128","129","130","131","132" ,"133","134","135","136","137","138","139","140","141","142","143","144","145","146","147","148","149" ,"150","151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166" ,"167","168","169","170","171","172","173","174","175","176","177","178","179","180","181","182","183" ,"184","185","186","187","188","189","190","191","192","193","194","195","196","197","198","199","200" ,"201","202","203","204","205","206","207","208","209","210","211","212","213","214","215","216","217" ,"218","219","220","221","222","223","224","225","226","227","228","229","230","231","232","233","234" ,"235","236","237","238","239","240","241","242","243","244","245","246","247","248","249","250","251" ,"252","253","254","255","256","257","258","259","260","261","262","263","264","265","266","267","268" ,"269","270","271","272","273","274","275","276","277","278","279","280","281","282","283","284","285" ,"286","287","288","289","290","291","292","293","294","295","296","297","298","299","300","301","302" ,"303","304","305","306","307","308","309","310","311","312","313","314","315","316","317","318","319" ,"320","321","322","323","324","325","326","327","328","329","330","331","332","333","334","335","336" ,"337","338","339","340","341","342","343","344","345","346","347","348","349","350","351","352","353" ,"354","355","356","357","358","359","360","361","362","363","364","365","366","367","368","369","370" ,"371","372","373","374","375","376","377","378","379","380","381","382","383","384","385","386","387" ,"388","389","390","391","392","393","394","395","396","397","398","399","400","401","402","403","404" ,"405","406","407","408","409","410","411","412","413","414","415","416","417","418","419","420","421" ,"422","423","424","425","426","427","428","429","430","431","432","433","434","435","436","437","438" ,"439","440","441","442","443","444","445","446","447","448","449","450","451","452","453","454","455" ,"456","457","458","459","460","461","462","463","464","465","466","467","468","469","470","471","472" ,"473","474","475","476","477","478","479","480","481","482","483","484","485","486","487","488","489" ,"490","491","492","493","494","495","496","497","498","499"]) ```
you're not going to like this response so much, but I'm convinced it's on your server side. Here's why: I've recreated your scenario and when I run with your JSONP responder I get IE6 hanging, as you've explained. However, when I change the JSONP responder to my own code (exactly the same output as you've give above) it works without any issue (in all browsers, but particularly IE6). Here's the example I mocked together: <http://jsbin.com/udako> (to edit <http://jsbin.com/udako/edit>) The callback is hitting <http://jsbin.com/rs.php?callback=>? Small note - I initially suspected the string length: I've read that strings in IE have a maxlength of ~1Mb which is what you were hitting (I'm not 100% sure if this is accurate), but I changed the concatenation to an array push - which is generally faster anyway.
129,160
<p>The resource definition in tomcat's <code>server.xml</code> looks something like this...</p> <pre class="lang-xml prettyprint-override"><code>&lt;Resource name="jdbc/tox" scope="Shareable" type="javax.sql.DataSource" url="jdbc:oracle:thin:@yourDBserver.yourCompany.com:1521:yourDBsid" driverClassName="oracle.jdbc.pool.OracleDataSource" username="tox" password="toxbaby" maxIdle="3" maxActive="10" removeAbandoned="true" removeAbandonedTimeout="60" testOnBorrow="true" validationQuery="select * from dual" logAbandoned="true" debug="99"/&gt; </code></pre> <p>The password is in the clear. How to avoid this?</p>
[ { "answer_id": 129268, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": -1, "selected": false, "text": "<p>We use C#'s SHA1CryptoServiceProvider </p>\n\n<pre><code>print(SHA1CryptoServiceProvider sHA1Hasher = new SHA1CryptoServiceProvider();\n ASCIIEncoding enc = new ASCIIEncoding();\n\n byte[] arrbytHashValue = sHA1Hasher.ComputeHash(enc.GetBytes(clearTextPW));\n string HashData = System.BitConverter.ToString(arrbytHashValue);\n HashData = HashData.Replace(\"-\", \"\");\n if (HashData == databaseHashedPassWO)\n {\n return true;\n }\n else\n {\n return false;\n });\n</code></pre>\n\n<p>)</p>\n" }, { "answer_id": 140358, "author": "gameame", "author_id": 6259, "author_profile": "https://Stackoverflow.com/users/6259", "pm_score": 2, "selected": false, "text": "<p>Tomcat needs to know how to connect to the database, so it needs access to the plain text password. If the password in encrypted, Tomcat needs to know how to decrypt it, so you are only moving the problem somewhere else.</p>\n\n<p>The real problem is: who can access <code>server.xml</code> except for Tomcat? A solution is to give read access to <code>server.xml</code> only to root user, requiring that Tomcat is started with root privileges: if a malicious user gains root privileges on the system, losing a database password is probably a minor concern.</p>\n\n<p>Otherwise you should type the password manually at every startup, but this is seldom a viable option.</p>\n" }, { "answer_id": 355758, "author": "Jerome Delattre", "author_id": 27762, "author_profile": "https://Stackoverflow.com/users/27762", "pm_score": 5, "selected": false, "text": "<p>As said before encrypting passwords is just moving the problem somewhere else.</p>\n\n<p>Anyway, it's quite simple.\nJust write a class with static fields for your secret key and so on, and static methods to encrypt, decrypt your passwords.\nEncrypt your password in Tomcat's configuration file (<code>server.xml</code> or <code>yourapp.xml</code>...) using this class.</p>\n\n<p>And to decrypt the password \"on the fly\" in Tomcat, extend the DBCP's <code>BasicDataSourceFactory</code> and use this factory in your resource.</p>\n\n<p>It will look like:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> &lt;Resource\n name=\"jdbc/myDataSource\"\n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n username=\"user\"\n password=\"encryptedpassword\"\n driverClassName=\"driverClass\"\n factory=\"mypackage.MyCustomBasicDataSourceFactory\"\n url=\"jdbc:blabla://...\"/&gt;\n</code></pre>\n\n<p>And for the custom factory:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>package mypackage;\n\n....\n\npublic class MyCustomBasicDataSourceFactory extends org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory {\n\n@Override\npublic Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {\n Object o = super.getObjectInstance(obj, name, nameCtx, environment);\n if (o != null) {\n BasicDataSource ds = (BasicDataSource) o;\n if (ds.getPassword() != null &amp;&amp; ds.getPassword().length() &gt; 0) {\n String pwd = MyPasswordUtilClass.unscramblePassword(ds.getPassword());\n ds.setPassword(pwd);\n }\n return ds;\n } else {\n return null;\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 30856697, "author": "Ryan", "author_id": 249623, "author_profile": "https://Stackoverflow.com/users/249623", "pm_score": 4, "selected": false, "text": "<p>Tomcat has <a href=\"https://cwiki.apache.org/confluence/display/TOMCAT/Password\" rel=\"nofollow noreferrer\">a Password FAQ</a> that specifically addresses your question. In short: Keep the password in the clear and properly lock-down your server.</p>\n\n<p>That page also offers some suggestions of how security-by-obscurity might be used to pass an auditor's checklist.</p>\n" }, { "answer_id": 39298913, "author": "JustinKSU", "author_id": 724835, "author_profile": "https://Stackoverflow.com/users/724835", "pm_score": 2, "selected": false, "text": "<p>As @Ryan mentioned, please read Tomcat's <a href=\"https://cwiki.apache.org/confluence/display/TOMCAT/Password\" rel=\"nofollow noreferrer\">Tomcat Password FAQ</a> before implementing this solution. You are only adding obscurity not security.</p>\n\n<p>@Jerome Delattre's answer will work for simple JDBC data sources, but not for more complicated ones that connect as part of the datasource construction (e.g. oracle.jdbc.xa.client.OracleXADataSource).</p>\n\n<p>This is alternative approach that modifies the password prior to calling the existing factory. Below is an example of a factory for a basic datasource and one for an Atomikos JTA compatible XA datasource.</p>\n\n<p>Basic Example:</p>\n\n<pre><code>public class MyEncryptedPasswordFactory extends BasicDataSourceFactory {\n\n @Override\n public Object getObjectInstance(Object obj, Name name, Context context, Hashtable&lt;?, ?&gt; environment)\n throws Exception {\n if (obj instanceof Reference) {\n Reference ref = (Reference) obj;\n DecryptPasswordUtil.replacePasswordWithDecrypted(ref, \"password\");\n return super.getObjectInstance(obj, name, context, environment);\n } else {\n throw new IllegalArgumentException(\n \"Expecting javax.naming.Reference as object type not \" + obj.getClass().getName());\n }\n }\n}\n</code></pre>\n\n<p>Atomikos Example:</p>\n\n<pre><code>public class MyEncryptedAtomikosPasswordFactory extends EnhancedTomcatAtomikosBeanFactory {\n @Override\n public Object getObjectInstance(Object obj, Name name, Context context, Hashtable&lt;?, ?&gt; environment)\n throws NamingException {\n if (obj instanceof Reference) {\n Reference ref = (Reference) obj;\n DecryptPasswordUtil.replacePasswordWithDecrypted(ref, \"xaProperties.password\");\n return super.getObjectInstance(obj, name, context, environment);\n } else {\n throw new IllegalArgumentException(\n \"Expecting javax.naming.Reference as object type not \" + obj.getClass().getName());\n }\n }\n}\n</code></pre>\n\n<p>Updating password value in Reference:</p>\n\n<pre><code>public class DecryptPasswordUtil {\n\n public static void replacePasswordWithDecrypted(Reference reference, String passwordKey) {\n if(reference == null) {\n throw new IllegalArgumentException(\"Reference object must not be null\");\n }\n\n // Search for password addr and replace with decrypted\n for (int i = 0; i &lt; reference.size(); i++) {\n RefAddr addr = reference.get(i);\n if (passwordKey.equals(addr.getType())) {\n if (addr.getContent() == null) {\n throw new IllegalArgumentException(\"Password must not be null for key \" + passwordKey);\n }\n String decrypted = yourDecryptionMethod(addr.getContent().toString());\n reference.remove(i);\n reference.add(i, new StringRefAddr(passwordKey, decrypted));\n break;\n }\n }\n }\n}\n</code></pre>\n\n<p>Once the .jar file containing these classes are in Tomcat's classpath you can update your server.xml to use them.</p>\n\n<pre><code>&lt;Resource factory=\"com.mycompany.MyEncryptedPasswordFactory\" username=\"user\" password=\"encryptedPassword\" ...other options... /&gt;\n\n&lt;Resource factory=\"com.mycompany.MyEncryptedAtomikosPasswordFactory\" type=\"com.atomikos.jdbc.AtomikosDataSourceBean\" xaProperties.user=\"user\" xaProperties.password=\"encryptedPassword\" ...other options... /&gt;\n</code></pre>\n" }, { "answer_id": 39302160, "author": "stuartw", "author_id": 1319814, "author_profile": "https://Stackoverflow.com/users/1319814", "pm_score": -1, "selected": false, "text": "<p>All of the foregoing having been said, if you still want to avoid plain text passwords you can use a hashing algorithm such as SHA-256 or (preferably) SHA-512. When a password is created, obtain the hashed value and store it rather than the password. When a user logs in, hash the password and see of it matches the stored hashed password.\nHashing algorithms take a character string (or number) from a small string (or number) space into a much larger one in a way that is expensive to reverse.</p>\n" }, { "answer_id": 48179892, "author": "HolloW", "author_id": 752900, "author_profile": "https://Stackoverflow.com/users/752900", "pm_score": 2, "selected": false, "text": "<p>After 4 hours of work, search questions and answers I got the solution.\nBased on the answer by @Jerome Delattre here is the complete code (with the JNDI Data source configuration).</p>\n\n<p>Context.xml</p>\n\n<pre><code>&lt;Resource\n name=\"jdbc/myDataSource\"\n auth=\"Container\"\n type=\"javax.sql.DataSource\"\n username=\"user\"\n password=\"encryptedpassword\"\n driverClassName=\"driverClass\"\n factory=\"mypackage.MyCustomBasicDataSourceFactory\"\n url=\"jdbc:blabla://...\"/&gt;\n</code></pre>\n\n<p>Custom Data Source Factory:</p>\n\n<pre><code>package mypackage;\n\npublic class MyCustomBasicDataSourceFactory extends org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory {\n @Override\n public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {\n Object o = super.getObjectInstance(obj, name, nameCtx, environment);\n if (o != null) {\n BasicDataSource ds = (BasicDataSource) o;\n if (ds.getPassword() != null &amp;&amp; ds.getPassword().length() &gt; 0) {\n String pwd = MyPasswordUtilClass.unscramblePassword(ds.getPassword());\n ds.setPassword(pwd);\n }\n return ds;\n } else {\n return null;\n }\n }\n}\n</code></pre>\n\n<p>Data source bean:</p>\n\n<pre><code>@Bean\npublic DataSource dataSource() {\n DataSource ds = null;\n JndiTemplate jndi = new JndiTemplate();\n try {\n ds = jndi.lookup(\"java:comp/env/jdbc/myDataSource\", DataSource.class);\n } catch (NamingException e) {\n log.error(\"NamingException for java:comp/env/jdbc/myDataSource\", e);\n }\n return ds;\n}\n</code></pre>\n" }, { "answer_id": 50167074, "author": "Gawri Edussuriya", "author_id": 9738900, "author_profile": "https://Stackoverflow.com/users/9738900", "pm_score": 2, "selected": false, "text": "<p><strong>Note:</strong> </p>\n\n<p>You can use <strong>WinDPAPI</strong> to encrypt and decrypt data</p>\n\n<pre><code>public class MyDataSourceFactory extends DataSourceFactory{\n\nprivate static WinDPAPI winDPAPI;\n\nprotected static final String DATA_SOURCE_FACTORY_PROP_PASSWORD = \"password\";\n\n@Override\npublic Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception{\n\n Reference ref = (Reference) obj;\n for (int i = 0; i &lt; ref.size(); i++) {\n RefAddr ra = ref.get(i);\n if (ra.getType().equals(DATA_SOURCE_FACTORY_PROP_PASSWORD)) {\n\n if (ra.getContent() != null &amp;&amp; ra.getContent().toString().length() &gt; 0) {\n String pwd = getUnprotectedData(ra.getContent().toString());\n ref.remove(i);\n ref.add(i, new StringRefAddr(DATA_SOURCE_FACTORY_PROP_PASSWORD, pwd));\n }\n\n break;\n }\n }\n\n return super.getObjectInstance(obj, name, nameCtx, environment);\n }\n}\n</code></pre>\n" }, { "answer_id": 63037815, "author": "Ricardo van den Broek", "author_id": 2348375, "author_profile": "https://Stackoverflow.com/users/2348375", "pm_score": 0, "selected": false, "text": "<p><strong>Problem</strong>: As pointed out, encrypting credentials in context.xml while storing the decryption key in the next file over is literally only moving the problem. Since the user accessing context.xml will also need access to the decryption key, all credentials are still compromised if the application or the OS user is compromised.</p>\n<p><strong>Solution</strong>: The only solution that would add security is one that completely removes the decryption key from the entire setup. This could be achieved by requiring someone to type a password in your application on startup which is then used to decrypt all credentials.</p>\n<p><strong>Further deferral of solution</strong>: In most cases, such a password would likely need to be known by a number of administrators and/or developers. By using a password sharing solution that allows sharing of passwords (e.g. 1Password), the security is then deferred to each admin/dev's individual master password used to unlock his personal password vault.</p>\n<p><strong>Possible degradation of solution/sarcasm</strong>: With this setup, the worst case scenario would be that someone would simply keep their master password on a sticky note attached to a monitor. Whether that is more secure than having the decryption key in a file next to encrypted values should probably be a separate SO question or maybe a future study.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
The resource definition in tomcat's `server.xml` looks something like this... ```xml <Resource name="jdbc/tox" scope="Shareable" type="javax.sql.DataSource" url="jdbc:oracle:thin:@yourDBserver.yourCompany.com:1521:yourDBsid" driverClassName="oracle.jdbc.pool.OracleDataSource" username="tox" password="toxbaby" maxIdle="3" maxActive="10" removeAbandoned="true" removeAbandonedTimeout="60" testOnBorrow="true" validationQuery="select * from dual" logAbandoned="true" debug="99"/> ``` The password is in the clear. How to avoid this?
As said before encrypting passwords is just moving the problem somewhere else. Anyway, it's quite simple. Just write a class with static fields for your secret key and so on, and static methods to encrypt, decrypt your passwords. Encrypt your password in Tomcat's configuration file (`server.xml` or `yourapp.xml`...) using this class. And to decrypt the password "on the fly" in Tomcat, extend the DBCP's `BasicDataSourceFactory` and use this factory in your resource. It will look like: ```xml <Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" username="user" password="encryptedpassword" driverClassName="driverClass" factory="mypackage.MyCustomBasicDataSourceFactory" url="jdbc:blabla://..."/> ``` And for the custom factory: ```java package mypackage; .... public class MyCustomBasicDataSourceFactory extends org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory { @Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { Object o = super.getObjectInstance(obj, name, nameCtx, environment); if (o != null) { BasicDataSource ds = (BasicDataSource) o; if (ds.getPassword() != null && ds.getPassword().length() > 0) { String pwd = MyPasswordUtilClass.unscramblePassword(ds.getPassword()); ds.setPassword(pwd); } return ds; } else { return null; } } ``` Hope this helps.
129,248
<p>I have a many to many index table, and I want to do an include/exclude type query on it.</p> <p>fid is really a integer index, but here as letters for easier understanding. Here's a sample table :</p> <p>table t</p> <pre><code>eid | fid ----+---- 1 | A 1 | B 1 | C 2 | B 2 | C 3 | A 3 | C 4 | A 4 | B 5 | B </code></pre> <p>Here are some sample queries I want.</p> <ol> <li>What eids have fid B, and NOT A? (Answer eid 2 and 5)</li> <li>What eids have fid C, and NOT A? (Answer eid 2)</li> </ol> <p>I can't seem to figure out a query that will do this. </p> <p>I've tried a self join like this:</p> <pre><code>select * from t as t1 join t as t2 where t1.eid=t2.eid and t1.fid!=t2.fid and t1.fid=B and t2.fid!=A </code></pre> <p>That won't work, because it will still return rows where eid=1 and fid=C.</p> <p>Am I clear on what I want?</p>
[ { "answer_id": 129260, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/ms188055.aspx\" rel=\"nofollow noreferrer\">set subtraction</a></p>\n\n<blockquote>\n<pre><code>Select eid from t where fid = 'B' \nEXCEPT\nselect eid from t where fid = 'A'\n</code></pre>\n</blockquote>\n" }, { "answer_id": 129289, "author": "Mike J", "author_id": 4443, "author_profile": "https://Stackoverflow.com/users/4443", "pm_score": 1, "selected": false, "text": "<p>You can use a sub-select</p>\n\n<p>select eid from t where fid = 'C' and eid not in (select eid from t where fid = 'A')</p>\n" }, { "answer_id": 129302, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": true, "text": "<p>Here's an example of a query for 1 (2 works much the same)</p>\n\n<pre><code>select t1.eid\n from t t1\n where t1.fid = 'B'\n and not exists\n (select 1\n from t t2\n where t2.eid = t1.eid\n and t2.fid = 'A')\n</code></pre>\n" }, { "answer_id": 129323, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html\" rel=\"nofollow noreferrer\">MySQL 5.0</a> supports the where exists/where not exists, as described by Nigel and Mike.</p>\n" }, { "answer_id": 129531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Version with straight joins that may be faster than using EXISTS:</p>\n\n<pre>\nSelect t1.eid\nFrom #test t1\n left join (\n Select eid\n From #test t2 \n Where fid = 'A'\n Group by eid\n ) t2 on t2.eid = t1.eid \nWhere t1.fid = 'B'\n and t2.eid is null\n</pre>\n" }, { "answer_id": 129770, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>It should be possible to do this without using a subquery:</p>\n\n<pre><code>SELECT DISTINCT t1.eid\nFROM table1 AS t1\n LEFT JOIN table1 AS t2 ON (t1.eid = t2.eid AND t2.fid = 'A')\nWHERE t2.eid IS NULL\n AND t1.fid = 'B';\n</code></pre>\n\n<p>To do your second example search, just change the value 'B' to 'C'.</p>\n" }, { "answer_id": 129976, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 0, "selected": false, "text": "<p>Look into the MINUS operator. It works like UNION, except that it subtracts where UNION adds. The previous answer with the word \"EXCEPT\" may be a different keyword for the same thing.</p>\n\n<p>Here's an untested answer:</p>\n\n<pre><code>select eid \nfrom t\nwhere fid = 'A'\nminus\nselect eid\nfrom t\nwhere fid = 'B'\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
I have a many to many index table, and I want to do an include/exclude type query on it. fid is really a integer index, but here as letters for easier understanding. Here's a sample table : table t ``` eid | fid ----+---- 1 | A 1 | B 1 | C 2 | B 2 | C 3 | A 3 | C 4 | A 4 | B 5 | B ``` Here are some sample queries I want. 1. What eids have fid B, and NOT A? (Answer eid 2 and 5) 2. What eids have fid C, and NOT A? (Answer eid 2) I can't seem to figure out a query that will do this. I've tried a self join like this: ``` select * from t as t1 join t as t2 where t1.eid=t2.eid and t1.fid!=t2.fid and t1.fid=B and t2.fid!=A ``` That won't work, because it will still return rows where eid=1 and fid=C. Am I clear on what I want?
Here's an example of a query for 1 (2 works much the same) ``` select t1.eid from t t1 where t1.fid = 'B' and not exists (select 1 from t t2 where t2.eid = t1.eid and t2.fid = 'A') ```
129,265
<p>I have a Postgresql database on which I want to do a few cascading deletes. However, the tables aren't set up with the ON DELETE CASCADE rule. Is there any way I can perform a delete and tell Postgresql to cascade it just this once? Something equivalent to</p> <pre><code>DELETE FROM some_table CASCADE; </code></pre> <p>The answers to <a href="https://stackoverflow.com/questions/45611/cascading-deletes-in-postgresql">this older question</a> make it seem like no such solution exists, but I figured I'd ask this question explicitly just to be sure.</p>
[ { "answer_id": 129300, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 9, "selected": true, "text": "<p>No. To do it just once you would simply write the delete statement for the table you want to cascade.</p>\n\n<pre><code>DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);\nDELETE FROM some_table;\n</code></pre>\n" }, { "answer_id": 135574, "author": "Grant Johnson", "author_id": 12518, "author_profile": "https://Stackoverflow.com/users/12518", "pm_score": 1, "selected": false, "text": "<p>The delete with the cascade option only applied to tables with foreign keys defined. If you do a delete, and it says you cannot because it would violate the foreign key constraint, the cascade will cause it to delete the offending rows.</p>\n\n<p>If you want to delete associated rows in this way, you will need to define the foreign keys first. Also, remember that unless you explicitly instruct it to begin a transaction, or you change the defaults, it will do an auto-commit, which could be very time consuming to clean up.</p>\n" }, { "answer_id": 160411, "author": "Ryszard Szopa", "author_id": 19922, "author_profile": "https://Stackoverflow.com/users/19922", "pm_score": 4, "selected": false, "text": "<p>If I understand correctly, you should be able to do what you want by dropping the foreign key constraint, adding a new one (which will cascade), doing your stuff, and recreating the restricting foreign key constraint.</p>\n\n<p>For example:</p>\n\n<pre><code>testing=# create table a (id integer primary key);\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"a_pkey\" for table \"a\"\nCREATE TABLE\ntesting=# create table b (id integer references a);\nCREATE TABLE\n\n-- put some data in the table\ntesting=# insert into a values(1);\nINSERT 0 1\ntesting=# insert into a values(2);\nINSERT 0 1\ntesting=# insert into b values(2);\nINSERT 0 1\ntesting=# insert into b values(1);\nINSERT 0 1\n\n-- restricting works\ntesting=# delete from a where id=1;\nERROR: update or delete on table \"a\" violates foreign key constraint \"b_id_fkey\" on table \"b\"\nDETAIL: Key (id)=(1) is still referenced from table \"b\".\n\n-- find the name of the constraint\ntesting=# \\d b;\n Table \"public.b\"\n Column | Type | Modifiers \n--------+---------+-----------\n id | integer | \nForeign-key constraints:\n \"b_id_fkey\" FOREIGN KEY (id) REFERENCES a(id)\n\n-- drop the constraint\ntesting=# alter table b drop constraint b_a_id_fkey;\nALTER TABLE\n\n-- create a cascading one\ntesting=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade; \nALTER TABLE\n\ntesting=# delete from a where id=1;\nDELETE 1\ntesting=# select * from a;\n id \n----\n 2\n(1 row)\n\ntesting=# select * from b;\n id \n----\n 2\n(1 row)\n\n-- it works, do your stuff.\n-- [stuff]\n\n-- recreate the previous state\ntesting=# \\d b;\n Table \"public.b\"\n Column | Type | Modifiers \n--------+---------+-----------\n id | integer | \nForeign-key constraints:\n \"b_id_fkey\" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE\n\ntesting=# alter table b drop constraint b_id_fkey;\nALTER TABLE\ntesting=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict; \nALTER TABLE\n</code></pre>\n\n<p>Of course, you should abstract stuff like that into a procedure, for the sake of your mental health.</p>\n" }, { "answer_id": 1409458, "author": "DanC", "author_id": 120202, "author_profile": "https://Stackoverflow.com/users/120202", "pm_score": 6, "selected": false, "text": "<p><strong>If you really want</strong> <code>DELETE FROM some_table CASCADE;</code> which means \"<em>remove all rows from table <code>some_table</code></em>\", you can use <code>TRUNCATE</code> instead of <code>DELETE</code> and <code>CASCADE</code> is always supported. However, if you want to use selective delete with a <code>where</code> clause, <code>TRUNCATE</code> is not good enough.</p>\n\n<p><strong>USE WITH CARE</strong> - This will <strong>drop all rows of all tables</strong> which have a foreign key constraint on <code>some_table</code> and all tables that have constraints on those tables, etc.</p>\n\n<p>Postgres supports <code>CASCADE</code> with <a href=\"https://www.postgresql.org/docs/current/sql-truncate.html\" rel=\"noreferrer\">TRUNCATE command</a>:</p>\n\n<pre><code>TRUNCATE some_table CASCADE;\n</code></pre>\n\n<p>Handily this is transactional (i.e. can be rolled back), although it is not fully isolated from other concurrent transactions, and has several other caveats. Read the docs for details.</p>\n" }, { "answer_id": 19103574, "author": "Joe Love", "author_id": 2283954, "author_profile": "https://Stackoverflow.com/users/2283954", "pm_score": 5, "selected": false, "text": "<p>I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as \"on delete cascade\". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions.\nI'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, but it could be written in a way that doesn't have that restriction. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything.\nBasically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow.\nI call it like so:\n<code>select delete_cascade('public','my_table','1');</code></p>\n\n<pre><code>create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)\n returns integer as $$\ndeclare\n rx record;\n rd record;\n v_sql varchar;\n v_recursion_key varchar;\n recnum integer;\n v_primary_key varchar;\n v_rows integer;\nbegin\n recnum := 0;\n select ccu.column_name into v_primary_key\n from\n information_schema.table_constraints tc\n join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema\n and tc.constraint_type='PRIMARY KEY'\n and tc.table_name=p_table\n and tc.table_schema=p_schema;\n\n for rx in (\n select kcu.table_name as foreign_table_name, \n kcu.column_name as foreign_column_name, \n kcu.table_schema foreign_table_schema,\n kcu2.column_name as foreign_table_primary_key\n from information_schema.constraint_column_usage ccu\n join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema \n join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema\n join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema\n join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema\n where ccu.table_name=p_table and ccu.table_schema=p_schema\n and TC.CONSTRAINT_TYPE='FOREIGN KEY'\n and tc2.constraint_type='PRIMARY KEY'\n)\n loop\n v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'\n where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';\n --raise notice '%',v_sql;\n --found a foreign key, now find the primary keys for any data that exists in any of those tables.\n for rd in execute v_sql\n loop\n v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;\n if (v_recursion_key = any (p_recursion)) then\n --raise notice 'Avoiding infinite loop';\n else\n --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;\n recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);\n end if;\n end loop;\n end loop;\n begin\n --actually delete original record.\n v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);\n execute v_sql;\n get diagnostics v_rows= row_count;\n --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;\n recnum:= recnum +v_rows;\n exception when others then recnum=0;\n end;\n\n return recnum;\nend;\n$$\nlanguage PLPGSQL;\n</code></pre>\n" }, { "answer_id": 37165401, "author": "atiruz", "author_id": 1491512, "author_profile": "https://Stackoverflow.com/users/1491512", "pm_score": 2, "selected": false, "text": "<p>You can use to automate this, you could define the foreign key constraint with <code>ON DELETE CASCADE</code>.<br>\nI quote the <a href=\"http://www.postgresql.org/docs/current/interactive/ddl-constraints.html#DDL-CONSTRAINTS-FK\" rel=\"nofollow noreferrer\">the manual of foreign key constraints</a>:</p>\n\n<blockquote>\n <p><code>CASCADE</code> specifies that when a referenced row is deleted, row(s)\n referencing it should be automatically deleted as well.</p>\n</blockquote>\n" }, { "answer_id": 45209745, "author": "Grzegorz Grabek", "author_id": 5135120, "author_profile": "https://Stackoverflow.com/users/5135120", "pm_score": 3, "selected": false, "text": "<p>I cannot comment Palehorse's answer so I added my own answer.\nPalehorse's logic is ok but efficiency can be bad with big data sets.</p>\n\n<pre><code>DELETE FROM some_child_table sct \n WHERE exists (SELECT FROM some_Table st \n WHERE sct.some_fk_fiel=st.some_id);\n\nDELETE FROM some_table;\n</code></pre>\n\n<p>It is faster if you have indexes on columns and data set is bigger than few records.</p>\n" }, { "answer_id": 50842421, "author": "Thomas C. G. de Vilhena", "author_id": 1205339, "author_profile": "https://Stackoverflow.com/users/1205339", "pm_score": 3, "selected": false, "text": "<p>I took Joe Love's answer and rewrote it using the <code>IN</code> operator with sub-selects instead of <code>=</code> to make the function faster (according to Hubbitus's suggestion):</p>\n\n<pre><code>create or replace function delete_cascade(p_schema varchar, p_table varchar, p_keys varchar, p_subquery varchar default null, p_foreign_keys varchar[] default array[]::varchar[])\n returns integer as $$\ndeclare\n\n rx record;\n rd record;\n v_sql varchar;\n v_subquery varchar;\n v_primary_key varchar;\n v_foreign_key varchar;\n v_rows integer;\n recnum integer;\n\nbegin\n\n recnum := 0;\n select ccu.column_name into v_primary_key\n from\n information_schema.table_constraints tc\n join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema\n and tc.constraint_type='PRIMARY KEY'\n and tc.table_name=p_table\n and tc.table_schema=p_schema;\n\n for rx in (\n select kcu.table_name as foreign_table_name, \n kcu.column_name as foreign_column_name, \n kcu.table_schema foreign_table_schema,\n kcu2.column_name as foreign_table_primary_key\n from information_schema.constraint_column_usage ccu\n join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema \n join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema\n join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema\n join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema\n where ccu.table_name=p_table and ccu.table_schema=p_schema\n and TC.CONSTRAINT_TYPE='FOREIGN KEY'\n and tc2.constraint_type='PRIMARY KEY'\n)\n loop\n v_foreign_key := rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name;\n v_subquery := 'select \"'||rx.foreign_table_primary_key||'\" as key from '||rx.foreign_table_schema||'.\"'||rx.foreign_table_name||'\"\n where \"'||rx.foreign_column_name||'\"in('||coalesce(p_keys, p_subquery)||') for update';\n if p_foreign_keys @&gt; ARRAY[v_foreign_key] then\n --raise notice 'circular recursion detected';\n else\n p_foreign_keys := array_append(p_foreign_keys, v_foreign_key);\n recnum:= recnum + delete_cascade(rx.foreign_table_schema, rx.foreign_table_name, null, v_subquery, p_foreign_keys);\n p_foreign_keys := array_remove(p_foreign_keys, v_foreign_key);\n end if;\n end loop;\n\n begin\n if (coalesce(p_keys, p_subquery) &lt;&gt; '') then\n v_sql := 'delete from '||p_schema||'.\"'||p_table||'\" where \"'||v_primary_key||'\"in('||coalesce(p_keys, p_subquery)||')';\n --raise notice '%',v_sql;\n execute v_sql;\n get diagnostics v_rows = row_count;\n recnum := recnum + v_rows;\n end if;\n exception when others then recnum=0;\n end;\n\n return recnum;\n\nend;\n$$\nlanguage PLPGSQL;\n</code></pre>\n" }, { "answer_id": 59243085, "author": "TRL", "author_id": 11558646, "author_profile": "https://Stackoverflow.com/users/11558646", "pm_score": 4, "selected": false, "text": "<p>Yeah, as others have said, there's no convenient 'DELETE FROM my_table ... CASCADE' (or equivalent). To delete non-cascading foreign key-protected child records and their referenced ancestors, your options include:</p>\n\n<ul>\n<li>Perform all the deletions explicitly, one query at a time, starting with child tables (though this won't fly if you've got circular references); or</li>\n<li>Perform all the deletions explicitly in a single (potentially massive) query; or</li>\n<li>Assuming your non-cascading foreign key constraints were created as 'ON DELETE NO ACTION DEFERRABLE', perform all the deletions explicitly in a single transaction; or </li>\n<li>Temporarily drop the 'no action' and 'restrict' foreign key constraints in the graph, recreate them as CASCADE, delete the offending ancestors, drop the foreign key constraints again, and finally recreate them as they were originally (thus temporarily weakening the integrity of your data); or</li>\n<li>Something probably equally fun.</li>\n</ul>\n\n<p>It's on purpose that circumventing foreign key constraints isn't made convenient, I assume; but I do understand why in particular circumstances you'd want to do it. If it's something you'll be doing with some frequency, and if you're willing to flout the wisdom of DBAs everywhere, you may want to automate it with a procedure. </p>\n\n<p>I came here a few months ago looking for an answer to the \"CASCADE DELETE just once\" question (originally asked over a decade ago!). I got some mileage out of Joe Love's clever solution (and Thomas C. G. de Vilhena's variant), but in the end my use case had particular requirements (handling of intra-table circular references, for one) that forced me to take a different approach. That approach ultimately became <a href=\"https://github.com/trlorenz/PG-recursively_delete\" rel=\"noreferrer\">recursively_delete</a> (PG 10.10).</p>\n\n<p>I've been using recursively_delete in production for a while, now, and finally feel (warily) confident enough to make it available to others who might wind up here looking for ideas. As with Joe Love's solution, it allows you to delete entire graphs of data as if all foreign key constraints in your database were momentarily set to CASCADE, but offers a couple additional features:</p>\n\n<ul>\n<li>Provides an ASCII preview of the deletion target and its graph of\ndependents.</li>\n<li>Performs deletion in a single query using recursive CTEs.</li>\n<li>Handles circular dependencies, intra- and inter-table.</li>\n<li>Handles composite keys.</li>\n<li>Skips 'set default' and 'set null' constraints.</li>\n</ul>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
I have a Postgresql database on which I want to do a few cascading deletes. However, the tables aren't set up with the ON DELETE CASCADE rule. Is there any way I can perform a delete and tell Postgresql to cascade it just this once? Something equivalent to ``` DELETE FROM some_table CASCADE; ``` The answers to [this older question](https://stackoverflow.com/questions/45611/cascading-deletes-in-postgresql) make it seem like no such solution exists, but I figured I'd ask this question explicitly just to be sure.
No. To do it just once you would simply write the delete statement for the table you want to cascade. ``` DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table); DELETE FROM some_table; ```
129,297
<p>I have a laptop running Ubuntu to which I connect an external monitor when I'm at the office. Usually this requires me to run <code>xrandr --auto</code> in order for the laptop to re-size the display to match the external monitor. It would be nice if this could be done automatically, either triggered when the monitor is connected, but it would be enough to actually run <code>xrandr --auto</code> when the laptop wakes up from suspend/hibernate.</p> <p>I created a script <code>/etc/pm/sleep.d/00xrandr.sh</code> containing the line</p> <pre><code>xrandr --auto </code></pre> <p>but this fails since the script does not have access to the X display.</p> <p>Any ideas?</p>
[ { "answer_id": 129493, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 0, "selected": false, "text": "<p>Have you tried to set the DISPLAY variable in the script correctly and granted access for other users to your DISPLAY with xhost + localhost? Don't know if that helps, but it's worth a try.</p>\n" }, { "answer_id": 154960, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 3, "selected": true, "text": "<p>I guees that the problem is that the script is being run as root, with no access to your xauth data. Depending on your setup, something like this could work:</p>\n\n<pre><code>xauth merge /home/your_username/.Xauthority\nexport DISPLAY=:0.0\nxrandr --auto\n</code></pre>\n\n<p>You could use something more clever to find out which user you need to extract xauth data from if you need to.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13051/" ]
I have a laptop running Ubuntu to which I connect an external monitor when I'm at the office. Usually this requires me to run `xrandr --auto` in order for the laptop to re-size the display to match the external monitor. It would be nice if this could be done automatically, either triggered when the monitor is connected, but it would be enough to actually run `xrandr --auto` when the laptop wakes up from suspend/hibernate. I created a script `/etc/pm/sleep.d/00xrandr.sh` containing the line ``` xrandr --auto ``` but this fails since the script does not have access to the X display. Any ideas?
I guees that the problem is that the script is being run as root, with no access to your xauth data. Depending on your setup, something like this could work: ``` xauth merge /home/your_username/.Xauthority export DISPLAY=:0.0 xrandr --auto ``` You could use something more clever to find out which user you need to extract xauth data from if you need to.
129,335
<p>When you call <code>RedirectToAction</code> within a controller, it automatically redirects using an HTTP GET. How do I explicitly tell it to use an HTTP POST?</p> <p>I have an action that accepts both GET and POST requests, and I want to be able to <code>RedirectToAction</code> using POST and send it some values.</p> <p>Like this:</p> <pre><code>this.RedirectToAction( "actionname", new RouteValueDictionary(new { someValue = 2, anotherValue = "text" }) ); </code></pre> <p>I want the <code>someValue</code> and <code>anotherValue</code> values to be sent using an HTTP POST instead of a GET. Does anyone know how to do this?</p>
[ { "answer_id": 129361, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 8, "selected": true, "text": "<p>HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP \"Location\" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.</p>\n" }, { "answer_id": 1343182, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 7, "selected": false, "text": "<p>For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):</p>\n\n<pre><code>[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult Index() {\n // obviously these values might come from somewhere non-trivial\n return Index(2, \"text\");\n}\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Index(int someValue, string anotherValue) {\n // would probably do something non-trivial here with the param values\n return View();\n}\n</code></pre>\n\n<p>That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.</p>\n\n<p>I would love to know what is \"wrong\" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 19378717, "author": "Otto Kanellis", "author_id": 1210599, "author_profile": "https://Stackoverflow.com/users/1210599", "pm_score": 5, "selected": false, "text": "<p>If you want to pass data between two actions during a redirect without include any data in the query string, put the model in the TempData object.</p>\n\n<p>ACTION</p>\n\n<p><code>TempData[\"datacontainer\"] = modelData;</code></p>\n\n<p>VIEW</p>\n\n<pre><code>var modelData= TempData[\"datacontainer\"] as ModelDataType; \n</code></pre>\n\n<p>TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this. </p>\n\n<p>Therefore, the only scenario where using TempData will reliably work is when you are redirecting.</p>\n" }, { "answer_id": 29889782, "author": "vicky", "author_id": 1805776, "author_profile": "https://Stackoverflow.com/users/1805776", "pm_score": 4, "selected": false, "text": "<p>try this one</p>\n\n<pre><code>return Content(\"&lt;form action='actionname' id='frmTest' method='post'&gt;&lt;input type='hidden' name='someValue' value='\" + someValue + \"' /&gt;&lt;input type='hidden' name='anotherValue' value='\" + anotherValue + \"' /&gt;&lt;/form&gt;&lt;script&gt;document.getElementById('frmTest').submit();&lt;/script&gt;\");\n</code></pre>\n" }, { "answer_id": 37805314, "author": "Yitzhak Weinberg", "author_id": 4871015, "author_profile": "https://Stackoverflow.com/users/4871015", "pm_score": 3, "selected": false, "text": "<p>I would like to expand the answer of Jason Bunting</p>\n\n<p>like this</p>\n\n<pre><code>ActionResult action = new SampelController().Index(2, \"text\");\nreturn action;\n</code></pre>\n\n<p>And Eli will be here for something idea on how to make it generic variable</p>\n\n<p>Can get all types of controller</p>\n" }, { "answer_id": 71077754, "author": "PowerMan2015", "author_id": 2339034, "author_profile": "https://Stackoverflow.com/users/2339034", "pm_score": 0, "selected": false, "text": "<p>I have just experienced the same problem.</p>\n<p>The solution was to call the controller action like a function:</p>\n<pre><code>return await ResendConfirmationEmail(new ResendConfirmationEmailViewModel() { Email = input.Email });\n</code></pre>\n<p>The controller action:</p>\n<pre><code>[HttpPost]\n[AllowAnonymous]\npublic async Task&lt;IActionResult&gt; ResendConfirmationEmail(ResendConfirmationEmailViewModel input)\n{\n ...\n \n return View(&quot;ResendConfirmationEmailConfirmed&quot;);\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
When you call `RedirectToAction` within a controller, it automatically redirects using an HTTP GET. How do I explicitly tell it to use an HTTP POST? I have an action that accepts both GET and POST requests, and I want to be able to `RedirectToAction` using POST and send it some values. Like this: ``` this.RedirectToAction( "actionname", new RouteValueDictionary(new { someValue = 2, anotherValue = "text" }) ); ``` I want the `someValue` and `anotherValue` values to be sent using an HTTP POST instead of a GET. Does anyone know how to do this?
HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.
129,345
<p>How can I pass arguments to a constructor in an IOC-framework? I want to do something like: (Trying to be IOC-framework agnostic ;) )</p> <pre><code>object objectToLogFor = xxx; container.Resolve&lt;ILogging&gt;(objectToLogFor); public class MyLogging : ILogging { public MyLogging(object objectToLogFor){} } </code></pre> <p>It seems that this is not possible in StructureMap. But I would love to see someone prove me wrong.</p> <p>Are other frameworks more feature-rich? Or am I using the IOC-framework in the wrong way?</p>
[ { "answer_id": 129363, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 0, "selected": false, "text": "<p>Yes, other frameworks are more feature-rich - you need to use an ioc framework that allows for constructor injection. Spring is an example of a multi-language ioc container that allows constructor dependency injection.</p>\n" }, { "answer_id": 129393, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 2, "selected": false, "text": "<p>How can this be language-agnostic? This is implementation detail of the framework in question.</p>\n\n<p>Spring alows you to specify c'tor args as a list of values/references, if that's your thing. It's not very readable, though, compared to property injection.</p>\n\n<p>Some people get hot under the collar about this, and insist that c'tor injection is the only thread-safe approach in java. Technically they're correct, but in practice it tends not to matter.</p>\n" }, { "answer_id": 129504, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 2, "selected": false, "text": "<p>It should not be a very common need, but sometimes it is a valid one. <a href=\"http://ninject.org/\" rel=\"nofollow noreferrer\">Ninject</a>, which is lighter than StructureMap, allows you to pass parameters when retrieving transient objects from the context. <a href=\"http://www.springframework.net/\" rel=\"nofollow noreferrer\">Spring.NET</a> too.</p>\n\n<p>Most of the time, objects declared in an IoC container aren't transient, and accept others non-transient objects through constructors/properties/methods as dependencies.</p>\n\n<p>However, if you really wan't to use the container as a factory, and if you have enough control on the objects you want to resolve, you could use property or method injection even if it sounds less natural and more risky in some way.</p>\n" }, { "answer_id": 151943, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 0, "selected": false, "text": "<p>Other IoC frameworks are more feature rich. </p>\n\n<p>I.e. check out the <a href=\"http://code.google.com/p/autofac/wiki/ResolveParameters\" rel=\"nofollow noreferrer\">ParameterResolution</a> with Autofac</p>\n" }, { "answer_id": 573438, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 4, "selected": true, "text": "<p>In structure map you could achieve this using the With method:</p>\n\n<pre><code>string objectToLogFor = \"PolicyName\";\nObjectFactory.With&lt;string&gt;(objectToLogFor).GetInstance&lt;ILogging&gt;();\n</code></pre>\n\n<p>See: <a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx</a></p>\n" }, { "answer_id": 586099, "author": "Krzysztof Kozmic", "author_id": 13163, "author_profile": "https://Stackoverflow.com/users/13163", "pm_score": 0, "selected": false, "text": "<p>You can also do that with Windsor easily</p>\n" }, { "answer_id": 586144, "author": "Remco Ros", "author_id": 70315, "author_profile": "https://Stackoverflow.com/users/70315", "pm_score": 3, "selected": false, "text": "<p>For Castle Windsor:</p>\n\n<pre><code>var foo = \"foo\";\nvar service = this.container.Resolve&lt;TContract&gt;(new { constructorArg1 = foo });\n</code></pre>\n\n<p>note the use of an anonymous object to specify constructor arguments.</p>\n\n<p>using StructureMap:</p>\n\n<pre><code>var foo = \"foo\";\nvar service = container.With(foo).GetInstance&lt;TContract&gt;();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21733/" ]
How can I pass arguments to a constructor in an IOC-framework? I want to do something like: (Trying to be IOC-framework agnostic ;) ) ``` object objectToLogFor = xxx; container.Resolve<ILogging>(objectToLogFor); public class MyLogging : ILogging { public MyLogging(object objectToLogFor){} } ``` It seems that this is not possible in StructureMap. But I would love to see someone prove me wrong. Are other frameworks more feature-rich? Or am I using the IOC-framework in the wrong way?
In structure map you could achieve this using the With method: ``` string objectToLogFor = "PolicyName"; ObjectFactory.With<string>(objectToLogFor).GetInstance<ILogging>(); ``` See: <http://codebetter.com/blogs/jeremy.miller/archive/2008/09/25/using-structuremap-2-5-to-inject-your-entity-objects-into-services.aspx>
129,360
<p>I'm working with jQuery for the first time and need some help. I have html that looks like the following:</p> <pre><code>&lt;div id='comment-8' class='comment'&gt; &lt;p&gt;Blah blah&lt;/p&gt; &lt;div class='tools'&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id='comment-9' class='comment'&gt; &lt;p&gt;Blah blah something else&lt;/p&gt; &lt;div class='tools'&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.</p> <p>What I have thus far is:</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { var actionSpan = $('&lt;span&gt;[Do Something]&lt;/span&gt;'); actionSpan.bind('click', doSomething); $('.tools').append(actionSpan); }); function doSomething(commentId) { alert(commentId); } &lt;/script&gt; </code></pre> <p>I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.</p> <p>Thanks, Brian</p>
[ { "answer_id": 129420, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 1, "selected": false, "text": "<p>To get from the span up to the surrounding divs, you can use <code>&lt;tt&gt;parent()&lt;/tt&gt;</code> (if you know the exact relationship), like this: <code>&lt;tt&gt;$(this).parent().attr('id')&lt;/tt&gt;;</code> or if the structure might be more deeply nested, you can use parents() to search up the DOM tree, like this: <code>&lt;tt&gt;$(this).parents('div:eq(0)').attr('id')&lt;/tt&gt;</code>.\n<p>\nTo keep my answer simple, I left off matching the class <code>&lt;tt&gt;\"comment\"&lt;/tt&gt;</code> but of course you could do that if it helps narrow down the div you are searching for.</p>\n" }, { "answer_id": 129430, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>You don't have a lot of control over the arguments passed to a bound event handler.</p>\n\n<p>Perhaps try something like this for your definition of <strong>doSomething()</strong>:</p>\n\n<pre><code>function doSomething() { \n var commentId = $(this).parent().attr('id');\n alert(commentId); \n}\n</code></pre>\n" }, { "answer_id": 129439, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 4, "selected": true, "text": "<p>Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a <code>target</code> property that references the element it was called for, and the <code>this</code> variable is a reference to the element the event handler was attached to. So you could do the following:</p>\n\n<pre><code>function doSomething(event)\n{\n var id = $(event.target).parents(\".tools\").attr(\"id\");\n id = substring(id.indexOf(\"-\")+1);\n alert(id);\n}\n</code></pre>\n\n<p>...or:</p>\n\n<pre><code>function doSomething(event)\n{\n var id = $(this).parents(\".tools\").attr(\"id\");\n id = substring(id.indexOf(\"-\")+1);\n alert(id);\n}\n</code></pre>\n" }, { "answer_id": 129524, "author": "Nick", "author_id": 21399, "author_profile": "https://Stackoverflow.com/users/21399", "pm_score": 0, "selected": false, "text": "<p>It might be easier to loop through the comments, and add the tool thing to each. That way you can give them each their own function. I've got the function returning a function so that when it's called later, it has the correct comment ID available to it.</p>\n\n<p>The other solutions (that navigate back up to find the ID of the parent) will likely be more memory efficient.</p>\n\n<pre><code>&lt;script type='text/javascript'&gt;\n\n$(function() {\n $('.comment').each(function(comment) {\n $('.tools', comment).append(\n $('&lt;span&gt;[Do Something]&lt;/span&gt;')\n .click(commentTool(comment.id));\n );\n });\n});\n\nfunction commentTool(commentId) {\n return function() {\n alert('Do cool stuff to ' + commentId);\n }\n}\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 129561, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 0, "selected": false, "text": "<p>Getting a little fancy to give you an idea of some of the things you can do:</p>\n\n<pre><code>var tool = $('&lt;span&gt;[Tool]&lt;/span&gt;');\n\nvar action = function (id) {\n return function () {\n alert('id');\n }\n}\n\n$('div.comment').each(function () {\n var id = $(this).attr('id');\n\n var child = tool.clone();\n child.click(action(id));\n\n $('.tools', this).append(child);\n});\n</code></pre>\n" }, { "answer_id": 129565, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 0, "selected": false, "text": "<p>The function bind() takes, takes the element as a parameter (in your case the span), so to get the id you want from it you should do some DOM traversal like:</p>\n\n<pre><code>function doSomething(eventObject) { \n var elComment = eventObject.parentNode.parentNode; //or something like that, \n //didn't test it\n var commentId= elComment.getAttribute('commentId')\n alert(commentId); \n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2656/" ]
I'm working with jQuery for the first time and need some help. I have html that looks like the following: ``` <div id='comment-8' class='comment'> <p>Blah blah</p> <div class='tools'></div> </div> <div id='comment-9' class='comment'> <p>Blah blah something else</p> <div class='tools'></div> </div> ``` I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment. What I have thus far is: ``` <script type='text/javascript'> $(function() { var actionSpan = $('<span>[Do Something]</span>'); actionSpan.bind('click', doSomething); $('.tools').append(actionSpan); }); function doSomething(commentId) { alert(commentId); } </script> ``` I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that. Thanks, Brian
Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a `target` property that references the element it was called for, and the `this` variable is a reference to the element the event handler was attached to. So you could do the following: ``` function doSomething(event) { var id = $(event.target).parents(".tools").attr("id"); id = substring(id.indexOf("-")+1); alert(id); } ``` ...or: ``` function doSomething(event) { var id = $(this).parents(".tools").attr("id"); id = substring(id.indexOf("-")+1); alert(id); } ```
129,388
<p>I am writing a webpage in C# .NET. In javascript there is a function called GetElementsByTagName... this is nice for javascript invoked from the .aspx page. My question is, is there any way I can have this kind of functionality from my C# code-behind?</p> <p>--</p> <p>The scenario for those curious: I used an asp:repeater to generate a lot of buttons, and now I'm essentially trying to make a button that clicks them all. I tried storing all the buttons in a list as I created them, but the list is getting cleared during every postback, so I thought I could try the above method.</p>
[ { "answer_id": 129400, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>FindControl(), or iterate through the controls on the page...</p>\n\n<pre><code>For each ctl as Control in Me.Controls\n If ctl.Name = whatYouWant Then\n do stuff\nNext 'ctl\n</code></pre>\n\n<p>--If you are creating the controls, you should be setting their ID's </p>\n\n<pre><code>Dim ctl as New Control()\nctl.ID = \"blah1\"\n</code></pre>\n\n<p>etc...</p>\n" }, { "answer_id": 129414, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 1, "selected": false, "text": "<p>Well, you can find controls with the page's FindControl method, but Repeater elements have names generated by .net.</p>\n\n<p>As an aside, if you really want to, you could store the list of buttons in your page's ViewState (or perhaps a list of their names).</p>\n" }, { "answer_id": 129418, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Whenever you do any postback, <em>everything</em> is recreated, including your databound controls. </p>\n\n<p>If your list is gone, so are the button controls. Unless, of course, you've recreated them, and in that case you should have recreated the list as well.</p>\n" }, { "answer_id": 129442, "author": "devlord", "author_id": 16454, "author_profile": "https://Stackoverflow.com/users/16454", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>foreach (Control ctl in myRepeater.Controls)\n{ \n if (ctl is Button)\n {\n ((Button)ctl).Click();\n }\n}\n</code></pre>\n\n<p>HTH...</p>\n" }, { "answer_id": 129456, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 0, "selected": false, "text": "<p>I don't know exactly what you mean by clicks them all. But how would this following code work for you? I don't know, I haven't tested... </p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n\n foreach (Control control in GetControlsByType(this, typeof(TextBox)))\n { \n //Do something?\n }\n\n}\npublic static System.Collections.Generic.List&lt;Control&gt; GetControlsByType(Control ctrl, Type t)\n{\n System.Collections.Generic.List&lt;Control&gt; cntrls = new System.Collections.Generic.List&lt;Control&gt;();\n\n\n foreach (Control child in ctrl.Controls)\n {\n if (t == child.GetType())\n cntrls.Add(child);\n cntrls.AddRange(GetControlsByType(child, t));\n }\n return cntrls;\n}\n</code></pre>\n" }, { "answer_id": 129571, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>ASPX:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %&gt;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head runat=\"server\"&gt;\n &lt;title&gt;Untitled Page&lt;/title&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;asp:Repeater runat=\"server\" ID=\"Repeater1\"&gt;\n &lt;ItemTemplate&gt;\n &lt;asp:Button runat=\"server\" ID=\"Button1\" Text=\"I was NOT changed\" /&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:Repeater&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>ASPX.CS:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\n\npublic partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(Object sender, EventArgs e)\n {\n DataTable dt = new DataTable();\n\n dt.Columns.Add(new DataColumn(\"column\"));\n\n DataRow dr = null;\n\n for (Int32 i = 0; i &lt; 10; i++)\n {\n dr = dt.NewRow();\n\n dr[\"column\"] = \"\";\n\n dt.Rows.Add(dr);\n }\n\n this.Repeater1.DataSource = dt;\n this.Repeater1.DataBind();\n\n\n foreach (RepeaterItem ri in this.Repeater1.Controls)\n {\n foreach (Control c in ri.Controls)\n {\n Button b = new Button();\n\n\n try\n {\n b = (Button)c;\n }\n\n catch (Exception exc)\n {\n }\n\n\n b.Text = \"I was found and changed\";\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 129645, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>Or a variation of my own code, only changing the ASPX.CS:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Collections.Generic;\n\n\npublic partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(Object sender, EventArgs e)\n {\n #region Fill Repeater1 with some dummy data\n DataTable dt = new DataTable();\n\n dt.Columns.Add(new DataColumn(\"column\"));\n\n DataRow dr = null;\n\n for (Int32 i = 0; i &lt; 10; i++)\n {\n dr = dt.NewRow();\n\n dr[\"column\"] = \"\";\n\n dt.Rows.Add(dr);\n }\n\n this.Repeater1.DataSource = dt;\n this.Repeater1.DataBind();\n #endregion\n\n\n foreach (Button b in this.FindButtonsInRepeater(ref this.Repeater1))\n {\n b.Text = \"I was found and changed\";\n }\n }\n\n\n private List&lt;Button&gt; FindButtonsInRepeater(ref Repeater repeater)\n {\n List&lt;Button&gt; buttonsFound = new List&lt;Button&gt;();\n\n\n foreach (RepeaterItem ri in repeater.Controls)\n {\n foreach (Control c in ri.Controls)\n {\n try\n {\n buttonsFound.Add((Button)c);\n }\n\n catch (Exception exc)\n {\n }\n }\n }\n\n\n return buttonsFound;\n }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13732/" ]
I am writing a webpage in C# .NET. In javascript there is a function called GetElementsByTagName... this is nice for javascript invoked from the .aspx page. My question is, is there any way I can have this kind of functionality from my C# code-behind? -- The scenario for those curious: I used an asp:repeater to generate a lot of buttons, and now I'm essentially trying to make a button that clicks them all. I tried storing all the buttons in a list as I created them, but the list is getting cleared during every postback, so I thought I could try the above method.
FindControl(), or iterate through the controls on the page... ``` For each ctl as Control in Me.Controls If ctl.Name = whatYouWant Then do stuff Next 'ctl ``` --If you are creating the controls, you should be setting their ID's ``` Dim ctl as New Control() ctl.ID = "blah1" ``` etc...
129,389
<p>I want a true deep copy. In Java, this was easy, but how do you do it in C#?</p>
[ { "answer_id": 129395, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 10, "selected": true, "text": "<h3>Important Note</h3>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-5.0\" rel=\"noreferrer\">BinaryFormatter</a> has been deprecated, and will no longer be available in .NET after November 2023. See <a href=\"https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md\" rel=\"noreferrer\">BinaryFormatter Obsoletion Strategy</a></p>\n<hr />\n<p>I've seen a few different approaches to this, but I use a generic utility method as such:</p>\n<pre><code>public static T DeepClone&lt;T&gt;(this T obj)\n{\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n\n return (T) formatter.Deserialize(ms);\n }\n}\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li><p>Your class MUST be marked as <code>[Serializable]</code> for this to work.</p>\n</li>\n<li><p>Your source file must include the following code:</p>\n<pre><code> using System.Runtime.Serialization.Formatters.Binary;\n using System.IO;\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 1213649, "author": "Neil", "author_id": 148593, "author_profile": "https://Stackoverflow.com/users/148593", "pm_score": 7, "selected": false, "text": "<p>Building on Kilhoffer's solution...</p>\n\n<p>With C# 3.0 you can create an extension method as follows:</p>\n\n<pre><code>public static class ExtensionMethods\n{\n // Deep clone\n public static T DeepClone&lt;T&gt;(this T a)\n {\n using (MemoryStream stream = new MemoryStream())\n {\n BinaryFormatter formatter = new BinaryFormatter();\n formatter.Serialize(stream, a);\n stream.Position = 0;\n return (T) formatter.Deserialize(stream);\n }\n }\n}\n</code></pre>\n\n<p>which extends any class that's been marked as [Serializable] with a DeepClone method</p>\n\n<pre><code>MyClass copy = obj.DeepClone();\n</code></pre>\n" }, { "answer_id": 4320823, "author": "David Thornley", "author_id": 196390, "author_profile": "https://Stackoverflow.com/users/196390", "pm_score": 2, "selected": false, "text": "<p>Maybe you only need a shallow copy, in that case use <code>Object.MemberWiseClone()</code>.</p>\n\n<p>There are good recommendations in the documentation for <code>MemberWiseClone()</code> for strategies to deep copy: -</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx</a></p>\n" }, { "answer_id": 6572475, "author": "Basil", "author_id": 828241, "author_profile": "https://Stackoverflow.com/users/828241", "pm_score": 0, "selected": false, "text": "<pre><code> public static object CopyObject(object input)\n {\n if (input != null)\n {\n object result = Activator.CreateInstance(input.GetType());\n foreach (FieldInfo field in input.GetType().GetFields(Consts.AppConsts.FullBindingList))\n {\n if (field.FieldType.GetInterface(\"IList\", false) == null)\n {\n field.SetValue(result, field.GetValue(input));\n }\n else\n {\n IList listObject = (IList)field.GetValue(result);\n if (listObject != null)\n {\n foreach (object item in ((IList)field.GetValue(input)))\n {\n listObject.Add(CopyObject(item));\n }\n }\n }\n }\n return result;\n }\n else\n {\n return null;\n }\n }\n</code></pre>\n\n<p>This way is a few times faster than <code>BinarySerialization</code> AND this does not require the <code>[Serializable]</code> attribute.</p>\n" }, { "answer_id": 8683002, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 6, "selected": false, "text": "<p>You can use <strong>Nested MemberwiseClone to do a deep copy</strong>. Its almost the same speed as copying a value struct, and its an order of magnitude faster than (a) reflection or (b) serialization (as described in other answers on this page).</p>\n\n<p>Note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.</p>\n\n<p>Here is the output of the code showing the relative performance difference (4.77 seconds for deep nested MemberwiseCopy vs. 39.93 seconds for Serialization). Using nested MemberwiseCopy is almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of, which is probably quite close to the speed of the same thing in C or C++ (but would have to run some equivalent benchmarks to check this claim).</p>\n\n<pre><code> Demo of shallow and deep copy, using classes and MemberwiseClone:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob &gt;&gt; BobsSon\n Adjust BobsSon details\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:04.7795670,30000000\n Demo of shallow and deep copy, using structs and value copying:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob &gt;&gt; BobsSon\n Adjust BobsSon details:\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:01.0875454,30000000\n Demo of deep copy, using class and serialize/deserialize:\n Elapsed time: 00:00:39.9339425,30000000\n</code></pre>\n\n<p>To understand how to do a deep copy using MemberwiseCopy, here is the demo project:</p>\n\n<pre><code>// Nested MemberwiseClone example. \n// Added to demo how to deep copy a reference class.\n[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.\npublic class Person\n{\n public Person(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n [Serializable] // Not required if using MemberwiseClone\n public class PurchaseType\n {\n public string Description;\n public PurchaseType ShallowCopy()\n {\n return (PurchaseType)this.MemberwiseClone();\n }\n }\n public PurchaseType Purchase = new PurchaseType();\n public int Age;\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person ShallowCopy()\n {\n return (Person)this.MemberwiseClone();\n }\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person DeepCopy()\n {\n // Clone the root ...\n Person other = (Person) this.MemberwiseClone();\n // ... then clone the nested class.\n other.Purchase = this.Purchase.ShallowCopy();\n return other;\n }\n}\n// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)\npublic struct PersonStruct\n{\n public PersonStruct(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n public struct PurchaseType\n {\n public string Description;\n }\n public PurchaseType Purchase;\n public int Age;\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct ShallowCopy()\n {\n return (PersonStruct)this;\n }\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct DeepCopy()\n {\n return (PersonStruct)this;\n }\n}\n// Added only for a speed comparison.\npublic class MyDeepCopy\n{\n public static T DeepCopy&lt;T&gt;(T obj)\n {\n object result = null;\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n result = (T)formatter.Deserialize(ms);\n ms.Close();\n }\n return (T)result;\n }\n}\n</code></pre>\n\n<p>Then, call the demo from main:</p>\n\n<pre><code> void MyMain(string[] args)\n {\n {\n Console.Write(\"Demo of shallow and deep copy, using classes and MemberwiseCopy:\\n\");\n var Bob = new Person(30, \"Lamborghini\");\n Console.Write(\" Create Bob\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Console.Write(\" Clone Bob &gt;&gt; BobsSon\\n\");\n var BobsSon = Bob.DeepCopy();\n Console.Write(\" Adjust BobsSon details\\n\");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = \"Toy car\";\n Console.Write(\" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n\", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(\" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == \"Lamborghini\");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i &lt; 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n { \n Console.Write(\"Demo of shallow and deep copy, using structs:\\n\");\n var Bob = new PersonStruct(30, \"Lamborghini\");\n Console.Write(\" Create Bob\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description);\n Console.Write(\" Clone Bob &gt;&gt; BobsSon\\n\");\n var BobsSon = Bob.DeepCopy();\n Console.Write(\" Adjust BobsSon details:\\n\");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = \"Toy car\";\n Console.Write(\" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n\", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(\" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n\");\n Console.Write(\" Bob.Age={0}, Bob.Purchase.Description={1}\\n\", Bob.Age, Bob.Purchase.Description); \n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == \"Lamborghini\");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i &lt; 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n {\n Console.Write(\"Demo of deep copy, using class and serialize/deserialize:\\n\");\n int total = 0;\n var sw = new Stopwatch();\n sw.Start();\n var Bob = new Person(30, \"Lamborghini\");\n for (int i = 0; i &lt; 100000; i++)\n {\n var BobsSon = MyDeepCopy.DeepCopy&lt;Person&gt;(Bob);\n total += BobsSon.Age;\n }\n Console.Write(\" Elapsed time: {0},{1}\\n\", sw.Elapsed, total);\n }\n Console.ReadKey();\n }\n</code></pre>\n\n<p>Again, note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.</p>\n\n<p>Note that when it comes to cloning an object, there is is a big difference between a \"struct\" and a \"class\":</p>\n\n<ul>\n<li>If you have a \"struct\", it's a value type so you can just copy it, and the contents will be cloned.</li>\n<li>If you have a \"class\", it's a reference type, so if you copy it, all you are doing is copying the pointer to it. To create a true clone, you have to be more creative, and use a method which creates another copy of the original object in memory.</li>\n<li>Cloning objects incorrectly can lead to very difficult-to-pin-down bugs. In production code, I tend to implement a checksum to double check that the object has been cloned properly, and hasn't been corrupted by another reference to it. This checksum can be switched off in Release mode.</li>\n<li>I find this method quite useful: often, you only want to clone parts of the object, not the entire thing. It's also essential for any use case where you are modifying objects, then feeding the modified copies into a queue.</li>\n</ul>\n\n<p><strong>Update</strong></p>\n\n<p>It's probably possible to use reflection to recursively walk through the object graph to do a deep copy. WCF uses this technique to serialize an object, including all of its children. The trick is to annotate all of the child objects with an attribute that makes it discoverable. You might lose some performance benefits, however.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Quote on independent speed test (see comments below):</p>\n\n<blockquote>\n <p>I've run my own speed test using Neil's serialize/deserialize\n extension method, Contango's Nested MemberwiseClone, Alex Burtsev's\n reflection-based extension method and AutoMapper, 1 million times\n each. Serialize-deserialize was slowest, taking 15.7 seconds. Then\n came AutoMapper, taking 10.1 seconds. Much faster was the\n reflection-based method which took 2.4 seconds. By far the fastest was\n Nested MemberwiseClone, taking 0.1 seconds. Comes down to performance\n versus hassle of adding code to each class to clone it. If performance\n isn't an issue go with Alex Burtsev's method. \n – Simon Tewsi</p>\n</blockquote>\n" }, { "answer_id": 8708249, "author": "Kurt Richardson", "author_id": 1013542, "author_profile": "https://Stackoverflow.com/users/1013542", "pm_score": 4, "selected": false, "text": "<p>I believe that the BinaryFormatter approach is relatively slow (which came as a surprise to me!). You might be able to use ProtoBuf .NET for some objects if they meet the requirements of ProtoBuf. From the ProtoBuf Getting Started page (<a href=\"http://code.google.com/p/protobuf-net/wiki/GettingStarted\" rel=\"noreferrer\">http://code.google.com/p/protobuf-net/wiki/GettingStarted</a>):</p>\n\n<p><strong>Notes on types supported:</strong></p>\n\n<p>Custom classes that:</p>\n\n<ul>\n<li>Are marked as data-contract</li>\n<li>Have a parameterless constructor</li>\n<li>For Silverlight: are public</li>\n<li>Many common primitives, etc.</li>\n<li><em>Single</em> dimension arrays: T[]</li>\n<li>List&lt;T> / IList&lt;T></li>\n<li>Dictionary&lt;TKey, TValue> / IDictionary&lt;TKey, TValue></li>\n<li>any type which implements IEnumerable&lt;T> and has an Add(T) method</li>\n</ul>\n\n<p>The code assumes that types will be mutable around the elected members. Accordingly, custom structs are not supported, since they should be immutable.</p>\n\n<p>If your class meets these requirements you could try:</p>\n\n<pre><code>public static void deepCopy&lt;T&gt;(ref T object2Copy, ref T objectCopy)\n{\n using (var stream = new MemoryStream())\n {\n Serializer.Serialize(stream, object2Copy);\n stream.Position = 0;\n objectCopy = Serializer.Deserialize&lt;T&gt;(stream);\n }\n}\n</code></pre>\n\n<p>Which is VERY fast indeed...</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Here is working code for a modification of this (tested on .NET 4.6). It uses System.Xml.Serialization and System.IO. No need to mark classes as serializable.</p>\n\n<pre><code>public void DeepCopy&lt;T&gt;(ref T object2Copy, ref T objectCopy)\n{\n using (var stream = new MemoryStream())\n {\n var serializer = new XS.XmlSerializer(typeof(T));\n\n serializer.Serialize(stream, object2Copy);\n stream.Position = 0;\n objectCopy = (T)serializer.Deserialize(stream);\n }\n}\n</code></pre>\n" }, { "answer_id": 9961788, "author": "Suresh Kumar Veluswamy", "author_id": 1305119, "author_profile": "https://Stackoverflow.com/users/1305119", "pm_score": 3, "selected": false, "text": "<p>You can try this</p>\n\n<pre><code> public static object DeepCopy(object obj)\n {\n if (obj == null)\n return null;\n Type type = obj.GetType();\n\n if (type.IsValueType || type == typeof(string))\n {\n return obj;\n }\n else if (type.IsArray)\n {\n Type elementType = Type.GetType(\n type.FullName.Replace(\"[]\", string.Empty));\n var array = obj as Array;\n Array copied = Array.CreateInstance(elementType, array.Length);\n for (int i = 0; i &lt; array.Length; i++)\n {\n copied.SetValue(DeepCopy(array.GetValue(i)), i);\n }\n return Convert.ChangeType(copied, obj.GetType());\n }\n else if (type.IsClass)\n {\n\n object toret = Activator.CreateInstance(obj.GetType());\n FieldInfo[] fields = type.GetFields(BindingFlags.Public |\n BindingFlags.NonPublic | BindingFlags.Instance);\n foreach (FieldInfo field in fields)\n {\n object fieldValue = field.GetValue(obj);\n if (fieldValue == null)\n continue;\n field.SetValue(toret, DeepCopy(fieldValue));\n }\n return toret;\n }\n else\n throw new ArgumentException(\"Unknown type\");\n }\n</code></pre>\n\n<p>Thanks to DetoX83 <a href=\"http://www.codeproject.com/Articles/38270/Deep-copy-of-objects-in-C\" rel=\"noreferrer\">article</a> on code project.</p>\n" }, { "answer_id": 10267513, "author": "alex", "author_id": 1349430, "author_profile": "https://Stackoverflow.com/users/1349430", "pm_score": 2, "selected": false, "text": "<p>The best way is:</p>\n\n<pre><code> public interface IDeepClonable&lt;T&gt; where T : class\n {\n T DeepClone();\n }\n\n public class MyObj : IDeepClonable&lt;MyObj&gt;\n {\n public MyObj Clone()\n {\n var myObj = new MyObj();\n myObj._field1 = _field1;//value type\n myObj._field2 = _field2;//value type\n myObj._field3 = _field3;//value type\n\n if (_child != null)\n {\n myObj._child = _child.DeepClone(); //reference type .DeepClone() that does the same\n }\n\n int len = _array.Length;\n myObj._array = new MyObj[len]; // array / collection\n for (int i = 0; i &lt; len; i++)\n {\n myObj._array[i] = _array[i];\n }\n\n return myObj;\n }\n\n private bool _field1;\n public bool Field1\n {\n get { return _field1; }\n set { _field1 = value; }\n }\n\n private int _field2;\n public int Property2\n {\n get { return _field2; }\n set { _field2 = value; }\n }\n\n private string _field3;\n public string Property3\n {\n get { return _field3; }\n set { _field3 = value; }\n }\n\n private MyObj _child;\n private MyObj Child\n {\n get { return _child; }\n set { _child = value; }\n }\n\n private MyObj[] _array = new MyObj[4];\n }\n</code></pre>\n" }, { "answer_id": 11308879, "author": "Alex Burtsev", "author_id": 235715, "author_profile": "https://Stackoverflow.com/users/235715", "pm_score": 9, "selected": false, "text": "<p>I <a href=\"https://github.com/Burtsev-Alexey/net-object-deep-copy\" rel=\"noreferrer\">wrote a deep object copy extension method</a>, based on recursive <strong>\"MemberwiseClone\"</strong>. It is fast (<strong>three times faster</strong> than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes.</p>\n\n<p>Source code:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Reflection;\nusing System.ArrayExtensions;\n\nnamespace System\n{\n public static class ObjectExtensions\n {\n private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod(\"MemberwiseClone\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n public static bool IsPrimitive(this Type type)\n {\n if (type == typeof(String)) return true;\n return (type.IsValueType &amp; type.IsPrimitive);\n }\n\n public static Object Copy(this Object originalObject)\n {\n return InternalCopy(originalObject, new Dictionary&lt;Object, Object&gt;(new ReferenceEqualityComparer()));\n }\n private static Object InternalCopy(Object originalObject, IDictionary&lt;Object, Object&gt; visited)\n {\n if (originalObject == null) return null;\n var typeToReflect = originalObject.GetType();\n if (IsPrimitive(typeToReflect)) return originalObject;\n if (visited.ContainsKey(originalObject)) return visited[originalObject];\n if (typeof(Delegate).IsAssignableFrom(typeToReflect)) return null;\n var cloneObject = CloneMethod.Invoke(originalObject, null);\n if (typeToReflect.IsArray)\n {\n var arrayType = typeToReflect.GetElementType();\n if (IsPrimitive(arrayType) == false)\n {\n Array clonedArray = (Array)cloneObject;\n clonedArray.ForEach((array, indices) =&gt; array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));\n }\n\n }\n visited.Add(originalObject, cloneObject);\n CopyFields(originalObject, visited, cloneObject, typeToReflect);\n RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);\n return cloneObject;\n }\n\n private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary&lt;object, object&gt; visited, object cloneObject, Type typeToReflect)\n {\n if (typeToReflect.BaseType != null)\n {\n RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);\n CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info =&gt; info.IsPrivate);\n }\n }\n\n private static void CopyFields(object originalObject, IDictionary&lt;object, object&gt; visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func&lt;FieldInfo, bool&gt; filter = null)\n {\n foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))\n {\n if (filter != null &amp;&amp; filter(fieldInfo) == false) continue;\n if (IsPrimitive(fieldInfo.FieldType)) continue;\n var originalFieldValue = fieldInfo.GetValue(originalObject);\n var clonedFieldValue = InternalCopy(originalFieldValue, visited);\n fieldInfo.SetValue(cloneObject, clonedFieldValue);\n }\n }\n public static T Copy&lt;T&gt;(this T original)\n {\n return (T)Copy((Object)original);\n }\n }\n\n public class ReferenceEqualityComparer : EqualityComparer&lt;Object&gt;\n {\n public override bool Equals(object x, object y)\n {\n return ReferenceEquals(x, y);\n }\n public override int GetHashCode(object obj)\n {\n if (obj == null) return 0;\n return obj.GetHashCode();\n }\n }\n\n namespace ArrayExtensions\n {\n public static class ArrayExtensions\n {\n public static void ForEach(this Array array, Action&lt;Array, int[]&gt; action)\n {\n if (array.LongLength == 0) return;\n ArrayTraverse walker = new ArrayTraverse(array);\n do action(array, walker.Position);\n while (walker.Step());\n }\n }\n\n internal class ArrayTraverse\n {\n public int[] Position;\n private int[] maxLengths;\n\n public ArrayTraverse(Array array)\n {\n maxLengths = new int[array.Rank];\n for (int i = 0; i &lt; array.Rank; ++i)\n {\n maxLengths[i] = array.GetLength(i) - 1;\n }\n Position = new int[array.Rank];\n }\n\n public bool Step()\n {\n for (int i = 0; i &lt; Position.Length; ++i)\n {\n if (Position[i] &lt; maxLengths[i])\n {\n Position[i]++;\n for (int j = 0; j &lt; i; j++)\n {\n Position[j] = 0;\n }\n return true;\n }\n }\n return false;\n }\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 14855086, "author": "Eugene", "author_id": 1958491, "author_profile": "https://Stackoverflow.com/users/1958491", "pm_score": 1, "selected": false, "text": "<p>The MSDN documentation seems to hint that Clone should perform a deep copy, but it is never explicitly stated:</p>\n\n<p>The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberWiseClone… The MemberwiseClone method creates a shallow copy…</p>\n\n<p>You can find my post helpful. </p>\n\n<p><a href=\"http://pragmaticcoding.com/index.php/cloning-objects-in-c/\" rel=\"nofollow\">http://pragmaticcoding.com/index.php/cloning-objects-in-c/</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ]
I want a true deep copy. In Java, this was easy, but how do you do it in C#?
### Important Note [BinaryFormatter](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-5.0) has been deprecated, and will no longer be available in .NET after November 2023. See [BinaryFormatter Obsoletion Strategy](https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md) --- I've seen a few different approaches to this, but I use a generic utility method as such: ``` public static T DeepClone<T>(this T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T) formatter.Deserialize(ms); } } ``` Notes: * Your class MUST be marked as `[Serializable]` for this to work. * Your source file must include the following code: ``` using System.Runtime.Serialization.Formatters.Binary; using System.IO; ```
129,406
<p>When my browser renders the following test case, there's a gap below the image. From my understanding of CSS, the bottom of the blue box should touch the bottom of the red box. But that's not the case. Why?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt; &lt;head&gt; &lt;title&gt;foo&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div style="border: solid blue 2px; padding: 0px;"&gt; &lt;img alt='' style="border: solid red 2px; margin: 0px;" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png" /&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 129412, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>Because the image is inline it sits on the baseline. Try</p>\n\n<pre><code>vertical-align: bottom;\n</code></pre>\n\n<p>Alternately, in IE sometimes if you have whitespace around an image you get that. So if you remove all the whitespace between the div and img tags, that may resolve it.</p>\n" }, { "answer_id": 129425, "author": "Thomas Koschel", "author_id": 2012356, "author_profile": "https://Stackoverflow.com/users/2012356", "pm_score": 1, "selected": false, "text": "<p>Remove the line break before the tag, so that it directly follows the tag with no blanks between it.</p>\n\n<p>I don't know why, but for the Internet Explorer, this works.</p>\n" }, { "answer_id": 129426, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 2, "selected": false, "text": "<pre><code>display: block\n</code></pre>\n\n<p>in the image fixes it as well, but probably breaks it in other ways ;)</p>\n" }, { "answer_id": 129459, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p><code>line-height: 0;</code> on the parent <code>DIV</code> fixes this for me. Presumably, this means the default line-height is not 0.</p>\n" }, { "answer_id": 129519, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "<p>Inline elements are vertically aligned to the baseline, not the very bottom of the containing box. This is because text needs a small amount of space underneath for descenders - the tails on letters like lowercase 'p'. So there is an imaginary line a short distance above the bottom, called the baseline, and inline elements are vertically aligned with it by default.</p>\n\n<p>There's two ways of fixing this problem. You can either specify that the image should be vertically aligned to the bottom, or you can set it to be a block element, in which case it is no longer treated as a part of the text.</p>\n\n<p>In addition to this, Internet Explorer has an HTML parsing bug that does not ignore trailing whitespace after a closing element, so removing this whitespace may be necessary if you are having problems with Internet Explorer compatibility.</p>\n" }, { "answer_id": 129982, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><code>font-size:0;</code> on the parent DIV is another tricky way to fix it.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
When my browser renders the following test case, there's a gap below the image. From my understanding of CSS, the bottom of the blue box should touch the bottom of the red box. But that's not the case. Why? ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>foo</title> </head> <body> <div style="border: solid blue 2px; padding: 0px;"> <img alt='' style="border: solid red 2px; margin: 0px;" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png" /> </div> </body> </html> ```
Inline elements are vertically aligned to the baseline, not the very bottom of the containing box. This is because text needs a small amount of space underneath for descenders - the tails on letters like lowercase 'p'. So there is an imaginary line a short distance above the bottom, called the baseline, and inline elements are vertically aligned with it by default. There's two ways of fixing this problem. You can either specify that the image should be vertically aligned to the bottom, or you can set it to be a block element, in which case it is no longer treated as a part of the text. In addition to this, Internet Explorer has an HTML parsing bug that does not ignore trailing whitespace after a closing element, so removing this whitespace may be necessary if you are having problems with Internet Explorer compatibility.
129,417
<p>Coming from a desktop background I'm not sure exactly how to pass the exceptions I have caught to an Error page in order to avoid the standard exception screen being seen by my users. </p> <p>My general question is how do I pass the exception from page X to my Error page in ASP.net?</p>
[ { "answer_id": 129421, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>I think you can use the <strong>global.asax</strong> -- <strong>Application_Exception</strong> handler to catch the exception and then store it for displaying in an error page.</p>\n\n<p>But actually, your error page shouldn't contains code that might cause just another error. It should be simple \"Oops! something went wrong\" page.</p>\n\n<p>If you want details on the error, use Windows' events viewer or <a href=\"http://code.google.com/p/elmah/\" rel=\"nofollow noreferrer\">ELMAH</a> or employ some logging mechanism.</p>\n" }, { "answer_id": 129434, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 4, "selected": true, "text": "<p>I suggest using the customErrors section in the web.config:</p>\n<pre><code> &lt;customErrors mode=&quot;RemoteOnly&quot; defaultRedirect=&quot;/error.html&quot;&gt;\n &lt;error statusCode=&quot;403&quot; redirect=&quot;/accessdenied.html&quot; /&gt;\n &lt;error statusCode=&quot;404&quot; redirect=&quot;/pagenotfound.html&quot; /&gt;\n &lt;/customErrors&gt;\n</code></pre>\n<p>And then using <a href=\"https://code.google.com/archive/p/elmah/\" rel=\"nofollow noreferrer\">ELMAH</a> to email and/or log the error.</p>\n" }, { "answer_id": 129436, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>Use the custom error pages in asp.net, you can find it in the <a href=\"http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx\" rel=\"nofollow noreferrer\">customError</a> section in the web.config</p>\n" }, { "answer_id": 129447, "author": "David", "author_id": 18981, "author_profile": "https://Stackoverflow.com/users/18981", "pm_score": 2, "selected": false, "text": "<p>The pattern I use is to log the error in a try/catch block (using log4net), then do a response.redirect to a simple error page. This assumes you don't need to show any error details.</p>\n\n<p>If you need the exception details on a separate page, you might want to look at Server.GetLastError. I use that in global.asax (in the Application_Error event) to log unhandled exceptions and redirect to an error page.</p>\n" }, { "answer_id": 129450, "author": "marc", "author_id": 12260, "author_profile": "https://Stackoverflow.com/users/12260", "pm_score": 2, "selected": false, "text": "<p>We've had good luck capturing exceptions in the Global.asax Application_Error event, storing them in session, and redirecting to our error page. Alternately you could encode the error message and pass it to the error page in the querystring.</p>\n" }, { "answer_id": 129455, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 2, "selected": false, "text": "<p>You can also get the exception from </p>\n\n<pre><code>Server.GetLastError();\n</code></pre>\n" }, { "answer_id": 129463, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 1, "selected": false, "text": "<p>We capture the exception in the Global.asax file, store it in Session, the user is then redirected to the Error Page where we grab the exception for our Session variable and display the Message information to the user.</p>\n\n<pre><code> protected void Application_Error(object sender, EventArgs e)\n {\n Exception ex = Server.GetLastError();\n this.Session[CacheProvider.ToCacheKey(CacheKeys.LastError)] = ex;\n }\n</code></pre>\n\n<p>We do log the error message prior to displaying it the user.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20748/" ]
Coming from a desktop background I'm not sure exactly how to pass the exceptions I have caught to an Error page in order to avoid the standard exception screen being seen by my users. My general question is how do I pass the exception from page X to my Error page in ASP.net?
I suggest using the customErrors section in the web.config: ``` <customErrors mode="RemoteOnly" defaultRedirect="/error.html"> <error statusCode="403" redirect="/accessdenied.html" /> <error statusCode="404" redirect="/pagenotfound.html" /> </customErrors> ``` And then using [ELMAH](https://code.google.com/archive/p/elmah/) to email and/or log the error.
129,445
<p>I'm new to postgreSQL and I have a simple question:</p> <p>I'm trying to create a simple script that creates a DB so I can later call it like this:</p> <pre><code>psql -f createDB.sql </code></pre> <p>I want the script to call other scripts (separate ones for creating tables, adding constraints, functions etc), like this:</p> <pre><code>\i script1.sql \i script2.sql </code></pre> <p>It works fine provided that createDB.sql is in the <strong>same dir</strong>.</p> <p>But if I move script2 to a directory under the one with createDB, and modify the createDB so it looks like this:</p> <pre><code>\i script1.sql \i somedir\script2.sql </code></pre> <p>I get an error:</p> <blockquote> <p>psql:createDB.sql:2: somedir: Permission denied</p> </blockquote> <p>I'm using Postgres Plus 8.3 for windows, default postgres user.</p> <p><strong>EDIT:</strong></p> <p>Silly me, unix slashes solved the problem.</p>
[ { "answer_id": 129496, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 8, "selected": true, "text": "<p>Postgres started on Linux/Unix. I suspect that reversing the slash with fix it.</p>\n\n<pre><code>\\i somedir/script2.sql \n</code></pre>\n\n<p>If you need to fully qualify something</p>\n\n<pre><code>\\i c:/somedir/script2.sql\n</code></pre>\n\n<p>If that doesn't fix it, my next guess would be you need to escape the backslash.</p>\n\n<pre><code>\\i somedir\\\\script2.sql\n</code></pre>\n" }, { "answer_id": 129527, "author": "Grant Johnson", "author_id": 12518, "author_profile": "https://Stackoverflow.com/users/12518", "pm_score": 3, "selected": false, "text": "<p>Have you tried using Unix style slashes (/ instead of \\)?</p>\n\n<p>\\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.</p>\n\n<p>Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.</p>\n" }, { "answer_id": 15415502, "author": "phipex", "author_id": 1421953, "author_profile": "https://Stackoverflow.com/users/1421953", "pm_score": 2, "selected": false, "text": "<p>Try this, I work myself to do so</p>\n\n<pre><code>\\i 'somedir\\\\script2.sql'\n</code></pre>\n" }, { "answer_id": 42409201, "author": "shiba sahu", "author_id": 5427397, "author_profile": "https://Stackoverflow.com/users/5427397", "pm_score": 0, "selected": false, "text": "<p>i did try this and its working in windows machine to run a sql file on a specific schema.</p>\n\n<blockquote>\n <p>psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname &lt; e:\\Table.sql </p>\n</blockquote>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21853/" ]
I'm new to postgreSQL and I have a simple question: I'm trying to create a simple script that creates a DB so I can later call it like this: ``` psql -f createDB.sql ``` I want the script to call other scripts (separate ones for creating tables, adding constraints, functions etc), like this: ``` \i script1.sql \i script2.sql ``` It works fine provided that createDB.sql is in the **same dir**. But if I move script2 to a directory under the one with createDB, and modify the createDB so it looks like this: ``` \i script1.sql \i somedir\script2.sql ``` I get an error: > > psql:createDB.sql:2: somedir: Permission denied > > > I'm using Postgres Plus 8.3 for windows, default postgres user. **EDIT:** Silly me, unix slashes solved the problem.
Postgres started on Linux/Unix. I suspect that reversing the slash with fix it. ``` \i somedir/script2.sql ``` If you need to fully qualify something ``` \i c:/somedir/script2.sql ``` If that doesn't fix it, my next guess would be you need to escape the backslash. ``` \i somedir\\script2.sql ```
129,451
<p>If you are using Java or JavaScript, is there a good way to do something like a String subtraction so that given two strings:</p> <pre><code>org.company.project.component org.company.project.component.sub_component </code></pre> <p>you just get:</p> <pre><code>sub_component </code></pre> <p>I know that I could just write code to walk the string comparing characters, but I was hoping there was a way to do it in a really compact way. </p> <p>Another use-case is to find the diff between the strings:</p> <pre><code>org.company.project.component.diff org.company.project.component.sub_component </code></pre> <p>I actually only want to remove the sections that are identical.</p>
[ { "answer_id": 129461, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "<pre><code>String result = \"org.company.project.component.sub_component\".replace(\"org.company.project.component\",\"\")\n</code></pre>\n\n<p>Should work...</p>\n\n<p>EDIT: Apache commons libraries are also great to use</p>\n\n<p>As noted below, the StringUtils class does in fact have a method for this:\n<a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#remove(java.lang.String,%20java.lang.String)\" rel=\"nofollow noreferrer\">StringUtils.remove()</a></p>\n" }, { "answer_id": 129462, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 0, "selected": false, "text": "<p>Can't you just replace the occurrences of the first string in the second with an empty string ?</p>\n" }, { "answer_id": 129472, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 4, "selected": true, "text": "<p>Depends on <em>precisely</em> what you want. If you're looking for a way to compare strings in the general case -- meaning finding common sub-strings between arbitrary inputs -- then you're looking at something closer to the Levenshtein distance and similar algorithms. However, if all you need is prefix/suffix comparison, this should work:</p>\n\n<pre><code>public static String sub(String a, String b) {\n if (b.startsWith(a)) {\n return b.subString(a.length());\n }\n\n if (b.endsWith(a)) {\n return b.subString(0, b.length() - a.length());\n }\n\n return \"\";\n}\n</code></pre>\n\n<p>...or something roughly to that effect.</p>\n" }, { "answer_id": 129517, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 0, "selected": false, "text": "<p>If you're just trying to get whatever's after the last dot, I find this method easy in Javascript:</p>\n\n<pre><code>var baseString = \"org.company.project.component.sub_component\";\nvar splitString = baseString.split(\".\");\nvar subString = splitString[splitString.length - 1];\n</code></pre>\n\n<p>subString will contain the value you're looking for.</p>\n" }, { "answer_id": 147234, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 2, "selected": false, "text": "<p>At first glance, I thought of RegExp, but adding to the question, you removed that possibility by adding to the start-string ...</p>\n\n<p>So you'll have to make a procedure, that takes every character that are equal out of the resulting string, something like this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar a = \"org.company.project.component.diff\";\nvar b = \"org.company.project.component.sub_component\";\nvar i = 0;\nwhile(a.charAt(i) == b.charAt(i)){\n i++;\n}\nalert(b.substring(i));\n&lt;/script&gt;\n</code></pre>\n\n<p>By the way it doesn't have a meaning to set Java and javascript as equals in any context, a popular way of putting it could be: </p>\n\n<p>Java and javascript has four things in common: j - a - v - a !-)</p>\n" }, { "answer_id": 147903, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<pre><code>function sub(a, b) {\n return [a, b].join('\\x01').match(/^([^\\x01]*)[^\\x01]*\\x01\\1(.*)/)[2];\n}\n</code></pre>\n\n<p>Though this relies on that the character with code 1 does not appear in any of those strings.</p>\n" }, { "answer_id": 34756652, "author": "Jangofett2008", "author_id": 5781728, "author_profile": "https://Stackoverflow.com/users/5781728", "pm_score": -1, "selected": false, "text": "<p>This is a solution for the Javascript end of the question:</p>\n\n<pre><code>String.prototype.contracat = function(string){\n var thing = this.valueOf();\n for(var i=0; i&lt;string.length;i++){\n thing=thing.replace(string.charAt(i),\"\");\n }\n return thing\n};\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5412/" ]
If you are using Java or JavaScript, is there a good way to do something like a String subtraction so that given two strings: ``` org.company.project.component org.company.project.component.sub_component ``` you just get: ``` sub_component ``` I know that I could just write code to walk the string comparing characters, but I was hoping there was a way to do it in a really compact way. Another use-case is to find the diff between the strings: ``` org.company.project.component.diff org.company.project.component.sub_component ``` I actually only want to remove the sections that are identical.
Depends on *precisely* what you want. If you're looking for a way to compare strings in the general case -- meaning finding common sub-strings between arbitrary inputs -- then you're looking at something closer to the Levenshtein distance and similar algorithms. However, if all you need is prefix/suffix comparison, this should work: ``` public static String sub(String a, String b) { if (b.startsWith(a)) { return b.subString(a.length()); } if (b.endsWith(a)) { return b.subString(0, b.length() - a.length()); } return ""; } ``` ...or something roughly to that effect.
129,453
<p>Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the <code>EventHandler</code>/<code>EventArgs</code> practice, but what I like to do is have something like:</p> <pre><code>public delegate void EventHandler&lt;T&gt;(object src, EventArgs&lt;T&gt; args); public class EventArgs&lt;T&gt;: EventArgs { private T item; public EventArgs(T item) { this.item = item; } public T Item { get { return item; } } } </code></pre> <p>Later, I can have my</p> <pre><code>public event EventHandler&lt;Foo&gt; FooChanged; public event EventHandler&lt;Bar&gt; BarChanged; </code></pre> <p>However, it seems that the standard for .NET is to create a new delegate and <code>EventArgs</code> subclass for each type of event. Is there something wrong with my generic approach? <hr/> EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic <code>EventHandler&lt;TEventArgs></code>, so you don't need to create the generic delegate, but you still need the generic <code>EventArgs&lt;T></code> class, because <code>TEventArgs: EventArgs</code>. <hr/> Another EDIT: One downside (to me) of the built-in solution is the extra verbosity:</p> <pre><code>public event EventHandler&lt;EventArgs&lt;Foo&gt;&gt; FooChanged; </code></pre> <p>vs.</p> <pre><code>public event EventHandler&lt;Foo&gt; FooChanged; </code></pre> <p>It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?</p>
[ { "answer_id": 129466, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "<p>No, I don't think this is the wrong approach. I think it's even recommended in the [fantastic] book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321246756\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Framework Design Guidelines</a>. I do the same thing.</p>\n" }, { "answer_id": 129492, "author": "Chuck", "author_id": 9714, "author_profile": "https://Stackoverflow.com/users/9714", "pm_score": 1, "selected": false, "text": "<p>I do believe that the recent versions of .NET have just such an event handler defined in them. That's a big thumbs up as far as I'm concerned.</p>\n\n<p>/EDIT</p>\n\n<p>Didn't get the distinction there originally. As long as you are passing back a class that inherits from EventArgs, which you are, I don't see a problem. I would be concerned if you weren't wrapping the resultfor maintainability reasons. I still say it looks good to me.</p>\n" }, { "answer_id": 129505, "author": "David Walschots", "author_id": 20057, "author_profile": "https://Stackoverflow.com/users/20057", "pm_score": 2, "selected": false, "text": "<p>This is the correct implementation. It has been added to the .NET Framework (mscorlib) since generics first came available (2.0).</p>\n\n<p>For more on its usage and implementation see MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/db0etb8x.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/db0etb8x.aspx</a></p>\n" }, { "answer_id": 129511, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>Since .NET 2.0 </p>\n\n<blockquote>\n <p><code>EventHandler&lt;T&gt;</code></p>\n</blockquote>\n\n<p>has been implemented.</p>\n" }, { "answer_id": 129543, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 2, "selected": false, "text": "<p>The first time I saw this little pattern, I was using <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=7B9BA1A7-DD6D-4144-8AC6-DF88223AEE19&amp;displaylang=en\" rel=\"nofollow noreferrer\">Composite UI Application block</a>, from MS Patterns &amp; Practices group.</p>\n\n<p>It doesn't throw any red flag to me ; in fact it is even a smart way of leveraging generics to follow the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> rule.</p>\n" }, { "answer_id": 129590, "author": "dance2die", "author_id": 4035, "author_profile": "https://Stackoverflow.com/users/4035", "pm_score": 2, "selected": false, "text": "<p>You can find Generic EventHandler on MSDN <a href=\"http://msdn.microsoft.com/en-us/library/db0etb8x.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/db0etb8x.aspx</a></p>\n\n<p>I have been using generic EventHandler extensively and was able to prevent so-called \"Explosion of Types(Classes)\"\nProject was kept smaller and easier to navigate around.</p>\n\n<p>Coming up with a new intuitive a delegate for non-generic EventHandler delegate is painful and overlap with existing types\nAppending \"*EventHandler\" to new delegate name does not help much in my opinion</p>\n" }, { "answer_id": 129613, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 6, "selected": true, "text": "<p>Delegate of the following form has been added since .NET Framework 2.0 </p>\n\n<pre><code>public delegate void EventHandler&lt;TArgs&gt;(object sender, TArgs args) where TArgs : EventArgs\n</code></pre>\n\n<p>You approach goes a bit further, since you provide out-of-the-box implementation for EventArgs with single data item, but it lacks several properties of the original idea:</p>\n\n<ol>\n<li>You cannot add more properties to the event data without changing dependent code. You will have to change the delegate signature to provide more data to the event subscriber. </li>\n<li>Your data object is generic, but it is also \"anonymous\", and while reading the code you will have to decipher the \"Item\" property from usages. It should be named according to the data it provides.</li>\n<li>Using generics this way you can't make parallel hierarchy of EventArgs, when you have hierarchy of underlying (item) types. E.g. EventArgs&lt;BaseType&gt; is not base type for EventArgs&lt;DerivedType&gt;, even if BaseType is base for DerivedType. </li>\n</ol>\n\n<p>So, I think it is better to use generic EventHandler&lt;T&gt;, but still have custom EventArgs classes, organized according to the requirements of the data model. With Visual Studio and extensions like ReSharper, it is only a matter of few commands to create new class like that. </p>\n" }, { "answer_id": 129816, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 3, "selected": false, "text": "<p>To make generic event declaration easier, I created a couple of code snippets for it. To use them:</p>\n\n<ul>\n<li>Copy the whole snippet.</li>\n<li>Paste it in a text file (e.g. in Notepad).</li>\n<li>Save the file with a .snippet extension.</li>\n<li>Put the .snippet file in your appropriate snippet directory, such as:</li>\n</ul>\n\n<p><strong>Visual Studio 2008\\Code Snippets\\Visual C#\\My Code Snippets</strong></p>\n\n<p>Here's one that uses a custom EventArgs class with one property:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\"&gt;\n &lt;CodeSnippet Format=\"1.0.0\"&gt;\n &lt;Header&gt;\n &lt;Title&gt;Generic event with one type/argument.&lt;/Title&gt;\n &lt;Shortcut&gt;ev1Generic&lt;/Shortcut&gt;\n &lt;Description&gt;Code snippet for event handler and On method&lt;/Description&gt;\n &lt;Author&gt;Ryan Lundy&lt;/Author&gt;\n &lt;SnippetTypes&gt;\n &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;\n &lt;/SnippetTypes&gt;\n &lt;/Header&gt;\n &lt;Snippet&gt;\n &lt;Declarations&gt;\n &lt;Literal&gt;\n &lt;ID&gt;type&lt;/ID&gt;\n &lt;ToolTip&gt;Type of the property in the EventArgs subclass.&lt;/ToolTip&gt;\n &lt;Default&gt;propertyType&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;argName&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the argument in the EventArgs subclass constructor.&lt;/ToolTip&gt;\n &lt;Default&gt;propertyName&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;propertyName&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the property in the EventArgs subclass.&lt;/ToolTip&gt;\n &lt;Default&gt;PropertyName&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;eventName&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the event&lt;/ToolTip&gt;\n &lt;Default&gt;NameOfEvent&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;/Declarations&gt;\n &lt;Code Language=\"CSharp\"&gt;&lt;![CDATA[public class $eventName$EventArgs : System.EventArgs\n {\n public $eventName$EventArgs($type$ $argName$)\n {\n this.$propertyName$ = $argName$;\n }\n\n public $type$ $propertyName$ { get; private set; }\n }\n\n public event EventHandler&lt;$eventName$EventArgs&gt; $eventName$;\n protected virtual void On$eventName$($eventName$EventArgs e)\n {\n var handler = $eventName$;\n if (handler != null)\n handler(this, e);\n }]]&gt;\n &lt;/Code&gt;\n &lt;Imports&gt;\n &lt;Import&gt;\n &lt;Namespace&gt;System&lt;/Namespace&gt;\n &lt;/Import&gt;\n &lt;/Imports&gt;\n &lt;/Snippet&gt;\n &lt;/CodeSnippet&gt;\n&lt;/CodeSnippets&gt;\n</code></pre>\n\n<p>And here's one that has two properties:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\"&gt;\n &lt;CodeSnippet Format=\"1.0.0\"&gt;\n &lt;Header&gt;\n &lt;Title&gt;Generic event with two types/arguments.&lt;/Title&gt;\n &lt;Shortcut&gt;ev2Generic&lt;/Shortcut&gt;\n &lt;Description&gt;Code snippet for event handler and On method&lt;/Description&gt;\n &lt;Author&gt;Ryan Lundy&lt;/Author&gt;\n &lt;SnippetTypes&gt;\n &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;\n &lt;/SnippetTypes&gt;\n &lt;/Header&gt;\n &lt;Snippet&gt;\n &lt;Declarations&gt;\n &lt;Literal&gt;\n &lt;ID&gt;type1&lt;/ID&gt;\n &lt;ToolTip&gt;Type of the first property in the EventArgs subclass.&lt;/ToolTip&gt;\n &lt;Default&gt;propertyType1&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;arg1Name&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the first argument in the EventArgs subclass constructor.&lt;/ToolTip&gt;\n &lt;Default&gt;property1Name&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;property1Name&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the first property in the EventArgs subclass.&lt;/ToolTip&gt;\n &lt;Default&gt;Property1Name&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;type2&lt;/ID&gt;\n &lt;ToolTip&gt;Type of the second property in the EventArgs subclass.&lt;/ToolTip&gt;\n &lt;Default&gt;propertyType1&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;arg2Name&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the second argument in the EventArgs subclass constructor.&lt;/ToolTip&gt;\n &lt;Default&gt;property1Name&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;property2Name&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the second property in the EventArgs subclass.&lt;/ToolTip&gt;\n &lt;Default&gt;Property2Name&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;eventName&lt;/ID&gt;\n &lt;ToolTip&gt;Name of the event&lt;/ToolTip&gt;\n &lt;Default&gt;NameOfEvent&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;/Declarations&gt;\n &lt;Code Language=\"CSharp\"&gt;\n &lt;![CDATA[public class $eventName$EventArgs : System.EventArgs\n {\n public $eventName$EventArgs($type1$ $arg1Name$, $type2$ $arg2Name$)\n {\n this.$property1Name$ = $arg1Name$;\n this.$property2Name$ = $arg2Name$;\n }\n\n public $type1$ $property1Name$ { get; private set; }\n public $type2$ $property2Name$ { get; private set; }\n }\n\n public event EventHandler&lt;$eventName$EventArgs&gt; $eventName$;\n protected virtual void On$eventName$($eventName$EventArgs e)\n {\n var handler = $eventName$;\n if (handler != null)\n handler(this, e);\n }]]&gt;\n &lt;/Code&gt;\n &lt;Imports&gt;\n &lt;Import&gt;\n &lt;Namespace&gt;System&lt;/Namespace&gt;\n &lt;/Import&gt;\n &lt;/Imports&gt;\n &lt;/Snippet&gt;\n &lt;/CodeSnippet&gt;\n&lt;/CodeSnippets&gt;\n</code></pre>\n\n<p>You can follow the pattern to create them with as many properties as you like.</p>\n" }, { "answer_id": 2620754, "author": "ligaoren", "author_id": 248524, "author_profile": "https://Stackoverflow.com/users/248524", "pm_score": 1, "selected": false, "text": "<p>Use generic event handler instances</p>\n\n<p>Before .NET Framework 2.0, in order to pass custom information to the event handler, a new delegate had to be declared that specified a class derived from the System.EventArgs class. This is no longer true in .NET </p>\n\n<p>Framework 2.0, which introduced the System.EventHandler&lt;T>) delegate. This generic delegate allows any class derived from EventArgs to be used with the event handler. </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the `EventHandler`/`EventArgs` practice, but what I like to do is have something like: ``` public delegate void EventHandler<T>(object src, EventArgs<T> args); public class EventArgs<T>: EventArgs { private T item; public EventArgs(T item) { this.item = item; } public T Item { get { return item; } } } ``` Later, I can have my ``` public event EventHandler<Foo> FooChanged; public event EventHandler<Bar> BarChanged; ``` However, it seems that the standard for .NET is to create a new delegate and `EventArgs` subclass for each type of event. Is there something wrong with my generic approach? --- EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic `EventHandler<TEventArgs>`, so you don't need to create the generic delegate, but you still need the generic `EventArgs<T>` class, because `TEventArgs: EventArgs`. --- Another EDIT: One downside (to me) of the built-in solution is the extra verbosity: ``` public event EventHandler<EventArgs<Foo>> FooChanged; ``` vs. ``` public event EventHandler<Foo> FooChanged; ``` It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?
Delegate of the following form has been added since .NET Framework 2.0 ``` public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs ``` You approach goes a bit further, since you provide out-of-the-box implementation for EventArgs with single data item, but it lacks several properties of the original idea: 1. You cannot add more properties to the event data without changing dependent code. You will have to change the delegate signature to provide more data to the event subscriber. 2. Your data object is generic, but it is also "anonymous", and while reading the code you will have to decipher the "Item" property from usages. It should be named according to the data it provides. 3. Using generics this way you can't make parallel hierarchy of EventArgs, when you have hierarchy of underlying (item) types. E.g. EventArgs<BaseType> is not base type for EventArgs<DerivedType>, even if BaseType is base for DerivedType. So, I think it is better to use generic EventHandler<T>, but still have custom EventArgs classes, organized according to the requirements of the data model. With Visual Studio and extensions like ReSharper, it is only a matter of few commands to create new class like that.
129,498
<p>I am using the ADONetAppender to (try) to log data via a stored procedure (so that I may inject logic into the logging routine).</p> <p>My configuration settings are listed below. Can anybody tell what I'm doing wrong?</p> <pre class="lang-xml prettyprint-override"><code>&lt;appender name="ADONetAppender_SqlServer" type="log4net.Appender.ADONetAppender"&gt; &lt;bufferSize value="1" /&gt; &lt;threshold value="ALL"/&gt; &lt;param name="ConnectionType" value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt; &lt;param name="ConnectionString" value="&lt;MyConnectionString&gt;" /&gt; &lt;param name="UseTransactions" value="False" /&gt; &lt;commandText value="dbo.LogDetail_via_Log4Net" /&gt; &lt;commandType value="StoredProcedure" /&gt; &lt;parameter&gt; &lt;parameterName value="@AppLogID"/&gt; &lt;dbType value="String"/&gt; &lt;size value="50" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%property{LoggingSessionId}" /&gt; &lt;/layout&gt; &lt;/parameter&gt; &lt;parameter&gt; &lt;parameterName value="@CreateUser"/&gt; &lt;dbType value="String"/&gt; &lt;size value="50" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%property{HttpUser}" /&gt; &lt;/layout&gt; &lt;/parameter&gt; &lt;parameter&gt; &lt;parameterName value="@Message"/&gt; &lt;dbType value="String"/&gt; &lt;size value="8000" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%message" /&gt; &lt;/layout&gt; &lt;/parameter&gt; &lt;parameter&gt; &lt;parameterName value="@LogLevel"/&gt; &lt;dbType value="String"/&gt; &lt;size value="50"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%level" /&gt; &lt;/layout&gt; &lt;/parameter&gt; &lt;/appender&gt; </code></pre>
[ { "answer_id": 130028, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Thanks to a vigilant DBA, we have solved the problem.</p>\n\n<p>Note the size of the \"@Message\" parameter. log4net is taking a guess at how to convert the type and (I think) converting it to nvarchar even though the column is a varchar. This is a big deal because nvarchar has a max size of 4000 while varchar has a max size of 8000.</p>\n\n<p>The DBA saw errors as described in this KB article: <a href=\"http://support.microsoft.com/kb/827366\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/827366</a></p>\n\n<p>I changed the size to 4000 and everything works swimingly.</p>\n\n<p>Hopefully this will help somebody else avoid the same problem.</p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 1037572, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>\n </p>\n\n<pre><code>&lt;/configSections&gt;\n&lt;log4net&gt;\n\n &lt;appender name=\"AdoNetAppender\" type=\"log4net.Appender.AdoNetAppender\"&gt;\n\n &lt;bufferSize value=\"1\"/&gt;\n\n &lt;connectionType value=\"System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089\"/&gt;\n\n &lt;connectionString value=\"Data Source=yourservername;initial Catalog=Databasename;User ID=sa;Password=xyz;\"/&gt;\n\n\n\n &lt;commandText value=\"INSERT INTO Log4Net ([Date], [Thread], [Level], [Logger], [Message], \n [Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)\"/&gt;\n\n &lt;parameter&gt;\n\n &lt;parameterName value=\"@log_date\"/&gt;\n\n &lt;dbType value=\"DateTime\"/&gt;\n\n &lt;layout type=\"log4net.Layout.RawTimeStampLayout\"/&gt;\n\n &lt;/parameter&gt;\n\n &lt;parameter&gt;\n\n &lt;parameterName value=\"@thread\"/&gt;\n\n &lt;dbType value=\"String\"/&gt;\n\n &lt;size value=\"255\"/&gt;\n\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n\n &lt;conversionPattern value=\"%thread ip=%property{ip}\"/&gt;\n\n &lt;/layout&gt;\n\n &lt;/parameter&gt;\n\n &lt;parameter&gt;\n\n &lt;parameterName value=\"@log_level\"/&gt;\n\n &lt;dbType value=\"String\"/&gt;\n\n &lt;size value=\"50\"/&gt;\n\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n\n &lt;conversionPattern value=\"%level\"/&gt;\n\n &lt;/layout&gt;\n\n &lt;/parameter&gt;\n\n &lt;parameter&gt;\n\n &lt;parameterName value=\"@logger\"/&gt;\n\n &lt;dbType value=\"String\"/&gt;\n\n &lt;size value=\"255\"/&gt;\n\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n\n &lt;conversionPattern value=\"%logger\"/&gt;\n\n &lt;/layout&gt;\n\n &lt;/parameter&gt;\n\n &lt;parameter&gt;\n\n &lt;parameterName value=\"@message\"/&gt;\n\n &lt;dbType value=\"String\"/&gt;\n\n &lt;size value=\"4000\"/&gt;\n\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n\n &lt;conversionPattern value=\"%message\"/&gt;\n\n &lt;/layout&gt;\n</code></pre>\n" }, { "answer_id": 3787492, "author": "Bob Banks", "author_id": 163222, "author_profile": "https://Stackoverflow.com/users/163222", "pm_score": 3, "selected": false, "text": "<p>Use \"AnsiString\" as dbType for varchar. \"String\" for nvarchar.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.dbtype%28v=VS.90%29.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.data.dbtype%28v=VS.90%29.aspx</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using the ADONetAppender to (try) to log data via a stored procedure (so that I may inject logic into the logging routine). My configuration settings are listed below. Can anybody tell what I'm doing wrong? ```xml <appender name="ADONetAppender_SqlServer" type="log4net.Appender.ADONetAppender"> <bufferSize value="1" /> <threshold value="ALL"/> <param name="ConnectionType" value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <param name="ConnectionString" value="<MyConnectionString>" /> <param name="UseTransactions" value="False" /> <commandText value="dbo.LogDetail_via_Log4Net" /> <commandType value="StoredProcedure" /> <parameter> <parameterName value="@AppLogID"/> <dbType value="String"/> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{LoggingSessionId}" /> </layout> </parameter> <parameter> <parameterName value="@CreateUser"/> <dbType value="String"/> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{HttpUser}" /> </layout> </parameter> <parameter> <parameterName value="@Message"/> <dbType value="String"/> <size value="8000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@LogLevel"/> <dbType value="String"/> <size value="50"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> </appender> ```
Use "AnsiString" as dbType for varchar. "String" for nvarchar. <http://msdn.microsoft.com/en-us/library/system.data.dbtype%28v=VS.90%29.aspx>
129,502
<p>This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.</p> <p>It feels like it should be possible to get text to wrap without creating a custom cell, since a <code>UITableViewCell</code> contains a <code>UILabel</code> by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.</p> <p>I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:</p> <pre><code>cell.text = @""; // create the label UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0]; </code></pre> <p>then I get a valid label, but setting <code>numberOfLines</code> on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the <code>UILabel</code> for the text to display - I'm just returning a large value for the height in <code>heightForRowAtIndexPath</code>.</p>
[ { "answer_id": 129743, "author": "drewh", "author_id": 1967, "author_profile": "https://Stackoverflow.com/users/1967", "pm_score": -1, "selected": false, "text": "<p>I don't think you can manipulate a base <code>UITableViewCell's</code> private <code>UILabel</code> to do this. You could add a new <code>UILabel</code> to the cell yourself and use <code>numberOfLines</code> with <code>sizeToFit</code> to size it appropriately. Something like:</p>\n\n<pre><code>UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];\nlabel.numberOfLines = &lt;...an appriate number of lines...&gt;\nlabel.text = &lt;...your text...&gt;\n[label sizeToFit];\n[cell addSubview:label];\n[label release];\n</code></pre>\n" }, { "answer_id": 905565, "author": "Tim Rupe", "author_id": 92208, "author_profile": "https://Stackoverflow.com/users/92208", "pm_score": 9, "selected": true, "text": "<p>Here is a simpler way, and it works for me:</p>\n\n<p>Inside your <code>cellForRowAtIndexPath:</code> function. The first time you create your cell:</p>\n\n<pre><code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\nif (cell == nil)\n{\n cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];\n cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;\n cell.textLabel.numberOfLines = 0;\n cell.textLabel.font = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n}\n</code></pre>\n\n<p>You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.</p>\n\n<p>The next part is to specify how large your <code>UITableViewCell</code> will be, so do that in your <code>heightForRowAtIndexPath</code> function:</p>\n\n<pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n NSString *cellText = @\"Go get some text for your cell.\";\n UIFont *cellFont = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);\n CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];\n\n return labelSize.height + 20;\n}\n</code></pre>\n\n<p>I added 20 to my returned cell height because I like a little buffer around my text.</p>\n" }, { "answer_id": 3054313, "author": "dukz", "author_id": 286105, "author_profile": "https://Stackoverflow.com/users/286105", "pm_score": 0, "selected": false, "text": "<p>I think this is a better and shorter solution. Just format the <code>UILabel</code> (<code>textLabel</code>) of the cell to auto calculate for the height by specifying <code>sizeToFit</code> and everything should be fine.</p>\n\n<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n static NSString *CellIdentifier = @\"Cell\";\n\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n if (cell == nil)\n {\n cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];\n }\n\n // Configure the cell...\n cell.textLabel.text = @\"Whatever text you want to put here is ok\";\n cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;\n cell.textLabel.numberOfLines = 0;\n [cell.textLabel sizeToFit];\n\n return cell;\n}\n</code></pre>\n" }, { "answer_id": 4990118, "author": "Richard Le Mesurier", "author_id": 383414, "author_profile": "https://Stackoverflow.com/users/383414", "pm_score": 2, "selected": false, "text": "<p>A brief comment / answer to record my experience when I had the same problem. Despite using the code examples, the table view cell height was adjusting, but the label inside the cell was still not adjusting correctly - solution was that I was loading my cell from a custom NIB file, which happens <strong>after</strong> the cell height in adjusted.</p>\n\n<p>And I had my settings inside the NIB file to not wrap text, and only have 1 line for the label; the NIB file settings were overriding the settings I adjusted inside the code.</p>\n\n<p>The lesson I took was to make sure to always bear in mind what the state of the objects are at each point in time - they might not have been created yet! ... hth someone down the line.</p>\n" }, { "answer_id": 10189219, "author": "Arshad Parwez", "author_id": 883657, "author_profile": "https://Stackoverflow.com/users/883657", "pm_score": 2, "selected": false, "text": "<p>If we are to add only text in <code>UITableView</code> cell, we need only two delegates to work with (no need to add extra <code>UILabels</code>)</p>\n\n<p>1) <code>cellForRowAtIndexPath</code></p>\n\n<p>2) <code>heightForRowAtIndexPath</code></p>\n\n<p>This solution worked for me:-</p>\n\n<pre><code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath\n{ \n static NSString *CellIdentifier = @\"Cell\";\n\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n\n if (cell == nil)\n {\n cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];\n }\n\n cell.textLabel.font = [UIFont fontWithName:@\"Helvetica\" size:16];\n cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;\n cell.textLabel.numberOfLines = 0;\n\n [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; \n cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];\n NSLog(@\"%@\",cell.textLabel.text);\n\n cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"arrow.png\" ]];\n\n return cell;\n\n}\n\n- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{ \n CGSize labelSize = CGSizeMake(200.0, 20.0);\n\n NSString *strTemp = [mutArr objectAtIndex:indexPath.section];\n\n if ([strTemp length] &gt; 0)\n labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];\n\n return (labelSize.height + 10);\n}\n</code></pre>\n\n<p>Here the string <code>mutArr</code> is a mutable array from which i am getting my data. </p>\n\n<p><strong>EDIT :-</strong> Here is the array which I took.</p>\n\n<pre><code>mutArr= [[NSMutableArray alloc] init];\n\n[mutArr addObject:@\"HEMAN\"];\n[mutArr addObject:@\"SUPERMAN\"];\n[mutArr addObject:@\"Is SUPERMAN powerful than HEMAN\"];\n[mutArr addObject:@\"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them\"];\n[mutArr addObject:@\"Where are BATMAN and SPIDERMAN\"];\n</code></pre>\n" }, { "answer_id": 11135174, "author": "Vincent", "author_id": 1276622, "author_profile": "https://Stackoverflow.com/users/1276622", "pm_score": 1, "selected": false, "text": "<p>I use the following solutions.</p>\n\n<p>The data is provided separately in a member:</p>\n\n<pre><code>-(NSString *)getHeaderData:(int)theSection {\n ...\n return rowText;\n}\n</code></pre>\n\n<p>The handling can be easily done in <code>cellForRowAtIndexPath</code>.\nDefine the cell / define the font and assign these values to the result \"cell\".\nNote that the <code>numberoflines</code> is set to \"0\", which means take what is needed.</p>\n\n<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n static NSString *CellIdentifier = @\"Cell\";\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n\n UIFont *cellFont = [UIFont fontWithName:@\"Verdana\" size:12.0];\n cell.textLabel.text= [self getRowData:indexPath.section];\n cell.textLabel.font = cellFont;\n cell.textLabel.numberOfLines=0;\n return cell;\n}\n</code></pre>\n\n<p>In <code>heightForRowAtIndexPath</code>, I calculate the heights of the wrapped text.\nThe boding size shall be related to the width of your cell. For iPad this shall be 1024.\nFor iPhone en iPod 320.</p>\n\n<pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n UIFont *cellFont = [UIFont fontWithName:@\"Verdana\" size:12.0];\n CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);\n CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];\n return requiredSize.height; \n}\n</code></pre>\n" }, { "answer_id": 22235855, "author": "ddiego", "author_id": 589472, "author_profile": "https://Stackoverflow.com/users/589472", "pm_score": 4, "selected": false, "text": "<p>Updated Tim Rupe's answer for iOS7:</p>\n\n<pre><code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\nif (cell == nil)\n{\n cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;\n cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;\n cell.textLabel.numberOfLines = 0;\n cell.textLabel.font = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n}\n\n- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath\n{\n NSString *cellText = @\"Go get some text for your cell.\";\n UIFont *cellFont = [UIFont fontWithName:@\"Helvetica\" size:17.0];\n\n NSAttributedString *attributedText =\n [[NSAttributedString alloc]\n initWithString:cellText\n attributes:@\n {\n NSFontAttributeName: cellFont\n }];\n CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)\n options:NSStringDrawingUsesLineFragmentOrigin\n context:nil];\n return rect.size.height + 20;\n}\n</code></pre>\n" }, { "answer_id": 29225817, "author": "Manish Kr. Shukla", "author_id": 3860249, "author_profile": "https://Stackoverflow.com/users/3860249", "pm_score": 1, "selected": false, "text": "<p>I found this to be quite simple and straightForward : </p>\n\n<pre><code>[self.tableView setRowHeight:whatEvereight.0f];\n</code></pre>\n\n<p>for e.g. :</p>\n\n<pre><code>[self.tableView setRowHeight:80.0f];\n</code></pre>\n\n<p><strong>This may or may not be the best / standard approach to do so, but it worked in my case.</strong></p>\n" }, { "answer_id": 39989707, "author": "Jason", "author_id": 1066787, "author_profile": "https://Stackoverflow.com/users/1066787", "pm_score": 2, "selected": false, "text": "<p>Now the tableviews can have self-sizing cells. Set the table view up as follows</p>\n\n<p><code>tableView.estimatedRowHeight = 85.0 //use an appropriate estimate\ntableView.rowHeight = UITableViewAutomaticDimension</code></p>\n\n<p><a href=\"https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html#//apple_ref/doc/uid/TP40010853-CH25-SW1\" rel=\"nofollow\">Apple Reference</a></p>\n" }, { "answer_id": 54085798, "author": "Naresh", "author_id": 8090893, "author_profile": "https://Stackoverflow.com/users/8090893", "pm_score": 1, "selected": false, "text": "<p>Try my code in swift . This code will work for normal UILabels also.</p>\n\n<pre><code>extension UILabel {\n func lblFunction() {\n //You can pass here all UILabel properties like Font, colour etc....\n numberOfLines = 0\n lineBreakMode = .byWordWrapping//If you want word wraping\n lineBreakMode = .byCharWrapping//If you want character wraping\n }\n}\n</code></pre>\n\n<p>Now call simply like this</p>\n\n<pre><code>cell.textLabel.lblFunction()//Replace your label name \n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18017/" ]
This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables. It feels like it should be possible to get text to wrap without creating a custom cell, since a `UITableViewCell` contains a `UILabel` by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work. I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this: ``` cell.text = @""; // create the label UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0]; ``` then I get a valid label, but setting `numberOfLines` on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the `UILabel` for the text to display - I'm just returning a large value for the height in `heightForRowAtIndexPath`.
Here is a simpler way, and it works for me: Inside your `cellForRowAtIndexPath:` function. The first time you create your cell: ``` UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; cell.textLabel.numberOfLines = 0; cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0]; } ``` You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs. The next part is to specify how large your `UITableViewCell` will be, so do that in your `heightForRowAtIndexPath` function: ``` - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *cellText = @"Go get some text for your cell."; UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0]; CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT); CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; return labelSize.height + 20; } ``` I added 20 to my returned cell height because I like a little buffer around my text.
129,507
<p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
[ { "answer_id": 129522, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 11, "selected": true, "text": "<p>Use <a href=\"http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises\" rel=\"noreferrer\"><code>TestCase.assertRaises</code></a> (or <code>TestCase.failUnlessRaises</code>) from the unittest module, for example:</p>\n\n<pre><code>import mymod\n\nclass MyTestCase(unittest.TestCase):\n def test1(self):\n self.assertRaises(SomeCoolException, mymod.myfunc)\n</code></pre>\n" }, { "answer_id": 129528, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 6, "selected": false, "text": "<p>Your code should follow this pattern (this is a unittest module style test):</p>\n\n<pre><code>def test_afunction_throws_exception(self):\n try:\n afunction()\n except ExpectedException:\n pass\n except Exception:\n self.fail('unexpected exception raised')\n else:\n self.fail('ExpectedException not raised')\n</code></pre>\n\n<p>On Python &lt; 2.7 this construct is useful for checking for specific values in the expected exception. The unittest function <code>assertRaises</code> only checks if an exception was raised.</p>\n" }, { "answer_id": 129610, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 9, "selected": false, "text": "<p>The code in my previous answer can be simplified to:</p>\n<pre><code>def test_afunction_throws_exception(self):\n self.assertRaises(ExpectedException, afunction)\n</code></pre>\n<p>And if a function takes arguments, just pass them into assertRaises like this:</p>\n<pre><code>def test_afunction_throws_exception(self):\n self.assertRaises(ExpectedException, afunction, arg1, arg2)\n</code></pre>\n" }, { "answer_id": 132682, "author": "pi.", "author_id": 15274, "author_profile": "https://Stackoverflow.com/users/15274", "pm_score": 3, "selected": false, "text": "<p>I use <strong>doctest</strong>[1] almost everywhere because I like the fact that I document and test my functions at the same time.</p>\n\n<p>Have a look at this code:</p>\n\n<pre><code>def throw_up(something, gowrong=False):\n \"\"\"\n &gt;&gt;&gt; throw_up('Fish n Chips')\n Traceback (most recent call last):\n ...\n Exception: Fish n Chips\n\n &gt;&gt;&gt; throw_up('Fish n Chips', gowrong=True)\n 'I feel fine!'\n \"\"\"\n if gowrong:\n return \"I feel fine!\"\n raise Exception(something)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n\n<p>If you put this example in a module and run it from the command line both test cases are evaluated and checked.</p>\n\n<p>[1] <a href=\"http://docs.python.org/lib/module-doctest.html\" rel=\"noreferrer\">Python documentation: 23.2 doctest -- Test interactive Python examples</a></p>\n" }, { "answer_id": 241809, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 3, "selected": false, "text": "<p>I just discovered that the <a href=\"http://www.voidspace.org.uk/python/mock.html\" rel=\"noreferrer\">Mock library</a> provides an assertRaisesWithMessage() method (in its unittest.TestCase subclass), which will check not only that the expected exception is raised, but also that it is raised with the expected message:</p>\n\n<pre><code>from testcase import TestCase\n\nimport mymod\n\nclass MyTestCase(TestCase):\n def test1(self):\n self.assertRaisesWithMessage(SomeCoolException,\n 'expected message',\n mymod.myfunc)\n</code></pre>\n" }, { "answer_id": 3166985, "author": "Art", "author_id": 62194, "author_profile": "https://Stackoverflow.com/users/62194", "pm_score": 9, "selected": false, "text": "<p>Since Python 2.7 you can use context manager to get ahold of the actual Exception object thrown:</p>\n\n<pre><code>import unittest\n\ndef broken_function():\n raise Exception('This is broken')\n\nclass MyTestCase(unittest.TestCase):\n def test(self):\n with self.assertRaises(Exception) as context:\n broken_function()\n\n self.assertTrue('This is broken' in context.exception)\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n\n<p><a href=\"http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises\" rel=\"noreferrer\">http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises</a></p>\n\n<hr>\n\n<p>In <strong>Python 3.5</strong>, you have to wrap <code>context.exception</code> in <code>str</code>, otherwise you'll get a <code>TypeError</code></p>\n\n<pre><code>self.assertTrue('This is broken' in str(context.exception))\n</code></pre>\n" }, { "answer_id": 3983323, "author": "Bruno Carvalho", "author_id": 482398, "author_profile": "https://Stackoverflow.com/users/482398", "pm_score": 3, "selected": false, "text": "<p>You can use assertRaises from the unittest module</p>\n\n<pre><code>import unittest\n\nclass TestClass():\n def raises_exception(self):\n raise Exception(\"test\")\n\nclass MyTestCase(unittest.TestCase):\n def test_if_method_raises_correct_exception(self):\n test_class = TestClass()\n # note that you dont use () when passing the method to assertRaises\n self.assertRaises(Exception, test_class.raises_exception)\n</code></pre>\n" }, { "answer_id": 14712903, "author": "macm", "author_id": 506038, "author_profile": "https://Stackoverflow.com/users/506038", "pm_score": 5, "selected": false, "text": "<p>from: <a href=\"http://www.lengrand.fr/2011/12/pythonunittest-assertraises-raises-error/\" rel=\"noreferrer\">http://www.lengrand.fr/2011/12/pythonunittest-assertraises-raises-error/</a></p>\n\n<p>First, here is the corresponding (still dum :p) function in file dum_function.py :</p>\n\n<pre><code>def square_value(a):\n \"\"\"\n Returns the square value of a.\n \"\"\"\n try:\n out = a*a\n except TypeError:\n raise TypeError(\"Input should be a string:\")\n\n return out\n</code></pre>\n\n<p>Here is the test to be performed (only this test is inserted):</p>\n\n<pre><code>import dum_function as df # import function module\nimport unittest\nclass Test(unittest.TestCase):\n \"\"\"\n The class inherits from unittest\n \"\"\"\n def setUp(self):\n \"\"\"\n This method is called before each test\n \"\"\"\n self.false_int = \"A\"\n\n def tearDown(self):\n \"\"\"\n This method is called after each test\n \"\"\"\n pass\n #---\n ## TESTS\n def test_square_value(self):\n # assertRaises(excClass, callableObj) prototype\n self.assertRaises(TypeError, df.square_value(self.false_int))\n\n if __name__ == \"__main__\":\n unittest.main()\n</code></pre>\n\n<p>We are now ready to test our function! Here is what happens when trying to run the test :</p>\n\n<pre><code>======================================================================\nERROR: test_square_value (__main__.Test)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"test_dum_function.py\", line 22, in test_square_value\n self.assertRaises(TypeError, df.square_value(self.false_int))\n File \"/home/jlengrand/Desktop/function.py\", line 8, in square_value\n raise TypeError(\"Input should be a string:\")\nTypeError: Input should be a string:\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (errors=1)\n</code></pre>\n\n<p>The TypeError is actullay raised, and generates a test failure. The problem is that this is exactly the behavior we wanted :s.</p>\n\n<p>To avoid this error, simply run the function using lambda in the test call :</p>\n\n<pre><code>self.assertRaises(TypeError, lambda: df.square_value(self.false_int))\n</code></pre>\n\n<p>The final output :</p>\n\n<pre><code>----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n</code></pre>\n\n<p>Perfect !</p>\n\n<p>... and for me is perfect too!!</p>\n\n<p>Thansk a lot Mr. Julien Lengrand-Lambert</p>\n\n<hr>\n\n<p>This test assert actually returns a <strong>false positive</strong>. That happens because the lambda inside the 'assertRaises' is the unit that raises type error and <strong>not</strong> the tested function.</p>\n" }, { "answer_id": 23780046, "author": "Pigueiras", "author_id": 1004046, "author_profile": "https://Stackoverflow.com/users/1004046", "pm_score": 5, "selected": false, "text": "<p>If you are using <code>pytest</code> you can use <code>pytest.raises(Exception)</code>:</p>\n<p>Example:</p>\n<pre><code>def test_div_zero():\n with pytest.raises(ZeroDivisionError):\n 1/0\n</code></pre>\n<p>And the result:</p>\n<pre><code>pigueiras@pigueiras$ py.test\n================= test session starts =================\nplatform linux2 -- Python 2.6.6 -- py-1.4.20 -- pytest-2.5.2 -- /usr/bin/python\ncollected 1 items \n\ntests/test_div_zero.py:6: test_div_zero PASSED\n</code></pre>\n<p>Or you can build your own <code>contextmanager</code> to check if the exception was raised.</p>\n<pre><code>import contextlib\n\[email protected]\ndef raises(exception):\n try:\n yield \n except exception as e:\n assert True\n else:\n assert False\n</code></pre>\n<p>And then you can use <code>raises</code> like this:</p>\n<pre><code>with raises(Exception):\n print &quot;Hola&quot; # Calls assert False\n\nwith raises(Exception):\n raise Exception # Calls assert True\n</code></pre>\n" }, { "answer_id": 28223420, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 7, "selected": false, "text": "<blockquote>\n <p><strong>How do you test that a Python function throws an exception?</strong></p>\n \n <p>How does one write a test that fails only if a function doesn't throw\n an expected exception?</p>\n</blockquote>\n\n<h1>Short Answer:</h1>\n\n<p>Use the <code>self.assertRaises</code> method as a context manager:</p>\n\n<pre><code> def test_1_cannot_add_int_and_str(self):\n with self.assertRaises(TypeError):\n 1 + '1'\n</code></pre>\n\n<h1>Demonstration</h1>\n\n<p>The best practice approach is fairly easy to demonstrate in a Python shell. </p>\n\n<p><strong>The <code>unittest</code> library</strong></p>\n\n<p>In Python 2.7 or 3:</p>\n\n<pre><code>import unittest\n</code></pre>\n\n<p>In Python 2.6, you can install a backport of 2.7's <code>unittest</code> library, called <a href=\"https://pypi.python.org/pypi/unittest2\" rel=\"noreferrer\">unittest2</a>, and just alias that as <code>unittest</code>:</p>\n\n<pre><code>import unittest2 as unittest\n</code></pre>\n\n<h1>Example tests</h1>\n\n<p>Now, paste into your Python shell the following test of Python's type-safety:</p>\n\n<pre><code>class MyTestCase(unittest.TestCase):\n def test_1_cannot_add_int_and_str(self):\n with self.assertRaises(TypeError):\n 1 + '1'\n def test_2_cannot_add_int_and_str(self):\n import operator\n self.assertRaises(TypeError, operator.add, 1, '1')\n</code></pre>\n\n<p>Test one uses <code>assertRaises</code> as a context manager, which ensures that the error is properly caught and cleaned up, while recorded. </p>\n\n<p>We could also write it <em>without</em> the context manager, see test two. The first argument would be the error type you expect to raise, the second argument, the function you are testing, and the remaining args and keyword args will be passed to that function. </p>\n\n<p>I think it's far more simple, readable, and maintainable to just to use the context manager.</p>\n\n<h1>Running the tests</h1>\n\n<p>To run the tests:</p>\n\n<pre><code>unittest.main(exit=False)\n</code></pre>\n\n<p>In Python 2.6, you'll probably <a href=\"https://stackoverflow.com/a/21262077/541136\">need the following</a>:</p>\n\n<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))\n</code></pre>\n\n<p>And your terminal should output the following:</p>\n\n<pre><code>..\n----------------------------------------------------------------------\nRan 2 tests in 0.007s\n\nOK\n&lt;unittest2.runner.TextTestResult run=2 errors=0 failures=0&gt;\n</code></pre>\n\n<p>And we see that as we expect, attempting to add a <code>1</code> and a <code>'1'</code> result in a <code>TypeError</code>.</p>\n\n<hr>\n\n<p>For more verbose output, try this:</p>\n\n<pre><code>unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))\n</code></pre>\n" }, { "answer_id": 56561182, "author": "Arindam Roychowdhury", "author_id": 1076965, "author_profile": "https://Stackoverflow.com/users/1076965", "pm_score": 3, "selected": false, "text": "<p>There are a lot of answers here. The code shows how we can create an Exception, how we can use that exception in our methods, and finally, how you can verify in a unit test, the correct exceptions being raised.</p>\n\n<pre><code>import unittest\n\nclass DeviceException(Exception):\n def __init__(self, msg, code):\n self.msg = msg\n self.code = code\n def __str__(self):\n return repr(\"Error {}: {}\".format(self.code, self.msg))\n\nclass MyDevice(object):\n def __init__(self):\n self.name = 'DefaultName'\n\n def setParameter(self, param, value):\n if isinstance(value, str):\n setattr(self, param , value)\n else:\n raise DeviceException('Incorrect type of argument passed. Name expects a string', 100001)\n\n def getParameter(self, param):\n return getattr(self, param)\n\nclass TestMyDevice(unittest.TestCase):\n\n def setUp(self):\n self.dev1 = MyDevice()\n\n def tearDown(self):\n del self.dev1\n\n def test_name(self):\n \"\"\" Test for valid input for name parameter \"\"\"\n\n self.dev1.setParameter('name', 'MyDevice')\n name = self.dev1.getParameter('name')\n self.assertEqual(name, 'MyDevice')\n\n def test_invalid_name(self):\n \"\"\" Test to check if error is raised if invalid type of input is provided \"\"\"\n\n self.assertRaises(DeviceException, self.dev1.setParameter, 'name', 1234)\n\n def test_exception_message(self):\n \"\"\" Test to check if correct exception message and code is raised when incorrect value is passed \"\"\"\n\n with self.assertRaises(DeviceException) as cm:\n self.dev1.setParameter('name', 1234)\n self.assertEqual(cm.exception.msg, 'Incorrect type of argument passed. Name expects a string', 'mismatch in expected error message')\n self.assertEqual(cm.exception.code, 100001, 'mismatch in expected error code')\n\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n" }, { "answer_id": 58225392, "author": "RUser4512", "author_id": 4791408, "author_profile": "https://Stackoverflow.com/users/4791408", "pm_score": -1, "selected": false, "text": "<p>While all the answers are perfectly fine, I was looking for a way to test if a function raised an exception without relying on unit testing frameworks and having to write test classes.</p>\n\n<p>I ended up writing the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def assert_error(e, x):\n try:\n e(x)\n except:\n return\n raise AssertionError()\n\ndef failing_function(x):\n raise ValueError()\n\ndef dummy_function(x):\n return x\n\nif __name__==\"__main__\":\n assert_error(failing_function, 0)\n assert_error(dummy_function, 0)\n</code></pre>\n\n<p>And it fails on the right line :</p>\n\n<pre><code>Traceback (most recent call last):\n File \"assert_error.py\", line 16, in &lt;module&gt;\n assert_error(dummy_function, 0)\n File \"assert_error.py\", line 6, in assert_error\n raise AssertionError()\nAssertionError\n</code></pre>\n" }, { "answer_id": 62253324, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 5, "selected": false, "text": "<p>As I haven't seen any detailed explanation on how to check if we got a specific exception among a list of accepted one using context manager, or other exception details I will add mine (checked on python 3.8).</p>\n<p>If I just want to check that function is raising for instance <code>TypeError</code>, I would write:</p>\n<pre><code>with self.assertRaises(TypeError):\n function_raising_some_exception(parameters)\n</code></pre>\n<p>If I want to check that function is raising either <code>TypeError</code> or <code>IndexError</code>, I would write:</p>\n<pre><code>with self.assertRaises((TypeError,IndexError)):\n function_raising_some_exception(parameters)\n</code></pre>\n<p>And if I want even more details about the Exception raised I could catch it in a context like this:</p>\n<pre><code># Here I catch any exception \nwith self.assertRaises(Exception) as e:\n function_raising_some_exception(parameters)\n\n# Here I check actual exception type (but I could\n# check anything else about that specific exception,\n# like it's actual message or values stored in the exception)\nself.assertTrue(type(e.exception) in [TypeError,MatrixIsSingular])\n</code></pre>\n" }, { "answer_id": 64540525, "author": "Denis Biwott", "author_id": 8173167, "author_profile": "https://Stackoverflow.com/users/8173167", "pm_score": 2, "selected": false, "text": "<p>For those on Django, you can use context manager to run the faulty function and assert it raises the exception with a certain message using <code>assertRaisesMessage</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>with self.assertRaisesMessage(SomeException,'Some error message e.g 404 Not Found'):\n faulty_funtion()\n\n</code></pre>\n" }, { "answer_id": 65671324, "author": "Stephan Schielke", "author_id": 411718, "author_profile": "https://Stackoverflow.com/users/411718", "pm_score": 2, "selected": false, "text": "<p>For await/async <strong>aiounittest</strong> there is a slightly different pattern:</p>\n<p><a href=\"https://aiounittest.readthedocs.io/en/latest/asynctestcase.html#aiounittest.AsyncTestCase\" rel=\"nofollow noreferrer\">https://aiounittest.readthedocs.io/en/latest/asynctestcase.html#aiounittest.AsyncTestCase</a></p>\n<pre><code>async def test_await_async_fail(self):\n with self.assertRaises(Exception) as e:\n await async_one()\n</code></pre>\n" }, { "answer_id": 67360753, "author": "mobius-crypt", "author_id": 5287734, "author_profile": "https://Stackoverflow.com/users/5287734", "pm_score": 2, "selected": false, "text": "<p>This will raise TypeError if setting stock_id to an Integer in this class will throw the error, the test will pass if this happens and fails otherwise</p>\n<pre><code>def set_string(prop, value):\n if not isinstance(value, str):\n raise TypeError(&quot;i told you i take strings only &quot;)\n return value\n\nclass BuyVolume(ndb.Model):\n stock_id = ndb.StringProperty(validator=set_string)\n\nfrom pytest import raises\nbuy_volume_instance: BuyVolume = BuyVolume()\nwith raises(TypeError):\n buy_volume_instance.stock_id = 25\n</code></pre>\n" }, { "answer_id": 69797577, "author": "ifedapo olarewaju", "author_id": 4088675, "author_profile": "https://Stackoverflow.com/users/4088675", "pm_score": 4, "selected": false, "text": "<p>If you are using Python 3, in order to assert an exception along with its message, you can use <code>assertRaises</code> in context manager and pass the message as a <code>msg</code> keyword argument like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import unittest\n\ndef your_function():\n raise RuntimeError('your exception message')\n\nclass YourTestCase(unittest.TestCase):\n def test(self):\n with self.assertRaises(RuntimeError, msg='your exception message'):\n your_function()\n\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n" }, { "answer_id": 70997465, "author": "Dr. Joy Singhal", "author_id": 15573016, "author_profile": "https://Stackoverflow.com/users/15573016", "pm_score": -1, "selected": false, "text": "<p>Unit testing with unittest would be preferred, but if you would like a quick fix, we can catch the exception, assign it to a variable, and see if that variable is an instance of that exception class.</p>\n<p>Lets assume our bad function throws a ValueError.</p>\n<pre><code> try:\n bad_function()\n except ValueError as e:\n assert isinstance(e, ValueError)\n</code></pre>\n" }, { "answer_id": 72968206, "author": "egvo", "author_id": 7744106, "author_profile": "https://Stackoverflow.com/users/7744106", "pm_score": 2, "selected": false, "text": "<p>There are 4 options (you'll find full example in the end):</p>\n<h2>assertRaises with context manager</h2>\n<pre><code>def test_raises(self):\n with self.assertRaises(RuntimeError):\n raise RuntimeError()\n</code></pre>\n<p>If you want to check the exception message (see the <em>&quot;assertRaisesRegex with context manager&quot;</em> option below to check only part of it):</p>\n<pre><code>def test_raises(self):\n with self.assertRaises(RuntimeError) as error:\n raise RuntimeError(&quot;your exception message&quot;)\n self.assertEqual(str(error.exception), &quot;your exception message&quot;)\n</code></pre>\n<h2>assertRaises one-liner</h2>\n<blockquote>\n<p>Pay attention: instead of function call, here you use your function as <a href=\"https://www.geeksforgeeks.org/callable-in-python/\" rel=\"nofollow noreferrer\">callable</a> (without round brackets).</p>\n</blockquote>\n<pre><code>def test_raises(self):\n self.assertRaises(RuntimeError, your_function)\n</code></pre>\n<h2>assertRaisesRegex with context manager</h2>\n<p>Second parameter is regex expression and is mandatory. Handy when you want check only part of the exception message.</p>\n<pre><code>def test_raises_regex(self):\n with self.assertRaisesRegex(RuntimeError, r'.* exception message'):\n raise RuntimeError('your exception message')\n</code></pre>\n<h2>assertRaisesRegex one-liner</h2>\n<p>Second parameter is regex expression and is mandatory. Handy when you want check only part of the exception message.</p>\n<blockquote>\n<p>Pay attention: instead of function call, here you use your function as <a href=\"https://www.geeksforgeeks.org/callable-in-python/\" rel=\"nofollow noreferrer\">callable</a> (without round brackets).</p>\n</blockquote>\n<pre><code>def test_raises_regex(self):\n self.assertRaisesRegex(RuntimeError, r'.* exception message', your_function)\n</code></pre>\n<hr />\n<h2>Full code example:</h2>\n<pre><code>import unittest\n\ndef your_function():\n raise RuntimeError('your exception message')\n\nclass YourTestCase(unittest.TestCase):\n\n def test_1_raises_context_manager(self):\n with self.assertRaises(RuntimeError):\n your_function()\n\n def test_1b_raises_context_manager_and_error_message(self):\n with self.assertRaises(RuntimeError) as error:\n your_function()\n self.assertEqual(str(error.exception), &quot;your exception message&quot;)\n\n def test_2_raises_oneliner(self):\n self.assertRaises(RuntimeError, your_function)\n\n def test_3_raises_regex_context_manager(self):\n with self.assertRaisesRegex(RuntimeError, r'.* exception message'):\n your_function()\n\n def test_4_raises_regex_oneliner(self):\n self.assertRaisesRegex(RuntimeError, r'.* exception message', your_function)\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n<p>Although it's up to developer which style to follow I prefer both methods using context manager.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
How does one write a unittest that fails only if a function doesn't throw an expected exception?
Use [`TestCase.assertRaises`](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises) (or `TestCase.failUnlessRaises`) from the unittest module, for example: ``` import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc) ```
129,510
<p>I have an application I'm writing where I'm allowing the administrators to add aliases for pages, categories, etc, and I would like to use a different controller/action depending on the alias (without redirecting, and I've found that render doesn't actually call the method. I just renders the template). I have tried a catch all route, but I'm not crazy about causing and catching a DoubleRender exception that gets thrown everytime.</p> <p>The solution for this I've come up with is dynamically generated routes when the server is started, and using callbacks from the Alias model to reload routes when an alias is created/updated/destroyed. Here is the code from my routes.rb:</p> <pre><code>Alias.find(:all).each do |alias_to_add| map.connect alias_to_add.name, :controller =&gt; alias_to_add.page_type.controller, :action =&gt; alias_to_add.page_type.action, :navigation_node_id =&gt; alias_to_add.navigation_node.id end </code></pre> <p>I am using callbacks in my Alias model as follows:</p> <pre><code>after_save :rebuild_routes after_destroy :rebuild_routes def rebuild_routes ActionController::Routing::Routes.reload! end </code></pre> <p>Is this against Rails best practices? Is there a better solution?</p>
[ { "answer_id": 130750, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>I'm not sure I fully understand the question, but you could use <code>method_missing</code> in your controllers and then lookup the alias, maybe like this:</p>\n\n<pre><code>class MyController\n def method_missing(sym, *args)\n aliased = Alias.find_by_action_name(sym)\n # sanity check here in case no alias\n\n self.send( aliased.real_action_name )\n # sanity check here in case the real action calls a different render explicitly\n render :action =&gt; aliased.real_action_name\n end\n\n def normal_action\n @thing = Things.find(params[:id])\n end\nend\n</code></pre>\n\n<p>If you wanted to optimize that, you could put a <code>define_method</code> in the <code>method_missing</code>, so it would only be 'missing' on the first invocation, and would be a normal method from then on.</p>\n" }, { "answer_id": 131325, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 4, "selected": true, "text": "<h2>Quick Solution</h2>\n\n<p>Have a catch-all route at the bottom of routes.rb. Implement any alias lookup logic you want in the action that route routes you to. </p>\n\n<p>In my implementation, I have a table which maps defined URLs to a controller, action, and parameter hash. I just pluck them out of the database, then call the appropriate action and then try to render the default template for the action. If the action already rendered something, that throws a DoubleRenderError, which I catch and ignore. </p>\n\n<p>You can extend this technique to be as complicated as you want, although as it gets more complicated it makes more sense to implement it by tweaking either your routes or the Rails default routing logic rather than by essentially reimplementing all the routing logic yourself.</p>\n\n<p>If you don't find an alias, you can throw the 404 or 500 error as you deem appropriate.</p>\n\n<h2><strong>Stuff to keep in mind:</strong></h2>\n\n<p><strong>Caching:</strong> Not knowing your URLs a priori can make page caching an absolute bear. Remember, it caches based on the URI supplied, NOT on the <code>url_for (:action_you_actually_executed</code>). This means that if you alias </p>\n\n<pre><code>/foo_action/bar_method\n</code></pre>\n\n<p>to</p>\n\n<pre><code>/some-wonderful-alias\n</code></pre>\n\n<p>you'll get some-wonderful-alias.html living in your cache directory. And when you try to sweep foo's bar, you won't sweep that file unless you specify it explicitly.</p>\n\n<p><strong>Fault Tolerance:</strong> Check to make sure someone doesn't accidentally alias over an existing route. You can do this trivially by forcing all aliases into a \"directory\" which is known to not otherwise be routable (in which case, the alias being textually unique is enough to make sure they never collide), but that isn't a maximally desirable solution for a few of the applications I can think of of this.</p>\n" }, { "answer_id": 148997, "author": "tomafro", "author_id": 7126, "author_profile": "https://Stackoverflow.com/users/7126", "pm_score": 2, "selected": false, "text": "<p>First, as other have suggested, create a catch-all route at the bottom of routes.rb:</p>\n\n<pre><code>map.connect ':name', :controller =&gt; 'aliases', :action =&gt; 'show'\n</code></pre>\n\n<p>Then, in AliasesController, you can use render_component to render the aliased action:</p>\n\n<pre><code>class AliasesController &lt; ApplicationController\n def show\n if alias = Alias.find_by_name(params[:name])\n render_component(:controller =&gt; alias.page_type.controller, \n :action =&gt; alias.page_type.action,\n :navigation_node_id =&gt; alias.navigation_node.id)\n else\n render :file =&gt; \"#{RAILS_ROOT}/public/404.html\", :status =&gt; :not_found\n end\n end\nend\n</code></pre>\n" }, { "answer_id": 4213087, "author": "mjnissim", "author_id": 348931, "author_profile": "https://Stackoverflow.com/users/348931", "pm_score": 4, "selected": false, "text": "<p>Ben,</p>\n\n<p>I find the method you're already using to be the best. Using Rails 3, you'd have to change the code a bit, to:</p>\n\n<pre><code>MyNewApplication::Application.reload_routes!\n</code></pre>\n\n<p>That's all.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6705/" ]
I have an application I'm writing where I'm allowing the administrators to add aliases for pages, categories, etc, and I would like to use a different controller/action depending on the alias (without redirecting, and I've found that render doesn't actually call the method. I just renders the template). I have tried a catch all route, but I'm not crazy about causing and catching a DoubleRender exception that gets thrown everytime. The solution for this I've come up with is dynamically generated routes when the server is started, and using callbacks from the Alias model to reload routes when an alias is created/updated/destroyed. Here is the code from my routes.rb: ``` Alias.find(:all).each do |alias_to_add| map.connect alias_to_add.name, :controller => alias_to_add.page_type.controller, :action => alias_to_add.page_type.action, :navigation_node_id => alias_to_add.navigation_node.id end ``` I am using callbacks in my Alias model as follows: ``` after_save :rebuild_routes after_destroy :rebuild_routes def rebuild_routes ActionController::Routing::Routes.reload! end ``` Is this against Rails best practices? Is there a better solution?
Quick Solution -------------- Have a catch-all route at the bottom of routes.rb. Implement any alias lookup logic you want in the action that route routes you to. In my implementation, I have a table which maps defined URLs to a controller, action, and parameter hash. I just pluck them out of the database, then call the appropriate action and then try to render the default template for the action. If the action already rendered something, that throws a DoubleRenderError, which I catch and ignore. You can extend this technique to be as complicated as you want, although as it gets more complicated it makes more sense to implement it by tweaking either your routes or the Rails default routing logic rather than by essentially reimplementing all the routing logic yourself. If you don't find an alias, you can throw the 404 or 500 error as you deem appropriate. **Stuff to keep in mind:** -------------------------- **Caching:** Not knowing your URLs a priori can make page caching an absolute bear. Remember, it caches based on the URI supplied, NOT on the `url_for (:action_you_actually_executed`). This means that if you alias ``` /foo_action/bar_method ``` to ``` /some-wonderful-alias ``` you'll get some-wonderful-alias.html living in your cache directory. And when you try to sweep foo's bar, you won't sweep that file unless you specify it explicitly. **Fault Tolerance:** Check to make sure someone doesn't accidentally alias over an existing route. You can do this trivially by forcing all aliases into a "directory" which is known to not otherwise be routable (in which case, the alias being textually unique is enough to make sure they never collide), but that isn't a maximally desirable solution for a few of the applications I can think of of this.
129,544
<p>I'm using the following code to make sure all certificates pass, even invalid ones, but I would like to know if there is a better way, as this event gets called globally and I only want the certificate to pass for a certain HTTP call and not for any others that are happening asynchronously.</p> <pre><code>// This delegate makes sure that non-validating SSL certificates are passed ServicePointManager.ServerCertificateValidationCallback = delegate(object certsender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error) { return true; }; </code></pre> <p>The code above is just an example of ignoring any non-validation on the certificate. The problem that I'm having is that it is a <strong>global</strong> event. I can't see which session the event is happening for. I might have a couple of http requests going through and I want to ask the user for an action <strong>for each request</strong>.</p>
[ { "answer_id": 141558, "author": "SecretDeveloper", "author_id": 2720, "author_profile": "https://Stackoverflow.com/users/2720", "pm_score": 1, "selected": false, "text": "<p>I have recently been looking into this issue but without the same requirements that you have. I haven't seen a script that does what you want but have you considered instead checking if .NET 2.0 is installed and if not then prompt them to download it. You can open a URL in the default browser and get the user to attempt the install again once the framework has been installed.</p>\n\n<p>This is not an ideal situation from a user perspective but i think going with what your planning you will have to write some complex stuff to handle the different language constraints just to get it working.</p>\n\n<p>Just my 2 cents.</p>\n" }, { "answer_id": 448302, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.codeproject.com/KB/install/dotnetfx_innosetup_instal.aspx\" rel=\"nofollow noreferrer\">.NET Framework 1.1/2.0/3.5 Installer for InnoSetup</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11421/" ]
I'm using the following code to make sure all certificates pass, even invalid ones, but I would like to know if there is a better way, as this event gets called globally and I only want the certificate to pass for a certain HTTP call and not for any others that are happening asynchronously. ``` // This delegate makes sure that non-validating SSL certificates are passed ServicePointManager.ServerCertificateValidationCallback = delegate(object certsender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error) { return true; }; ``` The code above is just an example of ignoring any non-validation on the certificate. The problem that I'm having is that it is a **global** event. I can't see which session the event is happening for. I might have a couple of http requests going through and I want to ask the user for an action **for each request**.
[.NET Framework 1.1/2.0/3.5 Installer for InnoSetup](http://www.codeproject.com/KB/install/dotnetfx_innosetup_instal.aspx)
129,607
<p>I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?</p>
[ { "answer_id": 129616, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 3, "selected": false, "text": "<p>Well Google really works for you on this one: <a href=\"http://www.perlmonks.org/?node_id=94007\" rel=\"noreferrer\">http://www.perlmonks.org/?node_id=94007</a></p>\n\n<p>From the link:</p>\n\n<blockquote>\n <p>Quick summary: 'my' creates a new\n variable, 'local' temporarily amends\n the value of a variable.</p>\n \n <p>ie, 'local' <em>temporarily changes the\n value of the variable</em>, but only\n <em>within the scope</em> it exists in.</p>\n</blockquote>\n\n<p>Generally use my, it's faster and doesn't do anything kind of weird.</p>\n" }, { "answer_id": 129652, "author": "catfood", "author_id": 12802, "author_profile": "https://Stackoverflow.com/users/12802", "pm_score": 3, "selected": false, "text": "<p>From <code>man perlsub</code>:</p>\n\n<p><em>Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines.</em> </p>\n\n<p>So, oversimplifying, <code>my</code> makes your variable visible only where it's declared. <code>local</code> makes it visible down the call stack too. You will usually want to use <code>my</code> instead of <code>local</code>.</p>\n" }, { "answer_id": 129657, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 2, "selected": false, "text": "<p>\"my\" variables are visible in the current code block only. \"local\" variables are also visible where ever they were visible before. For example, if you say \"my $x;\" and call a sub-function, it cannot see that variable $x. But if you say \"local $/;\" (to null out the value of the record separator) then you change the way reading from files works in any functions you call.\n<p>\nIn practice, you almost always want \"my\", not \"local\".</p>\n" }, { "answer_id": 129687, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()</a></p>\n\n<blockquote>\n <p>Unlike dynamic variables created by\n the local operator, lexical variables\n declared with my are totally hidden\n from the outside world, including any\n called subroutines. This is true if\n it's the same subroutine called from\n itself or elsewhere--every call gets\n its own copy.</p>\n</blockquote>\n\n<p><a href=\"http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()</a></p>\n\n<blockquote>\n <p>A local modifies its listed variables\n to be \"local\" to the enclosing block,\n eval, or do FILE --and to any\n subroutine called from within that\n block. A local just gives temporary\n values to global (meaning package)\n variables. It does not create a local\n variable. This is known as dynamic\n scoping. Lexical scoping is done with\n my, which works more like C's auto\n declarations.</p>\n</blockquote>\n\n<p>I don't think this is at all unclear, other than to say that by \"local to the enclosing block\", what it means is that the original value is restored when the block is exited.</p>\n" }, { "answer_id": 129714, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 7, "selected": true, "text": "<p>Dynamic Scoping. It is a neat concept. Many people don't use it, or understand it.</p>\n\n<p>Basically think of <code>my</code> as creating and anchoring a variable to one block of {}, A.K.A. scope.</p>\n\n<pre><code>my $foo if (true); # $foo lives and dies within the if statement.\n</code></pre>\n\n<p>So a <code>my</code> variable is what you are used to. whereas with dynamic scoping $var can be declared anywhere and used anywhere.\nSo with <code>local</code> you basically suspend the use of that global variable, and use a \"local value\" to work with it. So <code>local</code> creates a temporary scope for a temporary variable.</p>\n\n<pre><code>$var = 4;\nprint $var, \"\\n\";\n&amp;hello;\nprint $var, \"\\n\";\n\n# subroutines\nsub hello {\n local $var = 10;\n print $var, \"\\n\";\n &amp;gogo; # calling subroutine gogo\n print $var, \"\\n\";\n}\nsub gogo {\n $var ++;\n}\n</code></pre>\n\n<p>This should print:</p>\n\n<pre><code>4\n10\n11\n4\n</code></pre>\n" }, { "answer_id": 129739, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 6, "selected": false, "text": "<p>The short answer is that <code>my</code> marks a variable as private in a lexical scope, and <code>local</code> marks a variable as private in a dynamic scope.</p>\n\n<p>It's easier to understand <code>my</code>, since that creates a local variable in the usual sense. There is a new variable created and it's accessible only within the enclosing lexical block, which is usually marked by curly braces. There are some exceptions to the curly-brace rule, such as:</p>\n\n<pre><code>foreach my $x (@foo) { print \"$x\\n\"; }\n</code></pre>\n\n<p>But that's just Perl doing what you mean. Normally you have something like this:</p>\n\n<pre><code>sub Foo {\n my $x = shift;\n\n print \"$x\\n\";\n}\n</code></pre>\n\n<p>In that case, <code>$x</code> is private to the subroutine and its scope is enclosed by the curly braces. The thing to note, and this is the contrast to <code>local</code>, is that the scope of a <code>my</code> variable is defined with respect to your code as it is written in the file. It's a compile-time phenomenon.</p>\n\n<p>To understand <code>local</code>, you need to think in terms of the calling stack of your program as it is running. When a variable is <code>local</code>, it is redefined from the point at which the <code>local</code> statement executes for everything below that on the stack, until you return back up the stack to the caller of the block containing the <code>local</code>.</p>\n\n<p>This can be confusing at first, so consider the following example.</p>\n\n<pre><code>sub foo { print \"$x\\n\"; }\nsub bar { local $x; $x = 2; foo(); }\n\n$x = 1;\nfoo(); # prints '1'\nbar(); # prints '2' because $x was localed in bar\nfoo(); # prints '1' again because local from foo is no longer in effect\n</code></pre>\n\n<p>When <code>foo</code> is called the first time, it sees the global value of <code>$x</code> which is 1. When <code>bar</code> is called and <code>local $x</code> runs, that redefines the global <code>$x</code> on the stack. Now when <code>foo</code> is called from <code>bar</code>, it sees the new value of 2 for <code>$x</code>. So far that isn't very special, because the same thing would have happened without the call to <code>local</code>. The magic is that when <code>bar</code> returns we exit the dynamic scope created by <code>local $x</code> and the previous global <code>$x</code> comes back into scope. So for the final call of <code>foo</code>, <code>$x</code> is 1.</p>\n\n<p>You will almost always want to use <code>my</code>, since that gives you the local variable you're looking for. Once in a blue moon, <code>local</code> is really handy to do cool things.</p>\n" }, { "answer_id": 130460, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 5, "selected": false, "text": "<p>Quoting from <a href=\"http://oreilly.com/catalog/lperl3/chapter/ch04.html\" rel=\"noreferrer\"><em>Learning Perl</em></a>:</p>\n\n<blockquote>\n <p>But local is misnamed, or at least misleadingly named. Our friend Chip Salzenberg says that if he ever gets a chance to go back in a time machine to 1986 and give Larry one piece of advice, he'd tell Larry to call local by the name \"save\" instead.[14] That's because local actually will save the given global variable's value away, so it will later automatically be restored to the global variable. (That's right: these so-called \"local\" variables are actually globals!) This save-and-restore mechanism is the same one we've already seen twice now, in the control variable of a foreach loop, and in the @_ array of subroutine parameters.</p>\n</blockquote>\n\n<p>So, <code>local</code> saves a global variable's current value and then set it to some form of empty value. You'll often see it used to slurp an entire file, rather than leading just a line:</p>\n\n<pre><code>my $file_content;\n{\n local $/;\n open IN, \"foo.txt\";\n $file_content = &lt;IN&gt;;\n} \n</code></pre>\n\n<p>Calling <code>local $/</code> sets the input record separator (the value that Perl stops reading a \"line\" at) to an empty value, causing the spaceship operator to read the entire file, so it never hits the input record separator.</p>\n" }, { "answer_id": 131088, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "<p>Your confusion is understandable. Lexical scoping is fairly easy to understand but dynamic scoping is an unusual concept. The situation is made worse by the names <code>my</code> and <code>local</code> being somewhat inaccurate (or at least unintuitive) for historical reasons.</p>\n\n<p><code>my</code> declares a lexical variable -- one that is visible from the point of declaration until the end of the enclosing block (or file). It is completely independent from any other variables with the same name in the rest of the program. It is private to that block.</p>\n\n<p><code>local</code>, on the other hand, declares a temporary change to the value of a global variable. The change ends at the end of the enclosing scope, but the variable -- being global -- is visible anywhere in the program.</p>\n\n<p>As a rule of thumb, use <code>my</code> to declare your own variables and <code>local</code> to control the impact of changes to Perl's built-in variables.</p>\n\n<p>For a more thorough description see Mark Jason Dominus' article <a href=\"http://perl.plover.com/FAQs/Namespaces.html\" rel=\"noreferrer\">Coping with Scoping</a>.</p>\n" }, { "answer_id": 135205, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 3, "selected": false, "text": "<p>local is an older method of localization, from the times when Perl had only dynamic scoping. Lexical scoping is much more natural for the programmer and much safer in many situations. my variables belong to the scope (block, package, or file) in which they are declared.</p>\n\n<p>local variables instead actually belong to a global namespace. If you refer to a variable $x with local, you are actually referring to $main::x, which is a global variable. Contrary to what it's name implies, all local does is push a new value onto a stack of values for $main::x until the end of this block, at which time the old value will be restored. That's a useful feature in and of itself, but it's not a good way to have local variables for a host of reasons (think what happens when you have threads! and think what happens when you call a routine that genuinely wants to use a global that you have localized!). However, it was the only way to have variables that looked like local variables back in the bad old days before Perl 5. We're still stuck with it.</p>\n" }, { "answer_id": 136851, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 4, "selected": false, "text": "<p>I can’t believe no one has linked to Mark Jason Dominus’ exhaustive treatises on the matter:</p>\n\n<ul>\n<li><p><b><a href=\"http://perl.plover.com/FAQs/Namespaces.html\" rel=\"noreferrer\">Coping with Scoping</a></b></p></li>\n<li><p>And afterwards, if you want to know what <code>local</code> is good for after all,<br /><b><a href=\"http://perl.plover.com/local.html\" rel=\"noreferrer\">Seven Useful Uses of <code>local</code></a></b></p></li>\n</ul>\n" }, { "answer_id": 158357, "author": "phreakre", "author_id": 12051, "author_profile": "https://Stackoverflow.com/users/12051", "pm_score": 0, "selected": false, "text": "<p>dinomite's example of using local to redefine the record delimiter is the only time I have ran across in a lot of perl programming. I live in a niche perl environment [security programming], but it really is a rarely used scope in my experience.</p>\n" }, { "answer_id": 1237544, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>&amp;s;\n\nsub s()\n{\n local $s=\"5\";\n &amp;b;\n print $s;\n}\n\nsub b()\n{\n $s++;\n}\n</code></pre>\n\n<p>The above script prints 6.</p>\n\n<p>But if we change local to my it will print 5.</p>\n\n<p>This is the difference. Simple.</p>\n" }, { "answer_id": 15917874, "author": "Abhishek Kulkarni", "author_id": 1532338, "author_profile": "https://Stackoverflow.com/users/1532338", "pm_score": 2, "selected": false, "text": "<p>Look at the following code and its output to understand the difference.</p>\n\n<pre><code>our $name = \"Abhishek\";\n\nsub sub1\n{\n print \"\\nName = $name\\n\";\n local $name = \"Abhijeet\";\n\n &amp;sub2;\n &amp;sub3;\n}\n\nsub sub2\n{\n print \"\\nName = $name\\n\";\n}\n\nsub sub3\n{\n my $name = \"Abhinav\";\n print \"\\nName = $name\\n\";\n}\n\n\n&amp;sub1;\n</code></pre>\n\n<p>Output is :</p>\n\n<pre><code>Name = Abhishek\n\nName = Abhijeet\n\nName = Abhinav\n</code></pre>\n" }, { "answer_id": 25893773, "author": "Hawk", "author_id": 1038583, "author_profile": "https://Stackoverflow.com/users/1038583", "pm_score": 0, "selected": false, "text": "<p>I think the easiest way to remember it is this way. MY creates a new variable. LOCAL temporarily changes the value of an existing variable. </p>\n" }, { "answer_id": 68783034, "author": "Omtechnologies s", "author_id": 16665548, "author_profile": "https://Stackoverflow.com/users/16665548", "pm_score": 1, "selected": false, "text": "<p>It will differ only when you have a subroutine called within a subroutine, for example:</p>\n<pre class=\"lang-perl prettyprint-override\"><code>sub foo { \n print &quot;$x\\n&quot;; \n}\nsub bar { my $x; $x = 2; foo(); }\n \nbar(); \n</code></pre>\n<p>It prints nothing as <code>$x</code> is limited by <code>{}</code> of bar and not visible to called subroutines, for example:</p>\n<pre class=\"lang-perl prettyprint-override\"><code>sub foo { print &quot;$x\\n&quot;; }\n\nsub bar { local $x; $x = 2; foo(); }\n \nbar(); \n</code></pre>\n<p>It will print 2 as local variables are visible to called subroutines.</p>\n" }, { "answer_id": 74385561, "author": "Antti Rytsölä", "author_id": 468921, "author_profile": "https://Stackoverflow.com/users/468921", "pm_score": 0, "selected": false, "text": "<pre><code>#!/usr/bin/perl\n\nsub foo { print &quot;, x is $x\\n&quot;; }\n\nsub testdefault { $x++; foo(); } # prints 2\n\nsub testmy { my $x; $x++; foo(); } # prints 1\n\nsub testlocal { local $x = 2; foo(); } # prints 2. new set mandatory\n\n\nprint &quot;Default, everything is global&quot;;\n$x = 1;\ntestdefault();\n\nprint &quot;My does not affect function calls outside&quot;;\n$x = 1;\ntestmy();\n\nprint &quot;local is everything after this but initializes a new&quot;;\n$x = 1;\ntestlocal();\n</code></pre>\n<p>As mentioned in testlocal comment, declaring &quot;local $x;&quot; means that $x is now undef</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?
Dynamic Scoping. It is a neat concept. Many people don't use it, or understand it. Basically think of `my` as creating and anchoring a variable to one block of {}, A.K.A. scope. ``` my $foo if (true); # $foo lives and dies within the if statement. ``` So a `my` variable is what you are used to. whereas with dynamic scoping $var can be declared anywhere and used anywhere. So with `local` you basically suspend the use of that global variable, and use a "local value" to work with it. So `local` creates a temporary scope for a temporary variable. ``` $var = 4; print $var, "\n"; &hello; print $var, "\n"; # subroutines sub hello { local $var = 10; print $var, "\n"; &gogo; # calling subroutine gogo print $var, "\n"; } sub gogo { $var ++; } ``` This should print: ``` 4 10 11 4 ```
129,642
<p>With C#, How do I play (Pause, Forward...) a sound file (mp3, ogg)? The file could be on the hard disk, or on the internet.</p> <p>Is there any library or Class out there that can ease me the work ?</p>
[ { "answer_id": 129671, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>use <a href=\"http://www.codeproject.com/KB/audio-video/PlaySounds1.aspx\" rel=\"nofollow noreferrer\">PlaySound API call</a></p>\n" }, { "answer_id": 129750, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 3, "selected": false, "text": "<p>If you don't mind including <strong>Microsoft.VisualBasic.dll</strong> in your project, you can do it this way:</p>\n\n<pre><code>var audio = new Microsoft.VisualBasic.Devices.Audio();\naudio.Play(\"some file path\");\n</code></pre>\n\n<p>If you want to do more complex stuff, the easiest way I know of is to use the <strong>Windows Media Player API</strong>. You add the DLL and then work with it. The API is kind of clunky, but it does work; I've used it to make my own music player wrapper around Windows Media Player for personal use. Here are some helpful links to get you started:</p>\n\n<p><a href=\"http://blogs.msdn.com/coding4fun/archive/2006/10/31/913360.aspx\" rel=\"nofollow noreferrer\">Building a Web Site with ASP .NET 2.0 to Navigate Your Music Library</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb249259.aspx\" rel=\"nofollow noreferrer\">Windows Media Object Model</a></p>\n\n<p><a href=\"http://blogs.msdn.com/vbteam/archive/2007/10/30/let-the-music-play-matt-gertz.aspx\" rel=\"nofollow noreferrer\">Let the Music Play!</a></p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Since I wrote this, I've found an easier way, if you don't mind including WPF classes in your code. WPF (.NET 3.0 and forward) has a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.aspx\" rel=\"nofollow noreferrer\">MediaPlayer</a> class that's a wrapper around Windows Media Player. This means you don't have to write your own wrapper, which is nice since, as I mentioned above, the WMP API is rather clunky and hard to use.</p>\n" }, { "answer_id": 129776, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 2, "selected": false, "text": "<p>I would recommend the <a href=\"http://un4seen.com/\" rel=\"nofollow noreferrer\">BASS Library</a>.\nIt can play both filebased music files and streaming content.\nThere is also a .NET wrapper available.</p>\n" }, { "answer_id": 129809, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 0, "selected": false, "text": "<p>There's a media player control - basically what Media Player uses. You can put that in your program and there's an API you can use to control it. I think it's the best quick solution.</p>\n" }, { "answer_id": 21727628, "author": "Basil", "author_id": 3263181, "author_profile": "https://Stackoverflow.com/users/3263181", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://alvas.net\" rel=\"nofollow\">Alvas.Audio</a> has <a href=\"http://alvas.net/alvas.audio,samples.aspx#sample1\" rel=\"nofollow\">RecordPlayer</a> class with these possibilities: </p>\n\n<pre><code> public static void TestRecordPlayer()\n {\n RecordPlayer rp = new RecordPlayer();\n rp.PropertyChanged += new PropertyChangedEventHandler(rp_PropertyChanged);\n rp.Open(new Mp3Reader(File.OpenRead(\"in.mp3\")));\n rp.Play();\n rp.Forward(1000);\n rp.Pause();\n }\n\n static void rp_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case RecordPlayer.StateProperty:\n RecordPlayer rp = ((RecordPlayer)sender);\n if (rp.State == DeviceState.Stopped)\n {\n rp.Close();\n }\n break;\n }\n }\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20709/" ]
With C#, How do I play (Pause, Forward...) a sound file (mp3, ogg)? The file could be on the hard disk, or on the internet. Is there any library or Class out there that can ease me the work ?
If you don't mind including **Microsoft.VisualBasic.dll** in your project, you can do it this way: ``` var audio = new Microsoft.VisualBasic.Devices.Audio(); audio.Play("some file path"); ``` If you want to do more complex stuff, the easiest way I know of is to use the **Windows Media Player API**. You add the DLL and then work with it. The API is kind of clunky, but it does work; I've used it to make my own music player wrapper around Windows Media Player for personal use. Here are some helpful links to get you started: [Building a Web Site with ASP .NET 2.0 to Navigate Your Music Library](http://blogs.msdn.com/coding4fun/archive/2006/10/31/913360.aspx) [Windows Media Object Model](http://msdn.microsoft.com/en-us/library/bb249259.aspx) [Let the Music Play!](http://blogs.msdn.com/vbteam/archive/2007/10/30/let-the-music-play-matt-gertz.aspx) **EDIT:** Since I wrote this, I've found an easier way, if you don't mind including WPF classes in your code. WPF (.NET 3.0 and forward) has a [MediaPlayer](http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.aspx) class that's a wrapper around Windows Media Player. This means you don't have to write your own wrapper, which is nice since, as I mentioned above, the WMP API is rather clunky and hard to use.
129,650
<p>Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like <pre>FindAllPostByTags(IList&lt;Tag&gt; tags)</pre> that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!</p>
[ { "answer_id": 130339, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 0, "selected": false, "text": "<p>I don't have a system at hand with a Castle install right now, so I didn't test or compile this, but the code below should about do what you want.</p>\n\n<pre><code>Junction c = Expression.Conjunction();\nforeach(Tag t in tags)\n c = c.Add( Expression.Eq(\"Tag\", t);\n\nreturn sess.CreateCriteria(typeof(Post)).Add(c).List();\n</code></pre>\n" }, { "answer_id": 161706, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": true, "text": "<p>You could also just use an <code>IN</code> statement</p>\n\n<pre><code>DetachedCriteria query = DetachedCriteria.For&lt;Post&gt;();\nquery.CreateCriteria(\"Post\").Add(Expression.In(\"TagName\", string.Join(\",\",tags.ToArray()) );\n</code></pre>\n\n<p>I haven't compiled that so it could have errors</p>\n" }, { "answer_id": 268969, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 0, "selected": false, "text": "<p>I just had the same problem and tried to read the HQL-documentation, however some of the features doesn't seem to be implemented in NHibernate (with-keyword for example)</p>\n\n<p>I ended up with this sort of solution:</p>\n\n<pre>\nselect p \nFROM Post p\nJOIN p.Tags tag1\nJOIN p.Tags tag2\nWHERE\n tag1.Id = 1\n tag2.Id = 2\n\n</pre>\n\n<p>Meaning, dynamically build the HQL using join for each tag, then make the selection in your WHERE clause. This worked for me. I tried doing the same thing with a DetachedCriteria but ran into trouble when trying to join the table multiple times.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14064/" ]
Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like ``` FindAllPostByTags(IList<Tag> tags) ``` that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!
You could also just use an `IN` statement ``` DetachedCriteria query = DetachedCriteria.For<Post>(); query.CreateCriteria("Post").Add(Expression.In("TagName", string.Join(",",tags.ToArray()) ); ``` I haven't compiled that so it could have errors
129,651
<p>In the following HTML, I'd like the frame around the image to be snug -- not to stretch out and take up all the available width in the parent container. I know there are a couple of ways to do this (including horrible things like manually setting its width to a particular number of pixels), but what is the <em>right</em> way?</p> <p><strong>Edit:</strong> One answer suggests I turn off "display:block" -- but this causes the rendering to look malformed in every browser I've tested it in. Is there a way to get a nice-looking rendering with "display:block" off?</p> <p><strong>Edit:</strong> If I add "float: left" to the pictureframe and "clear:both" to the P tag, it looks great. But I don't always want these frames floated to the left. Is there a more direct way to accomplish whatever "float" is doing?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.pictureframe { display: block; margin: 5px; padding: 5px; border: solid brown 2px; background-color: #ffeecc; } #foo { border: solid blue 2px; float: left; } img { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="foo"&gt; &lt;span class="pictureframe"&gt; &lt;img alt='' src="http://stackoverflow.com/favicon.ico" /&gt; &lt;/span&gt; &lt;p&gt; Why is the beige rectangle so wide? &lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 129672, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": 2, "selected": false, "text": "<p>The beige rectangle is so wide because you have display: block on the span, turning an inline element into a block element. A block element is supposed to take up all available width, an inline element does not. Try removing the display: block from the css.</p>\n" }, { "answer_id": 129706, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 6, "selected": true, "text": "<p>The <em>right</em> way is to use:</p>\n\n<pre><code>.pictureframe {\n display: inline-block;\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Floating the element also produces the same effect, this is because floating elements use the same <a href=\"http://www.w3.org/TR/CSS21/visudet.html#shrink-to-fit-float\" rel=\"noreferrer\">shrink-to-fit</a> algorithm for determining the width.</p>\n" }, { "answer_id": 129798, "author": "Keeth", "author_id": 20588, "author_profile": "https://Stackoverflow.com/users/20588", "pm_score": -1, "selected": false, "text": "<p>The only way I've been able to do picture frames reliably across browsers is to set the width dynamically. Here is an example using jQuery:</p>\n\n<pre><code>$(window).load(function(){\n $('img').wrap('&lt;div class=\"pictureFrame\"&gt;&lt;/div&gt;');\n $('div.pictureFrame').each(function(i) {\n $(this).width($('*:first', this).width());\n });\n});\n</code></pre>\n\n<p>This will work even if you don't know the image dimensions ahead of time, because it waits for the images to load (note we're using $(window).load rather than the more common $(document).ready) before adding the picture frame. It's a bit ugly, but it works.</p>\n\n<p>Here is the pictureFrame CSS for this example:</p>\n\n<pre><code>.pictureFrame {\n background-color:#FFFFFF;\n border:1px solid #CCCCCC;\n line-height:0;\n padding:5px;\n}\n</code></pre>\n\n<p>I'd love to see a reliable, cross-browser, CSS-only solution to this problem. This solution is something I came up with for a past project after much frustration trying to get it working with only CSS and HTML.</p>\n" }, { "answer_id": 129863, "author": "stucampbell", "author_id": 21379, "author_profile": "https://Stackoverflow.com/users/21379", "pm_score": 2, "selected": false, "text": "<p>Yes\n<code>display:inline-block</code> is your friend.\nAlso have a look at: <code>display:-moz-inline-block</code> and <code>display:-moz-inline-box</code>.</p>\n" }, { "answer_id": 129957, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 2, "selected": false, "text": "<p>Adding \"float:left\" to the span.pictureFrame selector fixes the problem as that's what \"float:left\" does :) Apart from everything else floating an element to the left will make it occupy only the space required by its contents. Any following block elements (the \"p\" for example) will float around the \"floated\" element. If you \"clear\" the float of the \"p\" it would follow the normal document flow thus going below span.pictureFrame. In fact you need \"clear:left\" as the element has been \"float:left\"-ed. \nFor a more formal explanation you can check the CSS spec although it is beyond most people's comprehension.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
In the following HTML, I'd like the frame around the image to be snug -- not to stretch out and take up all the available width in the parent container. I know there are a couple of ways to do this (including horrible things like manually setting its width to a particular number of pixels), but what is the *right* way? **Edit:** One answer suggests I turn off "display:block" -- but this causes the rendering to look malformed in every browser I've tested it in. Is there a way to get a nice-looking rendering with "display:block" off? **Edit:** If I add "float: left" to the pictureframe and "clear:both" to the P tag, it looks great. But I don't always want these frames floated to the left. Is there a more direct way to accomplish whatever "float" is doing? ```css .pictureframe { display: block; margin: 5px; padding: 5px; border: solid brown 2px; background-color: #ffeecc; } #foo { border: solid blue 2px; float: left; } img { display: block; } ``` ```html <div id="foo"> <span class="pictureframe"> <img alt='' src="http://stackoverflow.com/favicon.ico" /> </span> <p> Why is the beige rectangle so wide? </p> </div> ```
The *right* way is to use: ``` .pictureframe { display: inline-block; } ``` **Edit:** Floating the element also produces the same effect, this is because floating elements use the same [shrink-to-fit](http://www.w3.org/TR/CSS21/visudet.html#shrink-to-fit-float) algorithm for determining the width.
129,693
<p>I ruined several unit tests some time ago when I went through and refactored them to make them more <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY</a>--the intent of each test was no longer clear. It seems there is a trade-off between tests' readability and maintainability. If I leave duplicated code in unit tests, they're more readable, but then if I change the <a href="http://en.wikipedia.org/wiki/System_Under_Test" rel="noreferrer">SUT</a>, I'll have to track down and change each copy of the duplicated code.</p> <p>Do you agree that this trade-off exists? If so, do you prefer your tests to be readable, or maintainable?</p>
[ { "answer_id": 129722, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 8, "selected": false, "text": "<p>Readability is more important for tests. If a test fails, you want the problem to be obvious. The developer shouldn't have to wade through a lot of heavily factored test code to determine exactly what failed. You don't want your test code to become so complex that you need to write unit-test-tests.</p>\n\n<p>However, eliminating duplication is usually a good thing, as long as it doesn't obscure anything, and eliminating the duplication in your tests may lead to a better API. Just make sure you don't go past the point of diminishing returns.</p>\n" }, { "answer_id": 129741, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 2, "selected": false, "text": "<p>I don't think there is a relation between more duplicated and readable code. I think your test code should be as good as your other code. Non-repeating code is more readable then duplicated code when done well.</p>\n" }, { "answer_id": 129756, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 2, "selected": false, "text": "<p>Ideally, unit tests shouldn't change much once they are written so I would lean towards readability.</p>\n\n<p>Having unit tests be as discrete as possible also helps to keep the tests focused on the specific functionality that they are targeting.</p>\n\n<p>With that said, I do tend to try and reuse certain pieces of code that I wind up using over and over, such as setup code that is exactly the same across a set of tests.</p>\n" }, { "answer_id": 129768, "author": "stucampbell", "author_id": 21379, "author_profile": "https://Stackoverflow.com/users/21379", "pm_score": 3, "selected": false, "text": "<p>I agree. The trade off exists but is different in different places.</p>\n\n<p>I'm more likely to refactor duplicated code for setting up state. But less likely to refactor the part of the test that actually exercises the code. That said, if exercising the code always takes several lines of code then I might think that is a smell and refactor the actual code under test. And that will improve readability and maintainability of both the code and the tests.</p>\n" }, { "answer_id": 130038, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 6, "selected": false, "text": "<p>Implementation code and tests are different animals and factoring rules apply differently to them.</p>\n\n<p>Duplicated code or structure is always a smell in implementation code. When you start having boilerplate in implementation, you need to revise your abstractions.</p>\n\n<p>On the other hand, testing code must maintain a level of duplication. Duplication in test code achieves two goals:</p>\n\n<ul>\n<li>Keeping tests decoupled. Excessive test coupling can make it hard to change a single failing test that needs updating because the contract has changed.</li>\n<li>Keeping the tests meaningful in isolation. When a single test is failing, it must be reasonably straightforward to find out exactly what it is testing.</li>\n</ul>\n\n<p>I tend to ignore trivial duplication in test code as long as each test method stays shorter than about 20 lines. I like when the setup-run-verify rhythm is apparent in test methods.</p>\n\n<p>When duplication creeps up in the \"verify\" part of tests, it is often beneficial to define custom assertion methods. Of course, those methods must still test a clearly identified relation that can be made apparent in the method name: <code>assertPegFitsInHole</code> -> good, <code>assertPegIsGood</code> -> bad.</p>\n\n<p>When test methods grow long and repetitive I sometimes find it useful to define fill-in-the-blanks test templates that take a few parameters. Then the actual test methods are reduced to a call to the template method with the appropriate parameters.</p>\n\n<p>As for a lot of things in programming and testing, there is no clear-cut answer. You need to develop a taste, and the best way to do so is to make mistakes.</p>\n" }, { "answer_id": 130040, "author": "Don Kirkby", "author_id": 4794, "author_profile": "https://Stackoverflow.com/users/4794", "pm_score": 3, "selected": false, "text": "<p>You can reduce repetition using several different flavours of <a href=\"http://xunitpatterns.com/Test%20Utility%20Method.html\" rel=\"noreferrer\">test utility methods</a>.</p>\n\n<p>I'm more tolerant of repetition in test code than in production code, but I have been frustrated by it sometimes. When you change a class's design and you have to go back and tweak 10 different test methods that all do the same setup steps, it's frustrating.</p>\n" }, { "answer_id": 130715, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>\"refactored them to make them more DRY--the intent of each test was no longer clear\"</p>\n\n<p>It sounds like you had trouble doing the refactoring. I'm just guessing, but if it wound up less clear, doesn't that mean you still have more work to do so that you have reasonably elegant tests which are perfectly clear?</p>\n\n<p>That's why tests are a subclass of UnitTest -- so you can design good test suites that are correct, easy to validate and clear.</p>\n\n<p>In the olden times we had testing tools that used different programming languages. It was hard (or impossible) to design pleasant, easy-to-work with tests.</p>\n\n<p>You have the full power of -- whatever language you're using -- Python, Java, C# -- so use that language well. You can achieve good-looking test code that's clear and not too redundant. There's no trade-off.</p>\n" }, { "answer_id": 130738, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>I LOVE rspec because of this:</p>\n\n<p>It has 2 things to help - </p>\n\n<ul>\n<li><p>shared example groups for testing common behaviour.<br>\nyou can define a set of tests, then 'include' that set in your real tests.</p></li>\n<li><p>nested contexts.<br>\nyou can essentially have a 'setup' and 'teardown' method for a specific subset of your tests, not just every one in the class.</p></li>\n</ul>\n\n<p>The sooner that .NET/Java/other test frameworks adopt these methods, the better (or you could use IronRuby or JRuby to write your tests, which I personally think is the better option)</p>\n" }, { "answer_id": 143699, "author": "spiv", "author_id": 22701, "author_profile": "https://Stackoverflow.com/users/22701", "pm_score": 7, "selected": true, "text": "<p>Duplicated code is a smell in unit test code just as much as in other code. If you have duplicated code in tests, it makes it harder to refactor the implementation code because you have a disproportionate number of tests to update. Tests should help you refactor with confidence, rather than be a large burden that impedes your work on the code being tested.</p>\n\n<p>If the duplication is in fixture set up, consider making more use of the <code>setUp</code> method or providing more (or more flexible) <a href=\"http://xunitpatterns.com/Creation%20Method.html\" rel=\"noreferrer\">Creation Methods</a>.</p>\n\n<p>If the duplication is in the code manipulating the SUT, then ask yourself why multiple so-called “unit” tests are exercising the exact same functionality.</p>\n\n<p>If the duplication is in the assertions, then perhaps you need some <a href=\"http://xunitpatterns.com/Custom%20Assertion.html\" rel=\"noreferrer\">Custom Assertions</a>. For example, if multiple tests have a string of assertions like:</p>\n\n<pre><code>assertEqual('Joe', person.getFirstName())\nassertEqual('Bloggs', person.getLastName())\nassertEqual(23, person.getAge())\n</code></pre>\n\n<p>Then perhaps you need a single <code>assertPersonEqual</code> method, so that you can write <code>assertPersonEqual(Person('Joe', 'Bloggs', 23), person)</code>. (Or perhaps you simply need to overload the equality operator on <code>Person</code>.)</p>\n\n<p>As you mention, it is important for test code to be readable. In particular, it is important that the <em>intent</em> of a test is clear. I find that if many tests look mostly the same, (e.g. three-quarters of the lines the same or virtually the same) it is hard to spot and recognise the significant differences without carefully reading and comparing them. So I find that refactoring to remove duplication <em>helps</em> readability, because every line of every test method is directly relevant to the purpose of the test. That's much more helpful for the reader than a random combination of lines that are directly relevant, and lines that are just boilerplate.</p>\n\n<p>That said, sometimes tests are exercising complex situations that are similiar but still significantly different, and it is hard to find a good way to reduce the duplication. Use common sense: if you feel the tests are readable and make their intent clear, and you're comfortable with perhaps needing to update more than a theoretically minimal number of tests when refactoring the code invoked by the tests, then accept the imperfection and move on to something more productive. You can always come back and refactor the tests later, when inspiration strikes!</p>\n" }, { "answer_id": 145167, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "<p>Jay Fields coined the phrase that \"DSLs should be DAMP, not DRY\", where <em>DAMP</em> means <em>descriptive and meaningful phrases</em>. I think the same applies to tests, too. Obviously, too much duplication is bad. But removing duplication at all costs is even worse. Tests should act as intent-revealing specifications. If, for example, you specify the same feature from several different angles, then a certain amount of duplication is to be expected.</p>\n" }, { "answer_id": 30008100, "author": "Kevin London", "author_id": 1021177, "author_profile": "https://Stackoverflow.com/users/1021177", "pm_score": 2, "selected": false, "text": "<p>I feel that test code requires a similar level of engineering that would normally be applied to production code. There can certainly be arguments made in favor of readability and I would agree that's important. </p>\n\n<p>In my experience, however, I find that well-factored tests are easier to read and understand. If there's 5 tests that each look the same except for one variable that's changed and the assertion at the end, it can be very difficult to find what that single differing item is. Similarly, if it is factored so that only the variable that's changing is visible and the assertion, then it's easy to figure out what the test is doing immediately.</p>\n\n<p>Finding the right level of abstraction when testing can be difficult and I feel it is worth doing.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
I ruined several unit tests some time ago when I went through and refactored them to make them more [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)--the intent of each test was no longer clear. It seems there is a trade-off between tests' readability and maintainability. If I leave duplicated code in unit tests, they're more readable, but then if I change the [SUT](http://en.wikipedia.org/wiki/System_Under_Test), I'll have to track down and change each copy of the duplicated code. Do you agree that this trade-off exists? If so, do you prefer your tests to be readable, or maintainable?
Duplicated code is a smell in unit test code just as much as in other code. If you have duplicated code in tests, it makes it harder to refactor the implementation code because you have a disproportionate number of tests to update. Tests should help you refactor with confidence, rather than be a large burden that impedes your work on the code being tested. If the duplication is in fixture set up, consider making more use of the `setUp` method or providing more (or more flexible) [Creation Methods](http://xunitpatterns.com/Creation%20Method.html). If the duplication is in the code manipulating the SUT, then ask yourself why multiple so-called “unit” tests are exercising the exact same functionality. If the duplication is in the assertions, then perhaps you need some [Custom Assertions](http://xunitpatterns.com/Custom%20Assertion.html). For example, if multiple tests have a string of assertions like: ``` assertEqual('Joe', person.getFirstName()) assertEqual('Bloggs', person.getLastName()) assertEqual(23, person.getAge()) ``` Then perhaps you need a single `assertPersonEqual` method, so that you can write `assertPersonEqual(Person('Joe', 'Bloggs', 23), person)`. (Or perhaps you simply need to overload the equality operator on `Person`.) As you mention, it is important for test code to be readable. In particular, it is important that the *intent* of a test is clear. I find that if many tests look mostly the same, (e.g. three-quarters of the lines the same or virtually the same) it is hard to spot and recognise the significant differences without carefully reading and comparing them. So I find that refactoring to remove duplication *helps* readability, because every line of every test method is directly relevant to the purpose of the test. That's much more helpful for the reader than a random combination of lines that are directly relevant, and lines that are just boilerplate. That said, sometimes tests are exercising complex situations that are similiar but still significantly different, and it is hard to find a good way to reduce the duplication. Use common sense: if you feel the tests are readable and make their intent clear, and you're comfortable with perhaps needing to update more than a theoretically minimal number of tests when refactoring the code invoked by the tests, then accept the imperfection and move on to something more productive. You can always come back and refactor the tests later, when inspiration strikes!
129,746
<p>I am trying to set up JBoss 4.2.2 and JConsole for remote monitoring. As per many of the how-to's I have found on the web to do this you need to enable jmxremote by setting the following options in run.conf. (I realize the other two opts disable authentication)</p> <pre><code>JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=11099" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.authenticate=false" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false" </code></pre> <p>Which results in the following exception:</p> <pre><code>13:06:56,418 INFO [TomcatDeployer] performDeployInternal :: deploy, ctxPath=/services, warUrl=.../tmp/deploy/tmp34585xxxxxxxxx.ear-contents/mDate-Services-exp.war/ 13:06:57,706 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:57,711 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:58,070 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:58,071 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:58,138 ERROR [MainDeployer] start :: Could not start deployment: file:/opt/jboss-4.2.2.GA/server/default/tmp/deploy/tmp34585xxxxxxxxx.ear-contents/xxxxx-Services.war java.lang.NullPointerException at org.jboss.wsf.stack.jbws.WSDLFilePublisher.getPublishLocation(WSDLFilePublisher.java:303) at org.jboss.wsf.stack.jbws.WSDLFilePublisher.publishWsdlFiles(WSDLFilePublisher.java:103) at org.jboss.wsf.stack.jbws.PublishContractDeploymentAspect.create(PublishContractDeploymentAspect.java:52) at org.jboss.wsf.framework.deployment.DeploymentAspectManagerImpl.deploy(DeploymentAspectManagerImpl.java:115) at org.jboss.wsf.container.jboss42.ArchiveDeployerHook.deploy(ArchiveDeployerHook.java:97) ... </code></pre> <p>My application uses JWS which according to this bug:</p> <p><a href="https://jira.jboss.org/jira/browse/JBWS-1943" rel="nofollow noreferrer">https://jira.jboss.org/jira/browse/JBWS-1943</a></p> <p>Suggests this workaround:</p> <pre><code>JAVA_OPTS="$JAVA_OPTS -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl" JAVA_OPTS="$JAVA_OPTS -Djboss.platform.mbeanserver" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote" </code></pre> <p>(<a href="https://developer.jboss.org/wiki/JBossWS-FAQ#jive_content_id_How_to_use_JDK_JMX_JConsole_with_JBossWS" rel="nofollow noreferrer">https://developer.jboss.org/wiki/JBossWS-FAQ#jive_content_id_How_to_use_JDK_JMX_JConsole_with_JBossWS</a>)</p> <p>I've tried that however that then throws the following exception while trying to deploy a sar file in my ear which only contains on class which implements Schedulable for a couple of scheduled jobs my application requires:</p> <pre><code>Caused by: java.lang.NullPointerException at EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap.hash(ConcurrentReaderHashMap.java:298) at EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap.get(ConcurrentReaderHashMap.java:410) at org.jboss.mx.server.registry.BasicMBeanRegistry.getMBeanMap(BasicMBeanRegistry.java:959) at org.jboss.mx.server.registry.BasicMBeanRegistry.contains(BasicMBeanRegistry.java:577) </code></pre> <p>Any suggestions on where to go from here?</p> <p>EDIT:</p> <p>I have also tried the following variation:</p> <pre><code>JAVA_OPTS="$JAVA_OPTS -DmbipropertyFile=../server/default/conf/mbi.properties -DpropertyFile=../server/default/conf/mdate.properties -Dwicket.configuration=DEVELOPMENT" JAVA_OPTS="$JAVA_OPTS -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl" JAVA_OPTS="$JAVA_OPTS -Djboss.platform.mbeanserver" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote" </code></pre> <p>I'm using JDK 1.6.0_01-b06</p>
[ { "answer_id": 129872, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 2, "selected": false, "text": "<p>I have honestly never tried this remoting approach. But, if both your client machine and the server happen to both be linux boxes or similar *nixes with SSH, then you can <code>ssh -XCA</code> to the server and start JConsole <em>on the server</em> and have the GUI display on your client machine with X port forwarding. A JConsole running locally to the server JVM you want to monitor <em>should</em> not have any trouble connecting.</p>\n\n<p>I personally think that's a nifty trick but I realize that it dosn't <em>really</em> solve the problem of getting JConsole to connect remotely through JWS.</p>\n" }, { "answer_id": 420801, "author": "Nik", "author_id": 13267, "author_profile": "https://Stackoverflow.com/users/13267", "pm_score": 0, "selected": false, "text": "<p>First thing I would do is to delete both /tmp and /work directories under JBoss /default and redeploy the WAR. If that doesn't, I would upgrade the JDK to use a more recent version of 1.6. 1.6.0_01 is pretty old. </p>\n" }, { "answer_id": 752695, "author": "mattkemp", "author_id": 90394, "author_profile": "https://Stackoverflow.com/users/90394", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if there's a specific reason you're trying to use WS to access the mbean server, but with JConsole you can directly access a remote JVM. To do this use \"service:jmx:rmi:///jndi/rmi://&lt;remote-machine&gt;:&lt;port&gt;/jmxrmi\" (where &lt;remote-machine&gt; is whatever machine your trying to connect to and &lt;port&gt; is 11099) as the remote process.</p>\n\n<p>I have used this to connect to any 1.6 JVM that exposes an mbean server (JBoss, ActiveMQ, etc).</p>\n" }, { "answer_id": 752964, "author": "Alexander Torstling", "author_id": 83741, "author_profile": "https://Stackoverflow.com/users/83741", "pm_score": 0, "selected": false, "text": "<p>I don't know if this is related, but JBoss has a tendency to redirect to itself. If you connect to a host, say jboss.localdomain:3873, wanting to connect to a ejb, JBoss might lookup its own hostname and redirect to the address it gets from there. If you have a public hostname, it might find that instead (say jboss.publicdomain.com), and tell the client to reconnect to jboss.publicdomain.com:1099. Depending on your DNS, this might or might not be a reachable address from your client.</p>\n\n<p>There are various varations of this problem, and as a bonus, sometimes the initial \"connection check\" works, so the client app deploys, but fails later on connect.</p>\n" }, { "answer_id": 830932, "author": "anikitin", "author_id": 102381, "author_profile": "https://Stackoverflow.com/users/102381", "pm_score": 0, "selected": false, "text": "<p>Had a similar issue, but with JBoss Seam: take a look at <a href=\"https://jira.jboss.org/jira/browse/JBSEAM-4029\" rel=\"nofollow noreferrer\">JBSEAM-4029</a>. As one of the workarounds it suggests to override the class running into the NPE - in Seam's case the <code>JBossClusterMonitor</code>.</p>\n\n<p>I bet the JWS code is running into exact same issue, i.e. ending up calling <code>MBeanServerFactory.findMBeanServer(null)</code> at some point in time. The stack trace should reveal which exact class does this.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419/" ]
I am trying to set up JBoss 4.2.2 and JConsole for remote monitoring. As per many of the how-to's I have found on the web to do this you need to enable jmxremote by setting the following options in run.conf. (I realize the other two opts disable authentication) ``` JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=11099" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.authenticate=false" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false" ``` Which results in the following exception: ``` 13:06:56,418 INFO [TomcatDeployer] performDeployInternal :: deploy, ctxPath=/services, warUrl=.../tmp/deploy/tmp34585xxxxxxxxx.ear-contents/mDate-Services-exp.war/ 13:06:57,706 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:57,711 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:58,070 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:58,071 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080' 13:06:58,138 ERROR [MainDeployer] start :: Could not start deployment: file:/opt/jboss-4.2.2.GA/server/default/tmp/deploy/tmp34585xxxxxxxxx.ear-contents/xxxxx-Services.war java.lang.NullPointerException at org.jboss.wsf.stack.jbws.WSDLFilePublisher.getPublishLocation(WSDLFilePublisher.java:303) at org.jboss.wsf.stack.jbws.WSDLFilePublisher.publishWsdlFiles(WSDLFilePublisher.java:103) at org.jboss.wsf.stack.jbws.PublishContractDeploymentAspect.create(PublishContractDeploymentAspect.java:52) at org.jboss.wsf.framework.deployment.DeploymentAspectManagerImpl.deploy(DeploymentAspectManagerImpl.java:115) at org.jboss.wsf.container.jboss42.ArchiveDeployerHook.deploy(ArchiveDeployerHook.java:97) ... ``` My application uses JWS which according to this bug: <https://jira.jboss.org/jira/browse/JBWS-1943> Suggests this workaround: ``` JAVA_OPTS="$JAVA_OPTS -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl" JAVA_OPTS="$JAVA_OPTS -Djboss.platform.mbeanserver" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote" ``` (<https://developer.jboss.org/wiki/JBossWS-FAQ#jive_content_id_How_to_use_JDK_JMX_JConsole_with_JBossWS>) I've tried that however that then throws the following exception while trying to deploy a sar file in my ear which only contains on class which implements Schedulable for a couple of scheduled jobs my application requires: ``` Caused by: java.lang.NullPointerException at EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap.hash(ConcurrentReaderHashMap.java:298) at EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap.get(ConcurrentReaderHashMap.java:410) at org.jboss.mx.server.registry.BasicMBeanRegistry.getMBeanMap(BasicMBeanRegistry.java:959) at org.jboss.mx.server.registry.BasicMBeanRegistry.contains(BasicMBeanRegistry.java:577) ``` Any suggestions on where to go from here? EDIT: I have also tried the following variation: ``` JAVA_OPTS="$JAVA_OPTS -DmbipropertyFile=../server/default/conf/mbi.properties -DpropertyFile=../server/default/conf/mdate.properties -Dwicket.configuration=DEVELOPMENT" JAVA_OPTS="$JAVA_OPTS -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl" JAVA_OPTS="$JAVA_OPTS -Djboss.platform.mbeanserver" JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote" ``` I'm using JDK 1.6.0\_01-b06
I have honestly never tried this remoting approach. But, if both your client machine and the server happen to both be linux boxes or similar \*nixes with SSH, then you can `ssh -XCA` to the server and start JConsole *on the server* and have the GUI display on your client machine with X port forwarding. A JConsole running locally to the server JVM you want to monitor *should* not have any trouble connecting. I personally think that's a nifty trick but I realize that it dosn't *really* solve the problem of getting JConsole to connect remotely through JWS.
129,773
<p>When you create your mapping files, do you map your properties to fields or properties :</p> <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Foo" namespace="Foo.Bar" &gt; &lt;class name="Foo" table="FOOS" batch-size="100"&gt; [...] &lt;property name="FooProperty1" access="field.camelcase" column="FOO_1" type="string" length="50" /&gt; &lt;property name="FooProperty2" column="FOO_2" type="string" length="50" /&gt; [...] &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>Of course, please explain why :)</p> <p>Usually, I map to properties, but mapping to fields can enable to put some "logic" in the getters/setters of the properties.</p> <p>Is it "bad" to map to fields ? Is there a best practice ?</p>
[ { "answer_id": 129797, "author": "Sara Chipps", "author_id": 4140, "author_profile": "https://Stackoverflow.com/users/4140", "pm_score": 1, "selected": false, "text": "<p>I map to properties, I haven't come across the situation where I would map to a field... and when I have I augment my B.O. design for the need. I think it allows for better architecture. </p>\n" }, { "answer_id": 129805, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 4, "selected": true, "text": "<p>I map to properties. If I find it necessary, I map the SETTER to a field. (usually via something like \"access=field.camelcase\").</p>\n\n<p>This lets me have nice looking Queries, e.g. \"from People Where FirstName = 'John'\" instead of something like \"from People Where firstName/_firstName\" and also avoid setter logic when hydrating my entities.</p>\n" }, { "answer_id": 130199, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 1, "selected": false, "text": "<p>I map to properties because I use automatic properties. </p>\n\n<p>Except for collections (like <code>set</code>s. Those I map to fields (<code>access=\"field.camelcase-underscore\"</code>) because I don't have public properties exposing them, but methods.</p>\n" }, { "answer_id": 137592, "author": "Jon Adams", "author_id": 2291, "author_profile": "https://Stackoverflow.com/users/2291", "pm_score": 2, "selected": false, "text": "<p>Properties are also useful in the case you need to do something funky with the data as it comes in and out of persistant storage. This should generally be avoided, but some rare business cases or legacy support sometimes calls for this.</p>\n\n<p><p>(Just remember that if you somehow transform the data when it comes back out with the getter, NHibernate will (by default) use the return from the getter and save it that way back to the database when the Session is flushed/closed. Make sure that is what you want.)</p>\n" }, { "answer_id": 212889, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<p>I tend to agree with the answers above. Generally, map to properties for almost everything, then map to fields for collection setters.<br>\nThe only other place you'd want to map to fields is when you have something:</p>\n\n<pre><code>public class AuditableEntity\n{\n /*...*/\n DateTime creationDate = DateTime.Now;\n /*...*/\n public DateTime CreationDate { get { return creationDate; } }\n}\n</code></pre>\n" }, { "answer_id": 373830, "author": "Jafin", "author_id": 40513, "author_profile": "https://Stackoverflow.com/users/40513", "pm_score": 1, "selected": false, "text": "<p><strong>Null Objects</strong></p>\n\n<p>Mapping to fields can be useful if you are implementing the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">null object pattern</a> if your classes. As this cannot be performed (easily) when mapping to Properties. You end up having to store fake objects in the database. </p>\n\n<p><strong>HQL</strong></p>\n\n<p>I was unsure that with HQL queries you had to change the property names if you were using a field access approach. ie if you had <code>&lt;property name=\"FirstName\" access=\"field.camelcase\" /&gt;</code> I thought you could still write <code>\"From Person where FirstName = :name\";</code> as it would use the property name still.</p>\n\n<p>Further discussion on field strategies and Null object can be found <a href=\"http://forum.hibernate.org/viewtopic.php?t=980694&amp;postdays=0&amp;postorder=asc&amp;start=15\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Performance</strong></p>\n\n<p>In relation to performance of field vs property on <a href=\"http://jaychapman.blogspot.com/2007/11/nhibernate-access-performance.html\" rel=\"nofollow noreferrer\">John Chapman's blog</a>\nIt appears there isn't much of an issue in performance with small-midrange result sets.</p>\n\n<p>In summary, each approach has certain perks that may be useful depending on the scenario (field access allows readonly getters, no need for setters, property access works when nothing special is required from your poco and seems to be the defacto approach. etc)</p>\n" }, { "answer_id": 1375684, "author": "quip", "author_id": 30469, "author_profile": "https://Stackoverflow.com/users/30469", "pm_score": 0, "selected": false, "text": "<p>I map directly to fields, which allows me to use the property setters to keep track of a property's dirty state.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971/" ]
When you create your mapping files, do you map your properties to fields or properties : ``` <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Foo" namespace="Foo.Bar" > <class name="Foo" table="FOOS" batch-size="100"> [...] <property name="FooProperty1" access="field.camelcase" column="FOO_1" type="string" length="50" /> <property name="FooProperty2" column="FOO_2" type="string" length="50" /> [...] </class> </hibernate-mapping> ``` Of course, please explain why :) Usually, I map to properties, but mapping to fields can enable to put some "logic" in the getters/setters of the properties. Is it "bad" to map to fields ? Is there a best practice ?
I map to properties. If I find it necessary, I map the SETTER to a field. (usually via something like "access=field.camelcase"). This lets me have nice looking Queries, e.g. "from People Where FirstName = 'John'" instead of something like "from People Where firstName/\_firstName" and also avoid setter logic when hydrating my entities.
129,815
<p>I am working on a geometry problem that requires finding the intersection of two parabolic arcs in any rotation. I was able to intesect a line and a parabolic arc by rotating the plane to align the arc with an axis, but two parabolas cannot both align with an axis. I am working on deriving the formulas, but I would like to know if there is a resource already available for this.</p>
[ { "answer_id": 129889, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 4, "selected": true, "text": "<p>I'd first define the equation for the parabolic arc in 2D without rotations:</p>\n\n<pre><code> x(t) = ax² + bx + c\n y(t) = t;\n</code></pre>\n\n<p>You can now apply the rotation by building a rotation matrix:</p>\n\n<pre><code> s = sin(angle)\n c = cos(angle)\n\n matrix = | c -s |\n | s c |\n</code></pre>\n\n<p>Apply that matrix and you'll get the rotated parametric equation:</p>\n\n<pre><code>x' (t) = x(t) * c - s*t;\ny' (t) = x(t) * s + c*t;\n</code></pre>\n\n<p>This will give you two equations (for x and y) of your parabolic arcs.</p>\n\n<p>Do that for both of your rotated arcs and subtract them. This gives you an equation like this:</p>\n\n<pre><code> xa'(t) = rotated equation of arc1 in x\n ya'(t) = rotated equation of arc1 in y.\n xb'(t) = rotated equation of arc2 in x\n yb'(t) = rotated equation of arc2 in y.\n t1 = parametric value of arc1\n t2 = parametric value of arc2\n\n 0 = xa'(t1) - xb'(t2)\n 0 = ya'(t1) - yb'(t2)\n</code></pre>\n\n<p>Each of these equation is just a order 2 polynomial. These are easy to solve.</p>\n\n<p>To find the intersection points you solve the above equation (e.g. find the roots).</p>\n\n<p>You'll get up to two roots for each axis. Any root that is equal on x and y is an intersection point between the curves.</p>\n\n<p>Getting the position is easy now: Just plug the root into your parametric equation and you can directly get x and y.</p>\n" }, { "answer_id": 4331193, "author": "xaq", "author_id": 527442, "author_profile": "https://Stackoverflow.com/users/527442", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, the general answer requires solution of a fourth-order polynomial. If we transform coordinates so one of the two parabolas is in the standard form y=x^2, then the second parabola satisfies (ax+by)^2+cx+dy+e==0. To find the intersection, solve both simultaneously. Substituting in y=x^2 we see that the result is a fourth-order polynomial: (ax+bx^2)^2+cx+dx^2+e==0. Nils solution therefore won't work (his mistake: each one is a 2nd order polynomial in each variable separately, but together they're not).</p>\n" }, { "answer_id": 5440819, "author": "Dr. belisarius", "author_id": 353410, "author_profile": "https://Stackoverflow.com/users/353410", "pm_score": 1, "selected": false, "text": "<p>It's easy if you have a CAS at hand. </p>\n\n<p>See the solution in Mathematica.</p>\n\n<p>Choose one parabola and change coordinates so its equation becomes y(x)=a x^2 (Normal form).</p>\n\n<p>The other parabola will have the general form: </p>\n\n<pre><code>A x^2 + B x y + CC y^2 + DD x + EE y + F == 0 \n\nwhere B^2-4 A C ==0 (so it's a parabola) \n</code></pre>\n\n<p>Let's solve a numeric case:</p>\n\n<pre><code>p = {a -&gt; 1, A -&gt; 1, B -&gt; 2, CC -&gt; 1, DD -&gt; 1, EE -&gt; -1, F -&gt; 1};\np1 = {ToRules@N@Reduce[\n (A x^2 + B x y + CC y^2 + DD x + EE y +F /. {y -&gt; a x^2 } /. p) == 0, x]}\n</code></pre>\n\n<p>{{x -> -2.11769}, {x -> -0.641445},\n {x -> 0.379567- 0.76948 I}, \n {x -> 0.379567+ 0.76948 I}}</p>\n\n<p>Let's plot it: </p>\n\n<pre><code>Show[{\n Plot[a x^2 /. p, {x, -10, 10}, PlotRange -&gt; {{-10, 10}, {-5, 5}}], \n ContourPlot[(A x^2 + B x y + CC y^2 + DD x + EE y + F /. p) == \n 0, {x, -10, 10}, {y, -10, 10}],\n Graphics[{\n PointSize[Large], Pink, Point[{x, x^2} /. p /. p1[[1]]],\n PointSize[Large], Pink, Point[{x, x^2} /. p /. p1[[2]]]\n }]}]\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/WhTZJ.png\" alt=\"enter image description here\"></p>\n\n<p>The general solution involves calculating the roots of: </p>\n\n<pre><code>4 A F + 4 A DD x + (4 A^2 + 4 a A EE) x^2 + 4 a A B x^3 + a^2 B^2 x^4 == 0 \n</code></pre>\n\n<p>Which is done easily in any CAS.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15032/" ]
I am working on a geometry problem that requires finding the intersection of two parabolic arcs in any rotation. I was able to intesect a line and a parabolic arc by rotating the plane to align the arc with an axis, but two parabolas cannot both align with an axis. I am working on deriving the formulas, but I would like to know if there is a resource already available for this.
I'd first define the equation for the parabolic arc in 2D without rotations: ``` x(t) = ax² + bx + c y(t) = t; ``` You can now apply the rotation by building a rotation matrix: ``` s = sin(angle) c = cos(angle) matrix = | c -s | | s c | ``` Apply that matrix and you'll get the rotated parametric equation: ``` x' (t) = x(t) * c - s*t; y' (t) = x(t) * s + c*t; ``` This will give you two equations (for x and y) of your parabolic arcs. Do that for both of your rotated arcs and subtract them. This gives you an equation like this: ``` xa'(t) = rotated equation of arc1 in x ya'(t) = rotated equation of arc1 in y. xb'(t) = rotated equation of arc2 in x yb'(t) = rotated equation of arc2 in y. t1 = parametric value of arc1 t2 = parametric value of arc2 0 = xa'(t1) - xb'(t2) 0 = ya'(t1) - yb'(t2) ``` Each of these equation is just a order 2 polynomial. These are easy to solve. To find the intersection points you solve the above equation (e.g. find the roots). You'll get up to two roots for each axis. Any root that is equal on x and y is an intersection point between the curves. Getting the position is easy now: Just plug the root into your parametric equation and you can directly get x and y.
129,828
<p>My workplace filters our internet traffic by forcing us to go through a proxy, and unfortunately sites such as IT Conversations and Libsyn are blocked. However, mp3 files in general are not filtered, if they come from sites not on the proxy's blacklist.</p> <p>So is there a website somewhere that will let me give it a URL and then download the MP3 at that URL and send it my way, thus slipping through the proxy?</p> <p>Alternatively, is there some other easy way for me to get the mp3 files for these podcasts from work?</p> <p>EDIT and UPDATE: Since I've gotten downvoted a few times, perhaps I should explain/justify my situation. I'm a contractor working at a government facility, and we use some commercial filtering software which is very aggressive and overzealous. My boss is fine with me listening to podcasts at work and is fine with me circumventing the proxy filtering, and doesn't want to deal with the significant red tape (it's the government after all) associated with getting the IT department to make an exception for IT Conversations or the Java Posse, etc. So I feel that this is an important and relevant question for programmers.</p> <p>Unfortunately, all of the proxy websites for bypassing web filters have also been blocked, so I may have to download the podcasts I like at home in advance and then bring them into work. If can tell me about a lesser-known service I can try which might not be blocked, I'd appreciate it.</p>
[ { "answer_id": 129886, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 1, "selected": false, "text": "<p>There are many other Development/Dotnet/Technology podcasts, try one of <a href=\"https://stackoverflow.com/questions/1644/what-good-technology-podcasts-are-out-there\">those</a>. for the blocked sites try an anonymous proxy site, there are plenty out there.</p>\n" }, { "answer_id": 129894, "author": "pdavis", "author_id": 7819, "author_profile": "https://Stackoverflow.com/users/7819", "pm_score": 1, "selected": false, "text": "<p>Since this is work related material, I would recommend opening up a request that the sites in question not be blocked.</p>\n" }, { "answer_id": 133360, "author": "Will Boyce", "author_id": 5757, "author_profile": "https://Stackoverflow.com/users/5757", "pm_score": 2, "selected": false, "text": "<p>Can you SSH out? SSH Tunnels are your friend!</p>\n" }, { "answer_id": 389873, "author": "Jim Anderson", "author_id": 42439, "author_profile": "https://Stackoverflow.com/users/42439", "pm_score": 2, "selected": false, "text": "<p>Why not subscribe at home and have your favorite podcasts copied to your mp3 player or a USB drive and just take it to work with you each day and back home in the evening? Then you can listen and your are not circumventing your clients network.</p>\n" }, { "answer_id": 1383922, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 1, "selected": true, "text": "<p>I ended up writing an extremely dumb-and-simple cgi-script and hosting it on my web server, with a script on my work computer to get at it. Here's the CGI script:</p>\n\n<pre><code>#!/usr/local/bin/python\n\nimport cgitb; cgitb.enable()\nimport cgi\nfrom urllib2 import urlopen\n\ndef tohex(data):\n return \"\".join(hex(ord(char))[2:].rjust(2,\"0\") for char in data)\n\ndef fromhex(encoded):\n data = \"\"\n while encoded:\n data += chr(int(encoded[:2], 16))\n encoded = encoded[2:]\n return data\n\nif __name__==\"__main__\":\n print(\"Content-type: text/plain\")\n print(\"\")\n url = fromhex( cgi.FieldStorage()[\"target\"].value )\n contents = urlopen(url).read()\n for i in range(len(contents)/40+1):\n print( tohex(contents[40*i:40*i+40]) )\n</code></pre>\n\n<p>and here's the client script used to download the podcasts:</p>\n\n<pre><code>#!/usr/bin/env python2.6\nimport os\nfrom sys import argv\nfrom urllib2 import build_opener, ProxyHandler\n\nif os.fork():\n exit()\n\ndef tohex(data):\n return \"\".join(hex(ord(char))[2:].rjust(2,\"0\") for char in data)\n\ndef fromhex(encoded):\n data = \"\"\n while encoded:\n data += chr(int(encoded[:2], 16))\n encoded = encoded[2:]\n return data\n\nif __name__==\"__main__\":\n if len(argv) &lt; 2:\n print(\"usage: %s URL [FILENAME]\" % argv[0])\n quit()\n\n os.chdir(\"/home/courtwright/mp3s\")\n url = \"http://example.com/cgi-bin/hex.py?target=%s\" % tohex(argv[1])\n fname = argv[2] if len(argv)&gt;2 else argv[1].split(\"/\")[-1]\n with open(fname, \"wb\") as dest:\n for line in build_opener(ProxyHandler({\"http\":\"proxy.example.com:8080\"})).open(url):\n dest.write( fromhex(line.strip()) )\n dest.flush()\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
My workplace filters our internet traffic by forcing us to go through a proxy, and unfortunately sites such as IT Conversations and Libsyn are blocked. However, mp3 files in general are not filtered, if they come from sites not on the proxy's blacklist. So is there a website somewhere that will let me give it a URL and then download the MP3 at that URL and send it my way, thus slipping through the proxy? Alternatively, is there some other easy way for me to get the mp3 files for these podcasts from work? EDIT and UPDATE: Since I've gotten downvoted a few times, perhaps I should explain/justify my situation. I'm a contractor working at a government facility, and we use some commercial filtering software which is very aggressive and overzealous. My boss is fine with me listening to podcasts at work and is fine with me circumventing the proxy filtering, and doesn't want to deal with the significant red tape (it's the government after all) associated with getting the IT department to make an exception for IT Conversations or the Java Posse, etc. So I feel that this is an important and relevant question for programmers. Unfortunately, all of the proxy websites for bypassing web filters have also been blocked, so I may have to download the podcasts I like at home in advance and then bring them into work. If can tell me about a lesser-known service I can try which might not be blocked, I'd appreciate it.
I ended up writing an extremely dumb-and-simple cgi-script and hosting it on my web server, with a script on my work computer to get at it. Here's the CGI script: ``` #!/usr/local/bin/python import cgitb; cgitb.enable() import cgi from urllib2 import urlopen def tohex(data): return "".join(hex(ord(char))[2:].rjust(2,"0") for char in data) def fromhex(encoded): data = "" while encoded: data += chr(int(encoded[:2], 16)) encoded = encoded[2:] return data if __name__=="__main__": print("Content-type: text/plain") print("") url = fromhex( cgi.FieldStorage()["target"].value ) contents = urlopen(url).read() for i in range(len(contents)/40+1): print( tohex(contents[40*i:40*i+40]) ) ``` and here's the client script used to download the podcasts: ``` #!/usr/bin/env python2.6 import os from sys import argv from urllib2 import build_opener, ProxyHandler if os.fork(): exit() def tohex(data): return "".join(hex(ord(char))[2:].rjust(2,"0") for char in data) def fromhex(encoded): data = "" while encoded: data += chr(int(encoded[:2], 16)) encoded = encoded[2:] return data if __name__=="__main__": if len(argv) < 2: print("usage: %s URL [FILENAME]" % argv[0]) quit() os.chdir("/home/courtwright/mp3s") url = "http://example.com/cgi-bin/hex.py?target=%s" % tohex(argv[1]) fname = argv[2] if len(argv)>2 else argv[1].split("/")[-1] with open(fname, "wb") as dest: for line in build_opener(ProxyHandler({"http":"proxy.example.com:8080"})).open(url): dest.write( fromhex(line.strip()) ) dest.flush() ```
129,861
<p>It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment.</p> <p>I've looked at all the @@ globals in Books Online. "<code>SELECT @@servername</code>" comes close, but I want the name of the database instance rather than the server.</p>
[ { "answer_id": 129879, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 6, "selected": false, "text": "<pre><code>SELECT DB_NAME()\n</code></pre>\n\n<p>Returns the database name.</p>\n" }, { "answer_id": 129882, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT DB_NAME() AS DatabaseName\n</code></pre>\n" }, { "answer_id": 129887, "author": "Gthompson83", "author_id": 20483, "author_profile": "https://Stackoverflow.com/users/20483", "pm_score": 1, "selected": false, "text": "<p>You should be able to use:</p>\n\n<pre><code>SELECT SERVERPROPERTY ('InstanceName') \n</code></pre>\n" }, { "answer_id": 129893, "author": "Giacomo Degli Esposti", "author_id": 20796, "author_profile": "https://Stackoverflow.com/users/20796", "pm_score": 3, "selected": false, "text": "<p>You can use <strong>DB_NAME()</strong> :</p>\n\n<pre><code>SELECT DB_NAME()\n</code></pre>\n" }, { "answer_id": 130068, "author": "Ollie", "author_id": 4453, "author_profile": "https://Stackoverflow.com/users/4453", "pm_score": 3, "selected": false, "text": "<p>I'm not sure what you were exactly asking. As you are writing this procedure for an Auditing need I guess you're asking how do you get the current database name when the Stored Procedure exists in another database. e.g.</p>\n\n<pre><code>USE DATABASE1\nGO\nCREATE PROC spGetContext AS\nSELECT DB_NAME()\nGO\nUSE DATABASE2\nGO\nEXEC DATABASE1..spGetContext\n/* RETURNS 'DATABASE1' not 'DATABASE2' */\n</code></pre>\n\n<p>This is the correct behaviour, but not always what you're looking for. To get round this you need to create the SP in the Master database and mark the procedure as a System Procedure. The method of doing this differs between SQL Server versions but here's the method for SQL Server 2005 (it is possible to do in 2000 with the <code>master.dbo.sp_MS_upd_sysobj_category</code> function).</p>\n\n<pre><code>USE MASTER\n/* You must begin function name with sp_ */\nCREATE FUNCTION sp_GetContext\nAS\nSELECT DB_NAME()\nGO\nEXEC sys.sp_MS_marksystemobject sp_GetContext\n\nUSE DATABASE2\n/* Note - no need to reference master when calling SP */\nEXEC sp_GetContext\n/* RETURNS 'DATABASE2' */\n</code></pre>\n\n<p>Hope this is what you were looking for</p>\n" }, { "answer_id": 30393299, "author": "kevin", "author_id": 4928422, "author_profile": "https://Stackoverflow.com/users/4928422", "pm_score": 6, "selected": true, "text": "<pre><code>SELECT\n @@servername AS 'Server Name' -- The database server's machine name\n,@@servicename AS 'Instance Name' -- e.g.: MSSQLSERVER\n,DB_NAME() AS 'Database Name'\n,HOST_NAME() AS 'Host Name' -- The database client's machine name\n</code></pre>\n" }, { "answer_id": 31559056, "author": "nad", "author_id": 4935612, "author_profile": "https://Stackoverflow.com/users/4935612", "pm_score": 2, "selected": false, "text": "<p><strong>simply use:</strong> </p>\n\n<pre><code>select @@servicename\n</code></pre>\n" }, { "answer_id": 73463689, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "<p>You can get <strong>the instance name</strong> of <strong>your current database</strong> as shown below:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT @@SERVICENAME -- SQLEXPRESS\nSELECT SERVERPROPERTY ('InstanceName') -- SQLEXPRESS\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470/" ]
It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment. I've looked at all the @@ globals in Books Online. "`SELECT @@servername`" comes close, but I want the name of the database instance rather than the server.
``` SELECT @@servername AS 'Server Name' -- The database server's machine name ,@@servicename AS 'Instance Name' -- e.g.: MSSQLSERVER ,DB_NAME() AS 'Database Name' ,HOST_NAME() AS 'Host Name' -- The database client's machine name ```
129,877
<p>I'm writing a function to find <a href="http://projecteuler.net/index.php?section=problems&amp;id=12" rel="noreferrer">triangle numbers</a> and the natural way to write it is recursively:</p> <pre><code>function triangle (x) if x == 0 then return 0 end return x+triangle(x-1) end </code></pre> <p>But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while. This is an ideal function to <a href="http://perl.plover.com/Memoize/" rel="noreferrer">memoize</a>, but I want a solution that will memoize any function I pass to it.</p>
[ { "answer_id": 129881, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "<pre><code>function memoize (f)\n local cache = {}\n return function (x)\n if cache[x] then\n return cache[x]\n else\n local y = f(x)\n cache[x] = y\n return y\n end\n end\nend\n\ntriangle = memoize(triangle);\n</code></pre>\n\n<p>Note that to avoid a stack overflow, triangle would still need to be seeded.</p>\n" }, { "answer_id": 129903, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 1, "selected": false, "text": "<p>Here is a generic C# 3.0 implementation, if it could help :</p>\n\n<pre><code>public static class Memoization\n{\n public static Func&lt;T, TResult&gt; Memoize&lt;T, TResult&gt;(this Func&lt;T, TResult&gt; function)\n {\n var cache = new Dictionary&lt;T, TResult&gt;();\n var nullCache = default(TResult);\n var isNullCacheSet = false;\n return parameter =&gt;\n {\n TResult value;\n\n if (parameter == null &amp;&amp; isNullCacheSet)\n {\n return nullCache;\n }\n\n if (parameter == null)\n {\n nullCache = function(parameter);\n isNullCacheSet = true;\n return nullCache;\n }\n\n if (cache.TryGetValue(parameter, out value))\n {\n return value;\n }\n\n value = function(parameter);\n cache.Add(parameter, value);\n return value;\n };\n }\n}\n</code></pre>\n\n<p>(Quoted from a <a href=\"http://codingly.com/2008/05/02/optimisation-des-invocations-dynamiques-de-methodes-en-c/\" rel=\"nofollow noreferrer\">french blog article</a>)</p>\n" }, { "answer_id": 129910, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>In Scala (untested):</p>\n\n<pre><code>def memoize[A, B](f: (A)=&gt;B) = {\n var cache = Map[A, B]()\n\n { x: A =&gt;\n if (cache contains x) cache(x) else {\n val back = f(x)\n cache += (x -&gt; back)\n\n back\n }\n }\n}\n</code></pre>\n\n<p>Note that this only works for functions of arity 1, but with currying you could make it work. The more subtle problem is that <code>memoize(f) != memoize(f)</code> for any function <code>f</code>. One very sneaky way to fix this would be something like the following:</p>\n\n<pre><code>val correctMem = memoize(memoize _)\n</code></pre>\n\n<p>I don't think that this will compile, but it does illustrate the idea.</p>\n" }, { "answer_id": 129924, "author": "Luke Halliwell", "author_id": 3974, "author_profile": "https://Stackoverflow.com/users/3974", "pm_score": 3, "selected": false, "text": "<p>You're also asking the wrong question for your original problem ;)</p>\n\n<p>This is a better way for that case:</p>\n\n<p>triangle(n) = n * (n - 1) / 2</p>\n\n<p>Furthermore, supposing the formula didn't have such a neat solution, memoisation would still be a poor approach here. You'd be better off just writing a simple loop in this case. See <a href=\"https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#130006\">this answer</a> for a fuller discussion.</p>\n" }, { "answer_id": 130006, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 2, "selected": false, "text": "<p><strong>Update</strong>: Commenters have pointed out that memoization is a good way to optimize recursion. Admittedly, I hadn't considered this before, since I generally work in a language (C#) where generalized memoization isn't so trivial to build. Take the post below with that grain of salt in mind.</p>\n\n<p>I think <a href=\"https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#129924\">Luke likely has the most appropriate solution</a> to this problem, but memoization is not generally the solution to any issue of stack overflow.</p>\n\n<p>Stack overflow usually is caused by recursion going deeper than the platform can handle. Languages sometimes support \"<a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"nofollow noreferrer\">tail recursion</a>\", which re-uses the context of the current call, rather than creating a new context for the recursive call. But a lot of mainstream languages/platforms don't support this. C# has no inherent support for tail-recursion, for example. The 64-bit version of the .NET JITter can apply it as an optimization at the IL level, which is all but useless if you need to support 32-bit platforms.</p>\n\n<p>If your language doesn't support tail recursion, your best option for avoiding stack overflows is either to convert to an explicit loop (much less elegant, but sometimes necessary), or find a non-iterative algorithm such as Luke provided for this problem.</p>\n" }, { "answer_id": 141231, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 0, "selected": false, "text": "<p>Extending the idea, it's also possible to memoize functions with two input parameters:</p>\n\n<pre><code>function memoize2 (f)\n local cache = {}\n return function (x, y)\n if cache[x..','..y] then\n return cache[x..','..y]\n else\n local z = f(x,y)\n cache[x..','..y] = z\n return z\n end\n end\nend\n</code></pre>\n\n<p>Notice that parameter order matters in the caching algorithm, so if parameter order doesn't matter in the functions to be memoized the odds of getting a cache hit would be increased by sorting the parameters before checking the cache.</p>\n\n<p>But it's important to note that some functions can't be profitably memoized. I wrote <strong>memoize2</strong> to see if the recursive <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow noreferrer\">Euclidean algorithm</a> for finding the greatest common divisor could be sped up.</p>\n\n<pre><code>function gcd (a, b) \n if b == 0 then return a end\n return gcd(b, a%b)\nend\n</code></pre>\n\n<p>As it turns out, <strong>gcd</strong> doesn't respond well to memoization. The calculation it does is far less expensive than the caching algorithm. Ever for large numbers, it terminates fairly quickly. After a while, the cache grows very large. This algorithm is probably as fast as it can be.</p>\n" }, { "answer_id": 141689, "author": "Lee Baldwin", "author_id": 5200, "author_profile": "https://Stackoverflow.com/users/5200", "pm_score": 4, "selected": true, "text": "<p>I bet something like this should work with variable argument lists in Lua:</p>\n\n<pre><code>local function varg_tostring(...)\n local s = select(1, ...)\n for n = 2, select('#', ...) do\n s = s..\",\"..select(n,...)\n end\n return s\nend\n\nlocal function memoize(f)\n local cache = {}\n return function (...)\n local al = varg_tostring(...)\n if cache[al] then\n return cache[al]\n else\n local y = f(...)\n cache[al] = y\n return y\n end\n end\nend\n</code></pre>\n\n<p>You could probably also do something clever with a metatables with __tostring so that the argument list could just be converted with a tostring(). Oh the possibilities.</p>\n" }, { "answer_id": 144633, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 1, "selected": false, "text": "<p>In the vein of posting memoization in different languages, i'd like to respond to @onebyone.livejournal.com with a non-language-changing C++ example.</p>\n\n<p>First, a memoizer for single arg functions:</p>\n\n<pre><code>template &lt;class Result, class Arg, class ResultStore = std::map&lt;Arg, Result&gt; &gt;\nclass memoizer1{\npublic:\n template &lt;class F&gt;\n const Result&amp; operator()(F f, const Arg&amp; a){\n typename ResultStore::const_iterator it = memo_.find(a);\n if(it == memo_.end()) {\n it = memo_.insert(make_pair(a, f(a))).first;\n }\n return it-&gt;second;\n }\nprivate:\n ResultStore memo_;\n};\n</code></pre>\n\n<p>Just create an instance of the memoizer, feed it your function and argument. Just make sure not to share the same memo between two different functions (but you can share it between different implementations of the same function).</p>\n\n<p>Next, a driver functon, and an implementation. only the driver function need be public\n int fib(int); // driver\n int fib_(int); // implementation</p>\n\n<p>Implemented:</p>\n\n<pre><code>int fib_(int n){\n ++total_ops;\n if(n == 0 || n == 1) \n return 1;\n else\n return fib(n-1) + fib(n-2);\n}\n</code></pre>\n\n<p>And the driver, to memoize</p>\n\n<pre><code>int fib(int n) {\n static memoizer1&lt;int,int&gt; memo;\n return memo(fib_, n);\n}\n</code></pre>\n\n<p><a href=\"http://codepad.org/4zddwKft\" rel=\"nofollow noreferrer\">Permalink showing output</a> on codepad.org. Number of calls is measured to verify correctness. (insert unit test here...)</p>\n\n<p>This only memoizes one input functions. Generalizing for multiple args or varying arguments left as an exercise for the reader. </p>\n" }, { "answer_id": 173038, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 3, "selected": false, "text": "<p>Mathematica has a particularly slick way to do memoization, relying on the fact that hashes and function calls use the same syntax:</p>\n\n<pre><code>triangle[0] = 0;\ntriangle[x_] := triangle[x] = x + triangle[x-1]\n</code></pre>\n\n<p>That's it. It works because the rules for pattern-matching function calls are such that it always uses a more specific definition before a more general definition.</p>\n\n<p>Of course, as has been pointed out, this example has a closed-form solution: <code>triangle[x_] := x*(x+1)/2</code>. Fibonacci numbers are the classic example of how adding memoization gives a drastic speedup:</p>\n\n<pre><code>fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n] = fib[n-1] + fib[n-2]\n</code></pre>\n\n<p>Although that too has a closed-form equivalent, albeit messier: <a href=\"http://mathworld.wolfram.com/FibonacciNumber.html\" rel=\"noreferrer\">http://mathworld.wolfram.com/FibonacciNumber.html</a></p>\n\n<p>I disagree with the person who suggested this was inappropriate for memoization because you could \"just use a loop\". The point of memoization is that any repeat function calls are O(1) time. That's a lot better than O(n). In fact, you could even concoct a scenario where the memoized implementation has better performance than the closed-form implementation!</p>\n" }, { "answer_id": 263308, "author": "Hercynium", "author_id": 14186, "author_profile": "https://Stackoverflow.com/users/14186", "pm_score": 1, "selected": false, "text": "<p>In Perl generic memoization is easy to get. The Memoize module is part of the perl core and is highly reliable, flexible, and easy-to-use. </p>\n\n<p>The example from it's manpage:</p>\n\n<pre><code># This is the documentation for Memoize 1.01\nuse Memoize;\nmemoize('slow_function');\nslow_function(arguments); # Is faster than it was before\n</code></pre>\n\n<p>You can add, remove, and customize memoization of functions <em>at run time!</em> You can provide callbacks for custom memento computation.</p>\n\n<p>Memoize.pm even has facilities for making the memento cache persistent, so it does not need to be re-filled on each invocation of your program!</p>\n\n<p>Here's the documentation: <a href=\"http://perldoc.perl.org/5.8.8/Memoize.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/5.8.8/Memoize.html</a></p>\n" }, { "answer_id": 3653922, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 2, "selected": false, "text": "<p>Here's something that works without converting the arguments to strings.\nThe only caveat is that it can't handle a nil argument. But the accepted solution can't distinguish the value <code>nil</code> from the string <code>\"nil\"</code>, so that's probably OK.</p>\n\n<pre><code>local function m(f)\n local t = { }\n local function mf(x, ...) -- memoized f\n assert(x ~= nil, 'nil passed to memoized function')\n if select('#', ...) &gt; 0 then\n t[x] = t[x] or m(function(...) return f(x, ...) end)\n return t[x](...)\n else\n t[x] = t[x] or f(x)\n assert(t[x] ~= nil, 'memoized function returns nil')\n return t[x]\n end\n end\n return mf\nend\n</code></pre>\n" }, { "answer_id": 5737216, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 2, "selected": false, "text": "<p>I've been inspired by this question to implement (yet another) flexible memoize function in Lua.</p>\n\n<p><a href=\"https://github.com/kikito/memoize.lua\" rel=\"nofollow\">https://github.com/kikito/memoize.lua</a></p>\n\n<p>Main advantages:</p>\n\n<ul>\n<li>Accepts a variable number of arguments</li>\n<li>Doesn't use tostring; instead, it organizes the cache in a tree structure, using the parameters to traverse it.</li>\n<li>Works just fine with functions that return <a href=\"http://www.lua.org/pil/5.1.html\" rel=\"nofollow\">multiple values</a>.</li>\n</ul>\n\n<p>Pasting the code here as reference:</p>\n\n<pre><code>local globalCache = {}\n\nlocal function getFromCache(cache, args)\n local node = cache\n for i=1, #args do\n if not node.children then return {} end\n node = node.children[args[i]]\n if not node then return {} end\n end\n return node.results\nend\n\nlocal function insertInCache(cache, args, results)\n local arg\n local node = cache\n for i=1, #args do\n arg = args[i]\n node.children = node.children or {}\n node.children[arg] = node.children[arg] or {}\n node = node.children[arg]\n end\n node.results = results\nend\n\n\n-- public function\n\nlocal function memoize(f)\n globalCache[f] = { results = {} }\n return function (...)\n local results = getFromCache( globalCache[f], {...} )\n\n if #results == 0 then\n results = { f(...) }\n insertInCache(globalCache[f], {...}, results)\n end\n\n return unpack(results)\n end\nend\n\nreturn memoize\n</code></pre>\n" }, { "answer_id": 8204369, "author": "Amir", "author_id": 13480, "author_profile": "https://Stackoverflow.com/users/13480", "pm_score": 3, "selected": false, "text": "<p>In C# 3.0 - for recursive functions, you can do something like:</p>\n\n<pre><code>public static class Helpers\n{\n public static Func&lt;A, R&gt; Memoize&lt;A, R&gt;(this Func&lt;A, Func&lt;A,R&gt;, R&gt; f)\n {\n var map = new Dictionary&lt;A, R&gt;();\n Func&lt;A, R&gt; self = null;\n self = (a) =&gt;\n {\n R value;\n if (map.TryGetValue(a, out value))\n return value;\n value = f(a, self);\n map.Add(a, value);\n return value;\n };\n return self;\n } \n}\n</code></pre>\n\n<p>Then you can create a memoized Fibonacci function like this:</p>\n\n<pre><code>var memoized_fib = Helpers.Memoize&lt;int, int&gt;((n,fib) =&gt; n &gt; 1 ? fib(n - 1) + fib(n - 2) : n);\nConsole.WriteLine(memoized_fib(40));\n</code></pre>\n" }, { "answer_id": 8395436, "author": "Fractaly", "author_id": 920769, "author_profile": "https://Stackoverflow.com/users/920769", "pm_score": 0, "selected": false, "text": "<p>Recursion isn't necessary. The nth triangle number is n(n-1)/2, so...</p>\n\n<pre><code>public int triangle(final int n){\n return n * (n - 1) / 2;\n}\n</code></pre>\n" }, { "answer_id": 15846127, "author": "arviman", "author_id": 315001, "author_profile": "https://Stackoverflow.com/users/315001", "pm_score": 0, "selected": false, "text": "<p>Please don't recurse this. Either use the x*(x+1)/2 formula or simply iterate the values and memoize as you go.</p>\n\n<pre><code>int[] memo = new int[n+1];\nint sum = 0;\nfor(int i = 0; i &lt;= n; ++i)\n{\n sum+=i;\n memo[i] = sum;\n}\nreturn memo[n];\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
I'm writing a function to find [triangle numbers](http://projecteuler.net/index.php?section=problems&id=12) and the natural way to write it is recursively: ``` function triangle (x) if x == 0 then return 0 end return x+triangle(x-1) end ``` But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while. This is an ideal function to [memoize](http://perl.plover.com/Memoize/), but I want a solution that will memoize any function I pass to it.
I bet something like this should work with variable argument lists in Lua: ``` local function varg_tostring(...) local s = select(1, ...) for n = 2, select('#', ...) do s = s..","..select(n,...) end return s end local function memoize(f) local cache = {} return function (...) local al = varg_tostring(...) if cache[al] then return cache[al] else local y = f(...) cache[al] = y return y end end end ``` You could probably also do something clever with a metatables with \_\_tostring so that the argument list could just be converted with a tostring(). Oh the possibilities.
129,890
<p>I'm getting lost in pointer land, I believe. I've got this (code syntax might be a little off, I am not looking at the machine with this code on it...but all the pertinent details are correct):</p> <pre><code>NSMutableArray *tmp = [[NSMutableArray alloc] init]; </code></pre> <p>I them pass that to a routine in another class</p> <pre><code>- (BOOL)myRoutine: (NSMutableArray *)inArray { // Adds items to the array -- if I break at the end of this function, the inArray variable has a count of 10 } </code></pre> <p>But when the code comes back into the calling routine, [tmp count] is 0.</p> <p>I must be missing something very simple and yet very fundamental, but for the life of me I can't see it. Can anyone point out what I'm doing wrong?</p> <p>EDIT: www.stray-bits.com asked if I have retained a reference to it, and I said "maybe...we tried this: NSMutableArray *tmp = [[[NSMutableArray alloc] init] retain]; not sure if that is what you mean, or if I did it right.</p> <p>EDIT2: Mike McMaster and Andy -- you guys are probably right, then. I don't have the code here (it's on a colleague's machine and they have left for the day), but to fill the array with values we were doing something along the lines of using a decoder(?) object. </p> <p>The purpose of this function is to open a file from the iPhone, read that file into an array (it's an array of objects that we saved in a previous run of the program). That "decoder" thing has a method that puts data into the array. </p> <p>Man, I've totally butchered this. I really hope you all can follow, and thanks for the advice. We'll look more closely at it.</p>
[ { "answer_id": 129906, "author": "user20456", "author_id": 20456, "author_profile": "https://Stackoverflow.com/users/20456", "pm_score": 1, "selected": false, "text": "<p>NSMutableArray retains objects added to it, but have you retained the array itself?</p>\n" }, { "answer_id": 130142, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 3, "selected": true, "text": "<p>You don't need to call retain in this case. [[NSMutableArray alloc] init] creates the object with a retain count of 1, so it won't get released until you specifically release it.</p>\n\n<p>It would be good to see more of the code. I don't think the error is in the very small amount you've posted so far..</p>\n" }, { "answer_id": 130200, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 2, "selected": false, "text": "<p>I agree with Mike - based on the code you've posted, it looks correct. In addition to posting the code used to call the function and add items to the array, you could try checking the memory addresses of the pointer at the end of the function (when it has all of the objects), and also once it has returned (when it has no objects). I'm not sure why it would be different, but then again the items should stick in the array as well.</p>\n" }, { "answer_id": 130310, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 2, "selected": false, "text": "<p>You need to show us a bit more of how you're adding objects to the array for us to really help.</p>\n\n<p>I've seen a lot of people write code like this:</p>\n\n<pre><code>NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];\n\narray = [foo bar];\n</code></pre>\n\n<p>People doing this think it \"creates and then sets\" a mutable array, but that's not at all what it does. Instead, it creates a mutable array, assigns it to the variable named <code>array</code>, and then assigns a <em>different</em> mutable array to that variable.</p>\n\n<p>So be sure you're not confusing the variable for the object to which it is a reference. The object isn't the variable, it's interacted with <em>through</em> the variable.</p>\n" }, { "answer_id": 147673, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 1, "selected": false, "text": "<p>The code you posted should work. You must be doing something funny in the decoder function.</p>\n\n<p>You should not retain that array. It's automatically retained with init. If you retain it, you'll leak memory. If you are just starting with objective c, take time and read \"Introduction to Memory Management Programming Guide for Cocoa\". It will spare you lots of headache.</p>\n\n<p>Why are you writing so much code to read an array from a file? It's already supported by the framework:</p>\n\n<blockquote>\n <p>+ arrayWithContentsOfFile:</p>\n \n <p>Returns an array initialized from the contents of a specified file.\n The specified file can be a full or\n relative pathname; the file that it\n names must contain a string\n representation of an array, such as\n that produced by the\n writeToFile:atomically: method.</p>\n</blockquote>\n\n<p>So you can do this:</p>\n\n<pre><code>NSMuatableArray *myArray = [NSMutableArray arrayWithContentsOfFile:@\"path/to/my/file\"];\n</code></pre>\n\n<p>This is a convenience method, so the object will autorelease. Make sure to retain this one if you want to keep it around.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
I'm getting lost in pointer land, I believe. I've got this (code syntax might be a little off, I am not looking at the machine with this code on it...but all the pertinent details are correct): ``` NSMutableArray *tmp = [[NSMutableArray alloc] init]; ``` I them pass that to a routine in another class ``` - (BOOL)myRoutine: (NSMutableArray *)inArray { // Adds items to the array -- if I break at the end of this function, the inArray variable has a count of 10 } ``` But when the code comes back into the calling routine, [tmp count] is 0. I must be missing something very simple and yet very fundamental, but for the life of me I can't see it. Can anyone point out what I'm doing wrong? EDIT: www.stray-bits.com asked if I have retained a reference to it, and I said "maybe...we tried this: NSMutableArray \*tmp = [[[NSMutableArray alloc] init] retain]; not sure if that is what you mean, or if I did it right. EDIT2: Mike McMaster and Andy -- you guys are probably right, then. I don't have the code here (it's on a colleague's machine and they have left for the day), but to fill the array with values we were doing something along the lines of using a decoder(?) object. The purpose of this function is to open a file from the iPhone, read that file into an array (it's an array of objects that we saved in a previous run of the program). That "decoder" thing has a method that puts data into the array. Man, I've totally butchered this. I really hope you all can follow, and thanks for the advice. We'll look more closely at it.
You don't need to call retain in this case. [[NSMutableArray alloc] init] creates the object with a retain count of 1, so it won't get released until you specifically release it. It would be good to see more of the code. I don't think the error is in the very small amount you've posted so far..
129,917
<p>It's common knowledge that using System.Diagnostics.Process.Start is the way to launch a url from a C# applicaiton:</p> <p>System.Diagnostics.Process.Start("<a href="http://www.mywebsite.com" rel="nofollow noreferrer">http://www.mywebsite.com</a>");</p> <p>However, if this url is invalid the application seems to have no way of knowing that the call failed or why. Is there a better way to launch a web browser? If not, what is my best option for url validation?</p>
[ { "answer_id": 129926, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "<p>If you need to verify that the URL exists, the only thing you can do is create a custom request in advance and verify that it works. I'd still use the Process.Start to shell out to the actual page, though.</p>\n" }, { "answer_id": 129956, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 4, "selected": true, "text": "<p>Try an approach as below.</p>\n\n<pre><code>try\n{\n var url = new Uri(\"http://www.example.com/\");\n\n Process.Start(url.AbsoluteUri);\n}\ncatch (UriFormatException)\n{\n // URL is not parsable\n}\n</code></pre>\n\n<p>This does not ensure that the resource exist, but it does ensure the URL is wellformed. You might also want to check if the scheme is matching http or https.</p>\n" }, { "answer_id": 138955, "author": "derigel", "author_id": 12045, "author_profile": "https://Stackoverflow.com/users/12045", "pm_score": 1, "selected": false, "text": "<p>Check the <strong>Uri.IsWellFormedUriString</strong> static method.\nIt's cheaper than catching exception.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9251/" ]
It's common knowledge that using System.Diagnostics.Process.Start is the way to launch a url from a C# applicaiton: System.Diagnostics.Process.Start("<http://www.mywebsite.com>"); However, if this url is invalid the application seems to have no way of knowing that the call failed or why. Is there a better way to launch a web browser? If not, what is my best option for url validation?
Try an approach as below. ``` try { var url = new Uri("http://www.example.com/"); Process.Start(url.AbsoluteUri); } catch (UriFormatException) { // URL is not parsable } ``` This does not ensure that the resource exist, but it does ensure the URL is wellformed. You might also want to check if the scheme is matching http or https.
129,927
<p>I have a page in my vb.net web application that needs to toss a bunch of data into a text file and then present it to the user for download. What's the best / most efficient way to build such a text file on a .net web server?</p> <p>Edit: to answer a question down below, this is going to be a download once and then throw-away kind of file.</p> <p>Update: I glued together the suggestions by John Rudy and DavidK, and it worked perfectly. Thanks, all!</p>
[ { "answer_id": 129953, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Use a StringBuilder to create the text of the file, and then send it to the user using Content-Disposition.</p>\n\n<p>Example found here:\n<a href=\"http://www.eggheadcafe.com/community/aspnet/17/76432/use-the-contentdispositi.aspx\" rel=\"nofollow noreferrer\">http://www.eggheadcafe.com/community/aspnet/17/76432/use-the-contentdispositi.aspx</a></p>\n\n<pre><code>private void Button1_Click(object sender, System.EventArgs e)\n{\n StringBuilder output = new StringBuilder;\n //populate output with the string content\n String fileName = \"textfile.txt\";\n\n Response.ContentType = \"application/octet-stream\";\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n Response.WriteFile(output.ToString());\n\n}\n</code></pre>\n" }, { "answer_id": 129963, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 2, "selected": false, "text": "<p>Don't build it at all, use an HttpHandler and serve the text file direct into the output stream:</p>\n\n<p><a href=\"http://digitalcolony.com/labels/HttpHandler.aspx\" rel=\"nofollow noreferrer\">http://digitalcolony.com/labels/HttpHandler.aspx</a></p>\n\n<p>The code block halfway down is a good example, you can adjust to your own:</p>\n\n<pre><code>public void ProcessRequest(HttpContext context)\n{\n response = context.Response;\n response.ContentType = \"text/xml\"; \n using (TextWriter textWriter = new StreamWriter(response.OutputStream, System.Text.Encoding.UTF8))\n {\n XmlTextWriter writer = new XmlTextWriter(textWriter);\n writer.Formatting = Formatting.Indented;\n writer.WriteStartDocument();\n writer.WriteStartElement(\"urlset\");\n writer.WriteAttributeString(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\");\n writer.WriteAttributeString(\"xsi:schemaLocation\", \"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\");\n writer.WriteAttributeString(\"xmlns\", \"http://www.sitemaps.org/schemas/sitemap/0.9\");\n\n // Add Home Page\n writer.WriteStartElement(\"url\");\n writer.WriteElementString(\"loc\", \"http://example.com\");\n writer.WriteElementString(\"changefreq\", \"daily\");\n writer.WriteEndElement(); // url\n\n // Add code Loop here for page nodes\n /*\n {\n writer.WriteStartElement(\"url\");\n writer.WriteElementString(\"loc\", url);\n writer.WriteElementString(\"changefreq\", \"monthly\");\n writer.WriteEndElement(); // url\n }\n */\n writer.WriteEndElement(); // urlset\n } \n}\n</code></pre>\n" }, { "answer_id": 129967, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 0, "selected": false, "text": "<p>Bear in mind it doesn't ever need to be a 'file' at the server end. It's the client which turns it into a file.</p>\n" }, { "answer_id": 129998, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": true, "text": "<p>The answer will depend on whether, as Forgotten Semicolon mentions, you need repeated downloads or once-and-done throwaways.</p>\n\n<p>Either way, the key will be to set the content-type of the output to ensure that a download window is displayed. The problem with straight text output is that the browser will attempt to display the data in its own window.</p>\n\n<p>The core way to set the content type would be something similar to the following, assuming that text is the output string and filename is the default name you want the file to be saved (locally) as.</p>\n\n<pre><code>HttpResponse response = HttpContext.Current.Response;\nresponse.Clear();\nresponse.ContentType = \"application/octet-stream\";\nresponse.Charset = \"\";\nresponse.AddHeader(\"Content-Disposition\", String.Format(\"attachment; filename=\\\"{0}\\\"\", filename));\nresponse.Flush();\nresponse.Write(text);\nresponse.End();\n</code></pre>\n\n<p>This will prompt a download for the user.</p>\n\n<p>Now it gets trickier if you need to literally save the file on your web server -- but not terribly so. There you'd want to write out the text to your text file using the classes in System.IO. Ensure that the path you write to is writable by the Network Service, IUSR_MachineName and ASPNET Windows users. Otherwise, same deal -- use content type and headers to ensure download.</p>\n\n<p>I'd recommend not literally saving the file unless you need to -- and even then, the technique of doing so directly on the server may not be the right idea. (EG, what if you need access control for downloading said file? Now you'd have to do that outside your app root, which may or may not even be possible depending on your hosting environment.)</p>\n\n<p>So without knowing whether you're in a one-off or file-must-really-save mode, and without knowing security implications (which you'll probably need to work out yourself if you really need server-side saves), that's about the best I can give you.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I have a page in my vb.net web application that needs to toss a bunch of data into a text file and then present it to the user for download. What's the best / most efficient way to build such a text file on a .net web server? Edit: to answer a question down below, this is going to be a download once and then throw-away kind of file. Update: I glued together the suggestions by John Rudy and DavidK, and it worked perfectly. Thanks, all!
The answer will depend on whether, as Forgotten Semicolon mentions, you need repeated downloads or once-and-done throwaways. Either way, the key will be to set the content-type of the output to ensure that a download window is displayed. The problem with straight text output is that the browser will attempt to display the data in its own window. The core way to set the content type would be something similar to the following, assuming that text is the output string and filename is the default name you want the file to be saved (locally) as. ``` HttpResponse response = HttpContext.Current.Response; response.Clear(); response.ContentType = "application/octet-stream"; response.Charset = ""; response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", filename)); response.Flush(); response.Write(text); response.End(); ``` This will prompt a download for the user. Now it gets trickier if you need to literally save the file on your web server -- but not terribly so. There you'd want to write out the text to your text file using the classes in System.IO. Ensure that the path you write to is writable by the Network Service, IUSR\_MachineName and ASPNET Windows users. Otherwise, same deal -- use content type and headers to ensure download. I'd recommend not literally saving the file unless you need to -- and even then, the technique of doing so directly on the server may not be the right idea. (EG, what if you need access control for downloading said file? Now you'd have to do that outside your app root, which may or may not even be possible depending on your hosting environment.) So without knowing whether you're in a one-off or file-must-really-save mode, and without knowing security implications (which you'll probably need to work out yourself if you really need server-side saves), that's about the best I can give you.
129,932
<p>I am running VS Team Studio 2008. I have created a web test that I want to use for monitoring a company web site. It interacts with the site and does some round trip processing. I want to create a standalone EXE file that can be run remotely. I have tried converting it to VB code and C# code and then creating compiling it into an EXE. But, when running it, no traffic is generated from the host to the webserver. Has anyone tried to do this before successfully?</p> <p>I tried this in VB. </p> <pre><code> Option Strict Off Option Explicit On Imports Microsoft.VisualStudio.TestTools.WebTesting Imports Microsoft.VisualStudio.TestTools.WebTesting.Rules Imports System Imports System.Collections.Generic Imports System.Text Public Module RunMonitor Sub Main() Dim S As Monitor.MonitorCoded = New Monitor.MonitorCoded() S.Run() End Sub End Module Namespace TheMonitor Public Class MonitorCoded Inherits ThreadedWebTest Public Sub New() MyBase.New() Me.PreAuthenticate = True End Sub Public Overrides Sub Run() 'WebRequest code is here' End Sub End Class End Namespace </code></pre> <p>Any suggestions appreciated. </p>
[ { "answer_id": 130855, "author": "Jay Mooney", "author_id": 733, "author_profile": "https://Stackoverflow.com/users/733", "pm_score": 1, "selected": false, "text": "<p>Can you call MSTest.exe? If your test was created using VisualStudio, it uses MSTest to execute it.</p>\n\n<p>If you didn't use VisualStudio to create the webTest, can you provide a little more detail?</p>\n" }, { "answer_id": 988592, "author": "Josh Christie", "author_id": 122240, "author_profile": "https://Stackoverflow.com/users/122240", "pm_score": 2, "selected": false, "text": "<p>Daniel,\nI created most of the classes in the Microsoft.VisualStudio.TestTools.WebTesting namespace and I can assure you it's NOT possible to run a coded web test without Visual Studio or MSTest.exe. Coded web tests basically hand WebTestRequests back to the web test engine, they don't start the web test engine themselves.</p>\n\n<p>We weren't trying to prevent the use case you described, but it just wasn't a design goal.</p>\n\n<p>Josh</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am running VS Team Studio 2008. I have created a web test that I want to use for monitoring a company web site. It interacts with the site and does some round trip processing. I want to create a standalone EXE file that can be run remotely. I have tried converting it to VB code and C# code and then creating compiling it into an EXE. But, when running it, no traffic is generated from the host to the webserver. Has anyone tried to do this before successfully? I tried this in VB. ``` Option Strict Off Option Explicit On Imports Microsoft.VisualStudio.TestTools.WebTesting Imports Microsoft.VisualStudio.TestTools.WebTesting.Rules Imports System Imports System.Collections.Generic Imports System.Text Public Module RunMonitor Sub Main() Dim S As Monitor.MonitorCoded = New Monitor.MonitorCoded() S.Run() End Sub End Module Namespace TheMonitor Public Class MonitorCoded Inherits ThreadedWebTest Public Sub New() MyBase.New() Me.PreAuthenticate = True End Sub Public Overrides Sub Run() 'WebRequest code is here' End Sub End Class End Namespace ``` Any suggestions appreciated.
Daniel, I created most of the classes in the Microsoft.VisualStudio.TestTools.WebTesting namespace and I can assure you it's NOT possible to run a coded web test without Visual Studio or MSTest.exe. Coded web tests basically hand WebTestRequests back to the web test engine, they don't start the web test engine themselves. We weren't trying to prevent the use case you described, but it just wasn't a design goal. Josh
129,968
<p>Is it possible to convert a <code>com.vividsolutions.jts.geom.Geometry</code> (or a subclass of it) into a class that implements <code>java.awt.Shape</code>? Which library or method can I use to achieve that goal?</p>
[ { "answer_id": 129995, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 3, "selected": true, "text": "<p>According to:</p>\n\n<p><a href=\"http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html\" rel=\"nofollow noreferrer\">http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html</a></p>\n\n<p>There's a class:</p>\n\n<pre><code>com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter\n</code></pre>\n\n<p>which can do it?</p>\n" }, { "answer_id": 30752409, "author": "user3776894", "author_id": 3776894, "author_profile": "https://Stackoverflow.com/users/3776894", "pm_score": 3, "selected": false, "text": "<p>Also have a look at <a href=\"http://tsusiatsoftware.net/jts/javadoc/index.html?com/vividsolutions/jts/awt/ShapeWriter.html\" rel=\"noreferrer\">ShapeWriter</a> provided by the JTS library. I used the following code snipped to convert jts geometry objects into an awt shape.</p>\n\n<pre><code>import java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Shape;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\nimport com.vividsolutions.jts.awt.ShapeWriter;\nimport com.vividsolutions.jts.geom.Coordinate;\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.LineString;\nimport com.vividsolutions.jts.geom.Polygon;\n\npublic class Paint extends JPanel{\n public void paint(Graphics g) {\n\n Coordinate[] coords = new Coordinate[] {new Coordinate(400, 0), new Coordinate(200, 200), new Coordinate(400, 400), new Coordinate(600, 200), new Coordinate(400, 0) };\n Polygon polygon = new GeometryFactory().createPolygon(coords);\n\n LineString ls = new GeometryFactory().createLineString(new Coordinate[] {new Coordinate(20, 20), new Coordinate(200, 20)});\n\n ShapeWriter sw = new ShapeWriter();\n Shape polyShape = sw.toShape(polygon);\n Shape linShape = sw.toShape(ls);\n\n ((Graphics2D) g).draw(polyShape);\n ((Graphics2D) g).draw(linShape);\n\n\n }\n public static void main(String[] args) {\n JFrame f = new JFrame();\n f.getContentPane().add(new Paint());\n f.setSize(700, 700);\n f.setVisible(true);\n }\n}\n</code></pre>\n\n<p>Edit: The result looks like this image <img src=\"https://i.stack.imgur.com/YIDD6.png\" alt=\"Visualization of jts geometry objects in awt\"></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/129968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
Is it possible to convert a `com.vividsolutions.jts.geom.Geometry` (or a subclass of it) into a class that implements `java.awt.Shape`? Which library or method can I use to achieve that goal?
According to: <http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html> There's a class: ``` com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter ``` which can do it?
130,020
<p>Can anyone recommend a dropdownlist control for asp.net (3.5) that can render option groups? Thanks</p>
[ { "answer_id": 130046, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 7, "selected": true, "text": "<p>I've used the standard control in the past, and just added a simple <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx\" rel=\"nofollow noreferrer\">ControlAdapter</a> for it that would override the default behavior so it could render &lt;optgroup>s in certain places. This works great even if you have controls that don't need the special behavior, because the additional feature doesn't get in the way.</p>\n\n<p>Note that this was for a specific purpose and written in .Net 2.0, so it may not suit you as well, but it should at least give you a starting point. Also, you have to hook it up using a .browserfile in your project (see the end of the post for an example).</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>'This codes makes the dropdownlist control recognize items with \"--\"\n'for the label or items with an OptionGroup attribute and render them\n'as &lt;optgroup&gt; instead of &lt;option&gt;.\nPublic Class DropDownListAdapter\n Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter\n\n Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)\n Dim list As DropDownList = Me.Control\n Dim currentOptionGroup As String\n Dim renderedOptionGroups As New Generic.List(Of String)\n\n For Each item As ListItem In list.Items\n Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value)\n If item.Attributes(\"OptionGroup\") IsNot Nothing Then\n 'The item is part of an option group\n currentOptionGroup = item.Attributes(\"OptionGroup\")\n If Not renderedOptionGroups.Contains(currentOptionGroup) Then\n 'the header was not written- do that first\n 'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list)\n If (renderedOptionGroups.Count &gt; 0) Then\n RenderOptionGroupEndTag(writer) 'need to close previous group\n End If\n RenderOptionGroupBeginTag(currentOptionGroup, writer)\n renderedOptionGroups.Add(currentOptionGroup)\n End If\n RenderListItem(item, writer)\n ElseIf item.Text = \"--\" Then 'simple separator\n RenderOptionGroupBeginTag(\"--\", writer)\n RenderOptionGroupEndTag(writer)\n Else\n 'default behavior: render the list item as normal\n RenderListItem(item, writer)\n End If\n Next item\n\n If renderedOptionGroups.Count &gt; 0 Then\n RenderOptionGroupEndTag(writer)\n End If\n End Sub\n\n Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"optgroup\")\n writer.WriteAttribute(\"label\", name)\n writer.Write(HtmlTextWriter.TagRightChar)\n writer.WriteLine()\n End Sub\n\n Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)\n writer.WriteEndTag(\"optgroup\")\n writer.WriteLine()\n End Sub\n\n Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"option\")\n writer.WriteAttribute(\"value\", item.Value, True)\n If item.Selected Then\n writer.WriteAttribute(\"selected\", \"selected\", False)\n End If\n\n For Each key As String In item.Attributes.Keys\n writer.WriteAttribute(key, item.Attributes(key))\n Next key\n\n writer.Write(HtmlTextWriter.TagRightChar)\n HttpUtility.HtmlEncode(item.Text, writer)\n writer.WriteEndTag(\"option\")\n writer.WriteLine()\n End Sub\nEnd Class\n</code></pre>\n\n<p>Here's a C# implementation of the same Class:</p>\n\n<pre><code>/* This codes makes the dropdownlist control recognize items with \"--\"\n * for the label or items with an OptionGroup attribute and render them\n * as &lt;optgroup&gt; instead of &lt;option&gt;.\n */\npublic class DropDownListAdapter : WebControlAdapter\n{\n protected override void RenderContents(HtmlTextWriter writer)\n {\n //System.Web.HttpContext.Current.Response.Write(\"here\");\n var list = (DropDownList)this.Control;\n string currentOptionGroup;\n var renderedOptionGroups = new List&lt;string&gt;();\n\n foreach (ListItem item in list.Items)\n {\n Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value);\n //Is the item part of an option group?\n if (item.Attributes[\"OptionGroup\"] != null)\n {\n currentOptionGroup = item.Attributes[\"OptionGroup\"];\n //Was the option header already written, then just render the list item\n if (renderedOptionGroups.Contains(currentOptionGroup))\n RenderListItem(item, writer);\n //The header was not written,do that first\n else\n {\n //Close previous group\n if (renderedOptionGroups.Count &gt; 0)\n RenderOptionGroupEndTag(writer);\n\n RenderOptionGroupBeginTag(currentOptionGroup, writer);\n renderedOptionGroups.Add(currentOptionGroup);\n RenderListItem(item, writer);\n }\n }\n //Simple separator\n else if (item.Text == \"--\")\n {\n RenderOptionGroupBeginTag(\"--\", writer);\n RenderOptionGroupEndTag(writer);\n }\n //Default behavior, render the list item as normal\n else\n RenderListItem(item, writer);\n }\n\n if (renderedOptionGroups.Count &gt; 0)\n RenderOptionGroupEndTag(writer);\n }\n\n private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"optgroup\");\n writer.WriteAttribute(\"label\", name);\n writer.Write(HtmlTextWriter.TagRightChar);\n writer.WriteLine();\n }\n private void RenderOptionGroupEndTag(HtmlTextWriter writer)\n {\n writer.WriteEndTag(\"optgroup\");\n writer.WriteLine();\n }\n private void RenderListItem(ListItem item, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"option\");\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Selected)\n writer.WriteAttribute(\"selected\", \"selected\", false);\n\n foreach (string key in item.Attributes.Keys)\n writer.WriteAttribute(key, item.Attributes[key]);\n\n writer.Write(HtmlTextWriter.TagRightChar);\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(\"option\");\n writer.WriteLine();\n }\n}\n</code></pre>\n\n<p>My browser file was named \"App_Browsers\\BrowserFile.browser\" and looked like this:</p>\n\n<pre><code>&lt;!--\n You can find existing browser definitions at\n &lt;windir&gt;\\Microsoft.NET\\Framework\\&lt;ver&gt;\\CONFIG\\Browsers\n--&gt;\n&lt;browsers&gt;\n &lt;browser refID=\"Default\"&gt;\n &lt;controlAdapters&gt;\n &lt;adapter controlType=\"System.Web.UI.WebControls.DropDownList\" \n adapterType=\"DropDownListAdapter\" /&gt;\n &lt;/controlAdapters&gt;\n &lt;/browser&gt;\n&lt;/browsers&gt;\n</code></pre>\n" }, { "answer_id": 130060, "author": "Chris Van Opstal", "author_id": 7264, "author_profile": "https://Stackoverflow.com/users/7264", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://www.codeplex.com/SharpPieces\" rel=\"nofollow noreferrer\">Sharp Pieces project on CodePlex</a> solves this (and several other) control limitations.</p>\n" }, { "answer_id": 1056436, "author": "Nick Franceschina", "author_id": 130221, "author_profile": "https://Stackoverflow.com/users/130221", "pm_score": 4, "selected": false, "text": "<p>Thanks Joel! everyone... here's C# version if you want it:</p>\n\n<pre><code>\n\nusing System;\nusing System.Web.UI.WebControls.Adapters;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Collections.Generic;\nusing System.Web;\n\n//This codes makes the dropdownlist control recognize items with \"--\"'\n//for the label or items with an OptionGroup attribute and render them'\n//as instead of .'\npublic class DropDownListAdapter : WebControlAdapter\n{\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n DropDownList list = Control as DropDownList;\n string currentOptionGroup;\n List renderedOptionGroups = new List();\n\n foreach(ListItem item in list.Items)\n {\n if (item.Attributes[\"OptionGroup\"] != null)\n {\n //'The item is part of an option group'\n currentOptionGroup = item.Attributes[\"OptionGroup\"];\n //'the option header was already written, just render the list item'\n if(renderedOptionGroups.Contains(currentOptionGroup))\n RenderListItem(item, writer);\n else\n {\n //the header was not written- do that first'\n if (renderedOptionGroups.Count > 0)\n RenderOptionGroupEndTag(writer); //'need to close previous group'\n RenderOptionGroupBeginTag(currentOptionGroup, writer);\n renderedOptionGroups.Add(currentOptionGroup);\n RenderListItem(item, writer);\n }\n }\n else if (item.Text == \"--\") //simple separator\n {\n RenderOptionGroupBeginTag(\"--\", writer);\n RenderOptionGroupEndTag(writer);\n }\n else\n {\n //default behavior: render the list item as normal'\n RenderListItem(item, writer);\n }\n }\n\n if(renderedOptionGroups.Count > 0)\n RenderOptionGroupEndTag(writer);\n }\n\n private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"optgroup\");\n writer.WriteAttribute(\"label\", name);\n writer.Write(HtmlTextWriter.TagRightChar);\n writer.WriteLine();\n }\n\n private void RenderOptionGroupEndTag(HtmlTextWriter writer)\n {\n writer.WriteEndTag(\"optgroup\");\n writer.WriteLine();\n }\n\n private void RenderListItem(ListItem item, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"option\");\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Selected)\n writer.WriteAttribute(\"selected\", \"selected\", false);\n\n\n foreach (string key in item.Attributes.Keys)\n writer.WriteAttribute(key, item.Attributes[key]);\n\n writer.Write(HtmlTextWriter.TagRightChar);\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(\"option\");\n writer.WriteLine();\n }\n\n}\n\n\n\n</code></pre>\n" }, { "answer_id": 1578193, "author": "Cédric Boivin", "author_id": 82595, "author_profile": "https://Stackoverflow.com/users/82595", "pm_score": 3, "selected": false, "text": "<p>I use the reflector to see why is not supported. There is why. In the render method of the ListControl no condition is there to create the optgroup. </p>\n\n<pre><code>protected internal override void RenderContents(HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n if (count &gt; 0)\n {\n bool flag = false;\n for (int i = 0; i &lt; count; i++)\n {\n ListItem item = items[i];\n if (item.Enabled)\n {\n writer.WriteBeginTag(\"option\");\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.HasAttributes)\n {\n item.Attributes.Render(writer);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n writer.Write('&gt;');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(\"option\");\n writer.WriteLine();\n }\n }\n }\n }\n</code></pre>\n\n<p>So i create my own dropdown Control with an override of the method RenderContents. There is my control. Is working fine. I use exactly the same code of Microsoft, just add a little condition to support listItem having attribute optgroup to create an optgroup and not a option.</p>\n\n<p>Give me some feed back</p>\n\n<pre><code>public class DropDownListWithOptionGroup : DropDownList\n {\n public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count; \n string tag;\n string optgroupLabel;\n if (count &gt; 0)\n {\n bool flag = false;\n for (int i = 0; i &lt; count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0 &amp;&amp; item.Attributes[OptionGroupTag] != null)\n {\n tag = OptionGroupTag;\n optgroupLabel = item.Attributes[OptionGroupTag];\n } \n writer.WriteBeginTag(tag);\n // NOTE(cboivin): Is optionGroup\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n else\n {\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0)\n {\n item.Attributes.Render(writer);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n }\n writer.Write('&gt;');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n }\n }\n }\n\n }\n }\n</code></pre>\n" }, { "answer_id": 1758950, "author": "Glennular", "author_id": 14753, "author_profile": "https://Stackoverflow.com/users/14753", "pm_score": 1, "selected": false, "text": "<p>As the answers above that overload the RenderContents method do work. You also have to remember to alter the viewstate. I have come into an issue when using the non-altered viewstate in UpdatePanels. This has parts taken from the <a href=\"http://www.codeplex.com/SharpPieces\" rel=\"nofollow noreferrer\">Sharp Pieces Project</a>.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> Protected Overloads Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)\n Dim list As DropDownList = Me\n\n Dim currentOptionGroup As String\n Dim renderedOptionGroups As New List(Of String)()\n\n For Each item As ListItem In list.Items\n If item.Attributes(\"OptionGroup\") Is Nothing Then\n RenderListItem(item, writer)\n Else\n currentOptionGroup = item.Attributes(\"OptionGroup\")\n\n If renderedOptionGroups.Contains(currentOptionGroup) Then\n RenderListItem(item, writer)\n Else\n If renderedOptionGroups.Count &gt; 0 Then\n RenderOptionGroupEndTag(writer)\n End If\n\n RenderOptionGroupBeginTag(currentOptionGroup, writer)\n renderedOptionGroups.Add(currentOptionGroup)\n\n RenderListItem(item, writer)\n End If\n End If\n Next\n\n If renderedOptionGroups.Count &gt; 0 Then\n RenderOptionGroupEndTag(writer)\n End If\nEnd Sub\n\nPrivate Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"optgroup\")\n writer.WriteAttribute(\"label\", name)\n writer.Write(HtmlTextWriter.TagRightChar)\n writer.WriteLine()\nEnd Sub\n\nPrivate Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)\n writer.WriteEndTag(\"optgroup\")\n writer.WriteLine()\nEnd Sub\n\nPrivate Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"option\")\n writer.WriteAttribute(\"value\", item.Value, True)\n\n If item.Selected Then\n writer.WriteAttribute(\"selected\", \"selected\", False)\n End If\n\n For Each key As String In item.Attributes.Keys\n writer.WriteAttribute(key, item.Attributes(key))\n Next\n\n writer.Write(HtmlTextWriter.TagRightChar)\n HttpUtility.HtmlEncode(item.Text, writer)\n writer.WriteEndTag(\"option\")\n writer.WriteLine()\nEnd Sub\nProtected Overrides Function SaveViewState() As Object\n ' Create an object array with one element for the CheckBoxList's\n ' ViewState contents, and one element for each ListItem in skmCheckBoxList\n Dim state(Me.Items.Count + 1 - 1) As Object 'stupid vb array\n Dim baseState As Object = MyBase.SaveViewState()\n\n state(0) = baseState\n ' Now, see if we even need to save the view state\n Dim itemHasAttributes As Boolean = False\n\n For i As Integer = 0 To Me.Items.Count - 1\n If Me.Items(i).Attributes.Count &gt; 0 Then\n itemHasAttributes = True\n ' Create an array of the item's Attribute's keys and values\n Dim attribKV(Me.Items(i).Attributes.Count * 2 - 1) As Object 'stupid vb array\n Dim k As Integer = 0\n For Each key As String In Me.Items(i).Attributes.Keys\n attribKV(k) = key\n k += 1\n attribKV(k) = Me.Items(i).Attributes(key)\n k += 1\n Next\n state(i + 1) = attribKV\n End If\n Next\n ' return either baseState or state, depending on whether or not\n ' any ListItems had attributes\n If (itemHasAttributes) Then\n Return state\n Else\n Return baseState\n End If\nEnd Function\n\n\nProtected Overrides Sub LoadViewState(ByVal savedState As Object)\n If savedState Is Nothing Then Return\n ' see if savedState is an object or object array\n If Not savedState.GetType.GetElementType() Is Nothing AndAlso savedState.GetType.GetElementType().Equals(GetType(Object)) Then\n\n ' we have just the base state\n MyBase.LoadViewState(savedState(0))\n 'we have an array of items with attributes\n Dim state() As Object = savedState\n MyBase.LoadViewState(state(0)) '/ load the base state\n For i As Integer = 1 To state.Length - 1\n If Not state(i) Is Nothing Then\n ' Load back in the attributes\n Dim attribKV() As Object = state(i)\n For k As Integer = 0 To attribKV.Length - 1 Step +2\n Me.Items(i - 1).Attributes.Add(attribKV(k).ToString(), attribKV(k + 1).ToString())\n Next\n End If\n Next\n Else\n 'load it normal\n MyBase.LoadViewState(savedState)\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 1942378, "author": "Irfan", "author_id": 236324, "author_profile": "https://Stackoverflow.com/users/236324", "pm_score": 5, "selected": false, "text": "<p>I have used JQuery to achieve this task. I first added an new attribute for every <code>ListItem</code> from the backend and then used that attribute in JQuery <code>wrapAll()</code> method to create groups...</p>\n\n<p><strong>C#:</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (ListItem item in ((DropDownList)sender).Items)\n{\n if (System.Int32.Parse(item.Value) &lt; 5)\n item.Attributes.Add(\"classification\", \"LessThanFive\");\n else\n item.Attributes.Add(\"classification\", \"GreaterThanFive\");\n} \n</code></pre>\n\n<p><strong>JQuery:</strong></p>\n\n<pre><code>$(document).ready(function() {\n //Create groups for dropdown list\n $(\"select.listsmall option[@classification='LessThanFive']\")\n .wrapAll(\"&amp;lt;optgroup label='Less than five'&amp;gt;\");\n $(\"select.listsmall option[@classification='GreaterThanFive']\")\n .wrapAll(\"&amp;lt;optgroup label='Greater than five'&amp;gt;\"); \n});\n</code></pre>\n" }, { "answer_id": 2117182, "author": "Tom Miller", "author_id": 256715, "author_profile": "https://Stackoverflow.com/users/256715", "pm_score": 3, "selected": false, "text": "<p>Based on the posts above I've created a c# version of this control with working view state.</p>\n\n<pre><code> public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n string tag;\n string optgroupLabel;\n if (count &gt; 0)\n {\n bool flag = false;\n for (int i = 0; i &lt; count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0 &amp;&amp; item.Attributes[OptionGroupTag] != null)\n {\n tag = OptionGroupTag;\n optgroupLabel = item.Attributes[OptionGroupTag];\n }\n writer.WriteBeginTag(tag);\n // NOTE(cboivin): Is optionGroup\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n else\n {\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0)\n {\n item.Attributes.Render(writer);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n }\n writer.Write('&gt;');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n }\n }\n }\n }\n\n protected override object SaveViewState()\n {\n object[] state = new object[this.Items.Count + 1];\n object baseState = base.SaveViewState();\n state[0] = baseState;\n bool itemHasAttributes = false;\n\n for (int i = 0; i &lt; this.Items.Count; i++)\n {\n if (this.Items[i].Attributes.Count &gt; 0)\n {\n itemHasAttributes = true;\n object[] attributes = new object[this.Items[i].Attributes.Count * 2];\n int k = 0;\n\n foreach (string key in this.Items[i].Attributes.Keys)\n {\n attributes[k] = key;\n k++;\n attributes[k] = this.Items[i].Attributes[key];\n k++;\n }\n state[i + 1] = attributes;\n }\n }\n\n if (itemHasAttributes)\n return state;\n return baseState;\n }\n\n protected override void LoadViewState(object savedState)\n {\n if (savedState == null)\n return;\n\n if (!(savedState.GetType().GetElementType() == null) &amp;&amp;\n (savedState.GetType().GetElementType().Equals(typeof(object))))\n {\n object[] state = (object[])savedState;\n base.LoadViewState(state[0]);\n\n for (int i = 1; i &lt; state.Length; i++)\n {\n if (state[i] != null)\n {\n object[] attributes = (object[])state[i];\n for (int k = 0; k &lt; attributes.Length; k += 2)\n {\n this.Items[i - 1].Attributes.Add\n (attributes[k].ToString(), attributes[k + 1].ToString());\n }\n }\n }\n }\n else\n {\n base.LoadViewState(savedState);\n }\n }\n</code></pre>\n\n<p>I hope this helps some people :-)</p>\n" }, { "answer_id": 3104581, "author": "nw.", "author_id": 307960, "author_profile": "https://Stackoverflow.com/users/307960", "pm_score": 4, "selected": false, "text": "<p>The above code renders the end tag for the optgroup before any of the options, so the options don't get indented like they should in addition to the markup not properly representing the grouping. Here's my slightly modified version of Tom's code:</p>\n\n<pre><code> public class ExtendedDropDownList : System.Web.UI.WebControls.DropDownList\n{\n public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n string tag;\n string optgroupLabel;\n if (count &gt; 0)\n {\n bool flag = false;\n string prevOptGroup = null;\n for (int i = 0; i &lt; count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0 &amp;&amp; item.Attributes[OptionGroupTag] != null)\n {\n optgroupLabel = item.Attributes[OptionGroupTag];\n\n if (prevOptGroup != optgroupLabel)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n writer.WriteBeginTag(OptionGroupTag);\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n writer.Write('&gt;');\n }\n item.Attributes.Remove(OptionGroupTag);\n prevOptGroup = optgroupLabel;\n }\n else\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n prevOptGroup = null;\n }\n\n writer.WriteBeginTag(tag);\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0)\n {\n item.Attributes.Render(writer);\n }\n if (optgroupLabel != null)\n {\n item.Attributes.Add(OptionGroupTag, optgroupLabel);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n\n writer.Write('&gt;');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n if (i == count - 1)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n }\n }\n }\n }\n }\n\n protected override object SaveViewState()\n {\n object[] state = new object[this.Items.Count + 1];\n object baseState = base.SaveViewState();\n state[0] = baseState;\n bool itemHasAttributes = false;\n\n for (int i = 0; i &lt; this.Items.Count; i++)\n {\n if (this.Items[i].Attributes.Count &gt; 0)\n {\n itemHasAttributes = true;\n object[] attributes = new object[this.Items[i].Attributes.Count * 2];\n int k = 0;\n\n foreach (string key in this.Items[i].Attributes.Keys)\n {\n attributes[k] = key;\n k++;\n attributes[k] = this.Items[i].Attributes[key];\n k++;\n }\n state[i + 1] = attributes;\n }\n }\n\n if (itemHasAttributes)\n return state;\n return baseState;\n }\n\n protected override void LoadViewState(object savedState)\n {\n if (savedState == null)\n return;\n\n if (!(savedState.GetType().GetElementType() == null) &amp;&amp;\n (savedState.GetType().GetElementType().Equals(typeof(object))))\n {\n object[] state = (object[])savedState;\n base.LoadViewState(state[0]);\n\n for (int i = 1; i &lt; state.Length; i++)\n {\n if (state[i] != null)\n {\n object[] attributes = (object[])state[i];\n for (int k = 0; k &lt; attributes.Length; k += 2)\n {\n this.Items[i - 1].Attributes.Add\n (attributes[k].ToString(), attributes[k + 1].ToString());\n }\n }\n }\n }\n else\n {\n base.LoadViewState(savedState);\n }\n }\n}\n</code></pre>\n\n<p>Use it like this:</p>\n\n<pre><code> ListItem item1 = new ListItem(\"option1\");\n item1.Attributes.Add(\"optgroup\", \"CatA\");\n ListItem item2 = new ListItem(\"option2\");\n item2.Attributes.Add(\"optgroup\", \"CatA\");\n ListItem item3 = new ListItem(\"option3\");\n item3.Attributes.Add(\"optgroup\", \"CatB\");\n ListItem item4 = new ListItem(\"option4\");\n item4.Attributes.Add(\"optgroup\", \"CatB\");\n ListItem item5 = new ListItem(\"NoOptGroup\");\n\n ddlTest.Items.Add(item1);\n ddlTest.Items.Add(item2);\n ddlTest.Items.Add(item3);\n ddlTest.Items.Add(item4);\n ddlTest.Items.Add(item5);\n</code></pre>\n\n<p>and here's the generated markup (indented for ease of viewing):</p>\n\n<pre><code> &lt;select name=\"ddlTest\" id=\"Select1\"&gt;\n &lt;optgroup label=\"CatA\"&gt;\n &lt;option selected=\"selected\" value=\"option1\"&gt;option1&lt;/option&gt;\n &lt;option value=\"option2\"&gt;option2&lt;/option&gt;\n &lt;/optgroup&gt;\n &lt;optgroup label=\"CatB\"&gt;\n &lt;option value=\"option3\"&gt;option3&lt;/option&gt;\n &lt;option value=\"option4\"&gt;option4&lt;/option&gt;\n &lt;/optgroup&gt;\n &lt;option value=\"NoOptGroup\"&gt;NoOptGroup&lt;/option&gt;\n &lt;/select&gt;\n</code></pre>\n" }, { "answer_id": 8851045, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code> // How to use:\n // 1. Create items in a select element or asp:DropDownList control\n // 2. Set value of an option or ListItem to \"_group_\", those will be converted to optgroups\n // 3. On page onload call createOptGroups(domElement), for example like this:\n // - var lst = document.getElementById('lst');\n // - createOptGroups(lst, \"_group_\");\n // 4. You can change groupMarkerValue to anything, I used \"_group_\"\n function createOptGroups(lst, groupMarkerValue) {\n // Get an array containing the options\n var childNodes = [];\n for (var i = 0; i &lt; lst.options.length; i++)\n childNodes.push(lst.options[i]);\n\n // Get the selected element so we can preserve selection\n var selectedIndex = lst.selectedIndex;\n var selectedChild = childNodes[selectedIndex];\n var selectedValue = selectedChild.value;\n\n // Remove all elements\n while (lst.hasChildNodes())\n lst.removeChild(lst.childNodes[0]);\n\n // Go through the array of options and convert some into groups\n var group = null;\n for (var i = 0; i &lt; childNodes.length; i++) {\n var node = childNodes[i];\n if (node.value == groupMarkerValue) {\n group = document.createElement(\"optgroup\");\n group.label = node.text;\n group.value = groupMarkerValue;\n lst.appendChild(group);\n continue;\n }\n\n // Add to group or directly under list\n (group == null ? lst : group).appendChild(node);\n }\n\n // Preserve selected, no support for multi-selection here, sorry\n selectedChild.selected = true;\n }\n</code></pre>\n\n<p>Tested on Chrome 16, Firefox 9 and IE8.</p>\n" }, { "answer_id": 21481634, "author": "mhu", "author_id": 932282, "author_profile": "https://Stackoverflow.com/users/932282", "pm_score": 3, "selected": false, "text": "<p>A more generic approach to <a href=\"https://stackoverflow.com/a/1942378/932282\">Irfan's</a> jQuery-based solution:</p>\n\n<p><strong>backend</strong></p>\n\n<pre><code>private void _addSelectItem(DropDownList list, string title, string value, string group = null) {\n ListItem item = new ListItem(title, value);\n if (!String.IsNullOrEmpty(group))\n {\n item.Attributes[\"data-category\"] = group;\n }\n list.Items.Add(item);\n}\n\n...\n_addSelectItem(dropDown, \"Option 1\", \"1\");\n_addSelectItem(dropDown, \"Option 2\", \"2\", \"Category\");\n_addSelectItem(dropDown, \"Option 3\", \"3\", \"Category\");\n...\n</code></pre>\n\n<p><strong>client</strong></p>\n\n<pre><code>var groups = {};\n$(\"select option[data-category]\").each(function () {\n groups[$.trim($(this).attr(\"data-category\"))] = true;\n});\n$.each(groups, function (c) {\n $(\"select option[data-category='\"+c+\"']\").wrapAll('&lt;optgroup label=\"' + c + '\"&gt;');\n});\n</code></pre>\n" }, { "answer_id": 27784921, "author": "Josh M.", "author_id": 374198, "author_profile": "https://Stackoverflow.com/users/374198", "pm_score": 2, "selected": false, "text": "<p>I've done this using an outer repeater for the select and optgroups and an inner repeater for the items within that group:</p>\n\n<pre><code>&lt;asp:Repeater ID=\"outerRepeater\" runat=\"server\"&gt;\n &lt;HeaderTemplate&gt;\n &lt;select id=\"&lt;%= outerRepeater.ClientID %&gt;\"&gt;\n &lt;/HeaderTemplate&gt;\n &lt;ItemTemplate&gt;\n &lt;optgroup label=\"&lt;%# Eval(\"GroupText\") %&gt;\"&gt;\n &lt;asp:Repeater runat=\"server\" DataSource='&lt;%# Eval(\"Items\") %&gt;'&gt;\n &lt;ItemTemplate&gt;\n &lt;option value=\"&lt;%# Eval(\"Value\") %&gt;\"&gt;&lt;%# Eval(\"Text\") %&gt;&lt;/option&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:Repeater&gt;\n &lt;/optgroup&gt;\n &lt;/ItemTemplate&gt;\n &lt;FooterTemplate&gt;\n &lt;/select&gt;\n &lt;/FooterTemplate&gt;\n&lt;/asp:Repeater&gt;\n</code></pre>\n\n<p>The data source for <code>outerRepeater</code> is a simple grouping as follows:</p>\n\n<pre><code>var data = (from o in thingsToDisplay\n group oby GetAlphaGrouping(o.Name) into g\n orderby g.Key\n select new\n {\n Alpha = g.Key,\n Items = g\n });\n</code></pre>\n\n<p>And to get the alpha grouping character:</p>\n\n<pre><code>private string GetAlphaGrouping(string value)\n{\n string firstChar = value.Substring(0, 1).ToUpper();\n int unused;\n\n if (int.TryParse(firstChar, out unused))\n return \"#\";\n\n return firstChar.ToUpper();\n}\n</code></pre>\n\n<p>It's not a perfect solution but it works. The <em>correct</em> solution would be to no longer use WebForms, but us MVC instead. :)</p>\n" }, { "answer_id": 59421415, "author": "brz", "author_id": 1465881, "author_profile": "https://Stackoverflow.com/users/1465881", "pm_score": 0, "selected": false, "text": "<p>I expanded upon <a href=\"https://stackoverflow.com/a/3104581/1465881\">mkl's answer</a> to make a DropDownList control to which you can DataBind. Here's the result (which may be subject to improvement):</p>\n\n<pre><code>public class UcDropDownListWithOptGroup : DropDownList\n{\n public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n string tag;\n string optgroupLabel;\n if (count &gt; 0)\n {\n bool flag = false;\n string prevOptGroup = null;\n for (int i = 0; i &lt; count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0 &amp;&amp; item.Attributes[\"data-optgroup\"] != null)\n {\n optgroupLabel = item.Attributes[\"data-optgroup\"];\n\n if (prevOptGroup != optgroupLabel)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n writer.WriteBeginTag(OptionGroupTag);\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n writer.Write('&gt;');\n }\n item.Attributes.Remove(OptionGroupTag);\n prevOptGroup = optgroupLabel;\n }\n else\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n prevOptGroup = null;\n }\n\n writer.WriteBeginTag(tag);\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null &amp;&amp; item.Attributes.Count &gt; 0)\n {\n item.Attributes.Render(writer);\n }\n if (optgroupLabel != null)\n {\n item.Attributes.Add(OptionGroupTag, optgroupLabel);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n\n writer.Write('&gt;');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n if (i == count - 1)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n }\n }\n }\n }\n }\n\n protected override object SaveViewState()\n {\n object[] state = new object[this.Items.Count + 1];\n object baseState = base.SaveViewState();\n state[0] = baseState;\n bool itemHasAttributes = false;\n\n for (int i = 0; i &lt; this.Items.Count; i++)\n {\n if (this.Items[i].Attributes.Count &gt; 0)\n {\n itemHasAttributes = true;\n object[] attributes = new object[this.Items[i].Attributes.Count * 2];\n int k = 0;\n\n foreach (string key in this.Items[i].Attributes.Keys)\n {\n attributes[k] = key;\n k++;\n attributes[k] = this.Items[i].Attributes[key];\n k++;\n }\n state[i + 1] = attributes;\n }\n }\n\n if (itemHasAttributes)\n return state;\n return baseState;\n }\n\n protected override void LoadViewState(object savedState)\n {\n if (savedState == null)\n return;\n\n if (!(savedState.GetType().GetElementType() == null) &amp;&amp;\n (savedState.GetType().GetElementType().Equals(typeof(object))))\n {\n object[] state = (object[])savedState;\n base.LoadViewState(state[0]);\n\n for (int i = 1; i &lt; state.Length; i++)\n {\n if (state[i] != null)\n {\n object[] attributes = (object[])state[i];\n for (int k = 0; k &lt; attributes.Length; k += 2)\n {\n this.Items[i - 1].Attributes.Add\n (attributes[k].ToString(), attributes[k + 1].ToString());\n }\n }\n }\n }\n else\n {\n base.LoadViewState(savedState);\n }\n }\n\n protected override void PerformDataBinding(IEnumerable dataSource)\n {\n base.PerformDataBinding(dataSource);\n\n if (!string.IsNullOrWhiteSpace(DataOptGroupField) &amp;&amp; OptGroupTitles != null)\n {\n var currentItems = Items;\n var dataSourceItems = dataSource.Cast&lt;object&gt;().ToList();\n\n var staticItemsCount = Items.Count - dataSourceItems.Count;\n\n for (var i = staticItemsCount; i &lt; Items.Count; i++)\n {\n var dataSourceItem = dataSourceItems[i - staticItemsCount];\n var optGroupValue = DataBinder.GetPropertyValue(dataSourceItem, DataOptGroupField);\n currentItems[i].Attributes.Add(\"data-optgroup\", OptGroupTitles[optGroupValue]);\n }\n }\n }\n\n public Dictionary&lt;object, string&gt; OptGroupTitles { get; set; }\n public string DataOptGroupField { get; set; }\n}\n</code></pre>\n\n<p>Things to note:</p>\n\n<ul>\n<li>You can set a DataOptGroupField property, similiar to DataTextField and DataValueField. It defines which property of the databound item it should take into consideration for determining the correct optgroup.</li>\n<li>You can set a OptGroupTitles property which defines to which optgroup label the property defined in DataOptGroupField should be translated.</li>\n</ul>\n\n<p>As an example, take the following code in your page or user control:</p>\n\n<pre><code>&lt;MyControls:UcDropDownListWithOptGroup runat=\"server\" DataSourceID=\"dsX\" DataTextField=\"MyDataTextField\" DataValueField=\"MyDataValueField\" DataOptGroupField=\"IsActive\" OptGroupTitles='&lt;%# MyGroupTitles %&gt;' /&gt;\n</code></pre>\n\n<p>Where the 'IsActive' property of the databound item is a boolean.</p>\n\n<p>In the code-behind of the page or user control, you define the following property:</p>\n\n<pre><code>public Dictionary&lt;object, string&gt; MyGroupTitles\n{\n get\n {\n return new Dictionary&lt;object, string&gt;\n {\n { true, \"Active\" },\n { false, \"Inactive\" }\n };\n }\n}\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
Can anyone recommend a dropdownlist control for asp.net (3.5) that can render option groups? Thanks
I've used the standard control in the past, and just added a simple [ControlAdapter](http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx) for it that would override the default behavior so it could render <optgroup>s in certain places. This works great even if you have controls that don't need the special behavior, because the additional feature doesn't get in the way. Note that this was for a specific purpose and written in .Net 2.0, so it may not suit you as well, but it should at least give you a starting point. Also, you have to hook it up using a .browserfile in your project (see the end of the post for an example). ```vb 'This codes makes the dropdownlist control recognize items with "--" 'for the label or items with an OptionGroup attribute and render them 'as <optgroup> instead of <option>. Public Class DropDownListAdapter Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter) Dim list As DropDownList = Me.Control Dim currentOptionGroup As String Dim renderedOptionGroups As New Generic.List(Of String) For Each item As ListItem In list.Items Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value) If item.Attributes("OptionGroup") IsNot Nothing Then 'The item is part of an option group currentOptionGroup = item.Attributes("OptionGroup") If Not renderedOptionGroups.Contains(currentOptionGroup) Then 'the header was not written- do that first 'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list) If (renderedOptionGroups.Count > 0) Then RenderOptionGroupEndTag(writer) 'need to close previous group End If RenderOptionGroupBeginTag(currentOptionGroup, writer) renderedOptionGroups.Add(currentOptionGroup) End If RenderListItem(item, writer) ElseIf item.Text = "--" Then 'simple separator RenderOptionGroupBeginTag("--", writer) RenderOptionGroupEndTag(writer) Else 'default behavior: render the list item as normal RenderListItem(item, writer) End If Next item If renderedOptionGroups.Count > 0 Then RenderOptionGroupEndTag(writer) End If End Sub Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter) writer.WriteBeginTag("optgroup") writer.WriteAttribute("label", name) writer.Write(HtmlTextWriter.TagRightChar) writer.WriteLine() End Sub Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter) writer.WriteEndTag("optgroup") writer.WriteLine() End Sub Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter) writer.WriteBeginTag("option") writer.WriteAttribute("value", item.Value, True) If item.Selected Then writer.WriteAttribute("selected", "selected", False) End If For Each key As String In item.Attributes.Keys writer.WriteAttribute(key, item.Attributes(key)) Next key writer.Write(HtmlTextWriter.TagRightChar) HttpUtility.HtmlEncode(item.Text, writer) writer.WriteEndTag("option") writer.WriteLine() End Sub End Class ``` Here's a C# implementation of the same Class: ``` /* This codes makes the dropdownlist control recognize items with "--" * for the label or items with an OptionGroup attribute and render them * as <optgroup> instead of <option>. */ public class DropDownListAdapter : WebControlAdapter { protected override void RenderContents(HtmlTextWriter writer) { //System.Web.HttpContext.Current.Response.Write("here"); var list = (DropDownList)this.Control; string currentOptionGroup; var renderedOptionGroups = new List<string>(); foreach (ListItem item in list.Items) { Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value); //Is the item part of an option group? if (item.Attributes["OptionGroup"] != null) { currentOptionGroup = item.Attributes["OptionGroup"]; //Was the option header already written, then just render the list item if (renderedOptionGroups.Contains(currentOptionGroup)) RenderListItem(item, writer); //The header was not written,do that first else { //Close previous group if (renderedOptionGroups.Count > 0) RenderOptionGroupEndTag(writer); RenderOptionGroupBeginTag(currentOptionGroup, writer); renderedOptionGroups.Add(currentOptionGroup); RenderListItem(item, writer); } } //Simple separator else if (item.Text == "--") { RenderOptionGroupBeginTag("--", writer); RenderOptionGroupEndTag(writer); } //Default behavior, render the list item as normal else RenderListItem(item, writer); } if (renderedOptionGroups.Count > 0) RenderOptionGroupEndTag(writer); } private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer) { writer.WriteBeginTag("optgroup"); writer.WriteAttribute("label", name); writer.Write(HtmlTextWriter.TagRightChar); writer.WriteLine(); } private void RenderOptionGroupEndTag(HtmlTextWriter writer) { writer.WriteEndTag("optgroup"); writer.WriteLine(); } private void RenderListItem(ListItem item, HtmlTextWriter writer) { writer.WriteBeginTag("option"); writer.WriteAttribute("value", item.Value, true); if (item.Selected) writer.WriteAttribute("selected", "selected", false); foreach (string key in item.Attributes.Keys) writer.WriteAttribute(key, item.Attributes[key]); writer.Write(HtmlTextWriter.TagRightChar); HttpUtility.HtmlEncode(item.Text, writer); writer.WriteEndTag("option"); writer.WriteLine(); } } ``` My browser file was named "App\_Browsers\BrowserFile.browser" and looked like this: ``` <!-- You can find existing browser definitions at <windir>\Microsoft.NET\Framework\<ver>\CONFIG\Browsers --> <browsers> <browser refID="Default"> <controlAdapters> <adapter controlType="System.Web.UI.WebControls.DropDownList" adapterType="DropDownListAdapter" /> </controlAdapters> </browser> </browsers> ```
130,032
<p>Is there a built-in editor for a multi-line string in a <code>PropertyGrid</code>.</p>
[ { "answer_id": 130079, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 2, "selected": false, "text": "<p>No, you will need to create what's called a modal UI type editor. You'll need to create a class that inherits from UITypeEditor. This is basically a form that gets shown when you click on the ellipsis button on the right side of the property you are editing.</p>\n\n<p>The only drawback I found, was that I needed to decorate the specific string property with a specific attribute. It's been a while since I had to do that. I got this information from a book by Chris Sells called \"Windows Forms Programming in C#\"</p>\n\n<p>There's a commercial propertygrid called <a href=\"http://www.visualhint.com/index.php/propertygrid/\" rel=\"nofollow noreferrer\">Smart PropertyGrid.NET</a> by VisualHint.</p>\n" }, { "answer_id": 130080, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 0, "selected": false, "text": "<p>Yes. I don't quite remember how it is called, but look at the Items property editor for something like ComboBox</p>\n\n<p>Edited: As of @fryguybob, ComboBox.Items uses the System.Windows.Forms.Design.ListControlStringCollectionEditor</p>\n" }, { "answer_id": 130168, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 7, "selected": true, "text": "<p>I found that <code>System.Design.dll</code> has <code>System.ComponentModel.Design.MultilineStringEditor</code> which can be used as follows:</p>\n\n<pre><code>public class Stuff\n{\n [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]\n public string MultiLineProperty { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 35866566, "author": "Sunil Kumar", "author_id": 663741, "author_profile": "https://Stackoverflow.com/users/663741", "pm_score": 2, "selected": false, "text": "<p>We need to write our custom editor to get the multiline support in property grid.</p>\n\n<p>Here is the customer text editor class implemented from <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.drawing.design.uitypeeditor?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">UITypeEditor</a> </p>\n\n<pre><code>public class MultiLineTextEditor : UITypeEditor\n{\n private IWindowsFormsEditorService _editorService;\n\n public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)\n {\n return UITypeEditorEditStyle.DropDown;\n }\n\n public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n {\n _editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));\n\n TextBox textEditorBox = new TextBox();\n textEditorBox.Multiline = true;\n textEditorBox.ScrollBars = ScrollBars.Vertical;\n textEditorBox.Width = 250;\n textEditorBox.Height = 150;\n textEditorBox.BorderStyle = BorderStyle.None;\n textEditorBox.AcceptsReturn = true;\n textEditorBox.Text = value as string;\n\n _editorService.DropDownControl(textEditorBox);\n\n return textEditorBox.Text;\n }\n}\n</code></pre>\n\n<p>Write your custom property grid and apply this Editor attribute to the property </p>\n\n<pre><code>class CustomPropertyGrid\n{\n private string multiLineStr = string.Empty;\n\n [Editor(typeof(MultiLineTextEditor), typeof(UITypeEditor))]\n public string MultiLineStr\n {\n get { return multiLineStr; }\n set { multiLineStr = value; }\n }\n}\n</code></pre>\n\n<p>In main form assign this object</p>\n\n<pre><code> propertyGrid1.SelectedObject = new CustomPropertyGrid();\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4592/" ]
Is there a built-in editor for a multi-line string in a `PropertyGrid`.
I found that `System.Design.dll` has `System.ComponentModel.Design.MultilineStringEditor` which can be used as follows: ``` public class Stuff { [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))] public string MultiLineProperty { get; set; } } ```
130,074
<p>python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:</p> <pre><code>time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone </code></pre> <p>Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?</p> <p>Bonus questions: what would you name the method ? How would you implement it ?</p>
[ { "answer_id": 130134, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": false, "text": "<p>I always thought the time and datetime modules were a little incoherent. Anyways, here's the inverse of mktime</p>\n\n<pre><code>import time\ndef mkgmtime(t):\n \"\"\"Convert UTC tuple to seconds since Epoch\"\"\"\n return time.mktime(t)-time.timezone\n</code></pre>\n" }, { "answer_id": 130138, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<p>I'm only a newbie to Python, but here's my approach.</p>\n\n<pre><code>def mkgmtime(fields):\n now = int(time.time())\n gmt = list(time.gmtime(now))\n gmt[8] = time.localtime(now).tm_isdst\n disp = now - time.mktime(tuple(gmt))\n return disp + time.mktime(fields)\n</code></pre>\n\n<p>There, my proposed name for the function too. :-) It's important to recalculate <code>disp</code> every time, in case the daylight-savings value changes or the like. (The conversion back to tuple is required for Jython. CPython doesn't seem to require it.)</p>\n\n<p>This is super ick, because <code>time.gmtime</code> sets the DST flag to false, always. I hate the code, though. There's got to be a better way to do it. And there are probably some corner cases that I haven't got, yet.</p>\n" }, { "answer_id": 161385, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 6, "selected": true, "text": "<p>There is actually an inverse function, but for some bizarre reason, it's in the <a href=\"https://docs.python.org/2/library/calendar.html\" rel=\"noreferrer\">calendar</a> module: calendar.timegm(). I listed the functions in this <a href=\"https://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python#79913\">answer</a>.</p>\n" }, { "answer_id": 18783518, "author": "Ilialuk", "author_id": 2121105, "author_profile": "https://Stackoverflow.com/users/2121105", "pm_score": 0, "selected": false, "text": "<p>mktime documentation is a bit misleading here, there is no meaning saying it's calculated as a local time, rather it's calculating the seconds from Epoch according to the supplied tuple - regardless of your computer locality.</p>\n\n<p>If you do want to do a conversion from a utc_tuple to local time you can do the following:</p>\n\n<pre><code>&gt;&gt;&gt; time.ctime(time.time())\n'Fri Sep 13 12:40:08 2013'\n\n&gt;&gt;&gt; utc_tuple = time.gmtime()\n&gt;&gt;&gt; time.ctime(time.mktime(utc_tuple))\n'Fri Sep 13 10:40:11 2013'\n\n&gt;&gt;&gt; time.ctime(time.mktime(utc_tuple) - time.timezone)\n'Fri Sep 13 12:40:11 2013'\n</code></pre>\n\n<p><BR>\nPerhaps a more accurate question would be how to <strong>convert a utc_tuple to a local_tuple</strong>.\nI would call it <strong>gm_tuple_to_local_tuple</strong> (I prefer long and descriptive names):</p>\n\n<pre><code>&gt;&gt;&gt; time.localtime(time.mktime(utc_tuple) - time.timezone)\ntime.struct_time(tm_year=2013, tm_mon=9, tm_mday=13, tm_hour=12, tm_min=40, tm_sec=11, tm_wday=4, tm_yday=256, tm_isdst=1)\n</code></pre>\n\n<p><BR>\n<strong>Validatation:</strong></p>\n\n<pre><code>&gt;&gt;&gt; time.ctime(time.mktime(time.localtime(time.mktime(utc_tuple) - time.timezone)))\n'Fri Sep 13 12:40:11 2013' \n</code></pre>\n\n<p>Hope this helps,\nilia.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring: ``` time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone ``` Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ? Bonus questions: what would you name the method ? How would you implement it ?
There is actually an inverse function, but for some bizarre reason, it's in the [calendar](https://docs.python.org/2/library/calendar.html) module: calendar.timegm(). I listed the functions in this [answer](https://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python#79913).
130,092
<p>Rails uses the concept of migrations to deal with model changes using the ActiveRecord API.</p> <p>CouchDB uses JSON (nested maps and arrays) to represent its model objects.</p> <p>In working with CouchDB so far, I don't see good ways of recognizing when the document's structure has changed (other than being disciplined as a developer), or for migrating documents from an old to a new model.</p> <p>Are there existing features or do you have best practices for handling model changes in CouchDB?</p>
[ { "answer_id": 130608, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"https://github.com/arunthampi/activecouch/tree/master\" rel=\"nofollow noreferrer\">ActiveCouch</a>.</p>\n\n<p>CouchDB is schema-less on purpose, so there is not a 1-to-1 mapping of concepts from the ActiveRecord migrations to a CouchDB equivalent. However, ActiveCouch does include migrations for CouchDB's 'views'.</p>\n" }, { "answer_id": 141086, "author": "Paul J. Davis", "author_id": 129506, "author_profile": "https://Stackoverflow.com/users/129506", "pm_score": 4, "selected": true, "text": "<p>Time for RDBMS de-brainwashing. :)</p>\n\n<p>One of the biggest points of couchdb's schema-less design is directly aimed at preventing the need for migrations. The JSON representation of objects makes it easy to just duck type your objects.</p>\n\n<p>For example, given that you have a blog type web app with posts and whatever fancy things people store in a blog. Your post documents have fields like author, title, created at, etc. Now you come along and think to yourself, \"I should track what phase the moon is in when I publish my posts...\" you can just start adding moon_phase as an attribute to new posts.</p>\n\n<p>If you want to be complete you'd go back and add moon_phase to old posts, but that's not strictly necessary.</p>\n\n<p>In your views, you can access moon_phase as an attribute. And it'll be null or cause an exception or something. (Not a JS expert, I think null is the right answer)</p>\n\n<p>Thing is, it doesn't really matter. If you feel like changing something just change it. Though make sure your views understand that change. Which in my experience doesn't really require much.</p>\n\n<p>Also, if you're really paranoid, you might store a version/type attribute, as in:</p>\n\n<pre><code>{\n _id: \"foo-post\",\n _rev: \"23490AD\",\n type: \"post\",\n typevers: 0,\n moon_phase: \"full\"\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 410840, "author": "max", "author_id": 49407, "author_profile": "https://Stackoverflow.com/users/49407", "pm_score": 2, "selected": false, "text": "<p>If you're into having schemas and still want to use CouchDB you get an \"impedance mismatch\".</p>\n\n<p>Nevertheless, having \"migrations\" is not that hard. Add a <code>schema_version</code> element to each document. Then have your \"document reading function\" include updating. Something like this:</p>\n\n<pre><code>def read(doc_id):\n doc = db.get(doc_id)\n if doc.schema_version == 1:\n # version 1 had names broken down too much\n doc.name = \"%s %s\" % (doc.first, doc.last)\n del doc.first\n del doc.last\n doc.schema_version = 2\n db.put(doc)\n if doc.schema_version == 2: weight\n # version 2 used kg instead of g\n doc.weight_g = doc.weight_kg * 1000\n del doc.volume_kg\n doc.schema_version = 3\n db.put(doc)\n return doc\n</code></pre>\n\n<p>If you want to upgrade the whole DB at once just call <code>read(doc_id)</code> for every document.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
Rails uses the concept of migrations to deal with model changes using the ActiveRecord API. CouchDB uses JSON (nested maps and arrays) to represent its model objects. In working with CouchDB so far, I don't see good ways of recognizing when the document's structure has changed (other than being disciplined as a developer), or for migrating documents from an old to a new model. Are there existing features or do you have best practices for handling model changes in CouchDB?
Time for RDBMS de-brainwashing. :) One of the biggest points of couchdb's schema-less design is directly aimed at preventing the need for migrations. The JSON representation of objects makes it easy to just duck type your objects. For example, given that you have a blog type web app with posts and whatever fancy things people store in a blog. Your post documents have fields like author, title, created at, etc. Now you come along and think to yourself, "I should track what phase the moon is in when I publish my posts..." you can just start adding moon\_phase as an attribute to new posts. If you want to be complete you'd go back and add moon\_phase to old posts, but that's not strictly necessary. In your views, you can access moon\_phase as an attribute. And it'll be null or cause an exception or something. (Not a JS expert, I think null is the right answer) Thing is, it doesn't really matter. If you feel like changing something just change it. Though make sure your views understand that change. Which in my experience doesn't really require much. Also, if you're really paranoid, you might store a version/type attribute, as in: ``` { _id: "foo-post", _rev: "23490AD", type: "post", typevers: 0, moon_phase: "full" } ``` Hope that helps.
130,116
<p>How can I read the first line from a text file using a Windows batch file? Since the file is large I only want to deal with the first line.</p>
[ { "answer_id": 130154, "author": "Ross Fuhrman", "author_id": 9431, "author_profile": "https://Stackoverflow.com/users/9431", "pm_score": 4, "selected": false, "text": "<p>You might give this a try:</p>\n\n<pre><code>@echo off\n\nfor /f %%a in (sample.txt) do (\n echo %%a\n exit /b\n)\n</code></pre>\n\n<p><strong>edit</strong>\nOr, say you have four columns of data and want from the 5th row down to the bottom, try this:</p>\n\n<pre><code>@echo off\n\nfor /f \"skip=4 tokens=1-4\" %%a in (junkl.txt) do (\n echo %%a %%b %%c %%d\n)\n</code></pre>\n" }, { "answer_id": 130209, "author": "Jesse Vogt", "author_id": 9822, "author_profile": "https://Stackoverflow.com/users/9822", "pm_score": 3, "selected": false, "text": "<p>Thanks to thetalkingwalnut with answer <a href=\"https://stackoverflow.com/questions/130116/dos-batch-commands-to-read-first-line-from-text-file#130154\">Windows batch command(s) to read first line from text file</a> I came up with the following solution:</p>\n\n<pre><code>@echo off\nfor /f \"delims=\" %%a in ('type sample.txt') do (\necho %%a\nexit /b\n)\n</code></pre>\n" }, { "answer_id": 130266, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 2, "selected": false, "text": "<p>Slightly building upon the answers of other people. Now allowing you to specify the file you want to read from and the variable you want the result put into:</p>\n\n<pre><code>@echo off\nfor /f \"delims=\" %%x in (%2) do (\nset %1=%%x\nexit /b\n)\n</code></pre>\n\n<p>This means you can use the above like this (assuming you called it getline.bat)</p>\n\n<pre><code>c:\\&gt; dir &gt; test-file\nc:\\&gt; getline variable test-file\nc:\\&gt; set variable \nvariable= Volume in drive C has no label.\n</code></pre>\n" }, { "answer_id": 130298, "author": "indiv", "author_id": 19719, "author_profile": "https://Stackoverflow.com/users/19719", "pm_score": 7, "selected": true, "text": "<p>Here's a general-purpose batch file to print the top <code>n</code> lines from a file like the GNU <code>head</code> utility, instead of just a single line.</p>\n\n<pre><code>@echo off\n\nif [%1] == [] goto usage\nif [%2] == [] goto usage\n\ncall :print_head %1 %2\ngoto :eof\n\nREM\nREM print_head\nREM Prints the first non-blank %1 lines in the file %2.\nREM\n:print_head\nsetlocal EnableDelayedExpansion\nset /a counter=0\n\nfor /f ^\"usebackq^ eol^=^\n\n^ delims^=^\" %%a in (%2) do (\n if \"!counter!\"==\"%1\" goto :eof\n echo %%a\n set /a counter+=1\n)\n\ngoto :eof\n\n:usage\necho Usage: head.bat COUNT FILENAME\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>Z:\\&gt;head 1 \"test file.c\"\n; this is line 1\n\nZ:\\&gt;head 3 \"test file.c\"\n; this is line 1\n this is line 2\nline 3 right here\n</code></pre>\n\n<p>It does not currently count blank lines. It is also subject to the batch-file line-length restriction of 8 KB.</p>\n" }, { "answer_id": 130379, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "<p>One liner, useful for stdout redirect with \">\":</p>\n\n<pre><code>@for /f %%i in ('type yourfile.txt') do @echo %%i &amp; exit\n</code></pre>\n" }, { "answer_id": 1365791, "author": "kevinjansz", "author_id": 166975, "author_profile": "https://Stackoverflow.com/users/166975", "pm_score": 0, "selected": false, "text": "<p>Note, the batch file approaches will be limited to the line limit for the DOS command processor - see <a href=\"http://blogs.msdn.com/oldnewthing/archive/2003/12/10/56028.aspx\" rel=\"nofollow noreferrer\">What is the command line length limit?</a>. </p>\n\n<p>So if trying to process a file that has any lines more that <strong>8192</strong> characters the script will just skip them as the value can't be held. </p>\n" }, { "answer_id": 6824444, "author": "Amit Naidu", "author_id": 209129, "author_profile": "https://Stackoverflow.com/users/209129", "pm_score": 5, "selected": false, "text": "<p>Uh you guys...</p>\n\n<pre><code>C:\\&gt;findstr /n . c:\\boot.ini | findstr ^1:\n\n1:[boot loader]\n\nC:\\&gt;findstr /n . c:\\boot.ini | findstr ^3:\n\n3:default=multi(0)disk(0)rdisk(0)partition(1)\\WINNT\n\nC:\\&gt;\n</code></pre>\n" }, { "answer_id": 7827243, "author": "Spaceballs", "author_id": 993642, "author_profile": "https://Stackoverflow.com/users/993642", "pm_score": 8, "selected": false, "text": "<p>uh?\nimo this is much simpler </p>\n\n<pre><code> set /p texte=&lt; file.txt \n echo %texte%\n</code></pre>\n" }, { "answer_id": 11654524, "author": "Timo Salmi", "author_id": 1321416, "author_profile": "https://Stackoverflow.com/users/1321416", "pm_score": 1, "selected": false, "text": "<p>The problem with the <code>EXIT /B</code> solutions, when more realistically inside a batch file as just one part of it is the following. There is no subsequent processing within the said batch file after the <code>EXIT /B</code>. Usually there is much more to batches than just the one, limited task.</p>\n\n<p>To counter that problem:</p>\n\n<pre><code>@echo off &amp; setlocal enableextensions enabledelayedexpansion\nset myfile_=C:\\_D\\TEST\\My test file.txt\nset FirstLine=\nfor /f \"delims=\" %%i in ('type \"%myfile_%\"') do (\n if not defined FirstLine set FirstLine=%%i)\necho FirstLine=%FirstLine%\nendlocal &amp; goto :EOF\n</code></pre>\n\n<p>(However, the so-called poison characters will still be a problem.)</p>\n\n<p>More on the subject of getting a particular line with batch commands:</p>\n\n<blockquote>\n <p>How do I get the n'th, the first and the last line of a text file?\"\n <a href=\"http://www.netikka.net/tsneti/info/tscmd023.htm\" rel=\"nofollow noreferrer\">http://www.netikka.net/tsneti/info/tscmd023.htm</a><br></p>\n</blockquote>\n\n<p><strong>[Added 28-Aug-2012]</strong> One can also have:</p>\n\n<pre><code>@echo off &amp; setlocal enableextensions\nset myfile_=C:\\_D\\TEST\\My test file.txt\nfor /f \"tokens=* delims=\" %%a in (\n 'type \"%myfile_%\"') do (\n set FirstLine=%%a&amp; goto _ExitForLoop)\n:_ExitForLoop\necho FirstLine=%FirstLine%\nendlocal &amp; goto :EOF\n</code></pre>\n" }, { "answer_id": 40871980, "author": "Sarath Subramanian", "author_id": 3312636, "author_profile": "https://Stackoverflow.com/users/3312636", "pm_score": 2, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>@echo off\nsetlocal enableextensions enabledelayedexpansion\nset firstLine=1\nfor /f \"delims=\" %%i in (yourfilename.txt) do (\n if !firstLine!==1 echo %%i\n set firstLine=0\n)\nendlocal\n</code></pre>\n" }, { "answer_id": 49002799, "author": "hhay", "author_id": 9417167, "author_profile": "https://Stackoverflow.com/users/9417167", "pm_score": 1, "selected": false, "text": "<p>Another way</p>\n\n<pre><code>setlocal enabledelayedexpansion\n@echo off\nfor /f \"delims=\" %%i in (filename.txt) do (\nif 1==1 (\nset first_line=%%i\necho !first_line!\ngoto :eof\n))\n</code></pre>\n" }, { "answer_id": 52422564, "author": "mmj", "author_id": 694360, "author_profile": "https://Stackoverflow.com/users/694360", "pm_score": 1, "selected": false, "text": "<p>Here is a workaround using <code>powershell</code>:</p>\n\n<pre><code>powershell (Get-Content file.txt)[0]\n</code></pre>\n\n<p>(You can easily read also a range of lines with <code>powershell (Get-Content file.txt)[0..3]</code>)</p>\n\n<p>If you need to set a variable inside a batch script as the first line of <code>file.txt</code> you may use:</p>\n\n<pre><code>for /f \"usebackq delims=\" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set \"head=%%a\")\n</code></pre>\n" }, { "answer_id": 55766309, "author": "Laercio", "author_id": 11385438, "author_profile": "https://Stackoverflow.com/users/11385438", "pm_score": 2, "selected": false, "text": "<p>To cicle a file (<code>file1.txt</code>, <code>file1[1].txt</code>, <code>file1[2].txt</code>, etc.):</p>\n\n<pre><code>START/WAIT C:\\LAERCIO\\DELPHI\\CICLADOR\\dprCiclador.exe C:\\LAERCIUM\\Ciclavel.txt\n\nrem set/p ciclo=&lt; C:\\LAERCIUM\\Ciclavel.txt:\nset/p ciclo=&lt; C:\\LAERCIUM\\Ciclavel.txt\n\nrem echo %ciclo%:\necho %ciclo%\n</code></pre>\n\n<p>And it's running.</p>\n" }, { "answer_id": 58732298, "author": "Zimba", "author_id": 5958708, "author_profile": "https://Stackoverflow.com/users/5958708", "pm_score": -1, "selected": false, "text": "<p>Print <em>1st line only</em> (no need to read entire file):</p>\n<pre><code>set /p a=&lt; file.txt &amp; echo !a!\n</code></pre>\n<p>To print one line at a time; user to press a key for next line:<br>\n(After printing required lines, press Ctrl+C to stop.)</p>\n<pre><code>for /f &quot;delims=&quot; %a in (downing.txt) do echo %a &amp; pause&gt;nul\n</code></pre>\n<p>To <em>print 1st n lines</em> (without user intervention):</p>\n<pre><code>type nul &gt; tmp &amp; fc tmp &quot;%file%&quot; /lb %n% /t | find /v &quot;?&quot; | more +2\n</code></pre>\n<p>Tested on Win 10 CMD.</p>\n" }, { "answer_id": 67532603, "author": "Jayabharathi Palanisamy", "author_id": 8830813, "author_profile": "https://Stackoverflow.com/users/8830813", "pm_score": 0, "selected": false, "text": "<p>In Windows PowerShell below cmd can be used to get the first line and replace it with a static value</p>\n<pre><code>powershell -Command &quot;(gc txt1.txt) -replace (gc txt1.txt)[0], 'This is the first line' | Out-File -encoding ASCII txt1.txt&quot;\n</code></pre>\n<p>Reference</p>\n<hr />\n<p><a href=\"https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir\">How can you find and replace text in a file using the Windows command-line environment?</a></p>\n" }, { "answer_id": 68846153, "author": "Ingmar", "author_id": 11519739, "author_profile": "https://Stackoverflow.com/users/11519739", "pm_score": 2, "selected": false, "text": "<p><code>powershell Get-Content file.txt -Head 1</code></p>\n<p>This one is much quicker than the other powershell examples above, where the full file is read.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9822/" ]
How can I read the first line from a text file using a Windows batch file? Since the file is large I only want to deal with the first line.
Here's a general-purpose batch file to print the top `n` lines from a file like the GNU `head` utility, instead of just a single line. ``` @echo off if [%1] == [] goto usage if [%2] == [] goto usage call :print_head %1 %2 goto :eof REM REM print_head REM Prints the first non-blank %1 lines in the file %2. REM :print_head setlocal EnableDelayedExpansion set /a counter=0 for /f ^"usebackq^ eol^=^ ^ delims^=^" %%a in (%2) do ( if "!counter!"=="%1" goto :eof echo %%a set /a counter+=1 ) goto :eof :usage echo Usage: head.bat COUNT FILENAME ``` For example: ``` Z:\>head 1 "test file.c" ; this is line 1 Z:\>head 3 "test file.c" ; this is line 1 this is line 2 line 3 right here ``` It does not currently count blank lines. It is also subject to the batch-file line-length restriction of 8 KB.
130,117
<p>Most people say <em>never</em> throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that <em>"the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails... There is really no good way to protect against exceptions thrown from destructors, so the library makes no guarantees if an element destructor throws" (from Appendix E3.2)</em>.</p> <p><a href="http://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml" rel="noreferrer">This article</a> seems to say otherwise - that throwing destructors are more or less okay.</p> <p><em>So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?</em></p> <p>If an error occurs during a cleanup operation, do you just ignore it? If it is an error that can potentially be handled up the stack but not right in the destructor, doesn't it make sense to throw an exception out of the destructor?</p> <p>Obviously these kinds of errors are rare, but possible.</p>
[ { "answer_id": 130123, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 9, "selected": true, "text": "<p>Throwing an exception out of a destructor is dangerous.<br />\nIf another exception is already propagating the application will terminate.</p>\n<pre><code>#include &lt;iostream&gt;\n\nclass Bad\n{\n public:\n // Added the noexcept(false) so the code keeps its original meaning.\n // Post C++11 destructors are by default `noexcept(true)` and\n // this will (by default) call terminate if an exception is\n // escapes the destructor.\n //\n // But this example is designed to show that terminate is called\n // if two exceptions are propagating at the same time.\n ~Bad() noexcept(false)\n {\n throw 1;\n }\n};\nclass Bad2\n{\n public:\n ~Bad2()\n {\n throw 1;\n }\n};\n\n\nint main(int argc, char* argv[])\n{\n try\n {\n Bad bad;\n }\n catch(...)\n {\n std::cout &lt;&lt; &quot;Print This\\n&quot;;\n }\n\n try\n {\n if (argc &gt; 3)\n {\n Bad bad; // This destructor will throw an exception that escapes (see above)\n throw 2; // But having two exceptions propagating at the\n // same time causes terminate to be called.\n }\n else\n {\n Bad2 bad; // The exception in this destructor will\n // cause terminate to be called.\n }\n }\n catch(...)\n {\n std::cout &lt;&lt; &quot;Never print this\\n&quot;;\n }\n\n}\n</code></pre>\n<p>This basically boils down to:</p>\n<p>Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly). The user of your class can then potentially handle these situations by using the public methods and catching any potential exceptions.</p>\n<p>The destructor will then finish off the object by calling these methods (if the user did not do so explicitly), but any exceptions throw are caught and dropped (after attempting to fix the problem).</p>\n<p>So in effect you pass the responsibility onto the user. If the user is in a position to correct exceptions they will manually call the appropriate functions and processes any errors. If the user of the object is not worried (as the object will be destroyed) then the destructor is left to take care of business.</p>\n<h1>An example:</h1>\n<p>std::fstream</p>\n<p>The close() method can potentially throw an exception.\nThe destructor calls close() if the file has been opened but makes sure that any exceptions do not propagate out of the destructor.</p>\n<p>So if the user of a file object wants to do special handling for problems associated to closing the file they will manually call close() and handle any exceptions. If on the other hand they do not care then the destructor will be left to handle the situation.</p>\n<p>Scott Myers has an excellent article about the subject in his book &quot;Effective C++&quot;</p>\n<h3>Edit:</h3>\n<p>Apparently also in &quot;More Effective C++&quot;<br />\n<a href=\"http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MEC/MI11_FR.HTM\" rel=\"noreferrer\">Item 11: Prevent exceptions from leaving destructors</a></p>\n" }, { "answer_id": 130145, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": false, "text": "<p>Your destructor might be executing inside a chain of other destructors. Throwing an exception that is not caught by your immediate caller can leave multiple objects in an inconsistent state, thus causing even more problems then ignoring the error in the cleanup operation.</p>\n" }, { "answer_id": 130152, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": false, "text": "<p>The real question to ask yourself about throwing from a destructor is \"What can the caller do with this?\" Is there actually anything useful you can do with the exception, that would offset the dangers created by throwing from a destructor?</p>\n\n<p>If I destroy a <code>Foo</code> object, and the <code>Foo</code> destructor tosses out an exception, what I can reasonably do with it? I can log it, or I can ignore it. That's all. I can't \"fix\" it, because the <code>Foo</code> object is already gone. Best case, I log the exception and continue as if nothing happened (or terminate the program). Is that really worth potentially causing undefined behavior by throwing from a destructor?</p>\n" }, { "answer_id": 130178, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 4, "selected": false, "text": "<p>Its dangerous, but it also doesn't make sense from a readability/code understandability standpoint.</p>\n\n<p>What you have to ask is in this situation</p>\n\n<pre><code>int foo()\n{\n Object o;\n // As foo exits, o's destructor is called\n}\n</code></pre>\n\n<p>What should catch the exception? Should the caller of foo? Or should foo handle it? Why should the caller of foo care about some object internal to foo? There might be a way the language defines this to make sense, but its going to be unreadable and difficult to understand.</p>\n\n<p>More importantly, where does the memory for Object go? Where does the memory the object owned go? Is it still allocated (ostensibly because the destructor failed)? Consider also the object was in <em>stack space</em>, so its obviously gone regardless.</p>\n\n<p>Then consider this case</p>\n\n<pre><code>class Object\n{ \n Object2 obj2;\n Object3* obj3;\n virtual ~Object()\n {\n // What should happen when this fails? How would I actually destroy this?\n delete obj3;\n\n // obj 2 fails to destruct when it goes out of scope, now what!?!?\n // should the exception propogate? \n } \n};\n</code></pre>\n\n<p>When the delete of obj3 fails, how do I actually delete in a way that is guaranteed to not fail? Its my memory dammit!</p>\n\n<p>Now consider in the first code snippet Object goes away automatically because its on the stack while Object3 is on the heap. Since the pointer to Object3 is gone, you're kind of SOL. You have a memory leak.</p>\n\n<p>Now one safe way to do things is the following</p>\n\n<pre><code>class Socket\n{\n virtual ~Socket()\n {\n try \n {\n Close();\n }\n catch (...) \n {\n // Why did close fail? make sure it *really* does close here\n }\n } \n\n};\n</code></pre>\n\n<p>Also see this <a href=\"http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.3\" rel=\"noreferrer\">FAQ</a></p>\n" }, { "answer_id": 374875, "author": "Gal Goldman", "author_id": 46418, "author_profile": "https://Stackoverflow.com/users/46418", "pm_score": 6, "selected": false, "text": "<p>Throwing out of a destructor can result in a crash, because this destructor might be called as part of \"Stack unwinding\".\nStack unwinding is a procedure which takes place when an exception is thrown.\nIn this procedure, all the objects that were pushed into the stack since the \"try\" and until the exception was thrown, will be terminated -> their destructors will be called.\nAnd during this procedure, another exception throw is not allowed, because it's not possible to handle two exceptions at a time, thus, this will provoke a call to abort(), the program will crash and the control will return to the OS. </p>\n" }, { "answer_id": 456630, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 3, "selected": false, "text": "<p>Everyone else has explained why throwing destructors are terrible... what can you do about it? If you're doing an operation that may fail, create a separate public method that performs cleanup and can throw arbitrary exceptions. In most cases, users will ignore that. If users want to monitor the success/failure of the cleanup, they can simply call the explicit cleanup routine.</p>\n\n<p>For example:</p>\n\n<pre><code>class TempFile {\npublic:\n TempFile(); // throws if the file couldn't be created\n ~TempFile() throw(); // does nothing if close() was already called; never throws\n void close(); // throws if the file couldn't be deleted (e.g. file is open by another process)\n // the rest of the class omitted...\n};\n</code></pre>\n" }, { "answer_id": 462851, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 2, "selected": false, "text": "<p>As an addition to the main answers, which are good, comprehensive and accurate, I would like to comment about the article you reference - the one that says \"throwing exceptions in destructors is not so bad\".</p>\n\n<p>The article takes the line \"what are the alternatives to throwing exceptions\", and lists some problems with each of the alternatives. Having done so it concludes that because we can't find a problem-free alternative we should keep throwing exceptions. </p>\n\n<p>The trouble is is that none of the problems it lists with the alternatives are anywhere near as bad as the exception behaviour, which, let's remember, is \"undefined behaviour of your program\". Some of the author's objections include \"aesthetically ugly\" and \"encourage bad style\". Now which would you rather have? A program with bad style, or one which exhibited undefined behaviour?</p>\n" }, { "answer_id": 739424, "author": "lothar", "author_id": 44434, "author_profile": "https://Stackoverflow.com/users/44434", "pm_score": 4, "selected": false, "text": "<p>From the ISO draft for C++ (ISO/IEC JTC 1/SC 22 N 4411)</p>\n\n<p><strong>So destructors should generally catch exceptions and not let them propagate out of the destructor.</strong></p>\n\n<blockquote>\n <p>3 The process of calling destructors for automatic objects constructed on the path from a try block to a throw-\n expression is called “stack unwinding.” [ Note: If a destructor called during stack unwinding exits with an\n exception, std::terminate is called (15.5.1). So destructors should generally catch exceptions and not let\n them propagate out of the destructor. — end note ]</p>\n</blockquote>\n" }, { "answer_id": 2182220, "author": "Matthew", "author_id": 264108, "author_profile": "https://Stackoverflow.com/users/264108", "pm_score": -1, "selected": false, "text": "<p>I currently follow the policy (that so many are saying) that classes shouldn't actively throw exceptions from their destructors but should instead provide a public \"close\" method to perform the operation that could fail...</p>\n\n<p>...but I do believe destructors for container-type classes, like a vector, should not mask exceptions thrown from classes they contain. In this case, I actually use a \"free/close\" method that calls itself recursively. Yes, I said recursively. There's a method to this madness. Exception propagation relies on there being a stack: If a single exception occurs, then both the remaining destructors will still run and the pending exception will propagate once the routine returns, which is great. If multiple exceptions occur, then (depending on the compiler) either that first exception will propagate or the program will terminate, which is okay. If so many exceptions occur that the recursion overflows the stack then something is seriously wrong, and someone's going to find out about it, which is also okay. Personally, I err on the side of errors blowing up rather than being hidden, secret, and insidious.</p>\n\n<p>The point is that the container remains neutral, and it's up to the contained classes to decide whether they behave or misbehave with regard to throwing exceptions from their destructors.</p>\n" }, { "answer_id": 2470770, "author": "MartinP", "author_id": 243879, "author_profile": "https://Stackoverflow.com/users/243879", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Q: So my question is this - if\n throwing from a destructor results in\n undefined behavior, how do you handle\n errors that occur during a destructor?</p>\n</blockquote>\n\n<p>A: There are several options:</p>\n\n<ol>\n<li><p>Let the exceptions flow out of your destructor, regardless of what's going on elsewhere. And in doing so be aware (or even fearful) that std::terminate may follow.</p></li>\n<li><p>Never let exception flow out of your destructor. May be write to a log, some big red bad text if you can. </p></li>\n<li><p><em>my fave</em> : If <code>std::uncaught_exception</code> returns false, let you exceptions flow out. If it returns true, then fall back to the logging approach.</p></li>\n</ol>\n\n<p>But is it good to throw in d'tors?</p>\n\n<p>I agree with most of the above that throwing is best avoided in destructor, where it can be. But sometimes you're best off accepting it can happen, and handle it well. I'd choose 3 above. </p>\n\n<p>There are a few odd cases where its actually a <em>great idea</em> to throw from a destructor.\nLike the \"must check\" error code. This is a value type which is returned from a function. If the caller reads/checks the contained error code, the returned value destructs silently.\n<em>But</em>, if the returned error code has not been read by the time the return values goes out of scope, it will throw some exception, <em>from its destructor</em>.</p>\n" }, { "answer_id": 4098662, "author": "Martin Ba", "author_id": 321013, "author_profile": "https://Stackoverflow.com/users/321013", "pm_score": 6, "selected": false, "text": "<p>We have to <strong>differentiate</strong> here instead of blindly following <em>general</em> advice for <em>specific</em> cases.</p>\n\n<p>Note that the following <em>ignores</em> the issue of containers of objects and what to do in the face of multiple d'tors of objects inside containers. (And it can be ignored partially, as some objects are just no good fit to put into a container.)</p>\n\n<p>The whole problem becomes easier to think about when we split classes in two types. A class dtor can have two different responsibilities:</p>\n\n<ul>\n<li>(R) release semantics (aka free that memory)</li>\n<li>(C) <em>commit</em> semantics (aka <em>flush</em> file to disk)</li>\n</ul>\n\n<p>If we view the question this way, then I think that it can be argued that (R) semantics should never cause an exception from a dtor as there is a) nothing we can do about it and b) many free-resource operations do not even provide for error checking, e.g. <em><code>void</code></em> <code>free(void* p);</code>.</p>\n\n<p>Objects with (C) semantics, like a file object that needs to successfully flush it's data or a (\"scope guarded\") database connection that does a commit in the dtor are of a different kind: We <em>can</em> do something about the error (on the application level) and we really should not continue as if nothing happened.</p>\n\n<p>If we follow the RAII route and allow for objects that have (C) semantics in their d'tors I think we then also have to allow for the odd case where such d'tors can throw. It follows that you should not put such objects into containers and it also follows that the program can still <code>terminate()</code> if a commit-dtor throws while another exception is active.</p>\n\n<hr>\n\n<p>With regard to error handling (Commit / Rollback semantics) and exceptions, there is a good talk by one <a href=\"http://erdani.com/\" rel=\"noreferrer\">Andrei Alexandrescu</a>: <em><a href=\"http://vimeo.com/channels/ndc2014/97329153\" rel=\"noreferrer\">Error Handling in C++ / Declarative Control Flow</a></em> (held at <a href=\"http://www.ndcoslo.com/poster\" rel=\"noreferrer\">NDC 2014</a>)</p>\n\n<p>In the details, he explains how the Folly library implements an <a href=\"https://github.com/facebook/folly/blob/master/folly/detail/UncaughtExceptionCounter.h\" rel=\"noreferrer\"><code>UncaughtExceptionCounter</code></a> for their <a href=\"https://github.com/facebook/folly/blob/master/folly/ScopeGuard.h\" rel=\"noreferrer\"><code>ScopeGuard</code></a> tooling.</p>\n\n<p>(I should note that <a href=\"https://github.com/panaseleus/stack_unwinding/\" rel=\"noreferrer\">others</a> also had similar ideas.)</p>\n\n<p>While the talk doesn't focus on throwing from a d'tor, it shows a tool that can be used <em>today</em> to get rid of the <a href=\"http://en.cppreference.com/w/cpp/error/uncaught_exception\" rel=\"noreferrer\">problems with when to throw</a> from a d'tor. </p>\n\n<p>In the <strike>future</strike>, there <strike>may</strike> be a std feature for this, <strike>see <a href=\"http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3614.pdf\" rel=\"noreferrer\">N3614</a>,</strike> and a <a href=\"https://groups.google.com/a/isocpp.org/forum/#!msg/std-proposals/PCpJMgzla80/-grf1-ITAYUJ\" rel=\"noreferrer\">discussion about it</a>.</p>\n\n<p>Upd '17: The C++17 std feature for this is <a href=\"http://en.cppreference.com/w/cpp/error/uncaught_exception\" rel=\"noreferrer\"><code>std::uncaught_exceptions</code></a> afaikt. I'll quickly quote the cppref article:</p>\n\n<blockquote>\n <h3>Notes</h3>\n \n <p>An example where <code>int</code>-returning <code>uncaught_exceptions</code> is used is ... ... first\n creates a guard object and records the number of uncaught exceptions\n in its constructor. The output is performed by the guard object's\n destructor unless foo() throws (<em>in which case the number of uncaught\n exceptions in the destructor is greater than what the constructor\n observed</em>)</p>\n</blockquote>\n" }, { "answer_id": 15062201, "author": "MRN", "author_id": 2103624, "author_profile": "https://Stackoverflow.com/users/2103624", "pm_score": 0, "selected": false, "text": "<p>Set an alarm event. Typically alarm events are better form of notifying failure while cleaning up objects</p>\n" }, { "answer_id": 19614326, "author": "Devesh Agrawal", "author_id": 1216931, "author_profile": "https://Stackoverflow.com/users/1216931", "pm_score": 0, "selected": false, "text": "<p>Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded, exceptions should not be thrown in destructors.</p>\n\n<p>The problem occurs when an exception is thrown from a destructor during the stack unwinding process. If that happens, the compiler is put in a situation where it doesn’t know whether to continue the stack unwinding process or handle the new exception. The end result is that your program will be terminated immediately.</p>\n\n<p>Consequently, the best course of action is just to abstain from using exceptions in destructors altogether. Write a message to a log file instead.</p>\n" }, { "answer_id": 29660507, "author": "user3726672", "author_id": 3726672, "author_profile": "https://Stackoverflow.com/users/3726672", "pm_score": -1, "selected": false, "text": "<p>Martin Ba (above) is on the right track- you architect differently for RELEASE and COMMIT logic.</p>\n\n<h2>For Release:</h2>\n\n<p>You should eat any errors. You're freeing memory, closing connections, etc. Nobody else in the system should ever SEE those things again, and you're handing back resources to the OS. If it looks like you need real error handling here, its likely a consequence of design flaws in your object model.</p>\n\n<h2>For Commit:</h2>\n\n<p>This is where you want the same kind of RAII wrapper objects that things like std::lock_guard are providing for mutexes. With those you don't put the commit logic in the dtor AT ALL. You have a dedicated API for it, then wrapper objects that will RAII commit it in THEIR dtors and handle the errors there. Remember, you can CATCH exceptions in a destructor just fine; its issuing them that's deadly. This also lets you implement policy and different error handling just by building a different wrapper (e.g. std::unique_lock vs. std::lock_guard), and ensures you won't forget to call the commit logic- which is the only half-way decent justification for putting it in a dtor in the 1st place.</p>\n" }, { "answer_id": 41429901, "author": "GaspardP", "author_id": 4660481, "author_profile": "https://Stackoverflow.com/users/4660481", "pm_score": 3, "selected": false, "text": "<p>I am in the group that considers that the \"scoped guard\" pattern throwing in the destructor is useful in many situations - particularly for unit tests. However, be aware that in C++11, throwing in a destructor results in a call to <code>std::terminate</code> since destructors are implicitly annotated with <code>noexcept</code>.</p>\n\n<p>Andrzej Krzemieński has a great post on the topic of destructors that throw: </p>\n\n<ul>\n<li><a href=\"https://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/\" rel=\"noreferrer\">https://akrzemi1.wordpress.com/2011/09/21/destructors-that-throw/</a></li>\n</ul>\n\n<p>He points out that C++11 has a mechanism to override the default <code>noexcept</code> for destructors:</p>\n\n<blockquote>\n <p>In C++11, a destructor is implicitly specified as <code>noexcept</code>. Even if you add no specification and define your destructor like this:</p>\n\n<pre><code> class MyType {\n public: ~MyType() { throw Exception(); } // ...\n };\n</code></pre>\n \n <p>The compiler will still invisibly add specification <code>noexcept</code> to your destructor. And this means that the moment your destructor throws an exception, <code>std::terminate</code> will be called, even if there was no double-exception situation. If you are really determined to allow your destructors to throw, you will have to specify this explicitly; you have three options:</p>\n \n <ul>\n <li>Explicitly specify your destructor as <code>noexcept(false)</code>,</li>\n <li>Inherit your class from another one that already specifies its destructor as <code>noexcept(false)</code>.</li>\n <li>Put a non-static data member in your class that already specifies its destructor as <code>noexcept(false)</code>.</li>\n </ul>\n</blockquote>\n\n<p>Finally, if you do decide to throw in the destructor, you should always be aware of the risk of a double-exception (throwing while the stack is being unwind because of an exception). This would cause a call to <code>std::terminate</code> and it is rarely what you want. To avoid this behaviour, you can simply check if there is already an exception before throwing a new one using <code>std::uncaught_exception()</code>.</p>\n" }, { "answer_id": 48114956, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>So my question is this - if throwing from a destructor results in\n undefined behavior, how do you handle errors that occur during a\n destructor?</p>\n</blockquote>\n\n<p>The main problem is this: you can't <em>fail to fail</em>. What does it mean to fail to fail, after all? If committing a transaction to a database fails, and it fails to fail (fails to rollback), what happens to the integrity of our data?</p>\n\n<p>Since destructors are invoked for both normal and exceptional (fail) paths, they themselves cannot fail or else we're \"failing to fail\".</p>\n\n<p>This is a conceptually difficult problem but often the solution is to just find a way to make sure that failing cannot fail. For example, a database might write changes prior to committing to an external data structure or file. If the transaction fails, then the file/data structure can be tossed away. All it has to then ensure is that committing the changes from that external structure/file an atomic transaction that can't fail.</p>\n\n<blockquote>\n <p>The pragmatic solution is perhaps just make sure that the chances of\n failing on failure are astronomically improbable, since making things\n impossible to fail to fail can be almost impossible in some cases.</p>\n</blockquote>\n\n<p>The most proper solution to me is to write your non-cleanup logic in a way such that the cleanup logic can't fail. For example, if you're tempted to create a new data structure in order to clean up an existing data structure, then perhaps you might seek to create that auxiliary structure in advance so that we no longer have to create it inside a destructor.</p>\n\n<p>This is all much easier said than done, admittedly, but it's the only really proper way I see to go about it. Sometimes I think there should be an ability to write separate destructor logic for normal execution paths away from exceptional ones, since sometimes destructors feel a little bit like they have double the responsibilities by trying to handle both (an example is scope guards which require explicit dismissal; they wouldn't require this if they could differentiate exceptional destruction paths from non-exceptional ones).</p>\n\n<p>Still the ultimate problem is that we can't fail to fail, and it's a hard conceptual design problem to solve perfectly in all cases. It does get easier if you don't get too wrapped up in complex control structures with tons of teeny objects interacting with each other, and instead model your designs in a slightly bulkier fashion (example: particle system with a destructor to destroy the entire particle system, not a separate non-trivial destructor per particle). When you model your designs at this kind of coarser level, you have less non-trivial destructors to deal with, and can also often afford whatever memory/processing overhead is required to make sure your destructors cannot fail.</p>\n\n<p>And that's one of the easiest solutions naturally is to use destructors less often. In the particle example above, perhaps upon destroying/removing a particle, some things should be done that could fail for whatever reason. In that case, instead of invoking such logic through the particle's dtor which could be executed in an exceptional path, you could instead have it all done by the particle system when it <em>removes</em> a particle. Removing a particle might always be done during a non-exceptional path. If the system is destroyed, maybe it can just purge all particles and not bother with that individual particle removal logic which can fail, while the logic that can fail is only executed during the particle system's normal execution when it's removing one or more particles.</p>\n\n<p>There are often solutions like that which crop up if you avoid dealing with lots of teeny objects with non-trivial destructors. Where you can get tangled up in a mess where it seems almost impossible to be exception-safety is when you do get tangled up in lots of teeny objects that all have non-trivial dtors.</p>\n\n<p>It would help a lot if nothrow/noexcept actually translated into a compiler error if anything which specifies it (including virtual functions which should inherit the noexcept specification of its base class) attempted to invoke anything that could throw. This way we'd be able to catch all this stuff at compile-time if we actually write a destructor inadvertently which could throw.</p>\n" }, { "answer_id": 68946906, "author": "Arthur P. Golubev", "author_id": 1790694, "author_profile": "https://Stackoverflow.com/users/1790694", "pm_score": 1, "selected": false, "text": "<p>Throwing an exception out of a destructor never causes undefined behaviour.</p>\n<p>The problem of throwing exceptions out a destructor is that destructors of successfully created objects which scopes are leaving while handling an uncaught exception (it is after an exception object is created and until completion of a handler of the exception activation), are called by exception handling mechanism; and, If such additional exception from the destructor called while processing the uncaught exception interrupts handling the uncaught exception, it will cause calling <code>std::terminate</code> (the other case when <code>std::exception</code> is called is that an exception is not handled by any handler but this is as for any other function, regardless of whether or not it was a destructor).</p>\n<hr />\n<p>If handling an uncaught exception in progress, your code never knows whether the additional exception will be caught or will archive an uncaught exception handling mechanism, so never know definitely whether it is safe to throw or not.</p>\n<p>Though, it is possible to know that handling an uncaught exception is in progress ( <a href=\"https://en.cppreference.com/w/cpp/error/uncaught_exception\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/error/uncaught_exception</a>), so you are able to overkill by checking the condition and throw only if it is not the case (it will not throw in some cases when it would be safe).</p>\n<p>But in practice such separating into two possible behaviours is not useful - it just does not help you to make a well-designed program.</p>\n<hr />\n<p>If you throw out of destructors ignoring whether or not an uncaught exception handling is in progress, in order to avoid possible calling <code>std::terminate</code>, you must guarantee that all exceptions thrown during lifetime of an object that may throw an exception from their destructor are caught before beginning of destruction of the object.\nIt is quite limited usage; you hardly can use all classes which would be reasonably allowed to throw out of their destructor in this way; and a combination of allowing such exceptions only for some classes with such restricted usage of these classes impede making a well-designed program, too.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
Most people say *never* throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that *"the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails... There is really no good way to protect against exceptions thrown from destructors, so the library makes no guarantees if an element destructor throws" (from Appendix E3.2)*. [This article](http://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml) seems to say otherwise - that throwing destructors are more or less okay. *So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?* If an error occurs during a cleanup operation, do you just ignore it? If it is an error that can potentially be handled up the stack but not right in the destructor, doesn't it make sense to throw an exception out of the destructor? Obviously these kinds of errors are rare, but possible.
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. ``` #include <iostream> class Bad { public: // Added the noexcept(false) so the code keeps its original meaning. // Post C++11 destructors are by default `noexcept(true)` and // this will (by default) call terminate if an exception is // escapes the destructor. // // But this example is designed to show that terminate is called // if two exceptions are propagating at the same time. ~Bad() noexcept(false) { throw 1; } }; class Bad2 { public: ~Bad2() { throw 1; } }; int main(int argc, char* argv[]) { try { Bad bad; } catch(...) { std::cout << "Print This\n"; } try { if (argc > 3) { Bad bad; // This destructor will throw an exception that escapes (see above) throw 2; // But having two exceptions propagating at the // same time causes terminate to be called. } else { Bad2 bad; // The exception in this destructor will // cause terminate to be called. } } catch(...) { std::cout << "Never print this\n"; } } ``` This basically boils down to: Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly). The user of your class can then potentially handle these situations by using the public methods and catching any potential exceptions. The destructor will then finish off the object by calling these methods (if the user did not do so explicitly), but any exceptions throw are caught and dropped (after attempting to fix the problem). So in effect you pass the responsibility onto the user. If the user is in a position to correct exceptions they will manually call the appropriate functions and processes any errors. If the user of the object is not worried (as the object will be destroyed) then the destructor is left to take care of business. An example: =========== std::fstream The close() method can potentially throw an exception. The destructor calls close() if the file has been opened but makes sure that any exceptions do not propagate out of the destructor. So if the user of a file object wants to do special handling for problems associated to closing the file they will manually call close() and handle any exceptions. If on the other hand they do not care then the destructor will be left to handle the situation. Scott Myers has an excellent article about the subject in his book "Effective C++" ### Edit: Apparently also in "More Effective C++" [Item 11: Prevent exceptions from leaving destructors](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MEC/MI11_FR.HTM)
130,132
<p>My form receives asynchronous callbacks from another object on random worker threads. I have been passing the data to the main thread (where it can be used to update onscreen controls) using delegates as shown below. Performance is dreadful -- once I reach 500 updates per second, the program completely locks up. My GUI processing itself is not the problem, as I can simulate this level of updating within the form and have no problems. Is there a more efficient mechanism I should be using to hand off the data from thread to thread?</p> <pre><code>delegate void DStatus( MyStatus obj ); DStatus _status; // set to MainThreadOnStatus during construction // this function only called on form's owner thread void MainThreadOnStatus( MyStatus obj ) { // screen updates here as needed } // this function called by arbitrary worker threads in external facility void OnStatus( MyStatus obj ) { this.BeginInvoke( _status, obj ); } </code></pre>
[ { "answer_id": 130175, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": true, "text": "<p>You probably don't need to update UI on every event, but rather \"not as often as X times per second\". You may utilize StopWatch or other timing system to collect events during a period of time, and then update UI when appropriate. </p>\n\n<p>If you need to capture all events, collect them in the Queue and fire event every so often, and that event handler will process the Queue and update UI once for all queued events. </p>\n" }, { "answer_id": 130247, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 0, "selected": false, "text": "<p>It is difficult to tell the exact problem, but some possibilities...</p>\n\n<p>Is your <code>MyStatus</code> object that you are passing to OnStatus derived from <code>MarshalByRefObject</code> (and every object in it)? If not it will be serailized on every call that is marshaled and that can cause a huge performance hit.</p>\n\n<p>Also, you should really call <code>this.InvokeRequired</code> before invoking the delegate using the control, but really that is just a best practice.</p>\n" }, { "answer_id": 130249, "author": "Andrew Queisser", "author_id": 18321, "author_profile": "https://Stackoverflow.com/users/18321", "pm_score": 1, "selected": false, "text": "<p>I've been doing what Ilya has been suggesting. For UIs that don't have to respond \"real time\" I have a stopwatch that goes twice a second or so. For faster updates I use a queue or other datastructure that stores the event data and then use \"lock (queue) { }\" to avoid contention. If you don't want to slow down the worker threads you have to make sure that the UI thread doesn't block the workers too long.</p>\n" }, { "answer_id": 137922, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I’m not a big fan of timers, if you want a more event driven approach, try something like this:</p>\n\n<pre><code>public class Foo\n{\n private AsyncOperation _asyncOperation = null;\n private SendOrPostCallback _notifyNewItem = null;\n\n //Make sure you call this on your UI thread.\n //Alternatively you can call something like the AttachUI() below later on and catch-up with\n //your workers later.\n public Foo()\n {\n this._notifyNewItem = new SendOrPostCallback(this.NewDataInTempList);\n this._asyncOperation = AsyncOperationManager.CreateOperation(this);\n }\n\n public void AttachUI()\n {\n if (this._asyncOperation != null)\n {\n this._asyncOperation.OperationCompleted();\n this._asyncOperation = null;\n }\n\n this._asyncOperation = AsyncOperationManager.CreateOperation(this);\n //This is for catching up with the workers if they’ve been busy already\n if (this._asyncOperation != null)\n {\n this._asyncOperation.Post(this._notifyNewItem, null);\n }\n }\n\n\n private int _tempCapacity = 500;\n private object _tempListLock = new object();\n private List&lt;MyStatus&gt; _tempList = null;\n\n //This gets called on the worker threads..\n //Keeps adding to the same list until UI grabs it, then create a new one.\n public void Add(MyStatus status)\n {\n bool notify = false;\n lock (_tempListLock)\n {\n if (this._tempList == null)\n {\n this._tempList = new List&lt;MyStatus&gt;(this._tempCapacity);\n notify = true;\n }\n\n this._tempList.Add(status);\n }\n if (notify)\n {\n if (this._asyncOperation != null)\n {\n this._asyncOperation.Post(this._notifyNewItem, null);\n }\n }\n }\n\n //This gets called on your UI thread.\n private void NewDataInTempList(object o)\n {\n List&lt;MyStatus&gt; statusList = null;\n lock (this._tempListLock)\n {\n //Grab the list, and release the lock as soon as possible.\n statusList = this._tempList;\n this._tempList = null;\n }\n if (statusList != null)\n {\n //Deal with it here at your leasure\n }\n }\n}\n</code></pre>\n\n<p>I’ve used this in a custom Log4Net logger collecting log entries and adding them to a circular array that’s bound to a grid. The performance ended up being pretty good for what it does.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
My form receives asynchronous callbacks from another object on random worker threads. I have been passing the data to the main thread (where it can be used to update onscreen controls) using delegates as shown below. Performance is dreadful -- once I reach 500 updates per second, the program completely locks up. My GUI processing itself is not the problem, as I can simulate this level of updating within the form and have no problems. Is there a more efficient mechanism I should be using to hand off the data from thread to thread? ``` delegate void DStatus( MyStatus obj ); DStatus _status; // set to MainThreadOnStatus during construction // this function only called on form's owner thread void MainThreadOnStatus( MyStatus obj ) { // screen updates here as needed } // this function called by arbitrary worker threads in external facility void OnStatus( MyStatus obj ) { this.BeginInvoke( _status, obj ); } ```
You probably don't need to update UI on every event, but rather "not as often as X times per second". You may utilize StopWatch or other timing system to collect events during a period of time, and then update UI when appropriate. If you need to capture all events, collect them in the Queue and fire event every so often, and that event handler will process the Queue and update UI once for all queued events.
130,166
<p>I am trying to write a macro that would "click" a command button that is in another workbook. Is that possible? Without changing any of the code within that other workbook?</p>
[ { "answer_id": 130325, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 1, "selected": false, "text": "<p>You can use <code>Application.Run</code> for that:</p>\n\n<pre><code>Run \"OtherWorkbook.xls!MyOtherMacro\"\n</code></pre>\n" }, { "answer_id": 130330, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>You sure you mean workbook and not sheet?\nAnyways if you \"<a href=\"http://www.contextures.com/xlfaqMac.html#LoopBooks\" rel=\"nofollow noreferrer\">want to loop through all workbooks in a folder and perform an operation on each of them</a>\"</p>\n\n<p>If you want to access another sheet it's done like this:</p>\n\n<pre><code>Worksheets(\"MySheet\").YourMethod()\n</code></pre>\n" }, { "answer_id": 130443, "author": "msulis", "author_id": 9317, "author_profile": "https://Stackoverflow.com/users/9317", "pm_score": -1, "selected": false, "text": "<p>There's not a clean way to do this through code, since the button's click event would typically be a private method of the other workbook.</p>\n\n<p><em>However</em>, you can automate the click through VBA code by opening the workbook, finding the control you want, and then activating it and sending it a space character (equivalent to pressing the button).</p>\n\n<p>This is almost certainly a terrible idea, and it will probably bring you and your offspring nothing but misery. I'd urge you to find a better solution, but in the meantime, this seems to work...</p>\n\n<pre><code>Public Sub RunButton(workbookName As String, worksheetName As String, controlName As String)\n Dim wkb As Workbook\n Dim wks As Worksheet\n Set wkb = Workbooks.Open(workbookName)\n wkb.Activate\n Dim obj As OLEObject\n For Each wks In wkb.Worksheets\n If wks.Name = worksheetName Then\n wks.Activate\n For Each obj In wks.OLEObjects\n If (obj.Name = controlName) Then\n obj.Activate\n SendKeys (\" \")\n End If\n Next obj\n End If\n Next wks\nEnd Sub\n</code></pre>\n" }, { "answer_id": 130699, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 1, "selected": false, "text": "<p>Instead of trying to programatically click the button, it is possible to run the macro linked to the button directly from your code.</p>\n\n<p>First you need to find the name of the macro that is run when the button is clicked.</p>\n\n<p>To do this, open the workbook that contains the command button.</p>\n\n<p>Right click on the command button and select <strong>'Assign macro'</strong></p>\n\n<p>The <strong>'Assign macro'</strong> dialog will be displayed.</p>\n\n<p>Make a note of the full name in the <strong>'Macro name'</strong> box at the top of the dialog.</p>\n\n<p>Click on the <strong>OK</strong> button.</p>\n\n<p>Your code in the workbook that needs to call the code should be as follows.</p>\n\n<pre><code>Sub Run_Macro()\n\n Workbooks.Open Filename:=\"C:\\Book1.xls\"\n'Open the workbook containing the command button\n'Change the path and filename as required\n\n Application.Run \"Book1.xls!Macro1\"\n'Run the macro \n'Change the filename and macro name as required\n\n'If the macro is attached to a worksheet rather than a module, the code would be\n'Application.Run \"Book1.xls!Sheet1.Macro1\"\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 2640395, "author": "DP.", "author_id": 316869, "author_profile": "https://Stackoverflow.com/users/316869", "pm_score": 0, "selected": false, "text": "<p>NOPE:</p>\n\n<p>This is EASY to do:</p>\n\n<ol>\n<li><p>In the worksheet ABC where you have the <code>Private Sub xyz_Click()</code>, add a new public subroutine:</p>\n\n<pre><code>Public Sub ForceClickOnBouttonXYZ()\n Call xyz_Click\nEnd Sub\n</code></pre></li>\n<li><p>In your other worksheet or module, add the code:</p>\n\n<pre><code>Sheets(\"ABC\").Activate\nCall Sheets(\"ABC\").ForceClickOnBouttonXYZ\n</code></pre></li>\n</ol>\n\n<p>THAT IS IT!!!\nIf you do not want the screen to flicker or show any activity, set the <code>Application.ScreenUpdating = False</code> before you call the <code>Sheets(\"ABC\").ForceClickOnBouttonXYZ</code> routine and then set <code>Application.ScreenUpdating = True</code> right after it.</p>\n" }, { "answer_id": 32892880, "author": "Robert Ovington", "author_id": 5398425, "author_profile": "https://Stackoverflow.com/users/5398425", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem as above and it took a while to figure out but this is all I had to do.</p>\n\n<p>On Sheet1 I created a button with the following:</p>\n\n<pre><code> Private Sub cmdRefreshAll_Click()\n Dim SheetName As String\n\n SheetName = \"Mon\"\n Worksheets(SheetName).Activate\n ActiveSheet.cmdRefresh_Click\n\n SheetName = \"Tue\"\n Worksheets(SheetName).Activate\n ActiveSheet.cmdRefresh_Click\n\n' \"I repeated the above code to loop through a worksheet for every day of the week\"\n\n End Sub\n</code></pre>\n\n<p>Then the importing bit to get it to work you need to go to the code on the other worksheets and change it from Private to Public.</p>\n\n<p>So far no bugs have popped up.</p>\n" }, { "answer_id": 33355307, "author": "Tristan Reischl", "author_id": 4764487, "author_profile": "https://Stackoverflow.com/users/4764487", "pm_score": 3, "selected": false, "text": "<p>For an ActiveX button in another workbook:</p>\n\n<pre><code>Workbooks(\"OtherBook\").Worksheets(\"Sheet1\").CommandButton1.Value = True\n</code></pre>\n\n<p>For an MSForms button in another workbook:</p>\n\n<pre><code>Application.Run Workbooks(\"OtherBook\").Worksheets(\"Sheet1\").Shapes(\"Button 1\").OnAction\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to write a macro that would "click" a command button that is in another workbook. Is that possible? Without changing any of the code within that other workbook?
For an ActiveX button in another workbook: ``` Workbooks("OtherBook").Worksheets("Sheet1").CommandButton1.Value = True ``` For an MSForms button in another workbook: ``` Application.Run Workbooks("OtherBook").Worksheets("Sheet1").Shapes("Button 1").OnAction ```
130,186
<p>I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Microsoft against IE8. If you can, please vote for this issue so that it can be fixed.</p> <p><a href="https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995" rel="nofollow noreferrer">https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995</a></p> <p>I've written a test case to demonstrate the effect:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;iframe id="editable"&gt; &lt;html&gt; &lt;body&gt; &lt;div id="test"&gt; Click to the right of this line -&amp;gt; &lt;p id="par"&gt;Block Element&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;/iframe&gt; &lt;input id="mytrigger" type="button" value="Then Click here to Save and Restore" /&gt; &lt;script type="text/javascript"&gt; window.onload = function() { var iframe = document.getElementById('editable'); var doc = iframe.contentDocument || iframe.contentWindow.document; // An IFRAME without a source points to a blank document. Here we'll // copy the content we stored in between the IFRAME tags into that // document. It's a hack to allow us to use only one HTML file for this // test. doc.body.innerHTML = iframe.textContent || iframe.innerHTML; // Marke the IFRAME as an editable document if (doc.body.contentEditable) { doc.body.contentEditable = true; } else { var mydoc = doc; doc.designMode = 'On'; } // A function to demonstrate the bug. var myhandler = function() { // Step 1 Get the current selection var selection = doc.selection || iframe.contentWindow.getSelection(); var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0); // Step 2 Restore the selection if (range.select) { range.select(); } else { selection.removeAllRanges(); selection.addRange(range); doc.body.focus(); } } // Set up the button to perform the test code. var button = document.getElementById('mytrigger'); if (button.addEventListener) { button.addEventListener('click', myhandler, false); } else { button.attachEvent('onclick', myhandler); } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem is exposed in the myhandler function. This is all that I'm doing, there is no Step 3 in between the saving and restoring the selection, and yet the cursor moves. It doesn't seem to happen unless the selection is empty (ie. I have a blinking cursor, but no text), and it only seems to happen whenever the cursor is at the end of a text node that immediately precedes a block node.</p> <p>It seems that the range is still in the correct position (if I call parentElement on the range it returns the div), but if I get a new range from the current selection, the new range is inside the paragraph tag, and that is its parentElement.</p> <p><strong>How do I work around this and consistently save and restore the selection in internet explorer?</strong></p>
[ { "answer_id": 149310, "author": "Dave R", "author_id": 6969, "author_profile": "https://Stackoverflow.com/users/6969", "pm_score": 0, "selected": false, "text": "<p>I recently worked at a site which used Microsoft CMS with the \"MSIB+ pack\" of controls which included a WYSIWYG editor which ran in Internet Explorer.</p>\n\n<p>I seem to remember some comments in the editor client-side Javascript which were specifically related to this bug in IE and the Range.Select() method.</p>\n\n<p>Unfortunately, I'm not working there anymore so I can't access the Javascript files, but perhaps you may be able to get them from elsewhere?</p>\n\n<p>Good luck</p>\n" }, { "answer_id": 822802, "author": "Alconja", "author_id": 68727, "author_profile": "https://Stackoverflow.com/users/68727", "pm_score": 1, "selected": false, "text": "<p>I've had a bit of a dig &amp; unfortunately can't see a workaround... Although one thing I noticed while debugging the javascript, it seems like the problem is actually with the range object itself rather than with the subsequent <code>range.select()</code>. If you look at the values on the range object that <code>selection.createRange()</code> returns, yes the parent dom object may be correct, but the positioning info is already referring to the start of the next line (i.e. offsetLeft/Top, boundingLeft/Top, etc are already wrong).</p>\n\n<p>Based on the info <a href=\"http://www.quirksmode.org/dom/range_intro.html\" rel=\"nofollow noreferrer\">here</a>, <a href=\"http://www.quirksmode.org/dom/w3c_range.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx\" rel=\"nofollow noreferrer\">here</a>, I think you're out of luck with IE, since you only have access to Microsoft's TextRange object, which appears to be broken. From my experimentation, you can move the range around and position it exactly where it should be, but once you do so, the range object automatically shifts down to the next line even before you've tried to <code>.select()</code> it. For example, you can see the problem by putting this code in between your Step 1 &amp; Step 2:</p>\n\n<pre><code>if (range.boundingWidth == 0)\n{\n //looks like its already at the start of the next line down...\n alert('default position: ' + range.offsetLeft + ', ' + range.offsetTop);\n //lets move the start of the range one character back\n //(i.e. select the last char on the line)\n range.moveStart(\"character\", -1);\n //now the range looks good (except that its width will be one char);\n alert('one char back: ' + range.offsetLeft + ', ' + range.offsetTop);\n //calculate the true end of the line...\n var left = range.offsetLeft + range.boundingWidth;\n var top = range.offsetTop;\n //now we can collapse back down to 0 width range\n range.collapse();\n //the position looks right\n alert('moving to: ' + left + ', ' + top);\n //move there.\n range.moveToPoint(left, top);\n //oops... on the next line again... stupid IE.\n alert('moved to: ' + range.offsetLeft + ', ' + range.offsetTop);\n}\n</code></pre>\n\n<p>So, unfortunately it doesn't look like there's any way to ensure that the range is in the right spot when you select it again.</p>\n\n<p>Obviously there's the trivial fix to your code above, by changing Step 2 it to this:</p>\n\n<pre><code>// Step 2 Restore the selection\nif (range.select) {\n if (range.boundingWidth &gt; 0) {\n range.select();\n }\n} else {\n selection.removeAllRanges();\n selection.addRange(range);\n doc.body.focus();\n}\n</code></pre>\n\n<p>But presumably, you actually want to do something between Step 1 &amp; Step 2 in your actual which involves moving the selection, hence the need to re-set it. But just in case. :)</p>\n\n<p>So, the best I can do is go &amp; vote for the bug you created... Hopefully they'll fix it.</p>\n" }, { "answer_id": 827264, "author": "Dan Eisenberg", "author_id": 101887, "author_profile": "https://Stackoverflow.com/users/101887", "pm_score": 5, "selected": true, "text": "<p>I've figured out a few methods for dealing with IE ranges like this.</p>\n\n<p>If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again:</p>\n\n<pre><code>// Save position of cursor\nrange.pasteHTML('&lt;span id=\"caret\"&gt;&lt;/span&gt;')\n\n...\n\n// Create new cursor and put it in the old position\nvar caretSpan = iframe.contentWindow.document.getElementById(\"caret\");\nvar selection = iframe.contentWindow.document.selection;\nnewRange = selection.createRange();\nnewRange.moveToElementText(caretSpan);\n</code></pre>\n\n<p>Alternatively, you can count how many characters precede the current cursor position and save that number:</p>\n\n<pre><code>var selection = iframe.contentWindow.document.selection;\nvar range = selection.createRange().duplicate();\nrange.moveStart('sentence', -1000000);\nvar cursorPosition = range.text.length;\n</code></pre>\n\n<p>To restore the cursor, you set it to the beginning and then move it that number of characters:</p>\n\n<pre><code>var newRange = selection.createRange();\nnewRange.move('sentence', -1000000);\nnewRange.move('character', cursorPosition);\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 829019, "author": "mercator", "author_id": 23263, "author_profile": "https://Stackoverflow.com/users/23263", "pm_score": 0, "selected": false, "text": "<p>Maybe I misunderstand, but if I click to the right of that first line, my cursor already immediately appears at the start of the second line, so that's not a TextRange issue, right?</p>\n\n<p>Adding a doctype so the test page is rendered in standards mode instead of quirks mode fixes that for me.</p>\n\n<p>And I can't reproduce what your myhandler function does, because clicking that button moves the focus away to the button so I can no longer see the cursor and can't get it back either. Finding the cursor position in a <em>contentEditable</em> area <a href=\"http://www.google.com/search?q=ie+cursor+position+contenteditable\" rel=\"nofollow noreferrer\">seems to be a different problem altogether</a>.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8458/" ]
I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Microsoft against IE8. If you can, please vote for this issue so that it can be fixed. <https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995> I've written a test case to demonstrate the effect: ``` <html> <body> <iframe id="editable"> <html> <body> <div id="test"> Click to the right of this line -&gt; <p id="par">Block Element</p> </div> </body> </html> </iframe> <input id="mytrigger" type="button" value="Then Click here to Save and Restore" /> <script type="text/javascript"> window.onload = function() { var iframe = document.getElementById('editable'); var doc = iframe.contentDocument || iframe.contentWindow.document; // An IFRAME without a source points to a blank document. Here we'll // copy the content we stored in between the IFRAME tags into that // document. It's a hack to allow us to use only one HTML file for this // test. doc.body.innerHTML = iframe.textContent || iframe.innerHTML; // Marke the IFRAME as an editable document if (doc.body.contentEditable) { doc.body.contentEditable = true; } else { var mydoc = doc; doc.designMode = 'On'; } // A function to demonstrate the bug. var myhandler = function() { // Step 1 Get the current selection var selection = doc.selection || iframe.contentWindow.getSelection(); var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0); // Step 2 Restore the selection if (range.select) { range.select(); } else { selection.removeAllRanges(); selection.addRange(range); doc.body.focus(); } } // Set up the button to perform the test code. var button = document.getElementById('mytrigger'); if (button.addEventListener) { button.addEventListener('click', myhandler, false); } else { button.attachEvent('onclick', myhandler); } } </script> </body> </html> ``` The problem is exposed in the myhandler function. This is all that I'm doing, there is no Step 3 in between the saving and restoring the selection, and yet the cursor moves. It doesn't seem to happen unless the selection is empty (ie. I have a blinking cursor, but no text), and it only seems to happen whenever the cursor is at the end of a text node that immediately precedes a block node. It seems that the range is still in the correct position (if I call parentElement on the range it returns the div), but if I get a new range from the current selection, the new range is inside the paragraph tag, and that is its parentElement. **How do I work around this and consistently save and restore the selection in internet explorer?**
I've figured out a few methods for dealing with IE ranges like this. If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again: ``` // Save position of cursor range.pasteHTML('<span id="caret"></span>') ... // Create new cursor and put it in the old position var caretSpan = iframe.contentWindow.document.getElementById("caret"); var selection = iframe.contentWindow.document.selection; newRange = selection.createRange(); newRange.moveToElementText(caretSpan); ``` Alternatively, you can count how many characters precede the current cursor position and save that number: ``` var selection = iframe.contentWindow.document.selection; var range = selection.createRange().duplicate(); range.moveStart('sentence', -1000000); var cursorPosition = range.text.length; ``` To restore the cursor, you set it to the beginning and then move it that number of characters: ``` var newRange = selection.createRange(); newRange.move('sentence', -1000000); newRange.move('character', cursorPosition); ``` Hope this helps.
130,187
<p>I want to index this view but because it has subquery i cant index. Can anyone suggest how to change this view so that i can index it.</p> <pre><code>ALTER VIEW [dbo].[Recon2] WITH SCHEMABINDING AS SELECT dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Transactions.TransType, dbo.Transactions.Copies, SUM(dbo.Transactions.TotalAmount) AS TotalAmount, '0' AS ReceiptNo, '2008-01-01' AS PaymentDate, 0 AS Amount, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, COUNT_BIG(*) AS COUNT FROM dbo.Publication_Master INNER JOIN dbo.Customer_Master INNER JOIN dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode WHERE (dbo.Customer_Master.CustomerCode NOT IN (SELECT CustomerCode FROM dbo.StreetSaleRcpt WHERE (PubCode = dbo.Transactions.PubCode) AND (TransactionDate = dbo.Transactions.TransDate) AND (Updated = 1) AND (PeriodMonth = dbo.Transactions.Period) AND (PeriodYear = dbo.Transactions.Year))) GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType, dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount </code></pre>
[ { "answer_id": 130279, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>I can't run it (obviously) but what about this?: </p>\n\n<pre><code>SELECT\ndbo.Transactions.CustomerCode, \ndbo.Customer_Master.CustomerName, \ndbo.Transactions.TransDate, \ndbo.Transactions.PubCode, \ndbo.Transactions.TransType, \ndbo.Transactions.Copies, \n'0' AS ReceiptNo, \n'2008-01-01' AS PaymentDate, \n0 AS Amount, \ndbo.Transactions.Period, \ndbo.Transactions.Year, \ndbo.Publication_Master.PubName, \ndbo.Customer_Master.SalesCode, \ndbo.StreetSaleRcpt.CustomerCode,\nSUM(dbo.Transactions.TotalAmount) AS TotalAmount, \nCOUNT_BIG(*) AS COUNT \nFROM dbo.Publication_Master \nINNER JOIN dbo.Customer_Master ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode \nINNER JOIN dbo.Transactions ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode \nLEFT OUTER JOIN dbo.StreetSaleRcpt ON (\n dbo.StreetSaleRcpt.PubCode = dbo.Transactions.PubCode \n AND dbo.StreetSaleRcpt.TransactionDate = dbo.Transactions.TransDate\n AND dbo.StreetSaleRcpt.PeriodMonth = dbo.Transactions.Period\n AND dbo.StreetSaleRcpt.PeriodYear = dbo.Transactions.Year\n AND dbo.StreetSaleRcpt.Updated = 1\n AND dbo.StreetSaleRcpt.CustomerCode = dbo.Customer_Master.CustomerCode\n)\nWHERE dbo.StreetSaleRcpt.CustomerCode IS NULL\nGROUP BY \ndbo.Transactions.CustomerCode, \ndbo.Customer_Master.CustomerName, \ndbo.Transactions.TransDate, \ndbo.Transactions.PubCode, \ndbo.Publication_Master.PubName, \ndbo.Customer_Master.SalesCode, \ndbo.Transactions.[Update], \ndbo.Transactions.TransType, \ndbo.Transactions.Copies, \ndbo.Transactions.Period, \ndbo.Transactions.Year, \ndbo.Transactions.TotalAmount,\ndbo.StreetSaleRcpt.CustomerCode\n</code></pre>\n\n<p>Make your correlated sub-query a left join and test for its absence ('WHERE dbo.StreetSaleRcpt.CustomerCode IS NULL') versus 'NOT IN'.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 130305, "author": "igelkott", "author_id": 2052165, "author_profile": "https://Stackoverflow.com/users/2052165", "pm_score": 0, "selected": false, "text": "<p>At least in Oracle, you can change from VIEW to MATERIALIZED VIEW. There will be a few other issues like table space and methods of synchronization to consider but it might be worth exploring.</p>\n\n<p>Depending on your application, another option would be to create a normal table based on the select of this view and either update it at an acceptable interval or use a lot of foreign keys.</p>\n\n<p>What's most practical depends on a number of factors -- table size, frequency of updates, need for most current data, etc.</p>\n" }, { "answer_id": 132733, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>This form would allow use of an index on StreetSaleRcpt for each Publication_Master row:</p>\n\n<pre><code>ALTER VIEW [dbo].[Recon2] WITH SCHEMABINDING AS SELECT\ndbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Transactions.TransType, dbo.Transactions.Copies, SUM(dbo.Transactions.TotalAmount) AS TotalAmount, '0' AS ReceiptNo, '2008-01-01' AS PaymentDate, 0 AS Amount, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, COUNT_BIG(*) AS COUNT\nFROM dbo.Publication_Master \nINNER JOIN dbo.Customer_Master \nINNER JOIN dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode \nWHERE\n(NOT EXISTS \n (SELECT NULL FROM dbo.StreetSaleRcpt \n WHERE (PubCode = dbo.Transactions.PubCode) \n AND (TransactionDate = dbo.Transactions.TransDate) \n AND (Updated = 1)\n AND (PeriodMonth = dbo.Transactions.Period) \n AND (PeriodYear = dbo.Transactions.Year)\n ANMD (CustomerCode = dbo.Customer_Master.CustomerCode)\n )\n) GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType, dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
I want to index this view but because it has subquery i cant index. Can anyone suggest how to change this view so that i can index it. ``` ALTER VIEW [dbo].[Recon2] WITH SCHEMABINDING AS SELECT dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Transactions.TransType, dbo.Transactions.Copies, SUM(dbo.Transactions.TotalAmount) AS TotalAmount, '0' AS ReceiptNo, '2008-01-01' AS PaymentDate, 0 AS Amount, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, COUNT_BIG(*) AS COUNT FROM dbo.Publication_Master INNER JOIN dbo.Customer_Master INNER JOIN dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode WHERE (dbo.Customer_Master.CustomerCode NOT IN (SELECT CustomerCode FROM dbo.StreetSaleRcpt WHERE (PubCode = dbo.Transactions.PubCode) AND (TransactionDate = dbo.Transactions.TransDate) AND (Updated = 1) AND (PeriodMonth = dbo.Transactions.Period) AND (PeriodYear = dbo.Transactions.Year))) GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType, dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount ```
I can't run it (obviously) but what about this?: ``` SELECT dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Transactions.TransType, dbo.Transactions.Copies, '0' AS ReceiptNo, '2008-01-01' AS PaymentDate, 0 AS Amount, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.StreetSaleRcpt.CustomerCode, SUM(dbo.Transactions.TotalAmount) AS TotalAmount, COUNT_BIG(*) AS COUNT FROM dbo.Publication_Master INNER JOIN dbo.Customer_Master ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode INNER JOIN dbo.Transactions ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode LEFT OUTER JOIN dbo.StreetSaleRcpt ON ( dbo.StreetSaleRcpt.PubCode = dbo.Transactions.PubCode AND dbo.StreetSaleRcpt.TransactionDate = dbo.Transactions.TransDate AND dbo.StreetSaleRcpt.PeriodMonth = dbo.Transactions.Period AND dbo.StreetSaleRcpt.PeriodYear = dbo.Transactions.Year AND dbo.StreetSaleRcpt.Updated = 1 AND dbo.StreetSaleRcpt.CustomerCode = dbo.Customer_Master.CustomerCode ) WHERE dbo.StreetSaleRcpt.CustomerCode IS NULL GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType, dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount, dbo.StreetSaleRcpt.CustomerCode ``` Make your correlated sub-query a left join and test for its absence ('WHERE dbo.StreetSaleRcpt.CustomerCode IS NULL') versus 'NOT IN'. Good luck.
130,192
<p>I was wondering if there is a clean way to represent an is-a relationship as illustrated by this example:</p> <p>This DB stores recording times for three types of programs: movies, game shows, drama. In an object oriented sense each of these is-a program. Each of these subclasses have different properties. Here are the tables (fk prefix indicates a foreign key):</p> <p><em>movie</em><br> id<br> name<br> fkDirector<br></p> <p><em>gameShow</em><br> id<br> name<br> fkHost<br> fkContestant<br></p> <p><em>drama</em><br> id<br> name<br></p> <p>In OO terms the record table would in sense look like this:<br><br> <em>record</em><br> id<br> fkProgram<br> startTime<br> endTime<br></p> <p>The only way I can think of doing this without violating the normal forms is to have three record tables namely <em>recordMovie</em>, <em>recordGameShow</em>, and <em>recordDrama</em>.</p> <p>Is there a way to consolidate these tables into one without violating the principles of database normalization?</p> <p>Here are some non-working examples to illustrate the idea:</p> <p><em>program</em><br> id<br> fkMovie<br> fkGameShow<br> fkDrama<br></p> <p>This table violates the first normal form because it will contain nulls. For each row only one of the 3 entries will be non null.</p> <p><em>program</em><br> id<br> fkSpecific ← fkMovie OR fkGameShow OR fkDrama<br> fkType ← would indicate what table to look into<br></p> <p>Here I will not be able to enforce referential integrity because the fkSpecific could potentially point to one of three tables.</p> <p>I'm just trying to save the overhead of having 3 tables here instead of one. Maybe this simply isn't applicable to an RDB.</p>
[ { "answer_id": 130211, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "<p>Yes, that should be one table like</p>\n\n<pre><code>Programs:\n id,\n name,\n type_id,\n length,\n etc...\n</code></pre>\n\n<p>with a reference table for the type of program if there are \nother bits of data associated with the type:</p>\n\n<pre><code>ProgramType\n type_id,\n type_name,\n etc...\n</code></pre>\n\n<p>Like that.</p>\n" }, { "answer_id": 130217, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 1, "selected": false, "text": "<p>This is a pretty standard problem faced by many people before, and all of the approaches you may consider have probably been done at one point.</p>\n\n<p>A <a href=\"http://www.google.com/search?client=safari&amp;rls=en-us&amp;q=inheritance+in+relational+databases\" rel=\"nofollow noreferrer\">simple Google search</a> comes up with some pretty good explanations of the pros and cons of each.</p>\n" }, { "answer_id": 130252, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 0, "selected": false, "text": "<p>My first idea was also to use one Program table for movies, shows &amp; drama's. Then add a ProgramType table and use a foreign key to it just like the parent post. </p>\n\n<p>Other columns can be added such as fkDirector, fkMovie. Then add a constraint that when the ProgramType is a movie, fkDirector can not be null or when it's a show, fkHost can not be null. </p>\n\n<p>This allows for easy lookup of all movies/shows/... recorded between start and enddate. Also makes sure all the data is filled in and the references are correct.</p>\n\n<p>Anyone has a better idea?</p>\n" }, { "answer_id": 130481, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 2, "selected": false, "text": "<p>Why do you want to store all the data on a single table? They are clearly different entities. Your idea of a main <em>Record</em> table, with auxiliary <em>recordMovie</em>, <em>recordGameShow</em>, and <em>RecordDrama</em>.</p>\n\n<p>To enforce the \"is-a\" relationship between the auxiliary tables and the main one, you need to do declare Record.id to be a foreign key in all these tables, and also add a constraint to it so it's unique - this enforces a one-to-one relationship which would convert these tables in extensions of the main one.</p>\n\n<p>You'd also need to add a new field in the main Record table to indicate what kind of record it is (movie, game show, drama, something else?). This could be either a foreign key reference to yet another table (RecordTypes?) or a string (with a constraint defined over the values it can accept).</p>\n" }, { "answer_id": 133797, "author": "Fredrick", "author_id": 21906, "author_profile": "https://Stackoverflow.com/users/21906", "pm_score": 0, "selected": false, "text": "<p>These are both good articles on the subject:<br>\n<a href=\"http://www.ibm.com/developerworks/library/ws-mapping-to-rdb/\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/library/ws-mapping-to-rdb/</a><br>\n<a href=\"http://www.agiledata.org/essays/mappingObjects.html\" rel=\"nofollow noreferrer\">http://www.agiledata.org/essays/mappingObjects.html</a> </p>\n\n<p>This what I will end up doing. My program table will simply be:</p>\n\n<p><em>program</em><br>\nid</p>\n\n<p>and then I will add fkProgram to each of the subclasses (drama, gameshow, and movie). This way the Program table will be an intermediate table between the subclasses. I can use a foreign key to the Program table to refer to an instance any of the sub-classes. This will allow me to have a single Record table and not violate any normal forms.</p>\n\n<p><em>movie</em><br>\nid<br>\nfkProgram<br>\nname<br>\nfkDirector<br></p>\n\n<p><em>record</em><br>\nid<br>\nfkProgram<br>\nstartTime<br>\nendTime<br></p>\n" }, { "answer_id": 525225, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": false, "text": "<p>Do a google search on \"generalization specialization relational modeling\". </p>\n\n<p>The \"gen-spec\" model follows the same pattern as the \"is-a\" relationship. </p>\n\n<p>For example, a car is a specialized vehicle. A truck is a different kind of specialized vehicle. A motorcycle is a third kind of specialized vehicle. </p>\n\n<p>You should find plenty of articles.</p>\n\n<p>Interestingly, if you just do a google search on \"gen-spec\" one of the top links is to a description of gen-spec modeling in Smalltalk.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21906/" ]
I was wondering if there is a clean way to represent an is-a relationship as illustrated by this example: This DB stores recording times for three types of programs: movies, game shows, drama. In an object oriented sense each of these is-a program. Each of these subclasses have different properties. Here are the tables (fk prefix indicates a foreign key): *movie* id name fkDirector *gameShow* id name fkHost fkContestant *drama* id name In OO terms the record table would in sense look like this: *record* id fkProgram startTime endTime The only way I can think of doing this without violating the normal forms is to have three record tables namely *recordMovie*, *recordGameShow*, and *recordDrama*. Is there a way to consolidate these tables into one without violating the principles of database normalization? Here are some non-working examples to illustrate the idea: *program* id fkMovie fkGameShow fkDrama This table violates the first normal form because it will contain nulls. For each row only one of the 3 entries will be non null. *program* id fkSpecific ← fkMovie OR fkGameShow OR fkDrama fkType ← would indicate what table to look into Here I will not be able to enforce referential integrity because the fkSpecific could potentially point to one of three tables. I'm just trying to save the overhead of having 3 tables here instead of one. Maybe this simply isn't applicable to an RDB.
Yes, that should be one table like ``` Programs: id, name, type_id, length, etc... ``` with a reference table for the type of program if there are other bits of data associated with the type: ``` ProgramType type_id, type_name, etc... ``` Like that.
130,193
<p>Is it possible to modify a registry value (whether string or DWORD) via a .bat/.cmd script?</p>
[ { "answer_id": 130201, "author": "schaelle", "author_id": 21911, "author_profile": "https://Stackoverflow.com/users/21911", "pm_score": -1, "selected": false, "text": "<p>See <a href=\"http://www.chaminade.org/MIS/Articles/RegistryEdit.htm\" rel=\"nofollow noreferrer\">http://www.chaminade.org/MIS/Articles/RegistryEdit.htm</a></p>\n" }, { "answer_id": 130202, "author": "Rui Vieira", "author_id": 143732, "author_profile": "https://Stackoverflow.com/users/143732", "pm_score": 6, "selected": true, "text": "<p>You can use the REG command. From <a href=\"http://www.ss64.com/nt/reg.html\" rel=\"noreferrer\">http://www.ss64.com/nt/reg.html</a>:</p>\n\n<pre><code>Syntax:\n\n REG QUERY [ROOT\\]RegKey /v ValueName [/s]\n REG QUERY [ROOT\\]RegKey /ve --This returns the (default) value\n\n REG ADD [ROOT\\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]\n REG ADD [ROOT\\]RegKey /ve [/d Data] [/f] -- Set the (default) value\n\n REG DELETE [ROOT\\]RegKey /v ValueName [/f]\n REG DELETE [ROOT\\]RegKey /ve [/f] -- Remove the (default) value\n REG DELETE [ROOT\\]RegKey /va [/f] -- Delete all values under this key\n\n REG COPY [\\\\SourceMachine\\][ROOT\\]RegKey [\\\\DestMachine\\][ROOT\\]RegKey\n\n REG EXPORT [ROOT\\]RegKey FileName.reg\n REG IMPORT FileName.reg\n REG SAVE [ROOT\\]RegKey FileName.hiv\n REG RESTORE \\\\MachineName\\[ROOT]\\KeyName FileName.hiv\n\n REG LOAD FileName KeyName\n REG UNLOAD KeyName\n\n REG COMPARE [ROOT\\]RegKey [ROOT\\]RegKey [/v ValueName] [Output] [/s]\n REG COMPARE [ROOT\\]RegKey [ROOT\\]RegKey [/ve] [Output] [/s]\n\nKey:\n ROOT :\n HKLM = HKey_Local_machine (default)\n HKCU = HKey_current_user\n HKU = HKey_users\n HKCR = HKey_classes_root\n\n ValueName : The value, under the selected RegKey, to edit.\n (default is all keys and values)\n\n /d Data : The actual data to store as a \"String\", integer etc\n\n /f : Force an update without prompting \"Value exists, overwrite Y/N\"\n\n \\\\Machine : Name of remote machine - omitting defaults to current machine.\n Only HKLM and HKU are available on remote machines.\n\n FileName : The filename to save or restore a registry hive.\n\n KeyName : A key name to load a hive file into. (Creating a new key)\n\n /S : Query all subkeys and values.\n\n /S Separator : Character to use as the separator in REG_MULTI_SZ values\n the default is \"\\0\" \n\n /t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ\n\n Output : /od (only differences) /os (only matches) /oa (all) /on (no output)\n</code></pre>\n" }, { "answer_id": 130203, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>You can make a .reg file and call start on it. You can export any part of the registry as a .reg file to see what the format is. </p>\n\n<p>Format here:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/310516\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/310516</a></p>\n\n<p>This can be run on any Windows machine without installing other software.</p>\n" }, { "answer_id": 130205, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 5, "selected": false, "text": "<p>Yes, you can script using the <code>reg</code> command.\nExample:</p>\n\n<pre><code>reg add HKCU\\Software\\SomeProduct\nreg add HKCU\\Software\\SomeProduct /v Version /t REG_SZ /d v2.4.6\n</code></pre>\n\n<p>This would create key <code>HKEY_CURRENT_USER\\Software\\SomeProduct</code>, and add a String value \"v2.4.6\" named \"Version\" to that key.</p>\n\n<p><code>reg /?</code> has the details.</p>\n" }, { "answer_id": 130212, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "<p>Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.</p>\n" }, { "answer_id": 130307, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 1, "selected": false, "text": "<p>In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.</p>\n" }, { "answer_id": 170321, "author": "nray", "author_id": 25092, "author_profile": "https://Stackoverflow.com/users/25092", "pm_score": 7, "selected": false, "text": "<p>@Franci Penov - modify <strong>is</strong> possible in the sense of <strong>overwrite</strong> with <code>/f</code>, eg </p>\n\n<pre><code>reg add \"HKCU\\Software\\etc\\etc\" /f /v \"value\" /t REG_SZ /d \"Yes\"\n</code></pre>\n" }, { "answer_id": 37511806, "author": "Shersha Fn", "author_id": 4254056, "author_profile": "https://Stackoverflow.com/users/4254056", "pm_score": 4, "selected": false, "text": "<p>This is how you can modify registry, without yes or no prompt and don't forget to run as administrator</p>\n\n<pre><code>reg add HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\etc\\etc /v Valuename /t REG_SZ /d valuedata /f \n</code></pre>\n\n<p>Below is a real example to set internet explorer as my default browser</p>\n\n<pre><code>reg add HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice /v ProgId /t REG_SZ /d IE.HTTPS /f \n</code></pre>\n\n<blockquote>\n <p>/f Force: Force an update without prompting \"Value exists, overwrite\n Y/N\"</p>\n \n <p>/d Data : The actual data to store as a \"String\", integer etc</p>\n \n <p>/v Value : The value name eg ProgId</p>\n \n <p>/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ |\n REG_MULTI_SZ</p>\n</blockquote>\n\n<p>Learn more about Read, Set or Delete registry keys and values, save and restore from a .REG file. from <a href=\"http://ss64.com/nt/reg.html\" rel=\"noreferrer\">here</a> </p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
Is it possible to modify a registry value (whether string or DWORD) via a .bat/.cmd script?
You can use the REG command. From <http://www.ss64.com/nt/reg.html>: ``` Syntax: REG QUERY [ROOT\]RegKey /v ValueName [/s] REG QUERY [ROOT\]RegKey /ve --This returns the (default) value REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f] REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the (default) value REG DELETE [ROOT\]RegKey /v ValueName [/f] REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default) value REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under this key REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey REG EXPORT [ROOT\]RegKey FileName.reg REG IMPORT FileName.reg REG SAVE [ROOT\]RegKey FileName.hiv REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv REG LOAD FileName KeyName REG UNLOAD KeyName REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s] REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s] Key: ROOT : HKLM = HKey_Local_machine (default) HKCU = HKey_current_user HKU = HKey_users HKCR = HKey_classes_root ValueName : The value, under the selected RegKey, to edit. (default is all keys and values) /d Data : The actual data to store as a "String", integer etc /f : Force an update without prompting "Value exists, overwrite Y/N" \\Machine : Name of remote machine - omitting defaults to current machine. Only HKLM and HKU are available on remote machines. FileName : The filename to save or restore a registry hive. KeyName : A key name to load a hive file into. (Creating a new key) /S : Query all subkeys and values. /S Separator : Character to use as the separator in REG_MULTI_SZ values the default is "\0" /t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ Output : /od (only differences) /os (only matches) /oa (all) /on (no output) ```
130,208
<p>Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object? </p> <p>If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.</p> <p>Markus Olsson gave an excellent example <a href="https://stackoverflow.com/questions/31238/c-instantiating-classes-from-xml">here</a>, but I don't see how to apply it to generics.</p>
[ { "answer_id": 130241, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 4, "selected": true, "text": "<p>Once you parse it up, use <a href=\"http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx\" rel=\"noreferrer\">Type.GetType(string)</a> to get a reference to the types involved, then use <a href=\"http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx\" rel=\"noreferrer\">Type.MakeGenericType(Type[])</a> to construct the specific generic type you need. Then, use <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getconstructor.aspx\" rel=\"noreferrer\">Type.GetConstructor(Type[])</a> to get a reference to a constructor for the specific generic type, and finally call <a href=\"http://msdn.microsoft.com/en-us/library/6ycw1y17.aspx\" rel=\"noreferrer\">ConstructorInfo.Invoke</a> to get an instance of the object.</p>\n\n<pre><code>Type t1 = Type.GetType(\"MyCustomGenericCollection\");\nType t2 = Type.GetType(\"MyCustomObjectClass\");\nType t3 = t1.MakeGenericType(new Type[] { t2 });\nConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);\nobject obj = ci.Invoke(null);\n</code></pre>\n" }, { "answer_id": 130245, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 1, "selected": false, "text": "<p>If you don't mind translating to VB.NET, something like this should work</p>\n\n<pre><code>foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())\n{\n // find the type of the item\n Type itemType = assembly.GetType(\"MyCustomObjectClass\", false);\n // if we didnt find it, go to the next assembly\n if (itemType == null)\n {\n continue;\n }\n // Now create a generic type for the collection\n Type colType = assembly.GetType(\"MyCusomgGenericCollection\").MakeGenericType(itemType);;\n\n IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType);\n break;\n}\n</code></pre>\n" }, { "answer_id": 130253, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 2, "selected": false, "text": "<p>The MSDN article <a href=\"http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx\" rel=\"nofollow noreferrer\">How to: Examine and Instantiate Generic Types with Reflection</a> describes how you can use Reflection to create an instance of a generic Type. Using that in conjunction with Marksus's sample should hopefully get you started.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ]
Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object? If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain. Markus Olsson gave an excellent example [here](https://stackoverflow.com/questions/31238/c-instantiating-classes-from-xml), but I don't see how to apply it to generics.
Once you parse it up, use [Type.GetType(string)](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx) to get a reference to the types involved, then use [Type.MakeGenericType(Type[])](http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx) to construct the specific generic type you need. Then, use [Type.GetConstructor(Type[])](http://msdn.microsoft.com/en-us/library/system.type.getconstructor.aspx) to get a reference to a constructor for the specific generic type, and finally call [ConstructorInfo.Invoke](http://msdn.microsoft.com/en-us/library/6ycw1y17.aspx) to get an instance of the object. ``` Type t1 = Type.GetType("MyCustomGenericCollection"); Type t2 = Type.GetType("MyCustomObjectClass"); Type t3 = t1.MakeGenericType(new Type[] { t2 }); ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes); object obj = ci.Invoke(null); ```
130,240
<p>I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like:</p> <pre><code>$total = $value1 + $value2 + ... + $value11; </code></pre> <p>All the values I want to add together are coming from an <code>HTML</code> form. I want to avoid javascript.</p> <p>But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea):</p> <pre><code>&lt;?php $tempTotal = 0; $pBalance1 = 5; $pBalance2 = 5; $pBalance3 = 5; for ($i = 1 ; $i &lt;= 3 ; $i++){ $tempTotal = $tempTotal + $pBalance.$i; } echo $tempTotal; ?&gt; </code></pre> <p>Is what I want to do possible in PHP?</p>
[ { "answer_id": 130242, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 2, "selected": false, "text": "<p>Uhm why don't you use an array? If you give the forms a name like foobar[] it will be an array in PHP.</p>\n" }, { "answer_id": 130244, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 4, "selected": true, "text": "<pre><code>for ($i = 1 ; $i &lt;= 3 ; $i++){\n $varName = \"pBalance\".$i;\n $tempTotal += $$varName;\n}\n</code></pre>\n\n<p>This will do what you want. However you might indeed consider using an array for this kind of thing.</p>\n" }, { "answer_id": 130248, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 2, "selected": false, "text": "<p>The values you need are posted from a form, right? If so, you could iterate through the keys in the $_POST variable that match your form field's generated names.</p>\n\n<pre><code>foreach($_POST as $key=&gt;$value)\n{\n if(strpos($key, 'pBalance')===0)\n {\n $final_total += $value;\n }\n}\n</code></pre>\n" }, { "answer_id": 130251, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "<p>Try</p>\n\n<pre><code>$varName = 'pBalance' . $i;\n$tempTotal = $tempTotal + $$varName;\n</code></pre>\n" }, { "answer_id": 130260, "author": "conmulligan", "author_id": 1467, "author_profile": "https://Stackoverflow.com/users/1467", "pm_score": 2, "selected": false, "text": "<p>You can use an array to store your data, and just loop over it.</p>\n\n<pre><code>$tempTotal = 0;\n\n$balances[] = 5;\n$balances[] = 5;\n$balances[] = 5;\n\nfor ($i = 0; $i &lt;= count($balances); $i++) {\n $tempTotal = $tempTotal + $balances[$i];\n}\n</code></pre>\n\n<p>Or for brevity, use a foreach loop:</p>\n\n<pre><code>foreach($balances as $balance) {\n $tempTotal += $balance;\n}\n</code></pre>\n" }, { "answer_id": 130272, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": -1, "selected": false, "text": "<p>The concept you're looking for is called a variable variable (at least it's called that in PHP). Here is the official <a href=\"http://ca.php.net/language.variables.variable\" rel=\"nofollow noreferrer\">documentation</a> and a useful <a href=\"http://www.devshed.com/c/a/PHP/Using-Variable-Variables-in-PHP/\" rel=\"nofollow noreferrer\">tutorial</a>. The syntax for a variable variable is a double dollar sign ($$).</p>\n" }, { "answer_id": 130277, "author": "Keeth", "author_id": 20588, "author_profile": "https://Stackoverflow.com/users/20588", "pm_score": 3, "selected": false, "text": "<p>I would use @unexist's solution.. give the input fields names like:</p>\n\n<pre><code>&lt;input name=\"myInput[]\" /&gt;\n&lt;input name=\"myInput[]\" /&gt;\n&lt;input name=\"myInput[]\" /&gt;\n...\n</code></pre>\n\n<p>Then in your PHP get the sum like this:</p>\n\n<pre><code>$total = array_sum($_REQUEST['myInput']);\n</code></pre>\n\n<p>Because of the '[]' at the end of each input name, PHP will make $_REQUEST['myInput'] automatically be an array. A handy feature of PHP!</p>\n" }, { "answer_id": 130283, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>If you're trying to collect the values of a POST, you should really use an array. You can avoid having to manually piece together such an array by using:</p>\n\n<pre><code>&lt;input type=\"text\" name=\"vals[]\" value=\"one\" /&gt;\n&lt;input type=\"text\" name=\"vals[]\" value=\"two\" /&gt;\n</code></pre>\n\n<p><code>$_POST[\"vals\"]</code> will then be array(\"one\", \"two\");</p>\n" }, { "answer_id": 130286, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 1, "selected": false, "text": "<p>In about 99% of all cases involving a PHP generated variable, you are doing The Wrong Thing. I'll just re-iterate what others have said:</p>\n\n<p><strong>USE AN ARRAY</strong></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16292/" ]
I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like: ``` $total = $value1 + $value2 + ... + $value11; ``` All the values I want to add together are coming from an `HTML` form. I want to avoid javascript. But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea): ``` <?php $tempTotal = 0; $pBalance1 = 5; $pBalance2 = 5; $pBalance3 = 5; for ($i = 1 ; $i <= 3 ; $i++){ $tempTotal = $tempTotal + $pBalance.$i; } echo $tempTotal; ?> ``` Is what I want to do possible in PHP?
``` for ($i = 1 ; $i <= 3 ; $i++){ $varName = "pBalance".$i; $tempTotal += $$varName; } ``` This will do what you want. However you might indeed consider using an array for this kind of thing.
130,262
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p> <pre><code>result = [x**2 for x in mylist if type(x) is int] </code></pre> <p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:</p> <pre><code>result = [expensive(x) for x in mylist if expensive(x)] </code></pre> <p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
[ { "answer_id": 130276, "author": "Nick", "author_id": 5222, "author_profile": "https://Stackoverflow.com/users/5222", "pm_score": 5, "selected": false, "text": "<p>Came up with my own answer after a minute of thought. It can be done with nested comprehensions:</p>\n\n<pre><code>result = [y for y in (expensive(x) for x in mylist) if y]\n</code></pre>\n\n<p>I guess that works, though I find nested comprehensions are only marginally readable </p>\n" }, { "answer_id": 130278, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 3, "selected": false, "text": "<pre><code>result = [x for x in map(expensive,mylist) if x]\n</code></pre>\n\n<p>map() will return a list of the values of each object in mylist passed to expensive(). Then you can list-comprehend that, and discard unnecessary values.</p>\n\n<p>This is somewhat like a nested comprehension, but should be faster (since the python interpreter can optimize it fairly easily).</p>\n" }, { "answer_id": 130285, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 2, "selected": false, "text": "<p>You could always <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoize</a> the <code>expensive()</code> function so that calling it the second time around is merely a lookup for the computed value of <code>x</code>.</p>\n\n<p><a href=\"http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622201abfac735ea47ffade5\" rel=\"nofollow noreferrer\">Here's just one of many implementations of memoize as a decorator</a>.</p>\n" }, { "answer_id": 130288, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 2, "selected": false, "text": "<p>You could memoize expensive(x) (and if you are calling expensive(x) frequently, you probably should memoize it any way. This page gives an implementation of memoize for python:</p>\n\n<p><a href=\"http://code.activestate.com/recipes/52201/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/52201/</a></p>\n\n<p>This has the added benefit that expensive(x) may be run <em>less</em> than N times, since any duplicate entries will make use of the memo from the previous execution.</p>\n\n<p>Note that this assumes expensive(x) is a true function, and does not depend on external state that may change. If expensive(x) does depend on external state, and you can detect when that state changes, or you know it <em>wont</em> change during your list comprehension, then you can reset the memos before the comprehension.</p>\n" }, { "answer_id": 130309, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "<p>If the calculations are already nicely bundled into functions, how about using <code>filter</code> and <code>map</code>?</p>\n\n<pre><code>result = filter (None, map (expensive, mylist))\n</code></pre>\n\n<p>You can use <code>itertools.imap</code> if the list is very large.</p>\n" }, { "answer_id": 130312, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 3, "selected": false, "text": "<p>The most obvious (and I would argue most readable) answer is to not use a list comprehension or generator expression, but rather a real generator:</p>\n\n<pre><code>def gen_expensive(mylist):\n for item in mylist:\n result = expensive(item)\n if result:\n yield result\n</code></pre>\n\n<p>It takes more horizontal space, but it's much easier to see what it does at a glance, and you end up not repeating yourself.</p>\n" }, { "answer_id": 133898, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 3, "selected": false, "text": "<p>This is exactly what generators are suited to handle:</p>\n\n<pre><code>result = (expensive(x) for x in mylist)\nresult = (do_something(x) for x in result if some_condition(x))\n...\nresult = [x for x in result if x] # finally, a list\n</code></pre>\n\n<ol>\n<li>This makes it totally clear what is happening during each stage of the pipeline.</li>\n<li>Explicit over implicit</li>\n<li>Uses generators everywhere until the final step, so no large intermediate lists</li>\n</ol>\n\n<p>cf: <a href=\"http://www.dabeaz.com/generators/\" rel=\"noreferrer\">'Generator Tricks for System Programmers' by David Beazley</a></p>\n" }, { "answer_id": 873661, "author": "odwl", "author_id": 2453648, "author_profile": "https://Stackoverflow.com/users/2453648", "pm_score": 1, "selected": false, "text": "<p>I will have a preference for:</p>\n\n<pre><code>itertools.ifilter(bool, (expensive(x) for x in mylist))\n</code></pre>\n\n<p>This has the advantage to:</p>\n\n<ul>\n<li>avoid None as the function (will be eliminated in Python 3): <a href=\"http://bugs.python.org/issue2186\" rel=\"nofollow noreferrer\">http://bugs.python.org/issue2186</a></li>\n<li>use only iterators.</li>\n</ul>\n" }, { "answer_id": 874319, "author": "Paddy3118", "author_id": 10562, "author_profile": "https://Stackoverflow.com/users/10562", "pm_score": 0, "selected": false, "text": "<p>There is the plain old use of a <code>for</code> loop to append to a list, too:</p>\n\n<pre><code>result = []\nfor x in mylist:\n expense = expensive(x)\n if expense:\n result.append(expense)\n</code></pre>\n" }, { "answer_id": 73438697, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 1, "selected": false, "text": "<p>In 3.8 and above, the &quot;walrus&quot; operator accomplishes this:</p>\n<pre><code>[e for x in mylist if (e:=expensive(x))]\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5222/" ]
The Python list comprehension syntax makes it easy to filter values within a comprehension. For example: ``` result = [x**2 for x in mylist if type(x) is int] ``` Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is: ``` result = [expensive(x) for x in mylist if expensive(x)] ``` This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?
If the calculations are already nicely bundled into functions, how about using `filter` and `map`? ``` result = filter (None, map (expensive, mylist)) ``` You can use `itertools.imap` if the list is very large.
130,268
<h3>Background</h3> <p>Normal rails eager-loading of collections works like this:</p> <pre><code>Person.find(:all, :include=&gt;:companies) </code></pre> <p>This generates some sql which does</p> <pre><code>LEFT OUTER JOIN companies ON people.company_id = companies.id </code></pre> <h3>Question</h3> <p>However, I need a custom join (this could also arise if I was using <code>find_by_sql</code>) so I can't use the vanilla <code>:include =&gt; :companies</code></p> <p>The custom join/sql will get me all the data I need, but how can I tell activerecord that it belongs to the associated <code>Company</code> objects rather than just being a pile of extra rows?</p> <h3>Update</h3> <p>I need to put additional conditions in the join. Something like this:</p> <pre><code>SELECT blah blah blah LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL &lt;Several other joins&gt; WHERE blahblahblah </code></pre>
[ { "answer_id": 131247, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 3, "selected": false, "text": "<p>Can you not add the join conditions using ActiveRecord?</p>\n\n<p>For example, I have a quite complex query using several dependent records and it works fine by combining conditions and include directives</p>\n\n<pre><code>Contractors.find(\n :all, \n :include =&gt; {:council_areas =&gt; :suburbs},\n :conditions =&gt; [\"suburbs.postcode = ?\", customer.postcode] \n) \n</code></pre>\n\n<p>Assuming that:</p>\n\n<ol>\n<li>Contractors have_many CouncilAreas</li>\n<li>CouncilAreas have_many Suburbs</li>\n</ol>\n\n<p>This join returns the Contractors in the suburb identified by <strong>customer.postcode</strong>.</p>\n\n<p>The generated query looks like:</p>\n\n<pre><code>SELECT contractors.*, council_areas.*, suburbs.*\nFROM `contractors` \nLEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id \nLEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id \nLEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id \nLEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')\n</code></pre>\n\n<p>(Note: I edited the column list for brevity).</p>\n" }, { "answer_id": 131650, "author": "user19898", "author_id": 19898, "author_profile": "https://Stackoverflow.com/users/19898", "pm_score": 1, "selected": false, "text": "<p>Can you elaborate a bit more on exactly what you are trying to accomplish with this query?</p>\n\n<p>Also take a look at at the :joins option for find. It allows you to specify how you want the tables joined. <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001298/\" rel=\"nofollow noreferrer\" title=\".find documentation\">link text</a></p>\n\n<p>And beware when using :include, the behavior changes a bit in Rails 2.1 and may cause some problems when used in conjunction with a :conditions option that references an included table. <a href=\"http://pivots.pivotallabs.com/users/stevend/blog/articles/514-standup-09-23-2008-disabling-pre-rails-2-1-style-include/\" rel=\"nofollow noreferrer\" title=\"Here\">link text</a> and <a href=\"http://pivots.pivotallabs.com/users/stevend/blog/articles/515-standup-09-24-2008-why-does-my-jvm-crash-running-solr-/\" rel=\"nofollow noreferrer\" title=\"here\">link text</a> are two articles from Pivotal that mention this gotcha.</p>\n" }, { "answer_id": 2447036, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 2, "selected": false, "text": "<p>You can use something like the following to get the appropriate left outer join syntactical magic.</p>\n\n<pre><code>Person.reflect_on_association(:companies).options[:conditions] = 'people.magical_flag IS NULL'\n</code></pre>\n" }, { "answer_id": 13749013, "author": "Tomek Wałkuski", "author_id": 907258, "author_profile": "https://Stackoverflow.com/users/907258", "pm_score": 2, "selected": false, "text": "<p>I'm not sure it's what you want (I'm not 100% sure I've understood your question and what you want to accomplish) but:</p>\n\n<p>What about providing both <code>:joins</code> and <code>:includes</code>?</p>\n\n<p><code>\nPerson.find(\n :all,\n :joins =&gt; 'LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_',\n :includes =&gt; :companies\n)\n</code></p>\n\n<p>Or AR3 way:</p>\n\n<p><code>\nPerson.includes(:companies).joins('LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_')\n</code></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
### Background Normal rails eager-loading of collections works like this: ``` Person.find(:all, :include=>:companies) ``` This generates some sql which does ``` LEFT OUTER JOIN companies ON people.company_id = companies.id ``` ### Question However, I need a custom join (this could also arise if I was using `find_by_sql`) so I can't use the vanilla `:include => :companies` The custom join/sql will get me all the data I need, but how can I tell activerecord that it belongs to the associated `Company` objects rather than just being a pile of extra rows? ### Update I need to put additional conditions in the join. Something like this: ``` SELECT blah blah blah LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL <Several other joins> WHERE blahblahblah ```
Can you not add the join conditions using ActiveRecord? For example, I have a quite complex query using several dependent records and it works fine by combining conditions and include directives ``` Contractors.find( :all, :include => {:council_areas => :suburbs}, :conditions => ["suburbs.postcode = ?", customer.postcode] ) ``` Assuming that: 1. Contractors have\_many CouncilAreas 2. CouncilAreas have\_many Suburbs This join returns the Contractors in the suburb identified by **customer.postcode**. The generated query looks like: ``` SELECT contractors.*, council_areas.*, suburbs.* FROM `contractors` LEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id LEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id LEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id LEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000') ``` (Note: I edited the column list for brevity).
130,273
<p>I'm trying to automate a program I made with a test suite via a .cmd file.</p> <p>I can get the program that I ran's return code via %errorlevel%. </p> <p>My program has certain return codes for each type of error.</p> <p>For example: </p> <p>1 - means failed for such and such a reason</p> <p>2 - means failed for some other reason</p> <p>...</p> <p>echo FAILED: Test case failed, error level: %errorlevel% >> TestSuite1Log.txt</p> <p>Instead I'd like to somehow say:</p> <p>echo FAILED: Test case failed, error reason: lookupError(%errorlevel%) >> TestSuite1Log.txt</p> <p>Is this possible with a .bat file? Or do I have to move to a scripting language like python/perl?</p>
[ { "answer_id": 130290, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 1, "selected": false, "text": "<p>Not exactly like that, with a subroutine, but you can either populate the a variable with the text using a <a href=\"http://www.robvanderwoude.com/goto.html\" rel=\"nofollow noreferrer\">goto</a> workaround.</p>\n\n<p>It may be easier if this test suite of yours grows quite a bit to use a more powerful language. Perl or even Windows Scripting Host can help you there.</p>\n" }, { "answer_id": 130291, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 1, "selected": false, "text": "<p>Yes you can use call. Just on a new line have call, and pas the errorcode. This should work, but i have not tested.</p>\n\n<pre><code>C:\\Users\\matt.MATTLANT&gt;help call\nCalls one batch program from another.\n\nCALL [drive:][path]filename [batch-parameters]\n\n batch-parameters Specifies any command-line information required by the\n batch program.\n</code></pre>\n\n<p>SEDIT: orry i may have misunderstood a bit, but you can use IF also</p>\n" }, { "answer_id": 130294, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 1, "selected": false, "text": "<p>Test your values in reverse order and use the overloaded behaviour of <strong>IF</strong>:</p>\n\n<pre><code>@echo off\nmyApp.exe\nif errorlevel 2 goto Do2\nif errorlevel 1 goto do1\necho Success\ngoto End\n\n:Do2\necho Something when 2 returned\ngoto End\n\n:Do1\necho Something when 1 returned\ngoto End\n\n:End\n</code></pre>\n\n<p>If you want to be more powerful, you could try something like this (you'd need to replace the %1 with %errorlevel but it's harder to test for me). You would need to put a label for each error level you deal with:</p>\n\n<pre><code>@echo off\necho passed %1\ngoto Label%1\n\n:Label\necho not matched!\ngoto end\n\n:Label1\necho One\ngoto end\n\n:Label2\necho Two\ngoto end\n\n:end\n</code></pre>\n\n<p>Here is a test:</p>\n\n<pre><code>C:\\&gt;test\npassed\nnot matched!\n\nC:\\&gt;test 9\npassed 9\nThe system cannot find the batch label specified - Label9\n\nC:\\&gt;test 1\npassed 1\nOne\n\nC:\\&gt;test 2\npassed 2\nTwo\n</code></pre>\n" }, { "answer_id": 130299, "author": "Keeth", "author_id": 20588, "author_profile": "https://Stackoverflow.com/users/20588", "pm_score": 0, "selected": false, "text": "<p>You can use the 'IF ERRORLEVEL' statement to do different things based on the return code. </p>\n\n<p>See:</p>\n\n<p><a href=\"http://www.robvanderwoude.com/errorlevel.html\" rel=\"nofollow noreferrer\">http://www.robvanderwoude.com/errorlevel.html</a></p>\n\n<p>In response to your second question, I would move to using a scripting language anyway, since Windows batch files are inherently so limited. There are great Windows distributions for Perl, Python, Ruby, etc., so no reason not to use them, really. I personally love doing Perl scripting on Windows.</p>\n" }, { "answer_id": 130308, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "<p>You can do something like the following code. Note that the error level comparisons should be in decreasing order due to a cmd quirk.</p>\n\n<pre><code>setlocal\n\nrem Main script\ncall :LookupErrorReason %errorlevel%\necho FAILED Test case failed, error reason: %errorreason% &gt;&gt; TestSuite1Log.txt\ngoto :EndOfScript\n\nrem Lookup subroutine\n:LookupErrorReason\n if %%1 == 3 set errorreason=Some reason\n if %%1 == 2 set errorreason=Another reason\n if %%1 == 1 set errorreason=Third reason\ngoto :EndOfScript\n\n:EndOfScript\nendlocal\n</code></pre>\n" }, { "answer_id": 130319, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 5, "selected": true, "text": "<p>You can do this quite neatly with the <code>ENABLEDELAYEDEXPANSION</code> option. This allows you to use <code>!</code> as variable marker that is evaluated after <code>%</code>.</p>\n\n<pre><code>REM Turn on Delayed Expansion\nSETLOCAL ENABLEDELAYEDEXPANSION\n\nREM Define messages as variables with the ERRORLEVEL on the end of the name\nSET MESSAGE0=Everything is fine\nSET MESSAGE1=Failed for such and such a reason\nSET MESSAGE2=Failed for some other reason\n\nREM Set ERRORLEVEL - or run command here\nSET ERRORLEVEL=2\n\nREM Print the message corresponding to the ERRORLEVEL\nECHO !MESSAGE%ERRORLEVEL%!\n</code></pre>\n\n<p>Type <code>HELP SETLOCAL</code> and <code>HELP SET</code> at a command prompt for more information on delayed expansion.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
I'm trying to automate a program I made with a test suite via a .cmd file. I can get the program that I ran's return code via %errorlevel%. My program has certain return codes for each type of error. For example: 1 - means failed for such and such a reason 2 - means failed for some other reason ... echo FAILED: Test case failed, error level: %errorlevel% >> TestSuite1Log.txt Instead I'd like to somehow say: echo FAILED: Test case failed, error reason: lookupError(%errorlevel%) >> TestSuite1Log.txt Is this possible with a .bat file? Or do I have to move to a scripting language like python/perl?
You can do this quite neatly with the `ENABLEDELAYEDEXPANSION` option. This allows you to use `!` as variable marker that is evaluated after `%`. ``` REM Turn on Delayed Expansion SETLOCAL ENABLEDELAYEDEXPANSION REM Define messages as variables with the ERRORLEVEL on the end of the name SET MESSAGE0=Everything is fine SET MESSAGE1=Failed for such and such a reason SET MESSAGE2=Failed for some other reason REM Set ERRORLEVEL - or run command here SET ERRORLEVEL=2 REM Print the message corresponding to the ERRORLEVEL ECHO !MESSAGE%ERRORLEVEL%! ``` Type `HELP SETLOCAL` and `HELP SET` at a command prompt for more information on delayed expansion.
130,292
<p>What is the proper way to inject a data access dependency when I do lazy loading?</p> <p>For example I have the following class structure</p> <pre><code>class CustomerDao : ICustomerDao public Customer GetById(int id) {...} class Transaction { int customer_id; //Transaction always knows this value Customer _customer = null; ICustomerDao _customer_dao; Customer GetCustomer() { if(_customer == null) _customer = _customer_dao.GetById(_customer_id); return _customer } </code></pre> <p>How do I get the reference to _customer_dao into the transaction object? Requiring it for the constructor seems like it wouldn't really make sense if I want the Transaction to at least look like a POCO. Is it ok to have the Transaction object reference the Inversion of Control Container directly? That also seems awkward too.</p> <p>How do frameworks like NHibernate handle this?</p>
[ { "answer_id": 131059, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 1, "selected": false, "text": "<p>I typically do the dependency injection in the constructor like you have above, but take the lazy loading a step further by acting only when the \"get\" is called like I have below. Not sure if this is the pure approach you are looking for, but it does eliminate the \"dirty\" constructor DI/Lazy Loading in 1 step ;)</p>\n\n<pre><code>public class Product\n{\n private int mProductID;\n private Supplier mSupplier;\n private ISupplierService mSupplierService;\n\n public Product()\n {\n //if you want your object to remain POCO you can use dual constr\n //this constr will be for app use, the next will be for testing\n } \n\n public Product(ISupplierService SupplierService)\n {\n mSupplierService = SupplierService;\n }\n\n public Supplier Supplier {\n get {\n if (mSupplier == null) {\n if (mSupplierService == null) {\n mSupplierService = new SupplierService();\n }\n mSupplier = mSupplierService.GetSupplierByProductID(mProductID);\n }\n return mSupplier;\n }\n set { mSupplier = value; }\n }\n}\n</code></pre>\n" }, { "answer_id": 131186, "author": "Michael Lang", "author_id": 19452, "author_profile": "https://Stackoverflow.com/users/19452", "pm_score": 1, "selected": false, "text": "<p>I'm not terribly familiar with the term POCO, but the definitions I've read seem to generally follow the spirit of the object being independent of some larger framework.</p>\n\n<p>That said, no matter how you slice it, if you're performing dependency injection, you're going to have collaborations with those classes whose functionality is injected in, and something that sticks the depended upon objects in, whether its a full blown injection framework or just some assembler class. </p>\n\n<p>To myself it seems strange to inject a reference to an IOC container into a class. I prefer my injections to occur in the constructor with code looking something like this:</p>\n\n<pre><code>public interface IDao&lt;T&gt;\n{\n public T GetById(int id);\n}\n\n\npublic interface ICustomerDao : IDao&lt;Customer&gt;\n{\n}\n\npublic class CustomerDao : ICustomerDao\n{\n public Customer GetById(int id) \n {...}\n}\n\npublic class Transaction&lt;T&gt; where T : class\n{\n\n int _id; //Transaction always knows this value\n T _dataObject;\n IDao&lt;T&gt; _dao;\n\n public Transaction(IDao&lt;T&gt; myDao, int id)\n {\n _id = id;\n _dao = myDao;\n }\n\n public T Get()\n {\n if (_dataObject == null)\n _dataObject = _dao.GetById(_id);\n return _dataObject;\n }\n}\n</code></pre>\n" }, { "answer_id": 522547, "author": "thinkbeforecoding", "author_id": 47001, "author_profile": "https://Stackoverflow.com/users/47001", "pm_score": 3, "selected": false, "text": "<p>I suggest something different...\nUse a lazy load class :</p>\n\n<pre><code>public class Lazy&lt;T&gt;\n{\n T value;\n Func&lt;T&gt; loader;\n\n public Lazy(T value) { this.value = value; }\n public Lazy(Func&lt;T&gt; loader { this.loader = loader; }\n\n T Value\n {\n get \n {\n if (loader != null)\n {\n value = loader();\n loader = null;\n }\n\n return value;\n }\n\n public static implicit operator T(Lazy&lt;T&gt; lazy)\n {\n return lazy.Value;\n }\n\n public static implicit operator Lazy&lt;T&gt;(T value)\n {\n return new Lazy&lt;T&gt;(value);\n }\n}\n</code></pre>\n\n<p>Once you get it, you don't need to inject the dao in you object anymore :</p>\n\n<pre><code>public class Transaction\n{\n private static readonly Lazy&lt;Customer&gt; customer;\n\n public Transaction(Lazy&lt;Customer&gt; customer)\n {\n this.customer = customer;\n }\n\n public Customer Customer\n {\n get { return customer; } // implicit cast happen here\n }\n}\n</code></pre>\n\n<p>When creating a Transcation object that is not bound to database :</p>\n\n<pre><code>new Transaction(new Customer(..)) // implicite cast \n //from Customer to Lazy&lt;Customer&gt;..\n</code></pre>\n\n<p>When regenerating a Transaction from the database in the repository:</p>\n\n<pre><code>public Transaction GetTransaction(Guid id)\n{\n custmerId = ... // find the customer id \n return new Transaction(() =&gt; dao.GetCustomer(customerId));\n}\n</code></pre>\n\n<p>Two interesting things happen :\n- Your domain objects can be used with or without data access, it becomes data acces ignorant. The only little twist is to enable to pass a function that give the object instead of the object itself.\n- The Lazy class is internaly mutable but can be used as an immutable value. The readonly keyword keeps its semantic, since its content cannot be changed externaly. </p>\n\n<p>When you want the field to be writable, simply remove the readonly keyword. when assigning a new value, a new Lazy will be created with the new value due to the implicit cast.</p>\n\n<p>Edit:\nI blogged about it here :</p>\n\n<p><a href=\"http://www.thinkbeforecoding.com/post/2009/02/07/Lazy-load-and-persistence-ignorance\" rel=\"nofollow noreferrer\">http://www.thinkbeforecoding.com/post/2009/02/07/Lazy-load-and-persistence-ignorance</a></p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
What is the proper way to inject a data access dependency when I do lazy loading? For example I have the following class structure ``` class CustomerDao : ICustomerDao public Customer GetById(int id) {...} class Transaction { int customer_id; //Transaction always knows this value Customer _customer = null; ICustomerDao _customer_dao; Customer GetCustomer() { if(_customer == null) _customer = _customer_dao.GetById(_customer_id); return _customer } ``` How do I get the reference to \_customer\_dao into the transaction object? Requiring it for the constructor seems like it wouldn't really make sense if I want the Transaction to at least look like a POCO. Is it ok to have the Transaction object reference the Inversion of Control Container directly? That also seems awkward too. How do frameworks like NHibernate handle this?
I suggest something different... Use a lazy load class : ``` public class Lazy<T> { T value; Func<T> loader; public Lazy(T value) { this.value = value; } public Lazy(Func<T> loader { this.loader = loader; } T Value { get { if (loader != null) { value = loader(); loader = null; } return value; } public static implicit operator T(Lazy<T> lazy) { return lazy.Value; } public static implicit operator Lazy<T>(T value) { return new Lazy<T>(value); } } ``` Once you get it, you don't need to inject the dao in you object anymore : ``` public class Transaction { private static readonly Lazy<Customer> customer; public Transaction(Lazy<Customer> customer) { this.customer = customer; } public Customer Customer { get { return customer; } // implicit cast happen here } } ``` When creating a Transcation object that is not bound to database : ``` new Transaction(new Customer(..)) // implicite cast //from Customer to Lazy<Customer>.. ``` When regenerating a Transaction from the database in the repository: ``` public Transaction GetTransaction(Guid id) { custmerId = ... // find the customer id return new Transaction(() => dao.GetCustomer(customerId)); } ``` Two interesting things happen : - Your domain objects can be used with or without data access, it becomes data acces ignorant. The only little twist is to enable to pass a function that give the object instead of the object itself. - The Lazy class is internaly mutable but can be used as an immutable value. The readonly keyword keeps its semantic, since its content cannot be changed externaly. When you want the field to be writable, simply remove the readonly keyword. when assigning a new value, a new Lazy will be created with the new value due to the implicit cast. Edit: I blogged about it here : <http://www.thinkbeforecoding.com/post/2009/02/07/Lazy-load-and-persistence-ignorance>
130,322
<p>I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions?</p> <p>Here is a copy of the class that is passing the member function:</p> <pre><code>class testMenu : public MenuScreen{ public: bool draw; MenuButton&lt;testMenu&gt; x; testMenu():MenuScreen("testMenu"){ x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&amp;this-&gt;test2); draw = false; } void test2(){ draw = true; } }; </code></pre> <p>The function x.SetButton(...) is contained in another class, where "object" is a template.</p> <pre><code>void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) { BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height); this-&gt;ButtonFunc = &amp;ButtonFunc; } </code></pre> <p>If anyone has any advice on how I can properly send this function so that I can use it later.</p>
[ { "answer_id": 130402, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 4, "selected": false, "text": "<p>I'd strongly recommend <code>boost::bind</code> and <code>boost::function</code> for anything like this.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/5245072/pass-and-call-a-member-function-boostbind-boostfunction\">Pass and call a member function (boost::bind / boost::function?)</a></p>\n" }, { "answer_id": 130519, "author": "Parappa", "author_id": 9974, "author_profile": "https://Stackoverflow.com/users/9974", "pm_score": 2, "selected": false, "text": "<p>In the rare case that you happen to be developing with Borland C++Builder and don't mind writing code specific to that development environment (that is, code that won't work with other C++ compilers), you can use the __closure keyword. I found a <a href=\"http://www.drbob42.com/cbuilder/lstfnd15.htm\" rel=\"nofollow noreferrer\">small article about C++Builder closures</a>. They're intended primarily for use with Borland VCL.</p>\n" }, { "answer_id": 130528, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 6, "selected": true, "text": "<p>To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in <code>MenuButton::SetButton()</code></p>\n\n<pre><code>template &lt;class object&gt;\nvoid MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath,\n LPCWSTR hoverFilePath, LPCWSTR pressedFilePath,\n int Width, int Height, object *ButtonObj, void (object::*ButtonFunc)())\n{\n BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);\n\n this-&gt;ButtonObj = ButtonObj;\n this-&gt;ButtonFunc = ButtonFunc;\n}\n</code></pre>\n\n<p>Then you can invoke the function using both pointers:</p>\n\n<pre><code>((ButtonObj)-&gt;*(ButtonFunc))();\n</code></pre>\n\n<p>Don't forget to pass the pointer to your object to <code>MenuButton::SetButton()</code>:</p>\n\n<pre><code>testMenu::testMenu()\n :MenuScreen(\"testMenu\")\n{\n x.SetButton(100,100,TEXT(\"buttonNormal.png\"), TEXT(\"buttonHover.png\"),\n TEXT(\"buttonPressed.png\"), 100, 40, this, test2);\n draw = false;\n}\n</code></pre>\n" }, { "answer_id": 132073, "author": "GKelly", "author_id": 18744, "author_profile": "https://Stackoverflow.com/users/18744", "pm_score": 3, "selected": false, "text": "<p>Would you not be better served to use standard OO. Define a contract (virtual class) and implement that in your own class, then just pass a reference to your own class and let the receiver call the contract function.</p>\n\n<p>Using your example (I've renamed the 'test2' method to 'buttonAction'):</p>\n\n<pre><code>class ButtonContract\n{\n public:\n virtual void buttonAction();\n}\n\n\nclass testMenu : public MenuScreen, public virtual ButtonContract\n{\n public:\n bool draw;\n MenuButton&lt;testMenu&gt; x;\n\n testMenu():MenuScreen(\"testMenu\")\n {\n x.SetButton(100,100,TEXT(\"buttonNormal.png\"), \n TEXT(\"buttonHover.png\"), \n TEXT(\"buttonPressed.png\"), \n 100, 40, &amp;this);\n draw = false;\n }\n\n //Implementation of the ButtonContract method!\n void buttonAction()\n {\n draw = true;\n }\n};\n</code></pre>\n\n<p>In the receiver method, you store the reference to a ButtonContract, then when you want to perform the button's action just call the 'buttonAction' method of that stored ButtonContract object.</p>\n" }, { "answer_id": 312716, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<p>Others have told you how to do it correctly. But I'm surprised no-one told you this code is actually dangerous:</p>\n\n<pre><code>this-&gt;ButtonFunc = &amp;ButtonFunc;\n</code></pre>\n\n<p>Since ButtonFunc is a parameter, it will go out of scope when the function returns. You are taking its address. You will get a value of type <code>void (object::**ButtonFunc)()</code> (<em>pointer to a pointer to a member function</em>) and assign it to this->ButtonFunc. At the time you would try to use this->ButtonFunc you would try to access the storage of the (now not existing anymore) local parameter, and your program would probably crash. </p>\n\n<p>I agree with Commodore's solution. But you have to change his line to</p>\n\n<pre><code>((ButtonObj)-&gt;*(ButtonFunc))();\n</code></pre>\n\n<p>since ButtonObj is a <em>pointer</em> to object.</p>\n" }, { "answer_id": 29659812, "author": "Yuanlong Li", "author_id": 2874994, "author_profile": "https://Stackoverflow.com/users/2874994", "pm_score": 3, "selected": false, "text": "<p>I know this is a quite old topic. But there is an elegant way to handle this with c++11 </p>\n\n<pre><code>#include &lt;functional&gt;\n</code></pre>\n\n<p>declare your function pointer like this</p>\n\n<pre><code>typedef std::function&lt;int(int,int) &gt; Max;\n</code></pre>\n\n<p>declare your the function your pass this thing into</p>\n\n<pre><code>void SetHandler(Max Handler);\n</code></pre>\n\n<p>suppose you pass a normal function to it you can use it like normal</p>\n\n<pre><code>SetHandler(&amp;some function);\n</code></pre>\n\n<p>suppose you have a member function</p>\n\n<pre><code>class test{\npublic:\n int GetMax(int a, int b);\n...\n}\n</code></pre>\n\n<p>in your code you can pass it using <code>std::placeholders</code> like this</p>\n\n<pre><code>test t;\nMax Handler = std::bind(&amp;test::GetMax,&amp;t,std::placeholders::_1,std::placeholders::_2);\nsome object.SetHandler(Handler);\n</code></pre>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions? Here is a copy of the class that is passing the member function: ``` class testMenu : public MenuScreen{ public: bool draw; MenuButton<testMenu> x; testMenu():MenuScreen("testMenu"){ x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&this->test2); draw = false; } void test2(){ draw = true; } }; ``` The function x.SetButton(...) is contained in another class, where "object" is a template. ``` void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) { BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height); this->ButtonFunc = &ButtonFunc; } ``` If anyone has any advice on how I can properly send this function so that I can use it later.
To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in `MenuButton::SetButton()` ``` template <class object> void MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, object *ButtonObj, void (object::*ButtonFunc)()) { BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height); this->ButtonObj = ButtonObj; this->ButtonFunc = ButtonFunc; } ``` Then you can invoke the function using both pointers: ``` ((ButtonObj)->*(ButtonFunc))(); ``` Don't forget to pass the pointer to your object to `MenuButton::SetButton()`: ``` testMenu::testMenu() :MenuScreen("testMenu") { x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"), TEXT("buttonPressed.png"), 100, 40, this, test2); draw = false; } ```
130,328
<p>How do I get the caller's IP address in a WebMethod?</p> <pre><code>[WebMethod] public void Foo() { // HttpRequest... ? - Not giving me any options through intellisense... } </code></pre> <p>using C# and ASP.NET</p>
[ { "answer_id": 130336, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 7, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress.aspx\" rel=\"noreferrer\">HttpContext.Current.Request.UserHostAddress</a> is what you want.</p>\n" }, { "answer_id": 130343, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 2, "selected": false, "text": "<p>The HttpContext is actually available inside the <code>WebService</code> base class, so just use <code>Context.Request</code> (or <code>HttpContext.Current</code> which also points to the current context) to get access to the members provided by the <code>HttpRequest</code>.</p>\n" }, { "answer_id": 130345, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>string ipAddress = HttpContext.Current.Request.ServerVariables[\"REMOTE_ADDR\"];\n</code></pre>\n\n<p>Haven't tried it in a webMethod, but I use it in standard HttpRequests</p>\n" }, { "answer_id": 130350, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>Context.Request.UserHostAddress\n</code></pre>\n" }, { "answer_id": 130453, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 3, "selected": false, "text": "<p>Just a caution. IP addresses can't be used to uniquely identify clients. NAT Firewalls and corporate proxies are everywhere, and hide many users behind a single IP.</p>\n" }, { "answer_id": 19522170, "author": "depoip", "author_id": 1597660, "author_profile": "https://Stackoverflow.com/users/1597660", "pm_score": 0, "selected": false, "text": "<p>I made the following function:</p>\n\n<pre><code>static public string sGetIP()\n{\n try\n {\n string functionReturnValue = null;\n\n String oRequestHttp =\n WebOperationContext.Current.IncomingRequest.Headers[\"User-Host-Address\"];\n if (string.IsNullOrEmpty(oRequestHttp))\n {\n OperationContext context = OperationContext.Current;\n MessageProperties prop = context.IncomingMessageProperties;\n RemoteEndpointMessageProperty endpoint =\n prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;\n oRequestHttp = endpoint.Address;\n }\n return functionReturnValue;\n }\n catch (Exception ex)\n {\n return \"unknown IP\";\n }\n}\n</code></pre>\n\n<p>This work only in Intranet, if you have some Proxy or natting you should study if the original IP is moved somewhere else in the http packet.</p>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/130328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
How do I get the caller's IP address in a WebMethod? ``` [WebMethod] public void Foo() { // HttpRequest... ? - Not giving me any options through intellisense... } ``` using C# and ASP.NET
[HttpContext.Current.Request.UserHostAddress](http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress.aspx) is what you want.