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> nam...
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/texta...
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>...
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" }, { ...
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 ...
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...
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 y...
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 exp...
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 c...
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...
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. ...
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 d...
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 validatio...
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 nee...
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 me...
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...
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...
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>\...
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, I...
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/p...
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...
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 rewriti...
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 alwa...
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 $OUTPU...
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 $OUTPU...
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-l...
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://framew...
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 #...
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 l...
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...
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.w3sch...
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 afte...
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...
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,\"...
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" }, { "ans...
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...
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 ...
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...
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\...
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\" ...
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 ...
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 y...
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 Ayend...
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 ...
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 a...
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 SHA1Crypto...
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><...
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>D...
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 ...
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 ...
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. S...
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 exa...
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.Contro...
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...
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\...
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 excep...
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 \...
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\"...
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://rad...
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 ta...
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 ...
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...
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 t...
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 s...
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:...
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 A...
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...
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 el...
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 ...
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 b...
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...
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² + b...
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/1...
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, "autho...
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 ...
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": ...
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 tha...
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>Examp...
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 di...
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=\"nofollo...
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/librar...
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 fr...
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\...
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</...
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)\...
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 appli...
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 u...
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><...
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 w...
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.Cus...
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......
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.chamina...
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\">Typ...
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" }, { ...
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 =...
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 sev...
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=\"...
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 fu...
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<...
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\">HttpCon...
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.