qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
42,187
<p>I have read about partial methods in the latest <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="noreferrer">C# language specification</a>, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?</p>
[ { "answer_id": 43557, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 6, "selected": true, "text": "#region" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
42,203
<p>I'm looking to use SQL to format a number with commas in the thousands, but no decimal (so can't use Money) - any suggestions?</p> <p>I'm using SQL Server 2005, but feel free to answer for others as well (like MySQL)</p>
[ { "answer_id": 42209, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "FORMAT()" }, { "answer_id": 42224, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 2, "selected": false, "text": "replace(convert(varchar, cast(column as money), 1), '.00', '')\n" }, { "answer_id": 42238, "author": "nickd", "author_id": 2373, "author_profile": "https://Stackoverflow.com/users/2373", "pm_score": 0, "selected": false, "text": "replace(convert (varchar, convert (money, 109999), 1), '.00','')\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
42,215
<p>We get the following error;</p> <pre><code>The request was aborted: Could not create SSL/TLS secure channel </code></pre> <p>while using a <code>WebRequest</code> object to make an <code>HTTPS</code> request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. </p> <p>Has anyone seen this kind of thing before?</p>
[ { "answer_id": 32132106, "author": "Vyacheslav Kinzerskiy", "author_id": 5250067, "author_profile": "https://Stackoverflow.com/users/5250067", "pm_score": 1, "selected": false, "text": "System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
42,239
<p>We're doing an "Amazing Race" kind of event, and thought it would be cool to have CDs that could only play once... like a "this message will self destruct in 5 seconds..." </p> <p>Any thoughts on how to do this? I was thinking it could be a compiled HTML website that would write a cookie and only play once. I don't want to write to the registry (don't want to depend on windows, don't want to install anything, etc).</p> <p>I also don't care if it's hackable... This is a one-time fun event, and I don't really care too much if people could remove the cookie or something.</p> <p>Any other ideas?</p>
[ { "answer_id": 42417, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 2, "selected": false, "text": "Math.floor(PI * E + 32/(new DateTime()).getYear())" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753/" ]
42,246
<p>I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. </p> <p>The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server.</p> <p>I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files.</p> <p>Are there any other suggestions?</p> <p>Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN:</p> <p>from <a href="http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml" rel="nofollow noreferrer">http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml</a></p> <pre><code>* select the two revisions * right-click, "compare revisions" * select all files in the list * right-click, choose "export to..." </code></pre>
[ { "answer_id": 42503, "author": "Dylan Bennett", "author_id": 551, "author_profile": "https://Stackoverflow.com/users/551", "pm_score": 1, "selected": false, "text": "/\n|+-DIR1\n| |- FILEa\n| |- FILEb\n|+-DIR2\n| |- FILEc\n| |- FILEd\n|- FILEe\n|- FILEf\n" }, { "answer_id": 45983, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 2, "selected": true, "text": "cd deploy\nsvn update\nrsync -a . server:webdir/\n" }, { "answer_id": 262104, "author": "bolk", "author_id": 32764, "author_profile": "https://Stackoverflow.com/users/32764", "pm_score": 2, "selected": false, "text": "svn export" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442/" ]
42,247
<p>The following code illustrates an object literal being assigned, but with no semicolon afterwards:</p> <pre><code>var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); </code></pre> <p>This appears to be legal, and doesn't issue a warning (at least in Firefox&nbsp;3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?</p> <p>I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.</p>
[ { "answer_id": 42259, "author": "Kamiel Wanrooij", "author_id": 4174, "author_profile": "https://Stackoverflow.com/users/4174", "pm_score": -1, "selected": false, "text": "var foo = \"bar\";\n" }, { "answer_id": 42269, "author": "Travis", "author_id": 4284, "author_profile": "https://Stackoverflow.com/users/4284", "pm_score": 0, "selected": false, "text": "javascript.options.strict" }, { "answer_id": 42311, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 4, "selected": false, "text": "var literal = {\n say: function(msg) { alert(msg); }\n}\n(function() {\n // ....\n})();\n" }, { "answer_id": 42317, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 2, "selected": false, "text": "break" }, { "answer_id": 42510, "author": "JesDaw", "author_id": 4440, "author_profile": "https://Stackoverflow.com/users/4440", "pm_score": 3, "selected": false, "text": "var foo = 'bar'\n// Valid, foo now contains 'bar'\nvar bas =\n { prop: 'yay!' }\n// Valid, bas now contains object with property 'prop' containing 'yay!'\nvar zeb =\nswitch (zeb) {\n ...\n// Invalid, because the lines following 'var zeb =' aren't an assignable value\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
42,251
<p>Has anyone worked much with Microsoft's Managed Extensibility Framework (MEF)? Kinda sounds like it's trying to be all things to all people - It's an add-in manager! It's duck typing! I'm wondering if anyone has an experience with it, positive or negative.</p> <p>We're currently planning on using an generic IoC implementation ala MvcContrib for our next big project. Should we throw MEF in the mix?</p>
[ { "answer_id": 57884, "author": "Andy S", "author_id": 3759, "author_profile": "https://Stackoverflow.com/users/3759", "pm_score": 3, "selected": false, "text": "private IGreetings greetings = CompositionServices.Empty<IGreetings>();\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3759/" ]
42,254
<p>I would like to flash a success message on my page.</p> <p>I am using the jQuery <code>fadeOut</code> method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.</p> <p>What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.</p> <p>How can you animate this using jQuery? </p>
[ { "answer_id": 42255, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "setTimeout(function(){$elem.hide();}, 5000);" }, { "answer_id": 42261, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 2, "selected": false, "text": "var $msg = $('#msg-container-id');\n$msg.fadeIn(function(){\n setTimeout(function(){\n $msg.fadeOut(function(){\n $msg.remove();\n });\n },5000);\n});\n" }, { "answer_id": 42271, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "$(\"#element\").animate({opacity: 1.0}, 5000).fadeOut();\n" }, { "answer_id": 42698, "author": "dansays", "author_id": 1923, "author_profile": "https://Stackoverflow.com/users/1923", "pm_score": 3, "selected": false, "text": "setTimeout()" }, { "answer_id": 80675, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 2, "selected": false, "text": "$('#thing') .animate({dummy:1}, 2000)\n .animate({ etc ... });" }, { "answer_id": 2068227, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 6, "selected": true, "text": "delay()" }, { "answer_id": 3040106, "author": "thekingoftruth", "author_id": 241367, "author_profile": "https://Stackoverflow.com/users/241367", "pm_score": 1, "selected": false, "text": "remove()" }, { "answer_id": 7735285, "author": "rjmoggach", "author_id": 586932, "author_profile": "https://Stackoverflow.com/users/586932", "pm_score": 0, "selected": false, "text": "fadeOut" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645/" ]
42,281
<p>It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on.</p> <p>Is there a specific HTTP Header that IE6 does listen too?</p>
[ { "answer_id": 43271, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 4, "selected": true, "text": "Cache-Control: private, max-age=0" }, { "answer_id": 203450, "author": "thesmart", "author_id": 20176, "author_profile": "https://Stackoverflow.com/users/20176", "pm_score": 1, "selected": false, "text": "http://test.com?nonce=0123 \n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
42,286
<p>It seems like there should be something shorter than this:</p> <pre><code>private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } } </code></pre>
[ { "answer_id": 42292, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "string text = File.ReadAllText(\"c:\\file1.txt\");\nFile.WriteAllText(\"c:\\file2.txt\", text);\n" }, { "answer_id": 42293, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 5, "selected": true, "text": "using System.IO;\n...\nstring filename = \"C:/example.txt\";\nstring content = File.ReadAllText(filename);\nFile.WriteAllText(filename, content);\n" }, { "answer_id": 42322, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 2, "selected": false, "text": " private string LoadFromFile(string path)\n {\n using(StreamReader rdr = File.OpenText(path))\n return rdr.ReadToEnd();\n }\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475/" ]
42,294
<p>I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case. </p>
[ { "answer_id": 42301, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 9, "selected": true, "text": "<div>" }, { "answer_id": 42314, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 4, "selected": false, "text": "#footer" }, { "answer_id": 42315, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 5, "selected": false, "text": "position: absolute" }, { "answer_id": 9345207, "author": "Sophivorus", "author_id": 809356, "author_profile": "https://Stackoverflow.com/users/809356", "pm_score": 4, "selected": false, "text": "$( function () {\n\n var height_diff = $( window ).height() - $( 'body' ).height();\n if ( height_diff > 0 ) {\n $( '#footer' ).css( 'margin-top', height_diff );\n }\n\n});\n" }, { "answer_id": 12130241, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 1, "selected": false, "text": "position: absolute; bottom: 0;" }, { "answer_id": 26090114, "author": "Danield", "author_id": 703717, "author_profile": "https://Stackoverflow.com/users/703717", "pm_score": 7, "selected": false, "text": "<header>header goes here</header>\n<div class=\"content\">This page has little content</div>\n<footer>This is my footer</footer>\n" }, { "answer_id": 27587208, "author": "Ajith", "author_id": 4357818, "author_profile": "https://Stackoverflow.com/users/4357818", "pm_score": 1, "selected": false, "text": " #container{\n width: 100%;\n height: 100vh;\n }\n #container.footer{\n float:left;\n width:100%;\n height:20vh;\n margin-top:80vh;\n background-color:red;\n }\n" }, { "answer_id": 31528677, "author": "Kyle Zimmer", "author_id": 4293638, "author_profile": "https://Stackoverflow.com/users/4293638", "pm_score": 0, "selected": false, "text": "html {\n position: relative;\n min-height: 100%;\n}\n\nbody {\n background-color: transparent;\n position: static;\n height: 100%;\n margin-bottom: 30px;\n}\n\n.site-footer {\n position: absolute;\n height: 30px;\n bottom: 0px;\n left: 0px;\n right: 0px;\n}\n" }, { "answer_id": 34146411, "author": "gcedo", "author_id": 1871238, "author_profile": "https://Stackoverflow.com/users/1871238", "pm_score": 6, "selected": false, "text": "display: flex" }, { "answer_id": 34823140, "author": "DevWL", "author_id": 2179965, "author_profile": "https://Stackoverflow.com/users/2179965", "pm_score": 0, "selected": false, "text": "auto" }, { "answer_id": 35310742, "author": "jjr2000", "author_id": 3412043, "author_profile": "https://Stackoverflow.com/users/3412043", "pm_score": 1, "selected": false, "text": "html,\nbody {\n height: 100%;\n margin: 0;\n}\n.body {\n min-height: calc(100% - 2rem);\n width: 100%;\n background-color: grey;\n}\n.footer {\n height: 2rem;\n width: 100%;\n background-color: yellow;\n}" }, { "answer_id": 39199515, "author": "user1235285", "author_id": 1235285, "author_profile": "https://Stackoverflow.com/users/1235285", "pm_score": 0, "selected": false, "text": "$(window).on('resize',sticky);\n$(document).bind(\"ready\", function() {\n sticky();\n});\n\nfunction sticky() {\n var fh = $(\"footer\").outerHeight();\n $(\"#push\").css({'height': fh});\n $(\"#wrapper\").css({'margin-bottom': -fh});\n}\n" }, { "answer_id": 39449537, "author": "Ravinder Payal", "author_id": 2988776, "author_profile": "https://Stackoverflow.com/users/2988776", "pm_score": 0, "selected": false, "text": "footer.init(document.getElementById(\"ID_OF_ELEMENT_CONTAINING_FOOTER\"));\n" }, { "answer_id": 44682287, "author": "Laughing Horse", "author_id": 6391229, "author_profile": "https://Stackoverflow.com/users/6391229", "pm_score": 0, "selected": false, "text": "footer {\n position: fixed;\n right: 0;\n bottom: 0;\n left: 0;\n padding: 1rem;\n background-color: #efefef;\n text-align: center;\n}\n" }, { "answer_id": 44771365, "author": "Reggie Pinkham", "author_id": 2927114, "author_profile": "https://Stackoverflow.com/users/2927114", "pm_score": 0, "selected": false, "text": "<body>\n <header>\n ...\n </header>\n <main>\n ...\n </main>\n <footer>\n ...\n </footer>\n</body> \n" }, { "answer_id": 45021713, "author": "Daniel Alsaker", "author_id": 5872527, "author_profile": "https://Stackoverflow.com/users/5872527", "pm_score": 2, "selected": false, "text": "html {\n position: relative;\n}\n\nhtml, body {\n margin: 0;\n padding: 0;\n min-height: 100%;\n}\n\nfooter {\n position: absolute;\n bottom: 0;\n}\n" }, { "answer_id": 47489319, "author": "juan Isaza", "author_id": 2394901, "author_profile": "https://Stackoverflow.com/users/2394901", "pm_score": 0, "selected": false, "text": "#my_footer {\n position: static\n fixed; bottom: 0\n}\n" }, { "answer_id": 47640893, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 3, "selected": false, "text": "margin-top:auto" }, { "answer_id": 52106754, "author": "Roger", "author_id": 558193, "author_profile": "https://Stackoverflow.com/users/558193", "pm_score": 0, "selected": false, "text": " jQuery(document).ready(function() {\n\n var fht = jQuery('footer').outerHeight(true);\n jQuery('main').css('min-height', \"calc(92vh - \" + fht + \"px)\");\n\n});\n" }, { "answer_id": 52440647, "author": "VXp", "author_id": 2851632, "author_profile": "https://Stackoverflow.com/users/2851632", "pm_score": 2, "selected": false, "text": "height: 100%" }, { "answer_id": 53919076, "author": "antelove", "author_id": 7656367, "author_profile": "https://Stackoverflow.com/users/7656367", "pm_score": 1, "selected": false, "text": "div.fixed {\n position: fixed;\n bottom: 0;\n right: 0;\n width: 100%;\n border: 3px solid #73AD21;\n}" }, { "answer_id": 58892044, "author": "kiko carisse", "author_id": 5045446, "author_profile": "https://Stackoverflow.com/users/5045446", "pm_score": 1, "selected": false, "text": "html {\n min-height: 100%;\n position: relative;\n}\n\n#site-footer {\n position: absolute;\n bottom: 0;\n left: 0;\n width: 100%;\n padding: 6px 2px;\n background: #32383e;\n}\n" }, { "answer_id": 63382499, "author": "cssyphus", "author_id": 1447509, "author_profile": "https://Stackoverflow.com/users/1447509", "pm_score": 0, "selected": false, "text": "html,body{height: 100%;}\nbody {display:flex; flex-direction:column;}\n.content {flex: 1 0 auto;} /* flex: grow / shrink / flex-basis; */\n.footer {flex-shrink: 0;}\n\n/* ---- BELOW IS ONLY for demo ---- */\n.footer{background: palegreen;}" }, { "answer_id": 65774517, "author": "Juliano Suman Curti", "author_id": 14145197, "author_profile": "https://Stackoverflow.com/users/14145197", "pm_score": 0, "selected": false, "text": "<div class=\"parent\">\n <header class=\"blue section\" contenteditable>Header</header>\n <main class=\"coral section\" contenteditable>Main</main>\n <footer class=\"purple section\" contenteditable>Footer Content</footer>\n</div>\n \n" }, { "answer_id": 67166444, "author": "siaeva", "author_id": 3494114, "author_profile": "https://Stackoverflow.com/users/3494114", "pm_score": 2, "selected": false, "text": ".page-body {min-height: calc(100vh - 400px);} /*Replace 400px with your footer height*/" }, { "answer_id": 67828478, "author": "Matt", "author_id": 10266312, "author_profile": "https://Stackoverflow.com/users/10266312", "pm_score": 1, "selected": false, "text": "position: fixed;\n" }, { "answer_id": 69988420, "author": "DINA TAKLIT", "author_id": 9039646, "author_profile": "https://Stackoverflow.com/users/9039646", "pm_score": 0, "selected": false, "text": "html" }, { "answer_id": 73325579, "author": "Shubham Sarda", "author_id": 7846238, "author_profile": "https://Stackoverflow.com/users/7846238", "pm_score": 0, "selected": false, "text": "<main>" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
42,308
<p>Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.</p>
[ { "answer_id": 42513, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 8, "selected": true, "text": "-M" }, { "answer_id": 1763463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ".dep:\n mkdir $@\n.dep/%.dep: %.c .dep\n (echo $@ \\\\; $(CC) $(IFLAGS) -MM $<) > $@ || (rm $@; false)\n.dep/%.dep: %.cpp .dep\n (echo $@ \\\\; $(CXX) $(IFLAGS) -MM $<) > $@ || (rm $@; false)\nDEPEND := $(patsubst %.dep,.dep/%.dep,$(OBJ:.o=.dep))\n-include $(DEPEND)\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
42,323
<p>I have the next function:</p> <pre><code>function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i &lt; images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } </code></pre> <p>I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. </p> <hr> <p><code>images[i].offsetWidth</code> returns 111 for an image of 109px width. Is this because 1px each side border? </p>
[ { "answer_id": 42331, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "var myImage = document.getElementById(\"myImagesId\");\nvar imageWidth = myImage.offsetWidth;\nvar imageHeight = myImage.offsetHeight;\n" }, { "answer_id": 42362, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 0, "selected": false, "text": "clientWidth" }, { "answer_id": 42381, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 0, "selected": false, "text": "// width in pixels\nfunction setImagesWidth(id,width) {\n var images = document.getElementById(id).getElementsByTagName(\"img\");\n for(var i = 0; i < images.length;i++) {\n if(images[i].offsetWidth > width) {\n images[i].style.width= (width+\".px\"); \n } \n } \n}\n" }, { "answer_id": 42494, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 2, "selected": true, "text": "clientWidth" }, { "answer_id": 28289783, "author": "Tomáš Zato", "author_id": 607407, "author_profile": "https://Stackoverflow.com/users/607407", "pm_score": 0, "selected": false, "text": "var img = new Image(\"path...\");\nvar width = image.naturalWidth;\nvar height = image.naturalHeight;\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
42,333
<p>I'm wondering how to use a VideoDisplay object (defined in MXML) to display video streamed from FMS via a NetStream.</p> <p>The <a href="http://livedocs.adobe.com/flex/3/langref/mx/controls/VideoDisplay.html" rel="noreferrer">Flex3 docs</a> suggest this is possible:</p> <blockquote> <p>The Video Display ... supports progressive download over HTTP, streaming from the Flash Media Server, and streaming from a Camera object.</p> </blockquote> <p>However, later in the docs all I can see is an attachCamera() method. There doesn't appear to be an attachStream() method like the old Video object has.</p> <p>It looks like you can play a fixed file served over HTML by using the source property, but I don't see anything about how to attach a NetStream.</p> <p>The old <a href="http://livedocs.adobe.com/flex/3/langref/flash/media/Video.html" rel="noreferrer">Video</a> object still seems to exist, though it's not based on UIComponent and doesn't appear to be usable in MXML.</p> <p>I found <a href="http://blog.flexexamples.com/2008/03/01/displaying-a-video-in-flex-using-the-netconnection-netstream-and-video-classes/" rel="noreferrer">this blog post</a> that shows how to do it with a regular Video object, but I'd much prefer to use VideoDisplay (or something else that can be put directly in the MXML).</p>
[ { "answer_id": 762430, "author": "Ken Smith", "author_id": 68231, "author_profile": "https://Stackoverflow.com/users/68231", "pm_score": 2, "selected": false, "text": "// Connect to the video stream in question.\nvar stream:NetStream = new NetStream( chatNC );\nstream.addEventListener( NetStatusEvent.NET_STATUS, handleStreamStatus );\nstream.addEventListener( IOErrorEvent.IO_ERROR, handleIOError );\n\n// Build the video player on the UI.\nvar video:Video = new Video(246, 189);\nvar uiComp:UIComponent = new UIComponent();\nuiComp.addChild( video );\nuiComp.width = 246;\nuiComp.height = 189;\nstream.play( streamName );\nvideo.attachNetStream( stream );\nvideo.smoothing = true;\nvideo.width = 246;\nvideo.height = 189;\nview.videoPlayerPanel.removeAllChildren();\nview.videoPlayerPanel.addChild( uiComp );\n" }, { "answer_id": 3117046, "author": "Cosma Colanicchia", "author_id": 11867, "author_profile": "https://Stackoverflow.com/users/11867", "pm_score": 4, "selected": false, "text": "VideoDisplay" }, { "answer_id": 3489354, "author": "Alexander Farber", "author_id": 165071, "author_profile": "https://Stackoverflow.com/users/165071", "pm_score": 2, "selected": false, "text": "<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n layout=\"vertical\"\n verticalAlign=\"middle\"\n backgroundColor=\"white\"\n creationComplete=\"init();\">\n\n<mx:Script>\n<![CDATA[\n import mx.utils.ObjectUtil;\n\n private var nc:NetConnection;\n private var ns:NetStream;\n private var video:Video;\n private var meta:Object;\n\n private function init():void {\n var nsClient:Object = {};\n nsClient.onMetaData = ns_onMetaData;\n nsClient.onCuePoint = ns_onCuePoint;\n\n nc = new NetConnection();\n nc.connect(null);\n\n ns = new NetStream(nc);\n ns.play(\"http://www.helpexamples.com/flash/video/cuepoints.flv\");\n ns.client = nsClient;\n\n video = new Video();\n video.attachNetStream(ns);\n uic.addChild(video);\n }\n\n private function ns_onMetaData(item:Object):void {\n trace(\"meta\");\n meta = item;\n // Resize Video object to same size as meta data.\n video.width = item.width;\n video.height = item.height;\n // Resize UIComponent to same size as Video object.\n uic.width = video.width;\n uic.height = video.height;\n panel.title = \"framerate: \" + item.framerate;\n panel.visible = true;\n trace(ObjectUtil.toString(item));\n }\n\n private function ns_onCuePoint(item:Object):void {\n trace(\"cue\");\n }\n]]>\n</mx:Script>\n\n<mx:Panel id=\"panel\" visible=\"false\">\n <mx:UIComponent id=\"uic\" />\n <mx:ControlBar>\n <mx:Button label=\"Play/Pause\" click=\"ns.togglePause();\" />\n <mx:Button label=\"Rewind\" click=\"ns.seek(0); ns.pause();\" />\n </mx:ControlBar>\n</mx:Panel>\n</mx:Application>\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409/" ]
42,342
<p>Sometimes IE6 will render the text of a <code>&lt;ul&gt;</code> list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.</p> <p>It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?</p>
[ { "answer_id": 42346, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": ".mylist {\n line-height: 1.6em;\n}\n" }, { "answer_id": 42352, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": true, "text": "zoom: 1\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
42,345
<p>How can I determine if a string is an IP address? Either <em>IPv4</em> or <em>IPv6</em>?</p> <p>What is the least and most number of characters?</p> <p>I assume this would be a <strong>regex</strong> answer.</p>
[ { "answer_id": 42359, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\n" }, { "answer_id": 42376, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 0, "selected": false, "text": "bool IsValidIPAddress(string possibleIP){\n CrazyRegex = \\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){4}\\b\n return Regex.Match(possibleIP+'.', CrazyRegex)\n}\n" }, { "answer_id": 42384, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}\n" }, { "answer_id": 42393, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){\n //validatedIPAddress is good\n}\n\n// or more simply:\nbool IsValidIPAddress(string possibleIP){\n return System.Net.IPAddress.TryParse(PossibleIPAddress, null)\n}\n" }, { "answer_id": 42413, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 3, "selected": false, "text": "function isDottedIPv4(s)\n{\n var match = s.match(/^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/);\n return match != null &&\n match[1] <= 255 && match[2] <= 255 &&\n match[3] <= 255 && match[4] <= 255;\n}\n" }, { "answer_id": 42584, "author": "Dough", "author_id": 4451, "author_profile": "https://Stackoverflow.com/users/4451", "pm_score": -1, "selected": false, "text": "/\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?/" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
42,357
<p>I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB.</p> <p>My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page.</p> <p>How do you check your URL's for SQL Injection attacks?</p>
[ { "answer_id": 42369, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "// Bad!\nSqlCommand foo = new SqlCommand(\"SELECT FOO FROM BAR WHERE LOL='\" + Request.QueryString[\"LOL\"] + \"'\");\n\n//Good! Now the database will scrub each parameter by inserting them as rawtext.\nSqlCommand foo = new SqlCommany(\"SELECT FOO FROM BAR WHERE LOL = @LOL\");\nfoo.Parameters.AddWithValue(\"@LOL\",Request.QueryString[\"LOL\"]);\n" }, { "answer_id": 42662, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "cast(0x" }, { "answer_id": 337965, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<iframe src=\"https://www.learnsecurityonline.com/XMLHttpRequest.html\" width=1 height=1></ifame>\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
42,383
<p>I am writing an immutable DOM tree in Java, to simplify access from multiple threads.*</p> <p>However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tree.</p> <p>My question is, would it be dramatically faster to pre-allocate nodes rather than create new ones every time the tree is modified? It would be fairly easy to do - keep a pool of several hundred unused nodes, and pull one out of the pool rather than create one whenever it was required for a modify operation. I can replenish the node pool when there's nothing else going on. (in case it isn't obvious, execution time is going to be much more at a premium in this application than heap space is)</p> <p>Is it worthwhile to do this? Any other tips on speeding it up?</p> <p>Alternatively, does anyone know if an immutable DOM library already? I searched, but couldn't find anything.</p> <p>*Note: For those of you who aren't familiar with the concept of immutability, it basically means that on any operation to an object that changes it, the method returns a copy of the object with the changes in place, rather than the changed object. Thus, if another thread is still reading the object it will continue to happily operate on the "old" version, unaware that changes have been made, rather than crashing horribly. See <a href="http://www.javapractices.com/topic/TopicAction.do?Id=29" rel="nofollow noreferrer">http://www.javapractices.com/topic/TopicAction.do?Id=29</a></p>
[ { "answer_id": 42500, "author": "levand", "author_id": 3044, "author_profile": "https://Stackoverflow.com/users/3044", "pm_score": 0, "selected": false, "text": "node.addChild()" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3044/" ]
42,386
<p>Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?</p> <pre><code>//pseudo-codeish string s = Coalesce(string1, string2, string3); </code></pre> <p>or, more generally,</p> <pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx); </code></pre>
[ { "answer_id": 42387, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "string a = nullstring ?? \"empty!\";\n" }, { "answer_id": 42397, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 4, "selected": false, "text": "object obj = Coalesce(obj1, obj2, obj3, ...objx);\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4438/" ]
42,395
<p>How do you write the syntax for a While loop?</p> <h2>C<code>#</code></h2> <pre><code>int i = 0; while (i != 10) { Console.WriteLine(i); i++; } </code></pre> <h2>VB.Net</h2> <pre><code>Dim i As Integer = 0 While i &lt;&gt; 10 Console.WriteLine(i) i += 1 End While </code></pre> <h2>PHP</h2> <pre><code>&lt;?php while(CONDITION) { //Do something here. } ?&gt; &lt;?php //MySQL query stuff here $result = mysql_query($sql, $link) or die("Opps"); while($row = mysql_fetch_assoc($result)) { $_SESSION['fName'] = $row['fName']; $_SESSION['lName'] = $row['lName']; //... } ?&gt; </code></pre> <h2>Python</h2> <pre><code>i = 0 while i != 10: print i i += 1 </code></pre>
[ { "answer_id": 42409, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 4, "selected": true, "text": "<?php\nwhile(CONDITION)\n{\n//Do something here.\n}\n?>\n" }, { "answer_id": 42420, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 3, "selected": false, "text": "While" }, { "answer_id": 1134686, "author": "SingleNegationElimination", "author_id": 65696, "author_profile": "https://Stackoverflow.com/users/65696", "pm_score": 0, "selected": false, "text": "set i 0\nwhile {$i != 10} {\n puts $i\n incr i\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
42,396
<p>Here's the code from the ascx that has the repeater:</p> <pre><code>&lt;asp:Repeater ID="ListOfEmails" runat="server" &gt; &lt;HeaderTemplate&gt;&lt;h3&gt;A sub-header:&lt;/h3&gt;&lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; [Some other stuff is here] &lt;asp:Button ID="removeEmail" runat="server" Text="X" ToolTip="remove" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <p>And in the codebehind for the repeater's databound and events:</p> <pre><code>Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("&lt;h1&gt;click&lt;/h1&gt;") End Sub Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write("&lt;h1&gt;command&lt;/h1&gt;") End Sub </code></pre> <p>Neither the click or command is getting called, what am I doing wrong?</p>
[ { "answer_id": 42412, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": "Repeater.ItemCommand" }, { "answer_id": 4996126, "author": "Piotr Latusek", "author_id": 562786, "author_profile": "https://Stackoverflow.com/users/562786", "pm_score": 2, "selected": false, "text": "protected void Page_Init(object sender, EventArgs e)\n{\n // rptr is your repeater's name\n rptr.ItemCommand += new RepeaterCommandEventHandler(rptr_ItemCommand);\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
42,416
<p>I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with : 'Thread (nil) may have been prematurely finalized'.</p>
[ { "answer_id": 67689, "author": "jldugger", "author_id": 9947, "author_profile": "https://Stackoverflow.com/users/9947", "pm_score": 3, "selected": true, "text": "apt-cache search libgluezilla\nlibmono-mozilla0.1-cil - Mono Mozilla library\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
42,422
<p>Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak.</p> <p>EG:</p> <pre><code>try dim mySQL as new sqlcommand(sSQL, cnInput) // do a sql execute and read the data mySQL = new sqlcommand(sSQLdifferent, cnInput) // do sql execute and read the data catch ... finally if mysql isnot nothing then mysql.dispose mysql = nothing end if </code></pre> <p>EDIT: put try catch in to avoid the comments about not using them</p>
[ { "answer_id": 42445, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": true, "text": "Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)\n ' do stuff'\nEnd Using\n\nUsing mysql as SqlCommand = new SqlCommand(otherSql, cnInput)\n ' do other stuff'\nEnd Using\n" }, { "answer_id": 42454, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 1, "selected": false, "text": "Dispose" }, { "answer_id": 42501, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "IDisposable" }, { "answer_id": 43118, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "Using mysql as New SqlCommand(sSql, cnInput)\n ' do stuff'\n\n mySql.CommandText = otherSql\n\n 'do other stuff'\nEnd Using\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
42,428
<p>X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.</p> <p>Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?</p> <p>I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.</p>
[ { "answer_id": 42445, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": true, "text": "Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)\n ' do stuff'\nEnd Using\n\nUsing mysql as SqlCommand = new SqlCommand(otherSql, cnInput)\n ' do other stuff'\nEnd Using\n" }, { "answer_id": 42454, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 1, "selected": false, "text": "Dispose" }, { "answer_id": 42501, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "IDisposable" }, { "answer_id": 43118, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "Using mysql as New SqlCommand(sSql, cnInput)\n ' do stuff'\n\n mySql.CommandText = otherSql\n\n 'do other stuff'\nEnd Using\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476/" ]
42,437
<p>I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters.</p> <p>Is there a better way to deal with this sort of input? </p> <p>Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.</p>
[ { "answer_id": 589283, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 2, "selected": false, "text": "KeyPress" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
42,438
<p>I have some code that uses SMO to populate a list of available SQL Servers and databases. While we no longer support SQL Server 2000, it's possible that the code could get run on a machine that SQL Server 2000 and not have the SMO library installed. I would perfer to check for SMO first and degrade the functionality gracefully instead of blowing up in the user's face. What is best way to detect whether or not SMO is available on a machine?</p> <p>Every example that I have seen through a quick Google scan was a variation of "look for C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll". The problem with that approach is that it only works with SQL Server 2005. If SQL Server 2008 is the only SQL Server installed then the path will be different.</p>
[ { "answer_id": 42577, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "private bool CheckForSmo()\n{\n string RegKeyName = @\"Microsoft.SqlServer.Management.Smo.Database\";\n bool result = false;\n Microsoft.Win32.RegistryKey hkcr = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(RegKeyName);\n result = hkcr != null;\n\n if (hkcr != null)\n {\n hkcr.Close();\n }\n\n return result;\n}\n" }, { "answer_id": 16062310, "author": "Manni", "author_id": 509535, "author_profile": "https://Stackoverflow.com/users/509535", "pm_score": 1, "selected": false, "text": "HKLM\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\SharedManagementObjects\\CurrentVersion\\Version\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206/" ]
42,446
<pre><code>class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; </code></pre> <p><code>MemoryStream</code> will take a <code>byte[]</code> but I'd <em>like</em> to do this without copying the data if possible.</p>
[ { "answer_id": 42605, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 0, "selected": false, "text": "\nstatic Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)\n{\n //validate the input parameter\n if (szUnicodeString == NULL)\n {\n return nullptr;\n }\n\n //get the length of the string\n size_t lengthInWChars = wcslen(szUnicodeString); \n size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);\n\n //allocate the .Net byte array\n array^ byteArray = gcnew array(lengthInBytes);\n\n //copy the unmanaged memory into the byte array\n Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);\n\n //create a memory stream from the byte array\n return gcnew MemoryStream(byteArray);\n}" }, { "answer_id": 42968, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 4, "selected": true, "text": "UnmanagedMemoryStream()" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
42,460
<p>I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked.</p> <p>Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding <code>WndProc</code> to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked?</p> <p>I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself.</p>
[ { "answer_id": 44398, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "src\\chrome\\browser\\views\\frame" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
42,482
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
[ { "answer_id": 43301, "author": "paulmorriss", "author_id": 2983, "author_profile": "https://Stackoverflow.com/users/2983", "pm_score": 2, "selected": false, "text": "RO = PropertyValue('ReadOnly', 0, True, 0)\nHidden = PropertyValue('Hidden', 0, True, 0)\nxDoc = desktop.loadComponentFromURL( docpath,\"_blank\", 0, (RO, Hidden,) )\n" }, { "answer_id": 43364, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 5, "selected": true, "text": "import os\n\ndef doc_to_text_catdoc(filename):\n (fi, fo, fe) = os.popen3('catdoc -w \"%s\"' % filename)\n fi.close()\n retval = fo.read()\n erroroutput = fe.read()\n fo.close()\n fe.close()\n if not erroroutput:\n return retval\n else:\n raise OSError(\"Executing the command caused an error: %s\" % erroroutput)\n\n# similar doc_to_text_antiword()\n" }, { "answer_id": 1979931, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 4, "selected": false, "text": "document = opendocx('Hello world.docx')\n\n# This location is where most document content lives \ndocbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0]\n\n# Extract all text\nprint getdocumenttext(document)\n" }, { "answer_id": 20663596, "author": "Etienne", "author_id": 146481, "author_profile": "https://Stackoverflow.com/users/146481", "pm_score": 2, "selected": false, "text": "python-docx" }, { "answer_id": 51905584, "author": "Dhinesh kumar M", "author_id": 7479213, "author_profile": "https://Stackoverflow.com/users/7479213", "pm_score": 2, "selected": false, "text": "pip install tika\n" }, { "answer_id": 62974454, "author": "prossblad", "author_id": 5012591, "author_profile": "https://Stackoverflow.com/users/5012591", "pm_score": 0, "selected": false, "text": "#!/bin/python\n# -*- coding: utf-8 -*-\n\n# Class to extract metadata and text from different file types (such as PPT, XLS, and PDF)\n# Developed by Philippe ROSSIGNOL\n#####################\n# TikaWrapper class #\n#####################\nclass TikaWrapper:\n\n java_home = None\n tikalib_path = None\n\n # Constructor\n def __init__(self, java_home, tikalib_path):\n self.java_home = java_home\n self.tika_lib_path = tikalib_path\n\n def extractMetadata(self, filePath, encoding=\"UTF-8\", returnTuple=False):\n '''\n - Description:\n Extract metadata from a document\n \n - Params:\n filePath: The document file path\n encoding: The encoding (default = \"UTF-8\")\n returnTuple: If True return a tuple which contains both the output and the error (default = False)\n \n - Examples:\n metadata = extractMetadata(filePath=\"MyDocument.docx\")\n metadata, error = extractMetadata(filePath=\"MyDocument.docx\", encoding=\"UTF-8\", returnTuple=True)\n '''\n cmd = self._getCmd(self._cmdExtractMetadata, filePath, encoding)\n out, err = self._execute(cmd, encoding)\n if (returnTuple): return out, err\n return out\n\n def extractText(self, filePath, encoding=\"UTF-8\", returnTuple=False):\n '''\n - Description:\n Extract text from a document\n \n - Params:\n filePath: The document file path\n encoding: The encoding (default = \"UTF-8\")\n returnTuple: If True return a tuple which contains both the output and the error (default = False)\n \n - Examples:\n text = extractText(filePath=\"MyDocument.docx\")\n text, error = extractText(filePath=\"MyDocument.docx\", encoding=\"UTF-8\", returnTuple=True)\n '''\n cmd = self._getCmd(self._cmdExtractText, filePath, encoding)\n out, err = self._execute(cmd, encoding)\n return out, err\n\n # ===========\n # = PRIVATE =\n # ===========\n\n _cmdExtractMetadata = \"${JAVA_HOME}/bin/java -jar ${TIKALIB_PATH} --metadata ${FILE_PATH}\"\n _cmdExtractText = \"${JAVA_HOME}/bin/java -jar ${TIKALIB_PATH} --encoding=${ENCODING} --text ${FILE_PATH}\"\n\n def _getCmd(self, cmdModel, filePath, encoding):\n cmd = cmdModel.replace(\"${JAVA_HOME}\", self.java_home)\n cmd = cmd.replace(\"${TIKALIB_PATH}\", self.tika_lib_path)\n cmd = cmd.replace(\"${ENCODING}\", encoding)\n cmd = cmd.replace(\"${FILE_PATH}\", filePath)\n return cmd\n\n def _execute(self, cmd, encoding):\n import subprocess\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = process.communicate()\n out = out.decode(encoding=encoding)\n err = err.decode(encoding=encoding)\n return out, err\n" }, { "answer_id": 70816823, "author": "vhx.ai", "author_id": 18004763, "author_profile": "https://Stackoverflow.com/users/18004763", "pm_score": 0, "selected": false, "text": "pip install textract-plus\n" }, { "answer_id": 71948159, "author": "CpILL", "author_id": 196732, "author_profile": "https://Stackoverflow.com/users/196732", "pm_score": 0, "selected": false, "text": "pandoc -s input_file.docx -o output_file.txt\n" }, { "answer_id": 72573235, "author": "r-or", "author_id": 12875177, "author_profile": "https://Stackoverflow.com/users/12875177", "pm_score": 0, "selected": false, "text": "getiterator" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2678/" ]
42,490
<p><em>Disclaimer: I'm stuck on TFS and I hate it.</em></p> <p>My source control structure looks like this:</p> <ul> <li>/dev</li> <li>/releases</li> <li>/branches</li> <li>/experimental-upgrade</li> </ul> <p>I branched from dev to experimental-upgrade and didn't touch it. I then did some more work in dev and merged to experimental-upgrade. Somehow TFS complained that I had changes in both source and target and I had to resolve them. I chose to "Copy item from source branch" for all 5 items.</p> <p>I check out the experimental-upgrade to a local folder and try to open the main solution file in there. TFS prompts me: </p> <blockquote> <p>"Projects have recently been added to this solution. Would you like to get them from source control?</p> </blockquote> <p>If I say yes it does some stuff but ultimately comes back failing to load a handful of the projects. If I say no I get the same result.</p> <p>Comparing my sln in both branches tells me that they are equal.</p> <p>Can anyone let me know what I'm doing wrong? This should be a straightforward branch/merge operation...</p> <p>TIA.</p> <hr> <p><strong>UPDATE:</strong></p> <p>I noticed that if I click "yes" on the above dialog, the projects are downloaded to the $/ root of source control... (i.e. out of the dev &amp; branches folders)</p> <p>If I open up the solution in the branch and remove the dead projects and try to re-add them (by right-clicking sln, add existing project, choose project located in the branch folder, it gives me the error...</p> <blockquote> <p>Cannot load the project c:\sandbox\my_solution\proj1\proj1.csproj, the file has been removed or deleted. The project path I was trying to add is this: c:\sandbox\my_solution\branches\experimental-upgrade\proj1\proj1.csproj</p> </blockquote> <p>What in the world is pointing these projects <em>outside</em> of their local root? The solution file is identical to the one in the dev branch, and those projects load just fine. I also looked at the vspscc and vssscc files but didn't find anything.</p> <p>Ideas?</p>
[ { "answer_id": 42553, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 3, "selected": true, "text": "tf destroy [/keephistory] itemspec1 [;versionspec]\n [itemspec2...itemspecN] [/stopat:versionspec] [/preview]\n [/startcleanup] [/noprompt]\n\nVersionspec:\n Date/Time Dmm/dd/yyyy\n or any .Net Framework-supported format\n or any of the date formats of the local machine\n Changeset number Cnnnnnn\n Label Llabelname\n Latest version T\n Workspace Wworkspacename;workspaceowner\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381/" ]
42,499
<p>I've started working with ASP.net AJAX (finally ☺). and I've got an update panel together with a asp:UpdateProgress. My Problem: The UpdateProgress always forces a line-break, because it renders out as a div-tag.</p> <p>Is there any way to force it being a span instead? I want to display it on the same line as some other controls without having to use a table or even <em>shudders</em> absolute positioning in CSS.</p> <p>I'm stuck with ASP.net AJAX 1.0 and .net 3.0 if that makes a difference.</p>
[ { "answer_id": 42521, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": -1, "selected": false, "text": "<div style=\"display:inline\">stuff</div>\n" }, { "answer_id": 43825, "author": "Steven Williams", "author_id": 3294, "author_profile": "https://Stackoverflow.com/users/3294", "pm_score": 3, "selected": false, "text": "<form id=\"form1\" runat=\"server\">\n <div>\n <asp:ScriptManager ID=\"sm\" runat=\"server\"></asp:ScriptManager>\n\n\n <asp:UpdatePanel runat=\"server\" ID=\"up1\" UpdateMode=\"Always\">\n <ContentTemplate>\n <asp:Label ID=\"lblTest\" runat=\"server\"></asp:Label>\n <asp:Button ID=\"btnTest\" runat=\"server\" Text=\"Test\" OnClick=\"btnTest_OnClick\" />\n </ContentTemplate> \n </asp:UpdatePanel>\n <img id=\"loadingImg\" src=\"../../../images/loading.gif\" style=\"display:none;\"/><span>Some Inline text</span>\n\n <script>\n\n Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function(sender, args) {\n if (args.get_postBackElement().id == \"btnTest\") {\n document.getElementById(\"loadingImg\").style.display = \"inline\";\n }\n });\n\n\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {\n if (document.getElementById(\"loadingImg\").style.display != \"none\") {\n document.getElementById(\"loadingImg\").style.display = \"none\";\n }\n });\n\n </script>\n\n </div>\n</form>\n" }, { "answer_id": 1433511, "author": "Adiel", "author_id": 85045, "author_profile": "https://Stackoverflow.com/users/85045", "pm_score": 0, "selected": false, "text": "float:left" }, { "answer_id": 6813411, "author": "hamed aj", "author_id": 552223, "author_profile": "https://Stackoverflow.com/users/552223", "pm_score": 1, "selected": false, "text": "<asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\" UpdateMode=\"Conditional\">\n <ContentTemplate>\n ..........\n <span style=\"position:absolute;\">\n <asp:UpdateProgress ID=\"UpdateProgress1\" runat=\"server\"\n AssociatedUpdatePanelID=\"UpdatePanel1\">\n <ProgressTemplate>\n <img alt=\"please wait...\"src=\"/Images/progress-dots.gif\" />\n </ProgressTemplate>\n </asp:UpdateProgress> \n </span> \n </ContentTemplate>\n</asp:UpdatePanel>\n" }, { "answer_id": 7034438, "author": "Adam Youngers", "author_id": 798420, "author_profile": "https://Stackoverflow.com/users/798420", "pm_score": 0, "selected": false, "text": "<div class=\"load-inline\">LOADER HERE</div>\n" }, { "answer_id": 28278793, "author": "Hammer", "author_id": 4520128, "author_profile": "https://Stackoverflow.com/users/4520128", "pm_score": 2, "selected": false, "text": ".progress[style*=\"display: block;\"] {\n display:inline !important;\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
42,505
<p>I have a C# singleton class that multiple classes use. Is access through <code>Instance</code> to the <code>Toggle()</code> method thread-safe? If yes, by what assumptions, rules, etc. If no, why <em>and</em> how can I fix it?</p> <pre><code>public class MyClass { private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } } </code></pre>
[ { "answer_id": 42511, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 0, "selected": false, "text": "if(value == 0) { value = 1; }\nif(value == 1) { value = 0; }\nreturn value;\n" }, { "answer_id": 42517, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 2, "selected": false, "text": "private static object _lockDummy = new object();\n\n\n...\n\nlock(_lockDummy)\n{\n //do stuff\n}\n" }, { "answer_id": 42526, "author": "levand", "author_id": 3044, "author_profile": "https://Stackoverflow.com/users/3044", "pm_score": -1, "selected": false, "text": "value" }, { "answer_id": 42533, "author": "Thomas Watnedal", "author_id": 4059, "author_profile": "https://Stackoverflow.com/users/4059", "pm_score": 3, "selected": false, "text": "public class MyClass\n{\n private Object thisLock = new Object();\n private static readonly MyClass instance = new MyClass();\n public static MyClass Instance\n {\n get { return instance; }\n }\n private Int32 value = 0;\n public Int32 Toggle()\n {\n lock(thisLock)\n {\n if(value == 0) \n {\n value = 1; \n }\n else if(value == 1) \n { \n value = 0; \n }\n return value;\n }\n }\n}\n" }, { "answer_id": 42551, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": true, "text": "Toggle" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
42,512
<p>Is it possible to delete an GAE application after it has been created?</p> <p>I made a mistake while typing the name and now have a dummy application that I haven't been able to remove.</p>
[ { "answer_id": 56090825, "author": "balazs630", "author_id": 7343596, "author_profile": "https://Stackoverflow.com/users/7343596", "pm_score": 3, "selected": false, "text": "APIs & Services" }, { "answer_id": 61952720, "author": "iengchen", "author_id": 4318846, "author_profile": "https://Stackoverflow.com/users/4318846", "pm_score": 2, "selected": false, "text": "delete" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ]
42,519
<p>Inspired by <a href="https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003" rel="noreferrer">Raymond Chen's post</a>, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.</p> <pre><code>[1][2][3][4] [5][6][7][8] [9][0][1][2] [3][4][5][6] </code></pre> <p>Becomes:</p> <pre><code>[3][9][5][1] [4][0][6][2] [5][1][7][3] [6][2][8][4] </code></pre> <p><strong>Update</strong>: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?</p>
[ { "answer_id": 42535, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 8, "selected": true, "text": "int[,] array = new int[4,4] {\n { 1,2,3,4 },\n { 5,6,7,8 },\n { 9,0,1,2 },\n { 3,4,5,6 }\n};\n\nint[,] rotated = RotateMatrix(array, 4);\n\nstatic int[,] RotateMatrix(int[,] matrix, int n) {\n int[,] ret = new int[n, n];\n\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n ret[i, j] = matrix[n - j - 1, i];\n }\n }\n\n return ret;\n}\n" }, { "answer_id": 42578, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "def rotate(matrix)\n result = []\n 4.times { |x|\n result[x] = []\n 4.times { |y|\n result[x][y] = matrix[y][3 - x]\n }\n }\n\n result\nend\n\nmatrix = []\nmatrix[0] = [1,2,3,4]\nmatrix[1] = [5,6,7,8]\nmatrix[2] = [9,0,1,2]\nmatrix[3] = [3,4,5,6]\n\ndef print_matrix(matrix)\n 4.times { |y|\n 4.times { |x|\n print \"#{matrix[x][y]} \"\n }\n puts \"\"\n }\nend\n\nprint_matrix(matrix)\nputs \"\"\nprint_matrix(rotate(matrix))\n" }, { "answer_id": 42590, "author": "Kevin Berridge", "author_id": 4407, "author_profile": "https://Stackoverflow.com/users/4407", "pm_score": 3, "selected": false, "text": "string[,] orig = new string[n, m];\nstring[,] rot = new string[m, n];\n\n...\n\nfor ( int i=0; i < n; i++ )\n for ( int j=0; j < m; j++ )\n rot[j, n - i - 1] = orig[i, j];\n" }, { "answer_id": 43333, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 5, "selected": false, "text": "static void Main (string [] args)\n{\n int [,]\n // create an arbitrary matrix\n m = {{0, 1}, {2, 3}, {4, 5}};\n\n Matrix\n // create wrappers for the data\n m1 = new Matrix (m),\n m2 = new Matrix (m),\n m3 = new Matrix (m);\n\n // rotate the matricies in various ways - all are O(1)\n m1.RotateClockwise90 ();\n m2.Rotate180 ();\n m3.RotateAnitclockwise90 ();\n\n // output the result of transforms\n System.Diagnostics.Trace.WriteLine (m1.ToString ());\n System.Diagnostics.Trace.WriteLine (m2.ToString ());\n System.Diagnostics.Trace.WriteLine (m3.ToString ());\n}\n\nclass Matrix\n{\n enum Rotation\n {\n None,\n Clockwise90,\n Clockwise180,\n Clockwise270\n }\n\n public Matrix (int [,] matrix)\n {\n m_matrix = matrix;\n m_rotation = Rotation.None;\n }\n\n // the transformation routines\n public void RotateClockwise90 ()\n {\n m_rotation = (Rotation) (((int) m_rotation + 1) & 3);\n }\n\n public void Rotate180 ()\n {\n m_rotation = (Rotation) (((int) m_rotation + 2) & 3);\n }\n\n public void RotateAnitclockwise90 ()\n {\n m_rotation = (Rotation) (((int) m_rotation + 3) & 3);\n }\n\n // accessor property to make class look like a two dimensional array\n public int this [int row, int column]\n {\n get\n {\n int\n value = 0;\n\n switch (m_rotation)\n {\n case Rotation.None:\n value = m_matrix [row, column];\n break;\n\n case Rotation.Clockwise90:\n value = m_matrix [m_matrix.GetUpperBound (0) - column, row];\n break;\n\n case Rotation.Clockwise180:\n value = m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column];\n break;\n\n case Rotation.Clockwise270:\n value = m_matrix [column, m_matrix.GetUpperBound (1) - row];\n break;\n }\n\n return value;\n }\n\n set\n {\n switch (m_rotation)\n {\n case Rotation.None:\n m_matrix [row, column] = value;\n break;\n\n case Rotation.Clockwise90:\n m_matrix [m_matrix.GetUpperBound (0) - column, row] = value;\n break;\n\n case Rotation.Clockwise180:\n m_matrix [m_matrix.GetUpperBound (0) - row, m_matrix.GetUpperBound (1) - column] = value;\n break;\n\n case Rotation.Clockwise270:\n m_matrix [column, m_matrix.GetUpperBound (1) - row] = value;\n break;\n }\n }\n }\n\n // creates a string with the matrix values\n public override string ToString ()\n {\n int\n num_rows = 0,\n num_columns = 0;\n\n switch (m_rotation)\n {\n case Rotation.None:\n case Rotation.Clockwise180:\n num_rows = m_matrix.GetUpperBound (0);\n num_columns = m_matrix.GetUpperBound (1);\n break;\n\n case Rotation.Clockwise90:\n case Rotation.Clockwise270:\n num_rows = m_matrix.GetUpperBound (1);\n num_columns = m_matrix.GetUpperBound (0);\n break;\n }\n\n StringBuilder\n output = new StringBuilder ();\n\n output.Append (\"{\");\n\n for (int row = 0 ; row <= num_rows ; ++row)\n {\n if (row != 0)\n {\n output.Append (\", \");\n }\n\n output.Append (\"{\");\n\n for (int column = 0 ; column <= num_columns ; ++column)\n {\n if (column != 0)\n {\n output.Append (\", \");\n }\n\n output.Append (this [row, column].ToString ());\n }\n\n output.Append (\"}\");\n }\n\n output.Append (\"}\");\n\n return output.ToString ();\n }\n\n int [,]\n // the original matrix\n m_matrix;\n\n Rotation\n // the current view of the matrix\n m_rotation;\n}\n" }, { "answer_id": 44368, "author": "dagorym", "author_id": 171, "author_profile": "https://Stackoverflow.com/users/171", "pm_score": 6, "selected": false, "text": "int a[4][4];\nint n = 4;\nint tmp;\nfor (int i = 0; i < n / 2; i++)\n{\n for (int j = i; j < n - i - 1; j++)\n {\n tmp = a[i][j];\n a[i][j] = a[j][n-i-1];\n a[j][n-i-1] = a[n-i-1][n-j-1];\n a[n-i-1][n-j-1] = a[n-j-1][i];\n a[n-j-1][i] = tmp;\n }\n}\n" }, { "answer_id": 48607, "author": "Nathan Fritz", "author_id": 4142, "author_profile": "https://Stackoverflow.com/users/4142", "pm_score": 1, "selected": false, "text": "require 'pp'\nn = 10\na = []\nn.times { a << (1..n).to_a }\n\npp a\n\n0.upto(n/2-1) do |i|\n i.upto(n-i-2) do |j|\n tmp = a[i][j]\n a[i][j] = a[n-j-1][i]\n a[n-j-1][i] = a[n-i-1][n-j-1]\n a[n-i-1][n-j-1] = a[j][n-i-1]\n a[j][n-i-1] = tmp\n end\nend\n\npp a\n" }, { "answer_id": 193942, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 5, "selected": false, "text": "interface IReadableMatrix\n{\n int GetValue(int x, int y);\n}\n" }, { "answer_id": 496056, "author": "recursive", "author_id": 44743, "author_profile": "https://Stackoverflow.com/users/44743", "pm_score": 7, "selected": false, "text": "rotated = list(zip(*original[::-1]))\n" }, { "answer_id": 768796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <iomanip>\n\nusing namespace std;\nconst int SIZE=3;\nvoid print(int a[][SIZE],int);\nvoid rotate(int a[][SIZE],int);\n\nvoid main()\n{\n int a[SIZE][SIZE]={{11,22,33},{44,55,66},{77,88,99}};\n cout<<\"the array befor rotate\\n\";\n\n print(a,SIZE);\n rotate( a,SIZE);\n cout<<\"the array after rotate\\n\";\n print(a,SIZE);\n cout<<endl;\n\n}\n\nvoid print(int a[][SIZE],int SIZE)\n{\n int i,j;\n for(i=0;i<SIZE;i++)\n for(j=0;j<SIZE;j++)\n cout<<a[i][j]<<setw(4);\n}\n\nvoid rotate(int a[][SIZE],int SIZE)\n{\n int temp[3][3],i,j;\n for(i=0;i<SIZE;i++)\n for(j=0;j<SIZE/2.5;j++)\n {\n temp[i][j]= a[i][j];\n a[i][j]= a[j][SIZE-i-1] ;\n a[j][SIZE-i-1] =temp[i][j];\n\n }\n}\n" }, { "answer_id": 948280, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "short normal[4][4] = {{8,4,7,5},{3,4,5,7},{9,5,5,6},{3,3,3,3}};\n\nshort rotated[4][4];\n\nfor (int r = 0; r < 4; ++r)\n{\n for (int c = 0; c < 4; ++c)\n {\n rotated[r][c] = normal[c][3-r];\n }\n}\n" }, { "answer_id": 1092721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public int[][] rotateMatrixRight(int[][] matrix)\n{\n /* W and H are already swapped */\n int w = matrix.length;\n int h = matrix[0].length;\n int[][] ret = new int[h][w];\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n ret[i][j] = matrix[w - j - 1][i];\n }\n }\n return ret;\n}\n\n\npublic int[][] rotateMatrixLeft(int[][] matrix)\n{\n /* W and H are already swapped */\n int w = matrix.length;\n int h = matrix[0].length; \n int[][] ret = new int[h][w];\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n ret[i][j] = matrix[j][h - i - 1];\n }\n }\n return ret;\n}\n" }, { "answer_id": 3137413, "author": "James Lin", "author_id": 342553, "author_profile": "https://Stackoverflow.com/users/342553", "pm_score": 2, "selected": false, "text": "<?php \n$a = array(array(1,2,3,4),array(5,6,7,8),array(9,0,1,2),array(3,4,5,6));\n$b = array(); //result\n\nwhile(count($a)>0)\n{\n $b[count($a[0])-1][] = array_shift($a[0]);\n if (count($a[0])==0)\n {\n array_shift($a);\n }\n}\n" }, { "answer_id": 3137649, "author": "Clark Gaebel", "author_id": 105760, "author_profile": "https://Stackoverflow.com/users/105760", "pm_score": 0, "selected": false, "text": "#include <algorithm>\n#include <cstddef>\n\n// Rotates an NxN matrix of type T 90 degrees to the right.\ntemplate <typename T, size_t N>\nvoid rotate_matrix(T (&matrix)[N][N])\n{\n for(size_t i = 0; i < N; ++i)\n for(size_t j = 0; j <= (N-i); ++j)\n std::swap(matrix[i][j], matrix[j][i]);\n}\n" }, { "answer_id": 3571501, "author": "Nakilon", "author_id": 322020, "author_profile": "https://Stackoverflow.com/users/322020", "pm_score": 4, "selected": false, "text": ".transpose.map &:reverse" }, { "answer_id": 8668894, "author": "Turk", "author_id": 1121328, "author_profile": "https://Stackoverflow.com/users/1121328", "pm_score": 1, "selected": false, "text": "For i:= 0 to X do\n For j := 0 to X do\n graphic[j][i] := graphic2[X-i][j]" }, { "answer_id": 9711525, "author": "James Yu", "author_id": 1270299, "author_profile": "https://Stackoverflow.com/users/1270299", "pm_score": 2, "selected": false, "text": "private void rotateInSpace(int[][] arr) {\n int z = arr.length;\n for (int i = 0; i < z / 2; i++) {\n for (int j = 0; j < (z / 2 + z % 2); j++) {\n int x = i, y = j;\n int temp = arr[x][y];\n for (int k = 0; k < 4; k++) {\n int temptemp = arr[y][z - x - 1];\n arr[y][z - x - 1] = temp;\n temp = temptemp;\n\n int tempX = y;\n y = z - x - 1;\n x = tempX;\n }\n }\n }\n}\n" }, { "answer_id": 10021595, "author": "Spidey", "author_id": 131326, "author_profile": "https://Stackoverflow.com/users/131326", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n\n#define M_SIZE 5\n\nstatic void initMatrix();\nstatic void printMatrix();\nstatic void rotateMatrix();\n\nstatic int m[M_SIZE][M_SIZE];\n\nint main(void){\n initMatrix();\n printMatrix();\n rotateMatrix();\n printMatrix();\n\n return 0;\n}\n\nstatic void initMatrix(){\n int i, j;\n\n for(i = 0; i < M_SIZE; i++){\n for(j = 0; j < M_SIZE; j++){\n m[i][j] = M_SIZE*i + j + 1;\n }\n }\n}\n\nstatic void printMatrix(){\n int i, j;\n\n printf(\"Matrix\\n\");\n for(i = 0; i < M_SIZE; i++){\n for(j = 0; j < M_SIZE; j++){\n printf(\"%02d \", m[i][j]);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nstatic void rotateMatrix(){\n int r, c;\n\n for(r = 0; r < M_SIZE/2; r++){\n for(c = r; c < M_SIZE - r - 1; c++){\n int tmp = m[r][c];\n\n m[r][c] = m[M_SIZE - c - 1][r];\n m[M_SIZE - c - 1][r] = m[M_SIZE - r - 1][M_SIZE - c - 1];\n m[M_SIZE - r - 1][M_SIZE - c - 1] = m[c][M_SIZE - r - 1];\n m[c][M_SIZE - r - 1] = tmp;\n }\n }\n}\n" }, { "answer_id": 11695638, "author": "k00ka", "author_id": 3410287, "author_profile": "https://Stackoverflow.com/users/3410287", "pm_score": 1, "selected": false, "text": "% irb\nirb(main):001:0> m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]]\n=> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6]] \nirb(main):002:0> m.reverse.transpose\n=> [[3, 9, 5, 1], [4, 0, 6, 2], [5, 1, 7, 3], [6, 2, 8, 4]]\n" }, { "answer_id": 15073652, "author": "rohitmb", "author_id": 2108332, "author_profile": "https://Stackoverflow.com/users/2108332", "pm_score": 1, "selected": false, "text": "void rotateInPlace(int * arr[size][size], int row, int column){\n int i, j;\n int temp = row>column?row:column;\n int flipTill = row < column ? row : column;\n for(i=0;i<flipTill;i++){\n for(j=0;j<i;j++){\n swapArrayElements(arr, i, j);\n }\n }\n\n temp = j+1;\n\n for(i = row>column?i:0; i<row; i++){\n for(j=row<column?temp:0; j<column; j++){\n swapArrayElements(arr, i, j);\n }\n }\n\n for(i=0;i<column;i++){\n for(j=0;j<row/2;j++){\n temp = arr[i][j];\n arr[i][j] = arr[i][row-j-1];\n arr[i][row-j-1] = temp;\n }\n }\n}\n" }, { "answer_id": 15432619, "author": "user1596193", "author_id": 1596193, "author_profile": "https://Stackoverflow.com/users/1596193", "pm_score": 1, "selected": false, "text": "#define ROWS 5\n#define COLS 5\n\nvoid print_matrix_b(int B[][COLS], int rows, int cols) \n{\n for (int i = 0; i <= rows; i++) {\n for (int j = 0; j <=cols; j++) {\n printf(\"%d \", B[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\nvoid swap_columns(int B[][COLS], int l, int r, int rows)\n{\n int tmp;\n for (int i = 0; i <= rows; i++) {\n tmp = B[i][l];\n B[i][l] = B[i][r];\n B[i][r] = tmp;\n }\n}\n\n\nvoid matrix_2d_rotation(int B[][COLS], int rows, int cols)\n{\n int tmp;\n // Transpose the matrix first\n for (int i = 0; i <= rows; i++) {\n for (int j = i; j <=cols; j++) {\n tmp = B[i][j];\n B[i][j] = B[j][i];\n B[j][i] = tmp;\n }\n }\n // Swap the first and last col and continue until\n // the middle.\n for (int i = 0; i < (cols / 2); i++)\n swap_columns(B, i, cols - i, rows);\n}\n\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n int B[ROWS][COLS] = { \n {1, 2, 3, 4, 5}, \n {6, 7, 8, 9, 10},\n {11, 12, 13, 14, 15},\n {16, 17, 18, 19, 20},\n {21, 22, 23, 24, 25}\n };\n\n matrix_2d_rotation(B, ROWS - 1, COLS - 1);\n\n print_matrix_b(B, ROWS - 1, COLS -1);\n return 0;\n}\n" }, { "answer_id": 15501334, "author": "ramon.liu", "author_id": 2025792, "author_profile": "https://Stackoverflow.com/users/2025792", "pm_score": -1, "selected": false, "text": "[3][9][5][1]\n[4][6][7][2]\n[5][0][1][3]\n[6][2][8][4]\n" }, { "answer_id": 16661397, "author": "radium", "author_id": 1642753, "author_profile": "https://Stackoverflow.com/users/1642753", "pm_score": 2, "selected": false, "text": "public static void rightRotate(int[][] matrix, int n) {\n for (int layer = 0; layer < n / 2; layer++) {\n int first = layer;\n int last = n - 1 - first;\n for (int i = first; i < last; i++) {\n int offset = i - first;\n int temp = matrix[first][i];\n matrix[first][i] = matrix[last-offset][first];\n matrix[last-offset][first] = matrix[last][last-offset];\n matrix[last][last-offset] = matrix[i][last];\n matrix[i][last] = temp;\n }\n }\n}\n" }, { "answer_id": 18013355, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "private static int[][] rotate(int[][] matrix, int n) {\n int[][] rotated = new int[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n rotated[i][j] = matrix[n-j-1][i];\n }\n }\n return rotated;\n}\n" }, { "answer_id": 18215843, "author": "thiagoh", "author_id": 889213, "author_profile": "https://Stackoverflow.com/users/889213", "pm_score": 1, "selected": false, "text": "void rotateRight(int matrix[][SIZE], int length) {\n\n int layer = 0;\n\n for (int layer = 0; layer < length / 2; ++layer) {\n\n int first = layer;\n int last = length - 1 - layer;\n\n for (int i = first; i < last; ++i) {\n\n int topline = matrix[first][i];\n int rightcol = matrix[i][last];\n int bottomline = matrix[last][length - layer - 1 - i];\n int leftcol = matrix[length - layer - 1 - i][first];\n\n matrix[first][i] = leftcol;\n matrix[i][last] = topline;\n matrix[last][length - layer - 1 - i] = rightcol;\n matrix[length - layer - 1 - i][first] = bottomline;\n }\n }\n}\n" }, { "answer_id": 18262380, "author": "mhawksey", "author_id": 1027723, "author_profile": "https://Stackoverflow.com/users/1027723", "pm_score": 2, "selected": false, "text": "function rotate90(a){\n // transpose from http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html\n a = Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });\n // row reverse\n for (i in a){\n a[i] = a[i].reverse();\n }\n return a;\n}\n" }, { "answer_id": 20199933, "author": "tweaking", "author_id": 2716562, "author_profile": "https://Stackoverflow.com/users/2716562", "pm_score": 5, "selected": false, "text": "1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n" }, { "answer_id": 21265476, "author": "user2793692", "author_id": 2793692, "author_profile": "https://Stackoverflow.com/users/2793692", "pm_score": 3, "selected": false, "text": "public void rotate(int[][] matrix) {\n int n = matrix.length;\n for (int i = 0; i < n / 2; i++) {\n int last = n - 1 - i;\n for (int j = i; j < last; j++) {\n int top = matrix[i][j];\n matrix[i][j] = matrix[last - j][i];\n matrix[last - j][i] = matrix[last][last - j];\n matrix[last][last - j] = matrix[j][last];\n matrix[j][last] = top;\n }\n }\n}\n" }, { "answer_id": 21977882, "author": "taxicala", "author_id": 2988337, "author_profile": "https://Stackoverflow.com/users/2988337", "pm_score": 0, "selected": false, "text": "$m = array();\n $m[0] = array('a', 'b', 'c');\n $m[1] = array('d', 'e', 'f');\n $m[2] = array('g', 'h', 'i');\n $newMatrix = array();\n\n function rotateMatrix($m, $i = 0, &$newMatrix)\n {\n foreach ($m as $chunk) {\n $newChunk[] = $chunk[$i];\n }\n $newMatrix[] = array_reverse($newChunk);\n $i++;\n\n if ($i < count($m)) {\n rotateMatrix($m, $i, $newMatrix);\n }\n }\n\n rotateMatrix($m, 0, $newMatrix);\n echo '<pre>';\n var_dump($newMatrix);\n echo '<pre>';\n" }, { "answer_id": 22858585, "author": "Alex", "author_id": 3497339, "author_profile": "https://Stackoverflow.com/users/3497339", "pm_score": 0, "selected": false, "text": "void rotate_matrix(int *matrix, int size)\n{\n\nint result[size*size];\n\n for (int i = 0; i < size; ++i)\n for (int j = 0; j < size; ++j)\n result[(size - 1 - i) + j*size] = matrix[i*size+j];\n\n for (int i = 0; i < size*size; ++i)\n matrix[i] = result[i];\n}\n" }, { "answer_id": 23486371, "author": "user4964091", "author_id": 4964091, "author_profile": "https://Stackoverflow.com/users/4964091", "pm_score": -1, "selected": false, "text": "#include<iostream.h>\n#include<conio.h>\n\nint main()\n{\n clrscr();\n\n int arr[10][10]; // 2d array that holds input elements \n int result[10][10]; //holds result\n\n int m,n; //rows and columns of arr[][]\n int x,y; //rows and columns of result[][]\n\n int i,j; //loop variables\n int t; //temporary , holds data while conversion\n\n cout<<\"Enter no. of rows and columns of array: \";\n cin>>m>>n;\n cout<<\"\\nEnter elements of array: \\n\\n\";\n for(i = 0; i < m; i++)\n {\n for(j = 0; j<n ; j++)\n {\n cin>>arr[i][j]; // input array elements from user\n }\n }\n\n\n //rotating matrix by +90 degrees\n\n x = n ; //for non-square matrix\n y = m ; \n\n for(i = 0; i < x; i++)\n { t = m-1; // to create required array bounds\n for(j = 0; j < y; j++)\n {\n result[i][j] = arr[t][i];\n t--;\n }\n }\n\n //print result\n\n cout<<\"\\nRotated matrix is: \\n\\n\";\n for(i = 0; i < x; i++)\n {\n for(j = 0; j < y; j++)\n {\n cout<<result[i][j]<<\" \";\n }\n cout<<\"\\n\";\n }\n\n getch();\n return 0;\n}\n" }, { "answer_id": 24356420, "author": "Paul Calabro", "author_id": 517137, "author_profile": "https://Stackoverflow.com/users/517137", "pm_score": -1, "selected": false, "text": "#!/usr/bin/env python\n\noriginal = [ [1,2,3],\n [4,5,6],\n [7,8,9] ]\n\n# Rotate matrix 90 degrees...\nfor i in map(None,*original[::-1]):\n print str(i) + '\\n'\n" }, { "answer_id": 26180084, "author": "obotezat", "author_id": 373108, "author_profile": "https://Stackoverflow.com/users/373108", "pm_score": -1, "selected": false, "text": "array_unshift($array, null);\n$array = call_user_func_array(\"array_map\", $array);\n" }, { "answer_id": 26320746, "author": "Mr. Nex", "author_id": 3680827, "author_profile": "https://Stackoverflow.com/users/3680827", "pm_score": 2, "selected": false, "text": " 1 2 3 0 0 1\nA = 4 5 6 B = 0 1 0\n 7 8 9 1 0 0\n" }, { "answer_id": 26374543, "author": "Jason Oster", "author_id": 466030, "author_profile": "https://Stackoverflow.com/users/466030", "pm_score": 4, "selected": false, "text": " // Get an array element in column/row order\n var getArray2d = function(a, x, y) {\n return a[y][x];\n };\n\n //demo\n var arr = [\n [5, 4, 6],\n [1, 7, 9],\n [-2, 11, 0],\n [8, 21, -3],\n [3, -1, 2]\n ];\n\n var newarr = [];\n arr[0].forEach(() => newarr.push(new Array(arr.length)));\n\n for (var i = 0; i < newarr.length; i++) {\n for (var j = 0; j < newarr[0].length; j++) {\n newarr[i][j] = getArray2d(arr, i, j);\n }\n }\n console.log(newarr);" }, { "answer_id": 27161656, "author": "spark", "author_id": 4279802, "author_profile": "https://Stackoverflow.com/users/4279802", "pm_score": -1, "selected": false, "text": "function rotateBy90(m) {\n var length = m.length;\n //for each layer of the matrix\n for (var first = 0; first < length >> 1; first++) {\n var last = length - 1 - first;\n for (var i = first; i < last; i++) {\n var top = m[first][i]; //store top\n m[first][i] = m[last - i][first]; //top = left\n m[last - i][first] = m[last][last - i]; //left = bottom\n m[last][last - i] = m[i][last]; //bottom = right\n m[i][last] = top; //right = top\n }\n }\n return m;\n}\n" }, { "answer_id": 28610081, "author": "ustmaestro", "author_id": 2624626, "author_profile": "https://Stackoverflow.com/users/2624626", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace MatrixProject\n{\n // mattrix class\n\n class Matrix{\n private int rows;\n private int cols;\n private int[,] matrix;\n\n public Matrix(int n){\n this.rows = n;\n this.cols = n;\n this.matrix = new int[this.rows,this.cols];\n\n }\n\n public Matrix(int n,int m){\n this.rows = n;\n this.cols = m;\n\n this.matrix = new int[this.rows,this.cols];\n }\n\n public void Show()\n {\n for (var i = 0; i < this.rows; i++)\n {\n for (var j = 0; j < this.cols; j++) {\n Console.Write(\"{0,3}\", this.matrix[i, j]);\n }\n Console.WriteLine();\n } \n }\n\n public void ReadElements()\n {\n for (var i = 0; i < this.rows; i++)\n for (var j = 0; j < this.cols; j++)\n {\n Console.Write(\"element[{0},{1}]=\",i,j);\n this.matrix[i, j] = Convert.ToInt32(Console.ReadLine());\n } \n }\n\n\n // rotate [n,m] 2D array by 90 deg right\n public void Rotate90DegRight()\n {\n\n // create a mirror of current matrix\n int[,] mirror = this.matrix;\n\n // create a new matrix\n this.matrix = new int[this.cols, this.rows];\n\n for (int i = 0; i < this.rows; i++)\n {\n for (int j = 0; j < this.cols; j++)\n {\n this.matrix[j, this.rows - i - 1] = mirror[i, j];\n }\n }\n\n // replace cols count with rows count\n int tmp = this.rows;\n this.rows = this.cols;\n this.cols = tmp; \n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n Matrix myMatrix = new Matrix(3,4);\n Console.WriteLine(\"Enter matrix elements:\");\n myMatrix.ReadElements();\n Console.WriteLine(\"Matrix elements are:\");\n myMatrix.Show();\n myMatrix.Rotate90DegRight();\n Console.WriteLine(\"Matrix rotated at 90 deg are:\");\n myMatrix.Show();\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 31079886, "author": "Shiva", "author_id": 5054208, "author_profile": "https://Stackoverflow.com/users/5054208", "pm_score": -1, "selected": false, "text": "/* 90-degree clockwise:\n temp_array = left_col\n left_col = bottom_row\n bottom_row = reverse(right_col)\n reverse(right_col) = reverse(top_row)\n reverse(top_row) = temp_array\n*/\nvoid RotateClockwise90(int ** arr, int lo, int hi) {\n\n if (lo >= hi) \n return;\n\n for (int i=lo; i<hi; i++) {\n int j = lo+hi-i;\n int temp = arr[i][lo];\n arr[i][lo] = arr[hi][i];\n arr[hi][i] = arr[j][hi];\n arr[j][hi] = arr[lo][j];\n arr[lo][j] = temp;\n }\n\n RotateClockwise90(arr, lo+1, hi-1);\n}\n" }, { "answer_id": 31904916, "author": "asad_nitp", "author_id": 5066038, "author_profile": "https://Stackoverflow.com/users/5066038", "pm_score": -1, "selected": false, "text": " #include<iostream>\n #include<vector>\n #include<algorithm>\n using namespace std;\n //Rotate a Matrix by 90 degrees\nvoid rotateMatrix(vector<vector<int> > &matrix){\n int n=matrix.size();\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n swap(matrix[i][j],matrix[j][i]);\n }\n }\n for(int i=0;i<n;i++){\n reverse(matrix[i].begin(),matrix[i].end());\n }\n }\n\n int main(){\n\n int n;\n cout<<\"enter the size of the matrix:\"<<endl;\n while (cin >> n) {\n vector< vector<int> > m;\n cout<<\"enter the elements\"<<endl;\n for (int i = 0; i < n; i++) {\n m.push_back(vector<int>(n));\n for (int j = 0; j < n; j++)\n scanf(\"%d\", &m[i][j]);\n }\n cout<<\"the rotated matrix is:\"<<endl;\n rotateMatrix(m);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++)\n cout << m[i][j] << ' ';\n cout << endl;\n }\n }\n return 0;\n }\n" }, { "answer_id": 32344382, "author": "Shawn", "author_id": 404760, "author_profile": "https://Stackoverflow.com/users/404760", "pm_score": 1, "selected": false, "text": " function rotate90(matrix){\n var length = matrix.length\n for(var row = 0; row < (length / 2); row++){\n for(var col = row; col < ( length - 1 - row); col++){\n var tmpVal = matrix[row][col];\n for(var i = 0; i < 4; i++){\n var rowSwap = col;\n var colSwap = (length - 1) - row;\n var poppedVal = matrix[rowSwap][colSwap];\n matrix[rowSwap][colSwap] = tmpVal;\n tmpVal = poppedVal;\n col = colSwap;\n row = rowSwap;\n }\n }\n }\n }\n" }, { "answer_id": 32940678, "author": "gmohim", "author_id": 4856100, "author_profile": "https://Stackoverflow.com/users/4856100", "pm_score": -1, "selected": false, "text": "30 --> 00\n20 --> 01\n10 --> 02\n00 --> 03\n\n31 --> 10\n21 --> 11\n11 --> 12\n01 --> 13\n" }, { "answer_id": 34534812, "author": "Prateek Joshi", "author_id": 4281711, "author_profile": "https://Stackoverflow.com/users/4281711", "pm_score": 2, "selected": false, "text": " 1 2 3\n 4 5 6\n 7 8 9\n" }, { "answer_id": 35113512, "author": "user4313807", "author_id": 4313807, "author_profile": "https://Stackoverflow.com/users/4313807", "pm_score": -1, "selected": false, "text": "public static void rotateInPlace(int[][] m) {\n for(int layer = 0; layer < m.length/2; layer++){\n int first = layer;\n int last = m.length - 1 - first;\n for(int i = first; i < last; i ++){\n int offset = i - first;\n int top = m[first][i];\n m[first][i] = m[last - offset][first];\n m[last - offset][first] = m[last][last - offset];\n m[last][last - offset] = m[i][last];\n m[i][last] = top;\n }\n }\n}\n" }, { "answer_id": 35438327, "author": "Jack", "author_id": 828547, "author_profile": "https://Stackoverflow.com/users/828547", "pm_score": 8, "selected": false, "text": "." }, { "answer_id": 35527917, "author": "Maaz Ashraf", "author_id": 5956013, "author_profile": "https://Stackoverflow.com/users/5956013", "pm_score": -1, "selected": false, "text": "#include <stdio.h>\n\nvoid main(){\nint arr[3][4] = {85, 2, 85, 4,\n 85, 6, 7, 85,\n 9, 85, 11, 12};\n\n\nint arr1[4][3];\n\nint i = 0, j = 0;\n\nfor(i=0;i<4;i++){\nint k = 2;//k = (number of columns in the new array arr1 - 1)\nfor(j=0;j<3;j++){\narr1[i][j]=arr[k][i];\nk--;\n}\n}\n\nint l, m;\nfor(l=0;l<4;l++){\nfor(m=0;m<3;m++){\nprintf(\"%d \", arr1[l][m]);\n}\nprintf(\"\\n\");\n}\n}//end main\n" }, { "answer_id": 37870786, "author": "Dudi", "author_id": 4572425, "author_profile": "https://Stackoverflow.com/users/4572425", "pm_score": -1, "selected": false, "text": "/* Author: Dudi,\n * http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMYm5qU3VjVGNuZFU */\n\nusing System.IO;\nusing System;\n\nclass Program\n{\n static void Main()\n {\n Console.WriteLine(\"Rotating this matrix by 90+ degree:\");\n\n int[,] values=new int[3,3]{{1,2,3}, {4,5,6}, {7,8,9}};\n //int[,] values=new int[4,4]{{101,102,103, 104}, {105,106, 107,108}, {109, 110, 111, 112}, {113, 114, 115, 116}};\n\n print2dArray(ref values);\n transpose2dArray(ref values);\n //print2dArray(ref values);\n reverse2dArray(ref values);\n Console.WriteLine(\"Output:\");\n print2dArray(ref values);\n }\n\n static void print2dArray(ref int[,] matrix){\n int nLen = matrix.GetLength(0);\n int mLen = matrix.GetLength(1); \n for(int n=0; n<nLen; n++){\n for(int m=0; m<mLen; m++){\n Console.Write(matrix[n,m] +\"\\t\");\n }\n Console.WriteLine(); \n }\n Console.WriteLine();\n }\n\n static void transpose2dArray(ref int[,] matrix){\n int nLen = matrix.GetLength(0);\n int mLen = matrix.GetLength(1); \n for(int n=0; n<nLen; n++){\n for(int m=0; m<mLen; m++){\n if(n>m){\n int tmp = matrix[n,m];\n matrix[n,m] = matrix[m,n];\n matrix[m,n] = tmp;\n }\n }\n }\n }\n\n static void reverse2dArray(ref int[,] matrix){\n int nLen = matrix.GetLength(0);\n int mLen = matrix.GetLength(1);\n for(int n=0; n<nLen; n++){\n for(int m=0; m<mLen/2; m++){ \n int tmp = matrix[n,m];\n matrix[n,m] = matrix[n, mLen-1-m];\n matrix[n,mLen-1-m] = tmp;\n }\n }\n }\n}\n\n/*\nRotating this matrix by 90+ degree: \n1 2 3 \n4 5 6 \n7 8 9 \n\nOutput: \n7 4 1 \n8 5 2 \n9 6 3 \n*/\n" }, { "answer_id": 38027015, "author": "Alexander Bekert", "author_id": 1322703, "author_profile": "https://Stackoverflow.com/users/1322703", "pm_score": -1, "selected": false, "text": "private static T[,] Rotate180 <T> (T[,] matrix)\n{\n var height = matrix.GetLength (0);\n var width = matrix.GetLength (1);\n var answer = new T[height, width];\n\n for (int y = 0; y < height / 2; y++)\n {\n int topY = y;\n int bottomY = height - 1 - y;\n for (int topX = 0; topX < width; topX++)\n {\n var bottomX = width - topX - 1;\n answer[topY, topX] = matrix[bottomY, bottomX];\n answer[bottomY, bottomX] = matrix[topY, topX];\n }\n }\n\n if (height % 2 == 0)\n return answer;\n\n var centerY = height / 2;\n for (int leftX = 0; leftX < Mathf.CeilToInt(width / 2f); leftX++)\n {\n var rightX = width - 1 - leftX;\n answer[centerY, leftX] = matrix[centerY, rightX];\n answer[centerY, rightX] = matrix[centerY, leftX];\n }\n\n return answer;\n}\n" }, { "answer_id": 38142398, "author": "Lee.O.", "author_id": 5976676, "author_profile": "https://Stackoverflow.com/users/5976676", "pm_score": -1, "selected": false, "text": " public static void rotateMatrix(int[,] matrix)\n {\n //C#, to rotate an N*N matrix in place\n int n = matrix.GetLength(0);\n int layers = n / 2;\n int temp, temp2;\n\n for (int i = 0; i < layers; i++) // for a 5 * 5 matrix, layers will be 2, since at layer three there would be only one element, (2,2), and we do not need to rotate it with itself \n {\n int offset = 0;\n while (offset < n - 2 * i - 1)\n {\n // top right <- top left \n temp = matrix[i + offset, n - i - 1]; //top right value when offset is zero\n matrix[i + offset, n - i - 1] = matrix[i, i + offset]; \n\n //bottom right <- top right \n temp2 = matrix[n - i - 1, n - i - 1 - offset]; //bottom right value when offset is zero\n matrix[n - i - 1, n - i - 1 - offset] = temp; \n\n //bottom left <- bottom right \n temp = matrix[n - i - 1 - offset, i];\n matrix[n - i - 1 - offset, i] = temp2; \n\n //top left <- bottom left \n matrix[i, i + offset] = temp; \n\n offset++;\n }\n }\n }\n" }, { "answer_id": 38518519, "author": "ThinkTankShark", "author_id": 5244684, "author_profile": "https://Stackoverflow.com/users/5244684", "pm_score": 1, "selected": false, "text": " // Input: 1 2 3\n // 4 5 6\n // 7 8 9\n\n // Transpose: \n // 1 4 7\n // 2 5 8\n // 3 6 9\n\n // Output: \n // +90 Degree:\n // 7 4 1\n // 8 5 2\n // 9 6 3\n\n // -90 Degree:\n // 3 6 9\n // 2 5 8\n // 1 4 7\n\n // Rotate +90\n function rotate90(matrix) {\n\n matrix = transpose(matrix);\n matrix.map(function(array) {\n array.reverse();\n });\n\n return matrix;\n }\n\n // Rotate -90\n function counterRotate90(matrix) {\n var result = createEmptyMatrix(matrix.length);\n matrix = transpose(matrix);\n var counter = 0;\n\n for (var i = matrix.length - 1; i >= 0; i--) {\n result[counter] = matrix[i];\n counter++;\n }\n\n return result;\n }\n\n // Create empty matrix\n function createEmptyMatrix(len) {\n var result = new Array();\n for (var i = 0; i < len; i++) {\n result.push([]);\n }\n return result;\n }\n\n // Transpose the matrix\n function transpose(matrix) {\n // make empty array\n var len = matrix.length;\n var result = createEmptyMatrix(len);\n\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n var temp = matrix[i][j];\n result[j][i] = temp;\n }\n }\n return result;\n }\n\n\n\n // Test Cases\n var array1 = [\n [1, 2],\n [3, 4]\n ];\n var array2 = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ];\n var array3 = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16]\n ];\n\n // +90 degress Rotation Tests\n\n var test1 = rotate90(array1);\n var test2 = rotate90(array2);\n var test3 = rotate90(array3);\n console.log(test1);\n console.log(test2);\n console.log(test3);\n\n // -90 degress Rotation Tests\n var test1 = counterRotate90(array1);\n var test2 = counterRotate90(array2);\n var test3 = counterRotate90(array3);\n console.log(test1);\n console.log(test2);\n console.log(test3);" }, { "answer_id": 39923587, "author": "Nicky Feller", "author_id": 4313927, "author_profile": "https://Stackoverflow.com/users/4313927", "pm_score": -1, "selected": false, "text": "func rot90(a [][]int) {\n n := len(a)\n if n == 1 {\n return\n }\n for i := 0; i < n; i++ {\n a[0][i], a[n-1-i][n-1] = a[n-1-i][n-1], a[0][i]\n }\n rot90(a[1:])\n}\n" }, { "answer_id": 40628762, "author": "Shrikant Dande", "author_id": 2449053, "author_profile": "https://Stackoverflow.com/users/2449053", "pm_score": -1, "selected": false, "text": "public class Matrix {\n/* Author Shrikant Dande */\nprivate static void showMatrix(int[][] arr,int rows,int col){\n\n for(int i =0 ;i<rows;i++){\n for(int j =0 ;j<col;j++){\n System.out.print(arr[i][j]+\" \");\n }\n System.out.println();\n }\n\n}\n\nprivate static void rotateMatrix(int[][] arr,int rows,int col){\n\n int[][] tempArr = new int[4][4];\n for(int i =0 ;i<rows;i++){\n for(int j =0 ;j<col;j++){\n tempArr[i][j] = arr[rows-1-j][i];\n System.out.print(tempArr[i][j]+\" \");\n }\n System.out.println();\n }\n\n}\npublic static void main(String[] args) {\n int[][] arr = { {1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 1, 2, 5},\n {7, 4, 8, 9}};\n int rows = 4,col = 4;\n\n showMatrix(arr, rows, col);\n System.out.println(\"------------------------------------------------\");\n rotateMatrix(arr, rows, col);\n\n}\n" }, { "answer_id": 44095272, "author": "Qian Chen", "author_id": 1663023, "author_profile": "https://Stackoverflow.com/users/1663023", "pm_score": 0, "selected": false, "text": "const transpose = m => m[0].map((x,i) => m.map(x => x[i]));\n\na: // original matrix\n123\n456\n789\n\ntranspose(a).reverse(); // rotate 90 degrees counter clockwise \n369\n258\n147\n\ntranspose(a.slice().reverse()); // rotate 90 degrees clockwise \n741\n852\n963\n\ntranspose(transpose(a.slice().reverse()).slice().reverse())\n// rotate 180 degrees \n987\n654\n321\n" }, { "answer_id": 44510769, "author": "user_3380739", "author_id": 3380739, "author_profile": "https://Stackoverflow.com/users/3380739", "pm_score": -1, "selected": false, "text": "@Test\npublic void test_42519() throws Exception {\n final IntMatrix matrix = IntMatrix.range(0, 16).reshape(4);\n\n N.println(\"======= original =======================\");\n matrix.println();\n // print out:\n // [0, 1, 2, 3]\n // [4, 5, 6, 7]\n // [8, 9, 10, 11]\n // [12, 13, 14, 15]\n\n N.println(\"======= rotate 90 ======================\");\n matrix.rotate90().println();\n // print out:\n // [12, 8, 4, 0]\n // [13, 9, 5, 1]\n // [14, 10, 6, 2]\n // [15, 11, 7, 3]\n\n N.println(\"======= rotate 180 =====================\");\n matrix.rotate180().println();\n // print out:\n // [15, 14, 13, 12]\n // [11, 10, 9, 8]\n // [7, 6, 5, 4]\n // [3, 2, 1, 0]\n\n N.println(\"======= rotate 270 ======================\");\n matrix.rotate270().println();\n // print out:\n // [3, 7, 11, 15]\n // [2, 6, 10, 14]\n // [1, 5, 9, 13]\n // [0, 4, 8, 12]\n\n N.println(\"======= transpose =======================\");\n matrix.transpose().println();\n // print out:\n // [0, 4, 8, 12]\n // [1, 5, 9, 13]\n // [2, 6, 10, 14]\n // [3, 7, 11, 15]\n\n final IntMatrix bigMatrix = IntMatrix.range(0, 10000_0000).reshape(10000);\n\n // It take about 2 seconds to rotate 10000 X 10000 matrix.\n Profiler.run(1, 2, 3, \"sequential\", () -> bigMatrix.rotate90()).printResult();\n\n // Want faster? Go parallel. 1 second to rotate 10000 X 10000 matrix.\n final int[][] a = bigMatrix.array();\n final int[][] c = new int[a[0].length][a.length];\n final int n = a.length;\n final int threadNum = 4;\n\n Profiler.run(1, 2, 3, \"parallel\", () -> {\n IntStream.range(0, n).parallel(threadNum).forEach(i -> {\n for (int j = 0; j < n; j++) {\n c[i][j] = a[n - j - 1][i];\n }\n });\n }).printResult();\n}\n" }, { "answer_id": 44940034, "author": "Vladimir Ramik", "author_id": 4644312, "author_profile": "https://Stackoverflow.com/users/4644312", "pm_score": 1, "selected": false, "text": "$aMatrix = array(\n array( 1, 2, 3 ),\n array( 4, 5, 6 ),\n array( 7, 8, 9 )\n );\n\nfunction CounterClockwise( $aMatrix )\n{\n $iCount = count( $aMatrix );\n $aReturn = array();\n for( $y = 0; $y < $iCount; ++$y )\n {\n for( $x = 0; $x < $iCount; ++$x )\n {\n $aReturn[ $iCount - $x - 1 ][ $y ] = $aMatrix[ $y ][ $x ];\n }\n }\n return $aReturn;\n}\n\nfunction Clockwise( $aMatrix )\n{\n $iCount = count( $aMatrix );\n $aReturn = array();\n for( $y = 0; $y < $iCount; ++$y )\n {\n for( $x = 0; $x < $iCount; ++$x )\n {\n $aReturn[ $x ][ $iCount - $y - 1 ] = $aMatrix[ $y ][ $x ];\n }\n }\n return $aReturn;\n}\n\nfunction printMatrix( $aMatrix )\n{\n $iCount = count( $aMatrix );\n for( $x = 0; $x < $iCount; ++$x )\n {\n for( $y = 0; $y < $iCount; ++$y )\n {\n echo $aMatrix[ $x ][ $y ];\n echo \" \";\n }\n echo \"\\n\";\n }\n}\nprintMatrix( $aMatrix );\necho \"\\n\";\n$aNewMatrix = CounterClockwise( $aMatrix );\nprintMatrix( $aNewMatrix );\necho \"\\n\";\n$aNewMatrix = Clockwise( $aMatrix );\nprintMatrix( $aNewMatrix );\n" }, { "answer_id": 49087988, "author": "Tom", "author_id": 882436, "author_profile": "https://Stackoverflow.com/users/882436", "pm_score": 1, "selected": false, "text": "#include <stdlib.h>\n#include <memory.h>\n#include <assert.h>\n\n/* \n Matrix transpose & rotate (+/-90, +/-180)\n Supports both 2D arrays and 1D pointers with logical rows/cols\n Supports square and non-square matrices, has in-place and copy features\n See tests for examples of usage\n tested gcc -std=c90 -Wall -pedantic, MSVC17\n*/\n\ntypedef int matrix_data_t; /* matrix data type */\n\nvoid transpose(const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);\nvoid transpose_inplace(matrix_data_t* data, int n );\nvoid rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);\nvoid rotate_inplace(int direction, matrix_data_t* data, int n);\nvoid reverse_rows(matrix_data_t* data, int rows, int cols);\nvoid reverse_cols(matrix_data_t* data, int rows, int cols);\n\n/* test/compare fn */\nint test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols );\n\n/* TESTS/USAGE */\nvoid transpose_test() {\n\n matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };/* 3x3 square, odd length side */\n matrix_data_t sq3x3_cpy[9];\n matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };/* 2D 3x3 square */\n matrix_data_t sq3x3_2D_copy[3][3];\n\n /* expected test values */\n const matrix_data_t sq3x3_orig[9] = { 0,1,2,3,4,5,6,7,8 };\n const matrix_data_t sq3x3_transposed[9] = { 0,3,6,1,4,7,2,5,8};\n\n matrix_data_t sq4x4[16]= { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };/* 4x4 square, even length*/\n const matrix_data_t sq4x4_orig[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };\n const matrix_data_t sq4x4_transposed[16] = { 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 };\n\n /* 2x3 rectangle */\n const matrix_data_t r2x3_orig[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r2x3_transposed[6] = { 0,3,1,4,2,5 };\n matrix_data_t r2x3_copy[6];\n\n matrix_data_t r2x3_2D[2][3] = { {0,1,2},{3,4,5} }; /* 2x3 2D rectangle */\n matrix_data_t r2x3_2D_t[3][2];\n\n /* matrix_data_t r3x2[6] = { 0,1,2,3,4,5 }; */\n matrix_data_t r3x2_copy[6];\n /* 3x2 rectangle */\n const matrix_data_t r3x2_orig[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r3x2_transposed[6] = { 0,2,4,1,3,5 };\n\n matrix_data_t r6x1[6] = { 0,1,2,3,4,5 }; /* 6x1 */\n matrix_data_t r6x1_copy[6];\n\n matrix_data_t r1x1[1] = { 0 }; /*1x1*/\n matrix_data_t r1x1_copy[1];\n\n /* 3x3 tests, 2D array tests */\n transpose_inplace(sq3x3, 3); /* transpose in place */\n assert(!test_cmp(sq3x3, sq3x3_transposed, 3, 3));\n transpose_inplace(sq3x3, 3); /* transpose again */\n assert(!test_cmp(sq3x3, sq3x3_orig, 3, 3));\n\n transpose(sq3x3, sq3x3_cpy, 3, 3); /* transpose copy 3x3*/\n assert(!test_cmp(sq3x3_cpy, sq3x3_transposed, 3, 3));\n\n transpose((matrix_data_t*)sq3x3_2D, (matrix_data_t*)sq3x3_2D_copy, 3, 3); /* 2D array transpose/copy */\n assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_transposed, 3, 3));\n transpose_inplace((matrix_data_t*)sq3x3_2D_copy, 3); /* 2D array transpose in place */\n assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_orig, 3, 3));\n\n /* 4x4 tests */\n transpose_inplace(sq4x4, 4); /* transpose in place */\n assert(!test_cmp(sq4x4, sq4x4_transposed, 4,4));\n transpose_inplace(sq4x4, 4); /* transpose again */\n assert(!test_cmp(sq4x4, sq4x4_orig, 3, 3));\n\n /* 2x3,3x2 tests */\n transpose(r2x3_orig, r2x3_copy, 2, 3);\n assert(!test_cmp(r2x3_copy, r2x3_transposed, 3, 2));\n\n transpose(r3x2_orig, r3x2_copy, 3, 2);\n assert(!test_cmp(r3x2_copy, r3x2_transposed, 2,3));\n\n /* 2D array */\n transpose((matrix_data_t*)r2x3_2D, (matrix_data_t*)r2x3_2D_t, 2, 3);\n assert(!test_cmp((matrix_data_t*)r2x3_2D_t, r2x3_transposed, 3,2));\n\n /* Nx1 test, 1x1 test */\n transpose(r6x1, r6x1_copy, 6, 1);\n assert(!test_cmp(r6x1_copy, r6x1, 1, 6));\n\n transpose(r1x1, r1x1_copy, 1, 1);\n assert(!test_cmp(r1x1_copy, r1x1, 1, 1));\n\n}\n\nvoid rotate_test() {\n\n /* 3x3 square */\n const matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };\n const matrix_data_t sq3x3_r90[9] = { 6,3,0,7,4,1,8,5,2 };\n const matrix_data_t sq3x3_180[9] = { 8,7,6,5,4,3,2,1,0 };\n const matrix_data_t sq3x3_l90[9] = { 2,5,8,1,4,7,0,3,6 };\n matrix_data_t sq3x3_copy[9];\n\n /* 3x3 square, 2D */\n matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };\n\n /* 4x4, 2D */\n matrix_data_t sq4x4[4][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 },{ 12,13,14,15 } };\n matrix_data_t sq4x4_copy[4][4];\n const matrix_data_t sq4x4_r90[16] = { 12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3 };\n const matrix_data_t sq4x4_l90[16] = { 3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12 };\n const matrix_data_t sq4x4_180[16] = { 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };\n\n matrix_data_t r6[6] = { 0,1,2,3,4,5 }; /* rectangle with area of 6 (1x6,2x3,3x2, or 6x1) */\n matrix_data_t r6_copy[6];\n const matrix_data_t r1x6_r90[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r1x6_l90[6] = { 5,4,3,2,1,0 };\n const matrix_data_t r1x6_180[6] = { 5,4,3,2,1,0 };\n\n const matrix_data_t r2x3_r90[6] = { 3,0,4,1,5,2 };\n const matrix_data_t r2x3_l90[6] = { 2,5,1,4,0,3 };\n const matrix_data_t r2x3_180[6] = { 5,4,3,2,1,0 };\n\n const matrix_data_t r3x2_r90[6] = { 4,2,0,5,3,1 };\n const matrix_data_t r3x2_l90[6] = { 1,3,5,0,2,4 };\n const matrix_data_t r3x2_180[6] = { 5,4,3,2,1,0 };\n\n const matrix_data_t r6x1_r90[6] = { 5,4,3,2,1,0 };\n const matrix_data_t r6x1_l90[6] = { 0,1,2,3,4,5 };\n const matrix_data_t r6x1_180[6] = { 5,4,3,2,1,0 };\n\n /* sq3x3 tests */\n rotate(90, sq3x3, sq3x3_copy, 3, 3); /* +90 */\n assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));\n rotate(-90, sq3x3, sq3x3_copy, 3, 3); /* -90 */\n assert(!test_cmp(sq3x3_copy, sq3x3_l90, 3, 3));\n rotate(180, sq3x3, sq3x3_copy, 3, 3); /* 180 */\n assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));\n /* sq3x3 in-place rotations */\n memcpy( sq3x3_copy, sq3x3, 3 * 3 * sizeof(matrix_data_t));\n rotate_inplace(90, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));\n rotate_inplace(-90, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3)); /* back to 0 orientation */\n rotate_inplace(180, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));\n rotate_inplace(-180, sq3x3_copy, 3);\n assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3));\n rotate_inplace(180, (matrix_data_t*)sq3x3_2D, 3);/* 2D test */\n assert(!test_cmp((matrix_data_t*)sq3x3_2D, sq3x3_180, 3, 3));\n\n /* sq4x4 */\n rotate(90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_r90, 4, 4));\n rotate(-90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_l90, 4, 4));\n rotate(180, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);\n assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_180, 4, 4));\n\n /* r6 as 1x6 */\n rotate(90, r6, r6_copy, 1, 6);\n assert(!test_cmp(r6_copy, r1x6_r90, 1, 6));\n rotate(-90, r6, r6_copy, 1, 6);\n assert(!test_cmp(r6_copy, r1x6_l90, 1, 6));\n rotate(180, r6, r6_copy, 1, 6);\n assert(!test_cmp(r6_copy, r1x6_180, 1, 6));\n\n /* r6 as 2x3 */\n rotate(90, r6, r6_copy, 2, 3);\n assert(!test_cmp(r6_copy, r2x3_r90, 2, 3));\n rotate(-90, r6, r6_copy, 2, 3);\n assert(!test_cmp(r6_copy, r2x3_l90, 2, 3));\n rotate(180, r6, r6_copy, 2, 3);\n assert(!test_cmp(r6_copy, r2x3_180, 2, 3));\n\n /* r6 as 3x2 */\n rotate(90, r6, r6_copy, 3, 2);\n assert(!test_cmp(r6_copy, r3x2_r90, 3, 2));\n rotate(-90, r6, r6_copy, 3, 2);\n assert(!test_cmp(r6_copy, r3x2_l90, 3, 2));\n rotate(180, r6, r6_copy, 3, 2);\n assert(!test_cmp(r6_copy, r3x2_180, 3, 2));\n\n /* r6 as 6x1 */\n rotate(90, r6, r6_copy, 6, 1);\n assert(!test_cmp(r6_copy, r6x1_r90, 6, 1));\n rotate(-90, r6, r6_copy, 6, 1);\n assert(!test_cmp(r6_copy, r6x1_l90, 6, 1));\n rotate(180, r6, r6_copy, 6, 1);\n assert(!test_cmp(r6_copy, r6x1_180, 6, 1));\n}\n\n/* test comparison fn, return 0 on match else non zero */\nint test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols) {\n\n int r, c;\n\n for (r = 0; r < rows; ++r) {\n for (c = 0; c < cols; ++c) {\n if ((lhs + r * cols)[c] != (rhs + r * cols)[c])\n return -1;\n }\n }\n return 0;\n}\n\n/*\nReverse values in place of each row in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols\n[A B C] -> [C B A]\n[D E F] [F E D]\n*/\nvoid reverse_rows(matrix_data_t* data, int rows, int cols) {\n\n int r, c;\n matrix_data_t temp;\n matrix_data_t* pRow = NULL;\n\n for (r = 0; r < rows; ++r) {\n pRow = (data + r * cols);\n for (c = 0; c < (int)(cols / 2); ++c) { /* explicit truncate */\n temp = pRow[c];\n pRow[c] = pRow[cols - 1 - c];\n pRow[cols - 1 - c] = temp;\n }\n }\n}\n\n/*\nReverse values in place of each column in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols\n[A B C] -> [D E F]\n[D E F] [A B C]\n*/\nvoid reverse_cols(matrix_data_t* data, int rows, int cols) {\n\n int r, c;\n matrix_data_t temp;\n matrix_data_t* pRowA = NULL;\n matrix_data_t* pRowB = NULL;\n\n for (c = 0; c < cols; ++c) {\n for (r = 0; r < (int)(rows / 2); ++r) { /* explicit truncate */\n pRowA = data + r * cols;\n pRowB = data + cols * (rows - 1 - r);\n temp = pRowA[c];\n pRowA[c] = pRowB[c];\n pRowB[c] = temp;\n }\n }\n}\n\n/* Transpose NxM matrix to MxN matrix in O(n) time */\nvoid transpose(const matrix_data_t* src, matrix_data_t* dst, int N, int M) {\n\n int i;\n for (i = 0; i<N*M; ++i) dst[(i%M)*N + (i / M)] = src[i]; /* one-liner version */\n\n /*\n expanded version of one-liner: calculate XY based on array index, then convert that to YX array index\n int i,j,x,y;\n for (i = 0; i < N*M; ++i) {\n x = i % M;\n y = (int)(i / M);\n j = x * N + y;\n dst[j] = src[i];\n }\n */\n\n /*\n nested for loop version\n using ptr arithmetic to get proper row/column\n this is really just dst[col][row]=src[row][col]\n\n int r, c;\n\n for (r = 0; r < rows; ++r) {\n for (c = 0; c < cols; ++c) {\n (dst + c * rows)[r] = (src + r * cols)[c];\n }\n }\n */\n}\n\n/*\nTranspose NxN matrix in place\n*/\nvoid transpose_inplace(matrix_data_t* data, int N ) {\n\n int r, c;\n matrix_data_t temp;\n\n for (r = 0; r < N; ++r) {\n for (c = r; c < N; ++c) { /*start at column=row*/\n /* using ptr arithmetic to get proper row/column */\n /* this is really just\n temp=dst[col][row];\n dst[col][row]=src[row][col];\n src[row][col]=temp;\n */\n temp = (data + c * N)[r];\n (data + c * N)[r] = (data + r * N)[c];\n (data + r * N)[c] = temp;\n }\n }\n}\n\n/*\nRotate 1D or 2D src matrix to dst matrix in a direction (90,180,-90)\nPrecondition: src and dst are 2d matrices with dimensions src[rows][cols] and dst[cols][rows] or 1D pointers with logical rows/cols\n*/\nvoid rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols) {\n\n switch (direction) {\n case -90:\n transpose(src, dst, rows, cols);\n reverse_cols(dst, cols, rows);\n break;\n case 90:\n transpose(src, dst, rows, cols);\n reverse_rows(dst, cols, rows);\n break;\n case 180:\n case -180:\n /* bit copy to dst, use in-place reversals */\n memcpy(dst, src, rows*cols*sizeof(matrix_data_t));\n reverse_cols(dst, cols, rows);\n reverse_rows(dst, cols, rows);\n break;\n }\n}\n\n/*\nRotate array in a direction.\nArray must be NxN 2D or 1D array with logical rows/cols\nDirection can be (90,180,-90,-180)\n*/\nvoid rotate_inplace( int direction, matrix_data_t* data, int n) {\n\n switch (direction) {\n case -90:\n transpose_inplace(data, n);\n reverse_cols(data, n, n);\n break;\n case 90:\n transpose_inplace(data, n);\n reverse_rows(data, n, n);\n break;\n case 180:\n case -180:\n reverse_cols(data, n, n);\n reverse_rows(data, n, n);\n break;\n }\n}\n" }, { "answer_id": 49619504, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "/// <param name=\"rotation\">The number of rotations (if negative, the <see cref=\"Matrix{TValue}\"/> is rotated counterclockwise; \n/// otherwise, it's rotated clockwise). A single (positive) rotation is equivalent to 90° or -270°; a single (negative) rotation is \n/// equivalent to -90° or 270°. Matrices may be rotated by 90°, 180°, or 270° only (or multiples thereof).</param>\n/// <returns></returns>\npublic Matrix<TValue> Rotate(int rotation)\n{\n var result = default(Matrix<TValue>);\n\n //This normalizes the requested rotation (for instance, if 10 is specified, the rotation is actually just +-2 or +-180°, but all \n //correspond to the same rotation).\n var d = rotation.ToDouble() / 4d;\n d = d - (int)d;\n\n var degree = (d - 1d) * 4d;\n\n //This gets the type of rotation to make; there are a total of four unique rotations possible (0°, 90°, 180°, and 270°).\n //Each correspond to 0, 1, 2, and 3, respectively (or 0, -1, -2, and -3, if in the other direction). Since\n //1 is equivalent to -3 and so forth, we combine both cases into one. \n switch (degree)\n {\n case -3:\n case +1:\n degree = 3;\n break;\n case -2:\n case +2:\n degree = 2;\n break;\n case -1:\n case +3:\n degree = 1;\n break;\n case -4:\n case 0:\n case +4:\n degree = 0;\n break;\n }\n switch (degree)\n {\n //The rotation is 0, +-180°\n case 0:\n case 2:\n result = new TValue[Rows, Columns];\n break;\n //The rotation is +-90°\n case 1:\n case 3:\n result = new TValue[Columns, Rows];\n break;\n }\n\n for (uint i = 0; i < Columns; ++i)\n {\n for (uint j = 0; j < Rows; ++j)\n {\n switch (degree)\n {\n //If rotation is 0°\n case 0:\n result._values[j][i] = _values[j][i];\n break;\n //If rotation is -90°\n case 1:\n //Transpose, then reverse each column OR reverse each row, then transpose\n result._values[i][j] = _values[j][Columns - i - 1];\n break;\n //If rotation is +-180°\n case 2:\n //Reverse each column, then reverse each row\n result._values[(Rows - 1) - j][(Columns - 1) - i] = _values[j][i];\n break;\n //If rotation is +90°\n case 3:\n //Transpose, then reverse each row\n result._values[i][j] = _values[Rows - j - 1][i];\n break;\n }\n }\n }\n return result;\n}\n" }, { "answer_id": 50540508, "author": "Crashalot", "author_id": 144088, "author_profile": "https://Stackoverflow.com/users/144088", "pm_score": 0, "selected": false, "text": "matrix" }, { "answer_id": 50983147, "author": "Toomtarm Kung", "author_id": 1483126, "author_profile": "https://Stackoverflow.com/users/1483126", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n int[][] a = new int[][] { \n { 1, 2, 3, 4 }, \n { 5, 6, 7, 8 }, \n { 9, 0, 1, 2 }, \n { 3, 4, 5, 6 }, \n { 7, 8, 9, 0 } \n };\n int[][] rotate180 = rotate90(rotate90(a));\n print(rotate180);\n}\n\nstatic int[][] rotate90(int[][] a) {\n int[][] ret = new int[a[0].length][a.length];\n for (int i = 0; i < a.length; i++) {\n for (int j = 0; j < a[i].length; j++) {\n ret[j][a.length - i - 1] = a[i][j];\n }\n }\n return ret;\n}\n\nstatic void print(int[][] array) {\n for (int i = 0; i < array.length; i++) {\n System.out.print(\"[\");\n for (int j = 0; j < array[i].length; j++) {\n System.out.print(array[i][j]);\n System.out.print(\" \");\n }\n System.out.println(\"]\");\n }\n}\n" }, { "answer_id": 61812224, "author": "advncd", "author_id": 996926, "author_profile": "https://Stackoverflow.com/users/996926", "pm_score": 0, "selected": false, "text": "/**\n * Rotates matrix 90 degrees clockwise\n * @param arr: the source array\n * @param n: the array side (array is square n^2)\n */\nfunction rotate (arr, n) {\n var rotated = [], indexes = []\n\n for (var i = 0; i < arr.length; i++) {\n if (i < n)\n indexes[i] = i * n + (n - 1)\n else\n indexes[i] = indexes[i - n] - 1\n\n rotated[indexes[i]] = arr[i]\n }\n return rotated\n}\n" }, { "answer_id": 63046730, "author": "Meow", "author_id": 1509571, "author_profile": "https://Stackoverflow.com/users/1509571", "pm_score": 0, "selected": false, "text": "Eigen::Matrix2d mat;\nmat << 1, 2,\n 3, 4;\nstd::cout << mat << \"\\n\\n\";\n\nEigen::Matrix2d r_plus_90 = mat.transpose().rowwise().reverse();\nstd::cout << r_plus_90 << \"\\n\\n\";\n\nEigen::Matrix2d r_minus_90 = mat.transpose().colwise().reverse();\nstd::cout << r_minus_90 << \"\\n\\n\";\n\nEigen::Matrix2d r_180 = mat.colwise().reverse().rowwise().reverse(); // +180 same as -180\nstd::cout << r_180 << \"\\n\\n\";\n" }, { "answer_id": 63949048, "author": "Kapil", "author_id": 7283174, "author_profile": "https://Stackoverflow.com/users/7283174", "pm_score": 3, "selected": false, "text": "1 2 3 7 8 9 7 4 1\n4 5 6 => 4 5 6 => 8 5 2\n7 8 9 1 2 3 9 6 3\n" }, { "answer_id": 67960479, "author": "Michael Dunne", "author_id": 6171525, "author_profile": "https://Stackoverflow.com/users/6171525", "pm_score": 2, "selected": false, "text": "import numpy as np\n\na = np.array(\n [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 1, 2],\n [3, 4, 5, 6]\n ]\n)\n\nprint(a)\nprint(b[::-1, :].T)\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
42,531
<p>Looking for an example that:</p> <ol> <li>Launches an EXE</li> <li>Waits for the EXE to finish.</li> <li>Properly closes all the handles when the executable finishes.</li> </ol>
[ { "answer_id": 42543, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 5, "selected": false, "text": "argv[1]" }, { "answer_id": 42544, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 7, "selected": true, "text": "STARTUPINFO info={sizeof(info)};\nPROCESS_INFORMATION processInfo;\nif (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))\n{\n WaitForSingleObject(processInfo.hProcess, INFINITE);\n CloseHandle(processInfo.hProcess);\n CloseHandle(processInfo.hThread);\n}\n" }, { "answer_id": 99645, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 4, "selected": false, "text": "WaitForSingleObject(&processInfo.hProcess, INFINITE)\n" }, { "answer_id": 340042, "author": "Bob Moore", "author_id": 9368, "author_profile": "https://Stackoverflow.com/users/9368", "pm_score": 2, "selected": false, "text": "WaitForSingleObject" }, { "answer_id": 46831649, "author": "Blue7", "author_id": 3052832, "author_profile": "https://Stackoverflow.com/users/3052832", "pm_score": 3, "selected": false, "text": "#ifdef _WIN32\n#include <Windows.h>\n#include <iostream>\n#include <stdio.h>\n#include <tchar.h>\n#include <cstdlib>\n#include <string>\n#include <algorithm>\n\nclass process\n{\npublic:\n\n static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)\n {\n\n // Prepare handles.\n STARTUPINFO si;\n PROCESS_INFORMATION pi; // The function returns this\n ZeroMemory( &si, sizeof(si) );\n si.cb = sizeof(si);\n ZeroMemory( &pi, sizeof(pi) );\n\n //Prepare CreateProcess args\n std::wstring app_w(app.length(), L' '); // Make room for characters\n std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.\n\n std::wstring arg_w(arg.length(), L' '); // Make room for characters\n std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.\n\n std::wstring input = app_w + L\" \" + arg_w;\n wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );\n const wchar_t* app_const = app_w.c_str();\n\n // Start the child process.\n if( !CreateProcessW(\n app_const, // app path\n arg_concat, // Command line (needs to include app path as first argument. args seperated by whitepace)\n NULL, // Process handle not inheritable\n NULL, // Thread handle not inheritable\n FALSE, // Set handle inheritance to FALSE\n 0, // No creation flags\n NULL, // Use parent's environment block\n NULL, // Use parent's starting directory\n &si, // Pointer to STARTUPINFO structure\n &pi ) // Pointer to PROCESS_INFORMATION structure\n )\n {\n printf( \"CreateProcess failed (%d).\\n\", GetLastError() );\n throw std::exception(\"Could not create child process\");\n }\n else\n {\n std::cout << \"[ ] Successfully launched child process\" << std::endl;\n }\n\n // Return process handle\n return pi;\n }\n\n static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)\n {\n // Check if handle is closed\n if ( pi.hProcess == NULL )\n {\n printf( \"Process handle is closed or invalid (%d).\\n\", GetLastError());\n return FALSE;\n }\n\n // If handle open, check if process is active\n DWORD lpExitCode = 0;\n if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)\n {\n printf( \"Cannot return exit code (%d).\\n\", GetLastError() );\n throw std::exception(\"Cannot return exit code\");\n }\n else\n {\n if (lpExitCode == STILL_ACTIVE)\n {\n return TRUE;\n }\n else\n {\n return FALSE;\n }\n }\n }\n\n static bool stopProcess( PROCESS_INFORMATION &pi)\n {\n // Check if handle is invalid or has allready been closed\n if ( pi.hProcess == NULL )\n {\n printf( \"Process handle invalid. Possibly allready been closed (%d).\\n\");\n return 0;\n }\n\n // Terminate Process\n if( !TerminateProcess(pi.hProcess,1))\n {\n printf( \"ExitProcess failed (%d).\\n\", GetLastError() );\n return 0;\n }\n\n // Wait until child process exits.\n if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)\n {\n printf( \"Wait for exit process failed(%d).\\n\", GetLastError() );\n return 0;\n }\n\n // Close process and thread handles.\n if( !CloseHandle( pi.hProcess ))\n {\n printf( \"Cannot close process handle(%d).\\n\", GetLastError() );\n return 0;\n }\n else\n {\n pi.hProcess = NULL;\n }\n\n if( !CloseHandle( pi.hThread ))\n {\n printf( \"Cannot close thread handle (%d).\\n\", GetLastError() );\n return 0;\n }\n else\n {\n pi.hProcess = NULL;\n }\n return 1;\n }\n};//class process\n#endif //win32\n" }, { "answer_id": 70626460, "author": "reem_mikulsky", "author_id": 15799356, "author_profile": "https://Stackoverflow.com/users/15799356", "pm_score": 0, "selected": false, "text": "CreateProcessA" }, { "answer_id": 71851383, "author": "Giver Khadka", "author_id": 10586192, "author_profile": "https://Stackoverflow.com/users/10586192", "pm_score": 0, "selected": false, "text": "#include <Windows.h>\nvoid my_cmd()\n{\n STARTUPINFO si;\n PROCESS_INFORMATION pi;\n ZeroMemory(&si, sizeof(si));\n si.cb = sizeof(si);\n ZeroMemory(&pi, sizeof(pi));\n // CMD command here\n char arg[] = \"cmd.exe /c E:/Softwares/program.exe\";\n // Convert char string to required LPWSTR string\n wchar_t text[500];\n mbstowcs(text, arg, strlen(arg) + 1);\n LPWSTR command = text;\n // Run process\n CreateProcess (NULL, command, NULL, NULL, 0, \n CREATE_NO_WINDOW, NULL, NULL, &si, &pi);\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
42,566
<p>I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?</p> <p>Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):</p> <blockquote> <p>The [below] code does NOT make a connection or send any packets (to 64.233.187.99 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket.</p> </blockquote>
[ { "answer_id": 42624, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 5, "selected": false, "text": "host = `hostname`.strip # Get the hostname from the shell and removing trailing \\n\nputs host # Output the hostname\n" }, { "answer_id": 42736, "author": "Jack M.", "author_id": 3421, "author_profile": "https://Stackoverflow.com/users/3421", "pm_score": 1, "selected": false, "text": "hostname" }, { "answer_id": 42923, "author": "titanous", "author_id": 399, "author_profile": "https://Stackoverflow.com/users/399", "pm_score": 7, "selected": true, "text": "require 'socket'\n\ndef local_ip\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n s.addr.last\n end\nensure\n Socket.do_not_reverse_lookup = orig\nend\n\n# irb:0> local_ip\n# => \"192.168.0.127\"\n" }, { "answer_id": 1535556, "author": "Tim Peters", "author_id": 180800, "author_profile": "https://Stackoverflow.com/users/180800", "pm_score": 7, "selected": false, "text": "require 'socket'\nhostname = Socket.gethostname\n" }, { "answer_id": 1619840, "author": "Sai", "author_id": 102580, "author_profile": "https://Stackoverflow.com/users/102580", "pm_score": 2, "selected": false, "text": "`dig #{request.host} +short`.strip # dig gives a newline at the end\n" }, { "answer_id": 3246800, "author": "Salil", "author_id": 297087, "author_profile": "https://Stackoverflow.com/users/297087", "pm_score": 3, "selected": false, "text": "host_with_port" }, { "answer_id": 4726312, "author": "hacintosh", "author_id": 50029, "author_profile": "https://Stackoverflow.com/users/50029", "pm_score": 2, "selected": false, "text": "request.env[\"SERVER_ADDR\"]\n" }, { "answer_id": 5030162, "author": "D-D-Doug", "author_id": 462965, "author_profile": "https://Stackoverflow.com/users/462965", "pm_score": 3, "selected": false, "text": "require \"socket\"\nlocal_ip = UDPSocket.open {|s| s.connect(\"64.233.187.99\", 1); s.addr.last}\n" }, { "answer_id": 7809076, "author": "Claudio Floreani", "author_id": 985792, "author_profile": "https://Stackoverflow.com/users/985792", "pm_score": 4, "selected": false, "text": "ip_address_list()" }, { "answer_id": 8174503, "author": "Kevin Krauss", "author_id": 1052717, "author_profile": "https://Stackoverflow.com/users/1052717", "pm_score": 1, "selected": false, "text": "io = IO.popen('hostname')\nhostname = io.readlines\n\nio = IO.popen('ifconfig')\nifconfig = io.readlines\nip = ifconfig[11].scan(/\\ \\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\ /)\n" }, { "answer_id": 12632929, "author": "Tilo", "author_id": 677684, "author_profile": "https://Stackoverflow.com/users/677684", "pm_score": 2, "selected": false, "text": "hostname" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
42,581
<p>The Python docs say:</p> <blockquote> <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p> </blockquote> <p>So what's going on when I get the following unexpected result?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox. ... // Jumped over the lazy dog.""" &gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' </code></pre>
[ { "answer_id": 42597, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 8, "selected": true, "text": "re.sub" }, { "answer_id": 2517216, "author": "Ferran", "author_id": 301850, "author_profile": "https://Stackoverflow.com/users/301850", "pm_score": 4, "selected": false, "text": "re.sub('(?m)^//', '', s)\n" }, { "answer_id": 7248027, "author": "pseudosudo", "author_id": 600012, "author_profile": "https://Stackoverflow.com/users/600012", "pm_score": 3, "selected": false, "text": "re.sub" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
42,587
<p>I have heard/read the term but don't quite understand what it means.</p> <p>When should I use this technique and how would I use it? Can anyone provide a good code sample?</p>
[ { "answer_id": 42656, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": true, "text": "using System.Linq; \n\nclass DoubleDispatch\n{ \n public T Foo<T>(object arg)\n { \n var method = from m in GetType().GetMethods()\n where m.Name == \"Foo\" \n && m.GetParameters().Length==1\n && arg.GetType().IsAssignableFrom\n (m.GetParameters()[0].GetType())\n && m.ReturnType == typeof(T)\n select m;\n\n return (T) method.Single().Invoke(this,new object[]{arg}); \n }\n\n public int Foo(int arg) { /* ... */ }\n\n static void Test() \n { \n object x = 5;\n Foo<int>(x); //should call Foo(int) via Foo<T>(object).\n }\n} \n" }, { "answer_id": 6274270, "author": "Zenwalker", "author_id": 785375, "author_profile": "https://Stackoverflow.com/users/785375", "pm_score": 4, "selected": false, "text": "class DoubleDispatch\n{\n public T Foo<T>(object arg)\n {\n var method = from m in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)\n where m.Name == \"Foo\"\n && m.GetParameters().Length == 1\n //&& arg.GetType().IsAssignableFrom\n // (m.GetParameters()[0].GetType())\n &&Type.GetType(m.GetParameters()[0].ParameterType.FullName).IsAssignableFrom(arg.GetType())\n && m.ReturnType == typeof(T)\n select m;\n\n\n return (T)method.Single().Invoke(this, new object[] { arg });\n }\n\n public int Foo(int arg)\n {\n return 10;\n }\n\n public string Foo(string arg)\n {\n return 5.ToString();\n }\n\n public static void Main(string[] args)\n {\n object x = 5;\n DoubleDispatch dispatch = new DoubleDispatch();\n\n Console.WriteLine(dispatch.Foo<int>(x));\n\n\n Console.WriteLine(dispatch.Foo<string>(x.ToString()));\n\n Console.ReadLine();\n }\n}\n" }, { "answer_id": 45053773, "author": "Micha Wiedenmann", "author_id": 1671066, "author_profile": "https://Stackoverflow.com/users/1671066", "pm_score": 3, "selected": false, "text": "dynamic" }, { "answer_id": 59370408, "author": "bugs-x64", "author_id": 12550816, "author_profile": "https://Stackoverflow.com/users/12550816", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Linq;\n\nnamespace TestConsoleApp\n{\n internal class Program\n {\n public static void Main(string[] args)\n {\n const int x = 5;\n var dispatch = new DoubleDispatch();\n\n Console.WriteLine(dispatch.Foo<int>(x));\n Console.WriteLine(dispatch.Foo<string>(x.ToString()));\n\n Console.ReadLine();\n }\n }\n\n public class DoubleDispatch\n {\n public T Foo<T>(T arg)\n {\n var method = GetType()\n .GetMethods()\n .Single(m =>\n m.Name == \"Foo\" &&\n m.GetParameters().Length == 1 &&\n arg.GetType().IsAssignableFrom(m.GetParameters()[0].ParameterType) &&\n m.ReturnType == typeof(T));\n\n return (T) method.Invoke(this, new object[] {arg});\n }\n\n public int Foo(int arg)\n {\n return arg;\n }\n\n public string Foo(string arg)\n {\n return arg;\n }\n }\n}\n" }, { "answer_id": 61877919, "author": "MikeJ", "author_id": 1413174, "author_profile": "https://Stackoverflow.com/users/1413174", "pm_score": 3, "selected": false, "text": "class SpaceShip\n{\n public virtual void CollideWith(Asteroid asteroid)\n {\n asteroid.CollideWith(this);\n }\n}\n\nclass ApolloSpacecraft : SpaceShip\n{\n public override void CollideWith(Asteroid asteroid)\n {\n asteroid.CollideWith(this);\n }\n}\n\nclass Asteroid\n{\n public virtual void CollideWith(SpaceShip target)\n {\n Console.WriteLine(\"Asteroid hit a SpaceShip\");\n }\n\n public virtual void CollideWith(ApolloSpacecraft target)\n {\n Console.WriteLine(\"Asteroid hit ApolloSpacecraft\");\n }\n}\n\nclass ExplodingAsteroid : Asteroid\n{\n public override void CollideWith(SpaceShip target)\n {\n Console.WriteLine(\"ExplodingAsteroid hit a SpaceShip\");\n }\n\n public override void CollideWith(ApolloSpacecraft target)\n {\n Console.WriteLine(\"ExplodingAsteroid hit ApolloSpacecraft\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Asteroid[] asteroids = new Asteroid[] { new Asteroid(), new ExplodingAsteroid() };\n\n ApolloSpacecraft spacecraft = new ApolloSpacecraft();\n\n spacecraft.CollideWith(asteroids[0]);\n spacecraft.CollideWith(asteroids[1]);\n\n SpaceShip spaceShip = new SpaceShip();\n\n spaceShip.CollideWith(asteroids[0]);\n spaceShip.CollideWith(asteroids[1]);\n }\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ]
42,627
<p>I am looking to write some C# code for linux/windows/mac/any other platform, and am looking for best practices for portable code.</p> <p>Project <a href="http://go-mono.org" rel="noreferrer">mono</a> has some great <a href="http://www.mono-project.com/Category:Porting" rel="noreferrer">porting</a> resources.</p> <p>What are the best practices for portable C#?</p>
[ { "answer_id": 55946, "author": "Sam Warwick", "author_id": 3873, "author_profile": "https://Stackoverflow.com/users/3873", "pm_score": 4, "selected": false, "text": "string myfile = somepath + \"\\\\file.txt\";\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ]
42,648
<p>How am I supposed to get the <code>IDENTITY</code> of an inserted row?</p> <p>I know about <code>@@IDENTITY</code> and <code>IDENT_CURRENT</code> and <code>SCOPE_IDENTITY</code>, but don't understand the implications or impacts attached to each.</p> <p>Can someone please explain the differences and when I would be using each?</p>
[ { "answer_id": 42655, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 12, "selected": true, "text": "@@IDENTITY" }, { "answer_id": 42669, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": false, "text": "@@IDENTITY" }, { "answer_id": 6073578, "author": "Orry", "author_id": 70454, "author_profile": "https://Stackoverflow.com/users/70454", "pm_score": 8, "selected": false, "text": "USE AdventureWorks2008R2;\nGO\nDECLARE @MyTableVar table( NewScrapReasonID smallint,\n Name varchar(50),\n ModifiedDate datetime);\nINSERT Production.ScrapReason\n OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate\n INTO @MyTableVar\nVALUES (N'Operator error', GETDATE());\n\n--Display the result set of the table variable.\nSELECT NewScrapReasonID, Name, ModifiedDate FROM @MyTableVar;\n--Display the result set of the table.\nSELECT ScrapReasonID, Name, ModifiedDate \nFROM Production.ScrapReason;\nGO\n" }, { "answer_id": 16273230, "author": "Ian Kemp", "author_id": 70345, "author_profile": "https://Stackoverflow.com/users/70345", "pm_score": 6, "selected": false, "text": "output" }, { "answer_id": 29353469, "author": "Jim", "author_id": 4546567, "author_profile": "https://Stackoverflow.com/users/4546567", "pm_score": 5, "selected": false, "text": "SELECT CAST(scope_identity() AS int);\n" }, { "answer_id": 40425907, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": false, "text": "OUTPUT" }, { "answer_id": 48040418, "author": "Khan Ataur Rahman", "author_id": 6880332, "author_profile": "https://Stackoverflow.com/users/6880332", "pm_score": -1, "selected": false, "text": "IDENT_CURRENT('tableName')\n" }, { "answer_id": 50725760, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 4, "selected": false, "text": "INSERT INTO MyTable\nOUTPUT INSERTED.ID\nVALUES (...)\n" }, { "answer_id": 55142419, "author": "Frank Roth", "author_id": 1073330, "author_profile": "https://Stackoverflow.com/users/1073330", "pm_score": 2, "selected": false, "text": "uuid" }, { "answer_id": 59266753, "author": "Andy Robertson", "author_id": 664210, "author_profile": "https://Stackoverflow.com/users/664210", "pm_score": 2, "selected": false, "text": "SET IDENTITY_INSERT ON" }, { "answer_id": 60305940, "author": "StevenJe", "author_id": 9195980, "author_profile": "https://Stackoverflow.com/users/9195980", "pm_score": 1, "selected": false, "text": "CREATE SEQUENCE CountBy1 \n START WITH 1 \n INCREMENT BY 1 ; \nGO \n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ]
42,672
<p>What would be the best way to do an <code>scp</code> or <code>sftp</code> copy in a Unix environment using C?</p> <p>I'm interested in knowing the best library to use and an example if at all possible. I'm working on a <a href="https://en.wikipedia.org/wiki/Solaris_%28operating_system%29" rel="nofollow noreferrer">Solaris</a> server with the <em><a href="https://en.wikipedia.org/wiki/Sun_Microsystems" rel="nofollow noreferrer">Sun</a> tools</em> installed.</p>
[ { "answer_id": 42705, "author": "Tyler Gooch", "author_id": 1372, "author_profile": "https://Stackoverflow.com/users/1372", "pm_score": 0, "selected": false, "text": "int transferFile()\n{\n // Declare the transfer command\n char transferCommand[50] = \"/home/tyler/transferFile.shl\";\n // Execute the command\n return system(transferCommand);\n}\n" }, { "answer_id": 24989730, "author": "Desphilboy", "author_id": 2023625, "author_profile": "https://Stackoverflow.com/users/2023625", "pm_score": 0, "selected": false, "text": "int main(array<System::String ^> ^args)\n{\n //Console::WriteLine(L\"Hello World\");\n\n pSFTPConnector sshc = new SFTPConnector(L\".\\\\\", L\"127.0.0.1\", 22, L\"iman\", L\"iman\"); // Change the hostname, port, username, password to your SFTP server, your credentials\n\n //FILE *nullfile = fopen(\"null\", \"w\");\n //sshc->setLogFile(nullfile);\n sshc->setVerbosity(SSH_LOG_RARE); // You can change the verbosity as appropriate for you\n\n int i = sshc->InitSession();\n i = sshc->ConnectSession();\n i = sshc->InitSFTP();\n\n //i = sshc->SFTPrename(\"renamed_myfile.txt\", \"myfile.txt\"); // Change these file names\n //i = sshc->Makedir(\"sftpdir\");\n //i = sshc->testUploadFile(\"myfile2.txt\", \"1234567890testfile\");\n\n // Change these file names to whatever appropriate\n //i = sshc->SFTPget(\"c:\\\\testdir\\\\Got_CAR_HIRE_FINAL_test.jpg\", \"CAR_HIRE_FINAL_test.jpg\", 64*1024);\n i = sshc->SFTPget(\"c:\\\\testdir\\\\get_downloaded_CAR_HIRE_FINAL.jpg\", \"CAR_HIRE_FINAL.jpg\", 64 *1024);\n i = sshc->SFTPreget(\"c:\\\\testdir\\\\reget_downloaded_CAR_HIRE_FINAL.jpg\", \"CAR_HIRE_FINAL.jpg\", 64 * 1024);\n i = sshc->SFTPput(\"c:\\\\testdir\\\\CAR_HIRE_FINAL.jpg\", \"put_CAR_HIRE_FINAL.jpg\", 64 * 1024);\n i = sshc->SFTPreput(\"c:\\\\testdir\\\\CAR_HIRE_FINAL.jpg\", \"reput_CAR_HIRE_FINAL.jpg\", 64 * 1024);\n\n delete sshc;\n return 0;\n}\n\ntypedef enum sshconerr {\n E_OK = 1, E_SESSION_ALOC = -1, E_SSH_CONNECT_ERR = -2, E_SFTP_ALLOC = -3, E_INIT_SFTP = -4, E_CREATE_DIR = -5, E_FILEOPEN_WRITE = -6, E_WRITE_ERR = -7,\n E_FILE_CLOSE = -8, E_FILE_OPEN_READ = -9, E_INVALID_PARAMS = -10, E_SFTP_ERR = -11, E_SFTP_READ_ERR = -12, E_SFTP_READBYTES_ERR = -13, E_GET_FILEINF = -14,\n E_LOCAL_FILE_NOTFOUND = -15, E_RENAME_ERR = -16, E_MEM_ALLOC = -17, E_LOCAL_FILE_READ = -18, E_LOCAL_FILE_RDWR = -19, E_REMOTEFILE_SEEK = -20,\n E_REMOTE_FILE_OPEN = -21, E_DELETE_ERR = -22, E_RENAME_LOCAL_FILE = -23, E_LOCAL_DELETE_FILE = -24, E_FILEOPEN_RDONLY = -25, E_SFTP_READ_EOF = -26,\n E_UNKNOWN = -999\n} ESSHERR;\n\n\n// Status of transfers;\ntypedef enum sftpstat{ES_DONE=0, ES_INPROGRESS, ES_FAILED, ES_STARTING, ES_PAUSED, ES_RESUMING, ES_CANCELLED, ES_NONE } ESFTPSTAT;\n\nusing namespace std;\n\n\n// Statistics about the transfer;\ntypedef struct transferstatstruct {\n string remote_file_name;\n string local_file_name;\n __int64 total_size;\n __int64 transferred;\n __int64 averagebps;\n long long seconds_elapsed;\n long long seconds_remained;\n int percent;\n ESFTPSTAT transferstate;\n} TTransStat;\n\n\n#define E_SESSION_NEW -1\n\n// These libraries are required\n#pragma comment(lib, \"ssh.lib\")\n\n// This is the main class that does the majority of the work\n\ntypedef class CSFTPConnector {\n\n private:\n ssh_session session; // SSH session\n sftp_session sftp; // SFTP session\n sftp_file file; // Structure for a remote file\n FILE *localfile; // Not used on Windows, but it could be local file pointer in Unix\n FILE *logfile; // The file for writing logs, default is set to stderr\n string filename; // File name of the transfer;\n string localfilename; // File name of local file;\n string tempfilename; // A temporary file name will be used during the transfer which is renamed when transfer is completed.\n ESFTPSTAT transferstatus; // State of the transfer which has one of the above values (ESFTPSTAT)\n time_t transferstarttime; // Time of start of the transfer\n wchar_t username[SHORT_BUFF_LEN];\n wchar_t password[SHORT_BUFF_LEN];\n wchar_t hostname[SHORT_BUFF_LEN]; // Hostname of the SFTP server\n wchar_t basedir[SHORT_BUFF_LEN]; // This base directory is the directory of the public and private key structure (NOT USED IN THIS VERSION)\n int port; // Port of the server;\n int verbosity; // Degree of verbosity of libssh\n __int64 filesize; // Total number of bytes to be transferred;\n DWORD local_file_size_hiDWORD; // Bill Gates cannot accept the file size\n // without twisting the programmers, so\n // he accepts them in two separate words\n // like this\n DWORD local_file_size_lowDWORD; // These two DWORDs when connected together comprise a 64 bit file size.\n __int64 lfilesize; // Local file size\n __int64 rfilesize; // Remote file size\n __int64 transferred; // Number of bytes already transferred\n bool pause; // Pause flag\n TTransStat stats; // Statistics of the transfer\n HANDLE localfilehandle; // Windows uses handles to manipulate files. this is the handle to local file.\n\n ESSHERR CSFTPConnector::rwopen_existing_SFTPfile(char *fn); // Open a file on remote (server) read/write for upload\n ESSHERR CSFTPConnector::rdopen_existing_SFTPfile(char *fn); // Open a file on remote (server) read only for download\n ESSHERR createSFTPfile(char *fn); // Create a file on server;\n ESSHERR writeSFTPfile(char *block, size_t blocksize); // Write a block of data to the open remote file\n ESSHERR readSFTPfile(char *block, size_t len, size_t *bytesread); // Read a block of data from the open remote file\n ESSHERR readSFTPfile(char *block, __int64 len, DWORD *bytesread);\n ESSHERR closeSFTPfile(); // Closes the remote file;\n ESSHERR openSFTPfile(char *fn); // Opens the remote file\n ESSHERR getSFTPfileinfo(); // Gets information about the remote file\n\n public:\n wstring errstring; // The string describing last error\n ESSHERR Err; // Error code of last error\n CSFTPConnector(); // Default constructor;\n CSFTPConnector(wchar_t *dir, wchar_t *hn, int hostport, wchar_t *un, wchar_t *pass); // Constructor\n void setVerbosity(int v);\n int getVerbosity();\n ESSHERR InitSession(); // Must be called before doing any transfer\n ESSHERR ConnectSession(); // Connects to the SSH server\n ESSHERR InitSFTP(); // Must be called before doing any transfer\n ESSHERR Makedir(char *newdir);\n ESSHERR testUploadFile(char *fn, char *block); // Do not use this, only for test purposes for myself\n ESSHERR SFTPput(char *lfn, char *rfn, size_t blocksize); // Upload a file from start\n ESSHERR SFTPreput(char *lfn, char *rfn, size_t blocksize); // Checks for previouse interrupted transfer, then\n // either continues the previous transfer (if\n // there was any) or starts a new one (UPLOAD)\n ESSHERR SFTPrename(char *newname, char *oldname); // Renames a remote file( must be closed)\n ESSHERR CSFTPConnector::SFTPdelete(char *remfile); // Deletes a remote file\n TTransStat getStatus(); // Gets statistics of the transfer\n ESSHERR CSFTPConnector::SFTPget(char *lfn, char *rfn, size_t blocksize); // Downloads a file from the SFTP server\n ESSHERR CSFTPConnector::SFTPreget(char *lfn, char *rfn, size_t blocksize); // Checks for a previous interrupted transfer,\n // then either continues the previous transfer\n // (if there was any) or starts a new one (DOWNLOAD).\n void CancelTransfer();\n void PauseTransfer();\n void setLogFile(FILE *logf); // Sets the log file. If not set, standard\n // error will be used. By default.\n void CloseLocalFile();\n void CloseRemoteFile();\n\n ~CSFTPConnector();\n} SFTPConnector, *pSFTPConnector;\n\nvoid CSFTPConnector::CloseLocalFile()\n{\n CloseHandle(localfilehandle);\n}\n\n\nvoid CSFTPConnector::CloseRemoteFile()\n{\n sftp_close(file);\n}\n\nvoid CSFTPConnector::setLogFile(FILE *logf)\n{\n logfile = logf;\n}\n\nvoid CSFTPConnector::CancelTransfer()\n{\n transferstatus = ES_CANCELLED;\n}\n\nvoid CSFTPConnector::PauseTransfer()\n{\n transferstatus = ES_PAUSED;\n pause = true;\n}\n\n//----------------------------------------\n\nESSHERR CSFTPConnector::SFTPget(char *lfn, char *rfn, size_t blocksize)\n{\n DWORD result;\n int rc;\n BOOL bresult;\n DWORD bytesread;\n filesize = 0;\n transferred = 0;\n\n pause = false;\n transferstatus = ES_NONE;\n char *block;\n struct stat st;\n wchar_t temp[SHORT_BUFF_LEN];\n size_t tempsize;\n wstring wlfn;\n int loopcounter = 0;\n\n localfilename = lfn;\n\n filename = rfn;\n\n tempfilename = string(lfn) + \".sftp_temp\";\n mbstowcs_s(&tempsize, temp, tempfilename.c_str(), SHORT_BUFF_LEN);\n\n localfilehandle = CreateFile(temp, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (localfilehandle == INVALID_HANDLE_VALUE)\n {\n transferstatus = ES_FAILED;\n errstring = L\"Could not open local file:\" + wstring(temp) + L\" for read and write\";\n Err = E_LOCAL_FILE_RDWR;\n return E_LOCAL_FILE_RDWR;\n }\n\n lfilesize = 0;\n transferred = 0;\n\n block = (char*)malloc(blocksize + 1);\n if (block == NULL) {\n Err = E_MEM_ALLOC;\n transferstatus = ES_FAILED;\n errstring = L\"Could not allocate memory for file block size\";\n CloseLocalFile();\n return E_MEM_ALLOC;\n }\n\n result = rdopen_existing_SFTPfile((char *)rfn);\n\n if (result == E_OK) {\n getSFTPfileinfo();\n filesize = rfilesize;\n }\n else\n {\n Err = E_REMOTE_FILE_OPEN;\n transferstatus = ES_FAILED;\n errstring = L\"Could not open remote file\";\n CloseLocalFile();\n delete block;\n return E_REMOTEFILE_SEEK;\n }\n\n transferstatus = ES_STARTING;\n\n sftp_file_set_blocking(file);\n transferstarttime = time(NULL);\n transferstatus = ES_INPROGRESS;\n\n while (transferstatus != ES_FAILED &&\n transferstatus != ES_PAUSED &&\n transferstatus != ES_CANCELLED &&\n transferstatus != ES_DONE)\n {\n loopcounter++;\n\n result = readSFTPfile(block, blocksize, (size_t *)&bytesread);\n if (result != E_OK && result!= E_SFTP_READ_EOF)\n {\n errstring = L\"Error reading from remote SFTP server file.\";\n Err = (ESSHERR)result;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n delete block;\n return (ESSHERR)result;\n }\n if (result == E_SFTP_READ_EOF)\n transferstatus = ES_DONE;\n fprintf(logfile, \"Read %d bytes from input file. Number of packets: %d, %llu from %llu bytes\\n\", bytesread, loopcounter, transferred, filesize);\n\n bresult = WriteFile(localfilehandle, (LPVOID)block, bytesread, &bytesread, NULL);\n if (bytesread < blocksize)\n {\n if (bresult == FALSE)\n {\n errstring = L\"Error writing to local file.\";\n Err = E_LOCAL_FILE_RDWR;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n delete block;\n return E_LOCAL_FILE_RDWR;\n }\n else if (bytesread == 0)\n {\n errstring = L\"Transfer done.\";\n Err = E_OK;\n transferstatus = ES_DONE;\n continue;\n }\n }\n\n Err = E_OK;\n\n if (pause == true)\n transferstatus = ES_PAUSED;\n if (bresult == TRUE && bytesread == 0)\n {\n // At the end of the file\n transferstatus = ES_DONE;\n }\n Sleep(BLOCKTRANSDELAY);\n if (loopcounter % 331 == 0)\n Sleep(77 * BLOCKTRANSDELAY);\n if (loopcounter % 3331 == 0)\n Sleep(777 * BLOCKTRANSDELAY);\n }\n\n // Closing files\n result = closeSFTPfile();\n CloseHandle(localfilehandle);\n\n Sleep(1000);\n\n if (transferstatus == ES_DONE)\n {\n wchar_t temp2[SHORT_BUFF_LEN];\n mbstowcs_s(&tempsize, temp2, lfn, SHORT_BUFF_LEN);\n bresult = MoveFile(temp, temp2);\n if (bresult != TRUE)\n {\n Err = E_RENAME_LOCAL_FILE;\n errstring = L\"Could not rename local file: \" + wstring(temp);\n transferstatus = ES_FAILED;\n delete block;\n return E_RENAME_LOCAL_FILE;\n }\n }\n\n if (transferstatus == ES_CANCELLED)\n {\n wchar_t temp2[SHORT_BUFF_LEN];\n mbstowcs_s(&tempsize, temp2, lfn, SHORT_BUFF_LEN);\n bresult = DeleteFile(temp);\n if (bresult != TRUE)\n {\n Err = E_LOCAL_DELETE_FILE;\n errstring = L\"Could not rename local file: \" + wstring(temp);\n transferstatus = ES_FAILED;\n delete block;\n return E_LOCAL_DELETE_FILE;\n }\n }\n delete block;\n return (ESSHERR) result;\n}\n\nTTransStat CSFTPConnector::getStatus()\n{\n stats.seconds_elapsed = time(NULL) - transferstarttime;\n stats.averagebps = (transferred * 8) / stats.seconds_elapsed;\n if (filesize > 0) {\n stats.percent = (transferred *100)/ filesize;\n stats.seconds_remained = ((filesize - transferred) * 8) / stats.averagebps;\n }\n else\n {\n stats.percent = -1;\n stats.seconds_remained = -1;\n }\n stats.total_size = filesize;\n stats.transferstate = transferstatus;\n stats.remote_file_name = filename;\n stats.local_file_name = localfilename;\n\n return stats;\n}\n\nESSHERR CSFTPConnector::SFTPrename(char *newname, char *oldname)\n{\n int rc = sftp_rename(sftp, oldname, newname);\n if (rc != SSH_OK) {\n return E_RENAME_ERR;\n }\n\n return E_OK;\n}\n\n\nESSHERR CSFTPConnector::SFTPdelete(char *remfile)\n{\n int rc = sftp_unlink(sftp, remfile);\n if (rc != SSH_OK) {\n return E_DELETE_ERR;\n }\n return E_OK;\n}\n\n\nESSHERR CSFTPConnector::SFTPreput(char *lfn, char *rfn, size_t blocksize)\n{\n ESSHERR result;\n BOOL bresult;\n DWORD bytesread;\n filesize = 0;\n transferred = 0;\n\n pause = false;\n transferstatus = ES_NONE;\n char *block;\n struct stat st;\n wchar_t temp[SHORT_BUFF_LEN];\n size_t tempsize;\n wstring wlfn;\n int loopcounter = 0;\n\n localfilename = lfn;\n //wlfn = wstring(lfn);\n //localfile = fopen(lfn, L\"r\");\n filename = rfn;\n mbstowcs_s(&tempsize, temp, lfn, SHORT_BUFF_LEN);\n\n //filesize = getFileSize(localfilename);\n\n /*if (filesize < 0) {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n return E_LOCAL_FILE_NOTFOUND;\n }*/\n\n localfilehandle = CreateFile(temp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n if (localfilehandle == INVALID_HANDLE_VALUE)\n {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n return E_LOCAL_FILE_NOTFOUND;\n }\n local_file_size_lowDWORD = GetFileSize(localfilehandle, &local_file_size_hiDWORD);\n filesize = (local_file_size_hiDWORD * 0x100000000) + local_file_size_lowDWORD;\n\n if (filesize < 0) {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n CloseLocalFile();\n return E_LOCAL_FILE_NOTFOUND;\n }\n\n block = (char*)malloc(blocksize + 1);\n if (block == NULL) {\n Err = E_MEM_ALLOC;\n transferstatus = ES_FAILED;\n errstring = L\"Could not allocate memory for file block size\";\n CloseLocalFile();\n return E_MEM_ALLOC;\n }\n\n tempfilename = string(rfn) + \".sftp_temp\";\n\n result = rwopen_existing_SFTPfile((char *)tempfilename.c_str());\n if (result == E_OK) {\n getSFTPfileinfo();\n sftp_seek64(file, rfilesize);\n __int64 tempi64 = rfilesize & 0x00000000FFFFFFFF;\n DWORD dwlow = tempi64;\n tempi64 = (rfilesize & 0x7FFFFFFF00000000);\n tempi64 = tempi64 >> 32;\n long dwhi = tempi64;\n DWORD dwResult = SetFilePointer(localfilehandle, dwlow, &dwhi, FILE_BEGIN);\n if (dwResult == INVALID_SET_FILE_POINTER)\n {\n transferstatus = ES_FAILED; Err = result; return result;\n }\n transferstatus = ES_RESUMING;\n transferred = rfilesize;\n }\n else{\n result = createSFTPfile((char *)tempfilename.c_str());\n transferstatus = ES_STARTING;\n if (result != E_OK) {\n transferstatus = ES_FAILED;\n Err = result;\n CloseLocalFile();\n return result;\n }\n }\n sftp_file_set_blocking(file);\n transferstarttime = time(NULL);\n transferstatus = ES_INPROGRESS;\n\n while (transferstatus != ES_FAILED &&\n transferstatus != ES_PAUSED &&\n transferstatus != ES_DONE)\n {\n loopcounter++;\n bresult = ReadFile(localfilehandle, (LPVOID)block, blocksize, &bytesread, NULL);\n fprintf(logfile, \"Read %d bytes from input file. Number of packets: %d, %llu from %llu bytes\\n\", bytesread, loopcounter, transferred, filesize);\n if (bytesread < blocksize)\n {\n if (bresult == FALSE)\n {\n errstring = L\"Error reading from local file.\";\n Err = E_LOCAL_FILE_READ;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n return E_LOCAL_FILE_READ;\n }\n else if (bytesread == 0)\n {\n errstring = L\"Transfer done.\";\n Err = E_OK;\n transferstatus = ES_DONE;\n continue;\n }\n }\n\n result = writeSFTPfile(block, bytesread);\n if (result != E_OK && bytesread>0)\n {\n errstring = L\"Error transmitting to remote SFTP server file.\";\n Err = result;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n return result;\n }\n\n Err = E_OK;\n //transferred = transferred + bytesread;\n if (pause == true)\n transferstatus = ES_PAUSED;\n if (bresult == TRUE && bytesread == 0)\n {\n // At the end of the file\n transferstatus = ES_DONE;\n }\n Sleep(BLOCKTRANSDELAY);\n if (loopcounter % 331 == 0)\n Sleep(77 * BLOCKTRANSDELAY);\n if (loopcounter % 3331 == 0)\n Sleep(777 * BLOCKTRANSDELAY);\n }\n\n CloseRemoteFile();\n CloseLocalFile();\n Sleep(1000);\n\n if (transferstatus == ES_CANCELLED)\n {\n result = SFTPdelete((char *)tempfilename.c_str());\n if (bresult != E_OK)\n {\n Err = E_DELETE_ERR;\n errstring = L\"Could not delete remote file.\";\n transferstatus = ES_FAILED;\n return E_DELETE_ERR;\n }\n }\n if (transferstatus == ES_DONE)\n result = SFTPrename(rfn, (char *)tempfilename.c_str());\n delete block;\n return result;\n}\n\n\nESSHERR CSFTPConnector::getSFTPfileinfo()\n{\n sftp_attributes fileinf = sftp_fstat(file);\n\n if (fileinf == NULL) {\n return E_GET_FILEINF;\n }\n\n rfilesize = fileinf->size;\n\n sftp_attributes_free(fileinf);\n return E_OK;\n}\n\nESSHERR CSFTPConnector::closeSFTPfile()\n{\n int rc = sftp_close(file);\n if (rc != SSH_OK)\n {\n fprintf(logfile, \"Can't close the written file: %s\\n\",\n ssh_get_error(session));\n return E_FILE_CLOSE;\n }\n return E_OK;\n}\n\nESSHERR CSFTPConnector::writeSFTPfile(char *block, size_t blocksize)\n{\n size_t nwritten = sftp_write(file, block, blocksize);\n if (nwritten != blocksize)\n {\n fprintf(logfile, \"Can't write data to file: %s\\n\",\n ssh_get_error(session));\n //sftp_close(file);\n transferred = transferred + nwritten;\n return E_WRITE_ERR;\n }\n\n transferred = transferred + nwritten;\n return E_OK;\n}\n\nESSHERR CSFTPConnector::readSFTPfile(char *block, size_t len, size_t *bytesread)\n{\n DWORD readbytes;\n *bytesread = 0;\n if (len <= 0)\n return E_INVALID_PARAMS;\n if (bytesread == NULL || block == NULL)\n return E_INVALID_PARAMS;\n\n readbytes = sftp_read(file, block, len);\n if (readbytes < 0)\n {\n fprintf(logfile, \"Can't read from remote file: %s %s\\n\", filename.c_str(), ssh_get_error(session));\n *bytesread = 0;\n return E_SFTP_READ_ERR;\n }\n\n if (readbytes < len)\n {\n *bytesread = readbytes;\n transferred = transferred + readbytes;\n return E_SFTP_READ_EOF;\n }\n\n *bytesread = readbytes;\n transferred = transferred + readbytes;\n\n return E_OK;\n}\n\nESSHERR CSFTPConnector::readSFTPfile(char *block, __int64 len, DWORD *bytesread)\n{\n DWORD readbytes;\n *bytesread = 0;\n if (len <= 0)\n return E_INVALID_PARAMS;\n if (bytesread == NULL || block == NULL)\n return E_INVALID_PARAMS;\n\n readbytes = sftp_read(file, block, len);\n if (readbytes < 0)\n {\n fprintf(logfile, \"Can't read from remote file: %s %s\\n\", filename.c_str(), ssh_get_error(session));\n *bytesread = 0;\n return E_SFTP_READ_ERR;\n }\n\n if (readbytes < len)\n {\n *bytesread = readbytes;\n return E_SFTP_READ_EOF;\n }\n\n *bytesread = readbytes;\n transferred = transferred + readbytes;\n\n return E_OK;\n}\n\nESSHERR CSFTPConnector::createSFTPfile(char *fn)\n{\n int access_type = O_CREAT | O_RDWR;\n int rc, nwritten;\n\n filename = string(fn);\n file = sftp_open(sftp, fn,\n access_type, S_IWRITE);\n if (file == NULL)\n {\n fprintf(logfile, \"Can't open file for writing: %s\\n\",\n ssh_get_error(session));\n return E_FILEOPEN_WRITE;\n }\n return E_OK;\n}\n\nESSHERR CSFTPConnector::rdopen_existing_SFTPfile(char *fn)\n{\n int access_type = O_RDONLY;\n int rc, nwritten;\n\n filename = string(fn);\n file = sftp_open(sftp, fn,\n access_type, S_IREAD);\n if (file == NULL)\n {\n fprintf(logfile, \"Can't open file for writing: %s\\n\",\n ssh_get_error(session));\n return E_FILEOPEN_RDONLY;\n }\n return E_OK;\n}\n\nESSHERR CSFTPConnector::openSFTPfile(char *fn)\n{\n int access_type = O_RDONLY;\n int rc, nwritten;\n\n filename = string(fn);\n file = sftp_open(sftp, fn,\n access_type, S_IWRITE);\n if (file == NULL)\n {\n fprintf(logfile, \"Can't open file for writing: %s\\n\",\n ssh_get_error(session));\n return E_FILE_OPEN_READ;\n }\n return E_OK;\n}\n\nESSHERR CSFTPConnector::Makedir(char *newdir)\n{\n int rc;\n rc = sftp_mkdir(sftp, newdir, S_IFDIR);\n if (rc != SSH_OK)\n {\n if (sftp_get_error(sftp) != SSH_FX_FILE_ALREADY_EXISTS)\n {\n fprintf(logfile, \"Can't create directory: %s\\n\",\n ssh_get_error(session));\n return E_CREATE_DIR;\n }\n }\n return E_OK;\n}\n\nSFTPConnector::CSFTPConnector()\n{\n //libssh2_init(0);\n session = ssh_new();\n if (session == NULL)\n {\n Err = E_SESSION_ALOC;\n errstring = L\"Could not allocate a session.\";\n\n }\n wcscpy(hostname, L\"localhost\");\n wcscpy(username, L\"User\");\n wcscpy(password, L\"Password\");\n wcscpy(basedir, L\".\\\\\");\n port = 22;\n verbosity = SSH_LOG_RARE;\n filesize = 0;\n transferred = 0;\n\n pause = false;\n transferstatus = ES_NONE;\n logfile = stderr;\n}\n\n\nCSFTPConnector::CSFTPConnector(wchar_t *dir, wchar_t *hn, int hostport, wchar_t *un, wchar_t *pass)\n{\n session = ssh_new();\n\n if (session == NULL)\n {\n Err = E_SESSION_ALOC;\n errstring = L\"Could not allocate a session.\";\n }\n wcscpy(hostname, hn);\n wcscpy(username, un);\n wcscpy(password, pass);\n wcscpy(basedir, dir);\n port = hostport;\n verbosity = SSH_LOG_RARE;\n filesize = 0;\n transferred = 0;\n\n pause = false;\n transferstatus = ES_NONE;\n logfile = stderr;\n}\n\nESSHERR CSFTPConnector::InitSFTP()\n{\n int rc;\n sftp = sftp_new(session);\n if (session == NULL)\n {\n Err = E_SFTP_ALLOC;\n errstring = L\"Could not allocate a sftp session.\";\n }\n\n rc = sftp_init(sftp);\n if (rc != SSH_OK)\n {\n fprintf(logfile, \"Error initializing SFTP session: %s.\\n\",\n sftp_get_error(sftp));\n sftp_free(sftp);\n return E_INIT_SFTP;\n }\n\n return E_OK;\n}\n\nESSHERR CSFTPConnector::ConnectSession()\n{\n char temp[SHORT_BUFF_LEN];\n size_t n_of_chars;\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)password, SHORT_BUFF_LEN);\n int ir;\n\n ir = ssh_connect(session);\n if (ir != SSH_OK) {\n errstring = L\"Could not connect the ssh session.\";\n return E_SSH_CONNECT_ERR;\n }\n\n ir = ssh_userauth_password(session, NULL, temp);\n if (ir != SSH_OK) {\n errstring = L\"Could not connect the ssh session.\";\n return E_SSH_CONNECT_ERR;\n }\n return E_OK;\n}\n\nESSHERR CSFTPConnector::InitSession()\n{\n char temp[SHORT_BUFF_LEN];\n size_t n_of_chars;\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *) hostname, SHORT_BUFF_LEN);\n ssh_options_set(session, SSH_OPTIONS_HOST, temp);\n ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);\n ssh_options_set(session, SSH_OPTIONS_PORT, &port);\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)username, SHORT_BUFF_LEN);\n ssh_options_set(session, SSH_OPTIONS_USER, temp);\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)basedir, SHORT_BUFF_LEN);\n ssh_options_set(session, SSH_OPTIONS_SSH_DIR, temp);\n\n return E_OK;\n}\n\nCSFTPConnector::~CSFTPConnector()\n{\n sftp_free(sftp);\n ssh_disconnect(session);\n ssh_free(session);\n\n return;\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
42,693
<p>What's the best way to get user input in a C program where the choices are of a limited number?</p> <p>Say for example the choices are:</p> <p>A) Print the list. B) Add 99 to the end of the list. C) Delete all duplicates. 5) Reset 5 times.</p> <p>Entering &quot;A&quot; and then Enter is OK. Or, just a single keystroke would work as well.</p>
[ { "answer_id": 42704, "author": "David Bryson", "author_id": 3663, "author_profile": "https://Stackoverflow.com/users/3663", "pm_score": 0, "selected": false, "text": "int intput()\n{\n char input = 0;\n int ret_val = 0;\n\n read(0, &input, 1);\n\n switch(input) {\n case 'c':\n // Do c\n break;\n\n case 'p':\n // Do p\n break;\n\n case 'd':\n // Do d\n break;\n\n case 'q':\n quit = 1;\n break;\n\n case '?':\n PRINT(ENABLE, \"c - connect\\n\");\n PRINT(ENABLE, \"p - ping\\n\");\n PRINT(ENABLE, \"d - disconnect\\n\");\n PRINT(ENABLE, \"q - quit\\n\");\n PRINT(ENABLE, \"? - this message\\n\");\n break;\n }\n\n return 0;\n}\n" }, { "answer_id": 43527, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": 0, "selected": false, "text": "switch(input)\n" }, { "answer_id": 48627, "author": "dmityugov", "author_id": 3232, "author_profile": "https://Stackoverflow.com/users/3232", "pm_score": 3, "selected": true, "text": "getchar()" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3807/" ]
42,703
<p>I am using sp_send_dbmail in SQL2005 to send an email with the results in an attachment. When the attachment is sent it is UCS-2 Encoded, I want it to be ANSI or UTF-8.</p> <p>Here is the SQL</p> <pre><code>EXEC msdb.dbo.sp_send_dbmail @recipients = 'temp@example.com' , @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom''' , @query_result_header=0 , @subject = 'see attach' , @body= 'temp body' , @profile_name= N'wksql01tAdmin' , @body_format = 'HTML' ,@query_result_separator = ',' ,@query_attachment_filename = 'results.csv' ,@query_no_truncate = '0' ,@attach_query_result_as_file = 1 </code></pre> <p>I have seen some comments on the internet that this is fixed with sql2005 SP2, but do not find it to be the case.</p>
[ { "answer_id": 5783390, "author": "bushtwig", "author_id": 588229, "author_profile": "https://Stackoverflow.com/users/588229", "pm_score": 0, "selected": false, "text": "msdb" }, { "answer_id": 14670451, "author": "Gena", "author_id": 2036703, "author_profile": "https://Stackoverflow.com/users/2036703", "pm_score": 4, "selected": false, "text": "sp_send_dbmail" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
42,706
<p>Is there a down side? I feel almost dependent on it now. Whenever a project gets past a certain size almost feel an allergic reaction to standard patterns and immediately re-wire it with a Dependency Injection framework.</p> <p>The largest issue I've found is it can be confusing for other developers who are just learning it.</p> <p>Also, I'd feel much better if it were a part of the language I was using. Though, for Java at least, there are a couple very lightweight libraries which are quite good.</p> <p>Thoughts? Bad experiences? Or just stop worrying about it?</p> <hr> <p>[EDIT] Re: Description of Dependency Injection itself</p> <p>Sorry for being vague. <a href="http://www.martinfowler.com/articles/injection.html" rel="noreferrer">Martin Fowler</a> probably describes it FAR better than I ever could... no need to waste the effort. </p> <p>Coincidentally, this confirms one point about it, that it's still not widely practiced and might tend to be a barrier when working with teams if everyone is not up to speed on it. </p>
[ { "answer_id": 42739, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": false, "text": " package dependecyinjection; \n import java.util.ServiceLoader; \n\n public abstract class FooService { \n\n public static FooService getService() { \n ServiceLoader<FooService> loader = ServiceLoader.load(FooService.class); \n\n for (FooService service : loader) { \n return provider; \n } \n\n throw new Exception (\"No service\"); \n } \n\n public abstract int fooOperation(); \n\n } \n\n package dependecyinjection; \n public class FooImpl extends FooService { \n @Override \n public int fooOperation() { \n return 2; \n } \n } \n" }, { "answer_id": 4980407, "author": "Tergiver", "author_id": 351385, "author_profile": "https://Stackoverflow.com/users/351385", "pm_score": 3, "selected": false, "text": "i = GetServiceOrInterfaceOrObject(...)\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758/" ]
42,710
<p>I need to implement a 4-to-1 function in Veriog. The input is 4 bits, a number from 0-15. The output is a single bit, 0 or 1. Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not. I want vcs to successfully optimizing the code and also have it be as short/neat as possible. My solution so far:</p> <pre><code>wire [3:0] a; wire b; wire [15:0] c; assign c = 16'b0100110010111010; //for example but could be any constant assign b = c[a]; </code></pre> <p>Having to declare c is ugly and I don't know if vcs will recognize the K-map there. Will this work as well as a case statement or an assignment in conjunctive normal form?</p>
[ { "answer_id": 99795, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 2, "selected": false, "text": "always_comb //or \"always @*\" if you don't have an SV-enabled tool flow\nbegin \n case(a)\n begin\n 4'b0000: b = 1'b0;\n 4'b0001: b = 1'b1;\n ...\n 4'b1111: b = 1'b0;\n //If you don't specify a \"default\" clause, your synthesis tool\n //Should scream at you if you didn't specify all cases,\n //Which is a good thing (tm)\n endcase //a\nend //always\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4454/" ]
42,721
<p>For some reason, I can't seem to get CruiseControl.net to checkout code to anywhere but the starteam working folder for a specificed view.</p> <p>I've tried both overrideViewWorkingDir and overrideFolderWorkingDir, and neither seem to work.</p> <p>Has anyone been able to do this?</p>
[ { "answer_id": 61163, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 0, "selected": false, "text": "<sourcecontrol type=\"starteam\">\n <executable>C:\\Program Files\\starbase\\StarTeam 5.4\\stcmd.exe</executable>\n <project>ProjectName/ViewName</project>\n <username>UserName</username>\n <password>Password</password>\n <host>127.0.0.1</host>\n <port>49201</port>\n <autoGetSource>true</autoGetSource>\n <overrideViewWorkingDir>C:\\temp\\ProjectName</overrideViewWorkingDir>\n</sourcecontrol>\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
42,762
<p>Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:</p> <pre><code>#define PRINT(x, format, ...) \ if ( x ) { \ if ( debug_fd != NULL ) { \ fprintf(debug_fd, format, ##__VA_ARGS__); \ } \ else { \ fprintf(stdout, format, ##__VA_ARGS__); \ } \ } </code></pre> <p>It seems as though the '\' causes the newlines to be ignored. Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up. As if the second one is absorbed. Am I missing something?</p>
[ { "answer_id": 42764, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 2, "selected": false, "text": "#define PRINT(x, format, ...) \\\nif ( x ) { \\\n if ( debug_fd != NULL ) { \\\n fprintf(debug_fd, format, ##VA_ARGS); \\\n} \\\nelse { \\\n fprintf(stdout, format, ##VA_ARGS); \\\n} \\\n}\n" }, { "answer_id": 42767, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "#define PRINT(x, format, ...)\nif ( x ) \n{\n if ( debug_fd != NULL ) \n { \n fprintf(debug_fd, format, ##VA_ARGS); \n } \n else \n { \n fprintf(stdout, format, ##VA_ARGS); \n } \n}\n" }, { "answer_id": 42776, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": true, "text": "#define PRINT(x, format, ...)\nif ( x ) \n{\n if ( debug_fd != NULL ) \n { \n fprintf(debug_fd, format, ##VA_ARGS); \n } \n else \n { \n fprintf(stdout, format, ##VA_ARGS); \n } \n}" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3663/" ]
42,763
<p>Does anyone know how many options a drop down list can have? Is it unlimited? How many before performance degrades?</p>
[ { "answer_id": 22330536, "author": "Katesclau", "author_id": 1014667, "author_profile": "https://Stackoverflow.com/users/1014667", "pm_score": 4, "selected": false, "text": "for (var i=0; i<10000; i++) {\n var name = \"Option \"+i;\n var sel = document.getElementById(\"list\");\n sel.options[sel.options.length] = new Option(name,i);\n}" }, { "answer_id": 24842757, "author": "Ben", "author_id": 3513171, "author_profile": "https://Stackoverflow.com/users/3513171", "pm_score": 0, "selected": false, "text": "document.write" }, { "answer_id": 33441179, "author": "Kevin London", "author_id": 1021177, "author_profile": "https://Stackoverflow.com/users/1021177", "pm_score": 3, "selected": false, "text": "select" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415/" ]
42,774
<p>I'm using <kbd>Ctrl</kbd>+<kbd>Left</kbd> / <kbd>Ctrl</kbd>+<kbd>Right</kbd> in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".</p>
[ { "answer_id": 42807, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 3, "selected": true, "text": "(function() {\n\nvar myActiveElement;\ndocument.onkeypress = function(event) {\n if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT')\n // do your magic\n};\nif (!document.activeElement) {\n var elements = document.getElementsByTagName('input');\n for(var i=0; i<elements.length; i++) {\n elements[i].addEventListener('focus',function() {\n myActiveElement = this;\n },false);\n elements[i].addEventListener('blur',function() {\n myActiveElement = null;\n },false);\n }\n}\n\n})();\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
42,778
<p>Is <a href="http://cpan.uwinnipeg.ca/dist/DBI" rel="noreferrer">CPAN DBI</a> the best database interface to use in Perl for general database use? Are there some better options?</p>
[ { "answer_id": 72471, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 3, "selected": false, "text": "DBI" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
42,793
<p>What techniques do you know\use to create user-friendly GUI ? </p> <p>I can name following techniques that I find especially useful: </p> <ul> <li>Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)</li> <li>Absence of "Save" button<br> MS OneNote as an example.<br> IM clients can save conversation history automatically</li> <li>Integrated search<br> Search not only through help files but rather make UI elements searchable.<br> Vista made a good step toward such GUI.<br> <a href="http://www.istartedsomething.com/20070124/scout-office-2007/" rel="nofollow noreferrer">Scout</a> addin Microsoft Office was a really great idea.</li> <li>Context oriented UI (Ribbon bar in MS Office 2007)</li> </ul> <p>Do you implement something like listed techniques in your software?</p> <p><strong>Edit:</strong><br> As <a href="https://stackoverflow.com/questions/42793/gui-design-techinques-to-enhance-user-experience#42843">Ryan P</a> mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.</p>
[ { "answer_id": 42891, "author": "wusher", "author_id": 1632, "author_profile": "https://Stackoverflow.com/users/1632", "pm_score": 5, "selected": false, "text": " Would you like to save? \n Yes No\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
42,797
<p>I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines.</p> <p>A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature.</p> <p>UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal.</p> <p>The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files.</p>
[ { "answer_id": 43186, "author": "DrFloyd5", "author_id": 1736623, "author_profile": "https://Stackoverflow.com/users/1736623", "pm_score": 2, "selected": false, "text": "robocopy.exe\nfor /?\n" }, { "answer_id": 380222, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 0, "selected": false, "text": "\\\\tsclient\\S\\MyWebsite" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/729/" ]
42,814
<p>How can I get the MAC Address using only the compact framework?</p>
[ { "answer_id": 42824, "author": "Greg Roberts", "author_id": 4269, "author_profile": "https://Stackoverflow.com/users/4269", "pm_score": -1, "selected": false, "text": "Dim mc As System.Management.ManagementClass\nDim mo As ManagementObject\nmc = New ManagementClass(\"Win32_NetworkAdapterConfiguration\")\nDim moc As ManagementObjectCollection = mc.GetInstances()\nFor Each mo In moc\n If mo.Item(\"IPEnabled\") = True Then\n ListBox1.Items.Add(\"MAC address \" & mo.Item(\"MacAddress\").ToString())\n End If\nNext\n" }, { "answer_id": 47574, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": " [DllImport (\"iphlpapi.dll\", SetLastError=true)]\n public static extern int GetAdaptersInfo( byte[] ip, ref int size );\n" }, { "answer_id": 424238, "author": "castle1971", "author_id": 36728, "author_profile": "https://Stackoverflow.com/users/36728", "pm_score": 0, "selected": false, "text": "LOCAL_MACHINE\\Comm\\PCI\\***\\Parms\\MacAddress" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4463/" ]
42,828
<p>I will elaborate somewhat. Jsf is kind-of extremely painful for working with from designer's perspective, somewhat in the range of trying to draw a picture while having hands tied at your back, but it is good for chewing up forms and listing lots of data. So sites we are making in my company are jsf admin pages and jsp user pages. Problem occurs when user pages have some complicated forms and stuff and jsf starts kickin' in. </p> <p>Here is the question: I'm on pure jsp page. I need to access some jsf page that uses session bean. How can I initialize that bean? If I was on jsf page, I could have some commandLink which would prepare data. Only thing I can come up with is having dummy jsf page that will do the work and redirect me to needed jsf page, but that's kind of ugly, and I don't want to end up with 50 dummy pages. I would rather find some mechanism to reinitialize bean that is already in session with some wanted parameters.</p> <p>Edit: some more details. In this specific situation, I have a tests that are either full or filtered. It's a same test with same logic and everything, except if test is filtered, it should eliminate some questions depending on answers. Upon a clicking a link, it should start a requested test in one of the two modes. Links are parts of main menu-tree and are visible on many sibling jsp pages. My task is to have 4 links: testA full, testA filtered, testB full, testB filtered, that all lead on same jsf page and TestFormBean should be reinitialized accordingly.</p> <p>Edit: I've researched facelets a bit, and while it won't help me now, I'll definitely keep that in mind for next project.</p>
[ { "answer_id": 43549, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 2, "selected": false, "text": "<input type=\"text\" jsfc=\"#{SomeBean.property}\" class=\"foo\" />\n" }, { "answer_id": 63883, "author": "Eric DeLabar", "author_id": 7556, "author_profile": "https://Stackoverflow.com/users/7556", "pm_score": 2, "selected": true, "text": "<c:import>" }, { "answer_id": 72213, "author": "Chris Hall", "author_id": 5933, "author_profile": "https://Stackoverflow.com/users/5933", "pm_score": 2, "selected": false, "text": "FacesContext context = FacesContext.getCurrentInstance();\nObject myBean = context.getELContext().getELResolver().getValue(context.getELContext(), null, \"myBeanName\");\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4433/" ]
42,830
<p>I'm using the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow noreferrer">AutoComplete</a> control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox. </p> <p>I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click. </p> <p>Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.</p>
[ { "answer_id": 42858, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 3, "selected": true, "text": "MainSearchBox_SearchTextBox" }, { "answer_id": 44006, "author": "Jason Shoulders", "author_id": 1953, "author_profile": "https://Stackoverflow.com/users/1953", "pm_score": 0, "selected": false, "text": "Public Sub SetFocus(ByVal ctrl As Control)\n Dim sb As New System.Text.StringBuilder\n Dim p As Control\n p = ctrl.Parent\n While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))\n p = p.Parent\n End While\n With sb\n .Append(\"<script language='JavaScript'>\")\n .Append(\"function SetFocus()\")\n .Append(\"{\")\n .Append(\"document.\")\n .Append(p.ClientID)\n .Append(\"['\")\n .Append(ctrl.UniqueID)\n .Append(\"'].focus();\")\n .Append(\"}\")\n .Append(\"window.onload = SetFocus;\")\n .Append(\"\")\n .Append(\"</script\")\n .Append(\">\")\n End With\n ctrl.Page.RegisterClientScriptBlock(\"SetFocus\", sb.ToString())\nEnd Sub\n" }, { "answer_id": 1059406, "author": "Kris", "author_id": 1457761, "author_profile": "https://Stackoverflow.com/users/1457761", "pm_score": 0, "selected": false, "text": "function setFocusTimeout(controlID) {\n focusControlID = controlID;\n setTimeout(\"setFocus(focusControlID)\", 100);\n}\n\nfunction setFocus() {\n document.getElementById(focusControlID).focus();\n}\n" }, { "answer_id": 2501610, "author": "Nathan Poorman", "author_id": 300096, "author_profile": "https://Stackoverflow.com/users/300096", "pm_score": 0, "selected": false, "text": "function setFocus(focusControlID) {\n $('#' + focusControlID).blur();\n $('#' + focusControlID).focus();\n}\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2034/" ]
42,863
<p>Of course the best metric would be a happiness of your users.<br> But what metrics do you know for GUI usability measurements?<br> For example, one of the common metrics is a average click count to perform action. What other metrics do you know? </p>
[ { "answer_id": 80040, "author": "rec", "author_id": 14022, "author_profile": "https://Stackoverflow.com/users/14022", "pm_score": 0, "selected": false, "text": "Q: “What percentage of your interface contains stuff that your customers\n want to see?”\n" } ]
2008/09/03
[ "https://Stackoverflow.com/questions/42863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ]
42,876
<p>Why does the following code not work as I was expecting?</p> <pre><code>&lt;?php $data = array( array('Area1', null, null), array(null, 'Section1', null), array(null, null, 'Location1'), array('Area2', null, null), array(null, 'Section2', null), array(null, null, 'Location2') ); $root = array(); foreach ($data as $row) { if ($row[0]) { $area = array(); $root[$row[0]] =&amp; $area; } elseif ($row[1]) { $section = array(); $area[$row[1]] =&amp; $section; } elseif ($row[2]) { $section[] = $row[2]; } } print_r($root); </code></pre> <p>Expected result:</p> <pre><code>Array( [Area1] =&gt; Array( [Section1] =&gt; Array( [0] =&gt; Location1 ) ) [Area2] =&gt; Array( [Section2] =&gt; Array( [0] =&gt; Location2 ) ) ) </code></pre> <p>Actual result:</p> <pre><code>Array( [Area1] =&gt; Array( [Section2] =&gt; Array( [0] =&gt; Location2 ) ) [Area2] =&gt; Array( [Section2] =&gt; Array( [0] =&gt; Location2 ) ) ) </code></pre>
[ { "answer_id": 42885, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 3, "selected": true, "text": "$area = array();\n\n$section = array();\n" }, { "answer_id": 42913, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 1, "selected": false, "text": "$root[$row[0]] = array();\n$area =& $root[$row[0]];\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
42,894
<p>Is there any benefit in using a <code>&lt;blockquote&gt;</code> element over a <code>&lt;div&gt;</code>? I was looking at a website's markup to learn CSS and I couldn't figure out why the <code>&lt;blockquote&gt;</code> was being used.</p> <p>EDIT: Yeah sorry I didn't clarify, it was used to hold the <code>&lt;div&gt;</code> tag with username as 'text' and an <code>input</code> tag. There was clearly no quote.</p>
[ { "answer_id": 42896, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 3, "selected": false, "text": "blockquote" }, { "answer_id": 42898, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<blockquote>" }, { "answer_id": 42922, "author": "Slartibartfast", "author_id": 4433, "author_profile": "https://Stackoverflow.com/users/4433", "pm_score": 0, "selected": false, "text": "<blockquote>" }, { "answer_id": 42979, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 4, "selected": true, "text": "<h1>" }, { "answer_id": 43847, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 0, "selected": false, "text": "blockquote" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438/" ]
42,934
<p>It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.</p> <p>What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?</p>
[ { "answer_id": 42955, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 7, "selected": false, "text": "qsort [] = []\nqsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)\n" }, { "answer_id": 42978, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": false, "text": "generics" }, { "answer_id": 43209, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 4, "selected": false, "text": "qsort [] = []\nqsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)\n" }, { "answer_id": 751953, "author": "majkinetor", "author_id": 82660, "author_profile": "https://Stackoverflow.com/users/82660", "pm_score": 3, "selected": false, "text": "print( loadstring( \"return \" .. io.read() )() )\n" }, { "answer_id": 1229675, "author": "RHSeeger", "author_id": 26816, "author_profile": "https://Stackoverflow.com/users/26816", "pm_score": 3, "selected": false, "text": " lindex $mylist end-2\n" }, { "answer_id": 1628579, "author": "RCIX", "author_id": 117069, "author_profile": "https://Stackoverflow.com/users/117069", "pm_score": 1, "selected": false, "text": "using System;\nclass MyProgram\n{\n public static void Main(string[] args)\n {\n foreach (string s in args)\n {\n Console.WriteLine(s);\n }\n }\n}\n" }, { "answer_id": 1629064, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 0, "selected": false, "text": "auto" }, { "answer_id": 2211451, "author": "Bob", "author_id": 259579, "author_profile": "https://Stackoverflow.com/users/259579", "pm_score": 1, "selected": false, "text": "var Person = {};" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
42,950
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
[ { "answer_id": 42997, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 7, "selected": false, "text": ">>> import datetime\n>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)\ndatetime.date(2000, 1, 31)\n" }, { "answer_id": 43088, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 6, "selected": false, "text": "def last_day_of_month(date):\n if date.month == 12:\n return date.replace(day=31)\n return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)\n\n>>> last_day_of_month(datetime.date(2002, 1, 17))\ndatetime.date(2002, 1, 31)\n>>> last_day_of_month(datetime.date(2002, 12, 9))\ndatetime.date(2002, 12, 31)\n>>> last_day_of_month(datetime.date(2008, 2, 14))\ndatetime.date(2008, 2, 29)\n" }, { "answer_id": 43663, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 11, "selected": true, "text": "calendar.monthrange" }, { "answer_id": 356535, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "from datetime import datetime\n\ndef last_day_of_month(year, month):\n \"\"\" Work out the last day of the month \"\"\"\n last_days = [31, 30, 29, 28, 27]\n for i in last_days:\n try:\n end = datetime(year, month, i)\n except ValueError:\n continue\n else:\n return end.date()\n return None\n" }, { "answer_id": 13386470, "author": "ely", "author_id": 567620, "author_profile": "https://Stackoverflow.com/users/567620", "pm_score": 2, "selected": false, "text": "calendar.monthcalendar" }, { "answer_id": 13565185, "author": "augustomen", "author_id": 317971, "author_profile": "https://Stackoverflow.com/users/317971", "pm_score": 8, "selected": false, "text": "calendar" }, { "answer_id": 14994380, "author": "Vince Spicer", "author_id": 272313, "author_profile": "https://Stackoverflow.com/users/272313", "pm_score": 7, "selected": false, "text": "dateutil.relativedelta" }, { "answer_id": 17135571, "author": "Анатолий Панин", "author_id": 1220682, "author_profile": "https://Stackoverflow.com/users/1220682", "pm_score": 3, "selected": false, "text": "import datetime\n\nnow = datetime.datetime.now()\nstart_month = datetime.datetime(now.year, now.month, 1)\ndate_on_next_month = start_month + datetime.timedelta(35)\nstart_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)\nlast_day_month = start_next_month - datetime.timedelta(1)\n" }, { "answer_id": 23383345, "author": "mathause", "author_id": 3010700, "author_profile": "https://Stackoverflow.com/users/3010700", "pm_score": 2, "selected": false, "text": "def eomday(year, month):\n \"\"\"returns the number of days in a given month\"\"\"\n days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n d = days_per_month[month - 1]\n if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):\n d = 29\n return d\n" }, { "answer_id": 23447523, "author": "Collin Anderson", "author_id": 131881, "author_profile": "https://Stackoverflow.com/users/131881", "pm_score": 4, "selected": false, "text": "from datetime import timedelta\n(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)\n" }, { "answer_id": 24929705, "author": "KravAn", "author_id": 3153739, "author_profile": "https://Stackoverflow.com/users/3153739", "pm_score": 2, "selected": false, "text": "selected_date = date(some_year, some_month, some_day)\n\nif selected_date.month == 12: # December\n last_day_selected_month = date(selected_date.year, selected_date.month, 31)\nelse:\n last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)\n" }, { "answer_id": 27667421, "author": "Satish Reddy", "author_id": 4380501, "author_profile": "https://Stackoverflow.com/users/4380501", "pm_score": 5, "selected": false, "text": "dateutil.relativedelta" }, { "answer_id": 28886669, "author": "DoOrDoNot", "author_id": 2330429, "author_profile": "https://Stackoverflow.com/users/2330429", "pm_score": 4, "selected": false, "text": ">>> import datetime\n>>> import calendar\n>>> date = datetime.datetime.now()\n\n>>> print date\n2015-03-06 01:25:14.939574\n\n>>> print date.replace(day = 1)\n2015-03-01 01:25:14.939574\n\n>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])\n2015-03-31 01:25:14.939574\n" }, { "answer_id": 31618852, "author": "Steve Schulist", "author_id": 1913647, "author_profile": "https://Stackoverflow.com/users/1913647", "pm_score": 4, "selected": false, "text": "def isMonthEnd(date):\n return date + pd.offsets.MonthEnd(0) == date\n\nisMonthEnd(datetime(1999, 12, 31))\nTrue\nisMonthEnd(pd.Timestamp('1999-12-31'))\nTrue\nisMonthEnd(pd.Timestamp(1965, 1, 10))\nFalse\n" }, { "answer_id": 37246666, "author": "Audstanley", "author_id": 4447347, "author_profile": "https://Stackoverflow.com/users/4447347", "pm_score": 2, "selected": false, "text": "import calendar\nfrom time import gmtime, strftime\ncalendar.monthrange(int(strftime(\"%Y\", gmtime())), int(strftime(\"%m\", gmtime())))[1]\n" }, { "answer_id": 39141916, "author": "MikA", "author_id": 1099499, "author_profile": "https://Stackoverflow.com/users/1099499", "pm_score": 2, "selected": false, "text": "import datetime\nimport calendar\n\ndate=datetime.datetime.now()\nmonth_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)\n" }, { "answer_id": 39223365, "author": "Siddharth K", "author_id": 6667427, "author_profile": "https://Stackoverflow.com/users/6667427", "pm_score": 4, "selected": false, "text": "from datetime import date, timedelta\nimport calendar\nlast_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])\n" }, { "answer_id": 39288092, "author": "Vipul Vishnu av", "author_id": 3520792, "author_profile": "https://Stackoverflow.com/users/3520792", "pm_score": 2, "selected": false, "text": "import datetime\n\ndef end_date_of_a_month(date):\n\n\n start_date_of_this_month = date.replace(day=1)\n\n month = start_date_of_this_month.month\n year = start_date_of_this_month.year\n if month == 12:\n month = 1\n year += 1\n else:\n month += 1\n next_month_start_date = start_date_of_this_month.replace(month=month, year=year)\n\n this_month_end_date = next_month_start_date - datetime.timedelta(days=1)\n return this_month_end_date\n" }, { "answer_id": 40827688, "author": "Blake", "author_id": 137488, "author_profile": "https://Stackoverflow.com/users/137488", "pm_score": 4, "selected": false, "text": "import arrow\narrow.utcnow().ceil('month').date()\n" }, { "answer_id": 47358096, "author": "Vishal", "author_id": 4001154, "author_profile": "https://Stackoverflow.com/users/4001154", "pm_score": 2, "selected": false, "text": "import datetime as dt\nfrom dateutil.relativedelta import relativedelta\n\nthisDate = dt.datetime(2017, 11, 17)\n\nlast_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)\nprint last_day_of_the_month\n" }, { "answer_id": 49238615, "author": "JLord", "author_id": 7685142, "author_profile": "https://Stackoverflow.com/users/7685142", "pm_score": 0, "selected": false, "text": "def last_day_of_month(any_days):\n res = []\n for any_day in any_days:\n nday = any_day.days_in_month -any_day.day\n res.append(any_day + timedelta(days=nday))\n return res\n" }, { "answer_id": 49712748, "author": "Johannes Blaschke", "author_id": 9550561, "author_profile": "https://Stackoverflow.com/users/9550561", "pm_score": 0, "selected": false, "text": "next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)\nmonth_end = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)\n" }, { "answer_id": 53293564, "author": "Pulkit Bansal", "author_id": 6644783, "author_profile": "https://Stackoverflow.com/users/6644783", "pm_score": 0, "selected": false, "text": "import datetime\n\ndef DateTime( d ):\n return datetime.datetime.strptime( d, '%Y-%m-%d').date()\n\ndef RelativeDate( start, num_days ):\n d = DateTime( start )\n return str( d + datetime.timedelta( days = num_days ) )\n\ndef get_first_day_of_month( dt ):\n return dt[:-2] + '01'\n\ndef get_last_day_of_month( dt ):\n fd = get_first_day_of_month( dt )\n fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )\n return RelativeDate( fd_next_month, -1 )\n" }, { "answer_id": 53548552, "author": "kevswanberg", "author_id": 2599940, "author_profile": "https://Stackoverflow.com/users/2599940", "pm_score": 3, "selected": false, "text": "datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)\n" }, { "answer_id": 53725380, "author": "Jake Boomgaarden", "author_id": 5175802, "author_profile": "https://Stackoverflow.com/users/5175802", "pm_score": 3, "selected": false, "text": "\nmonth_end = <your datetime value within the month> + relativedelta(day=31)\n" }, { "answer_id": 54724461, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "calendar.monthlen(year, month)" }, { "answer_id": 56706717, "author": "Toby Petty", "author_id": 6286540, "author_profile": "https://Stackoverflow.com/users/6286540", "pm_score": 3, "selected": false, "text": "import datetime\n\ndef get_month_end(dt):\n first_of_month = datetime.datetime(dt.year, dt.month, 1)\n next_month_date = first_of_month + datetime.timedelta(days=32)\n new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)\n return new_dt - datetime.timedelta(days=1)\n" }, { "answer_id": 56738379, "author": "Eugene Yarmash", "author_id": 244297, "author_profile": "https://Stackoverflow.com/users/244297", "pm_score": 2, "selected": false, "text": "datetime" }, { "answer_id": 59815795, "author": "jp0d", "author_id": 5645055, "author_profile": "https://Stackoverflow.com/users/5645055", "pm_score": 2, "selected": false, "text": "def last_day_month(year, month):\n leap_year_flag = 0\n end_dates = {\n 1: 31,\n 2: 28,\n 3: 31,\n 4: 30,\n 5: 31,\n 6: 30,\n 7: 31,\n 8: 31,\n 9: 30,\n 10: 31,\n 11: 30,\n 12: 31\n }\n\n # Checking for regular leap year \n if year % 4 == 0:\n leap_year_flag = 1\n else:\n leap_year_flag = 0\n\n # Checking for century leap year \n if year % 100 == 0:\n if year % 400 == 0:\n leap_year_flag = 1\n else:\n leap_year_flag = 0\n else:\n pass\n\n # return end date of the year-month\n if leap_year_flag == 1 and month == 2:\n return 29\n elif leap_year_flag == 1 and month != 2:\n return end_dates[month]\n else:\n return end_dates[month]\n" }, { "answer_id": 62875046, "author": "Ayush Lal Shrestha", "author_id": 6370679, "author_profile": "https://Stackoverflow.com/users/6370679", "pm_score": 3, "selected": false, "text": "from datetime import datetime\nimport calendar\ndays_in_month = calendar.monthrange(2020, 12)[1]\nend_dt = datetime(2020, 12, days_in_month)\n" }, { "answer_id": 64407503, "author": "BIOHAZARD", "author_id": 1503846, "author_profile": "https://Stackoverflow.com/users/1503846", "pm_score": 2, "selected": false, "text": "import datetime\nnow = datetime.datetime.now()\ndatetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)\n" }, { "answer_id": 64560243, "author": "Rakesh Chintha", "author_id": 2340382, "author_profile": "https://Stackoverflow.com/users/2340382", "pm_score": 0, "selected": false, "text": "import datetime\nref_date = datetime.today() # or what ever specified date\n\nend_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)\n" }, { "answer_id": 66756563, "author": "Piero", "author_id": 11002328, "author_profile": "https://Stackoverflow.com/users/11002328", "pm_score": 3, "selected": false, "text": " from datetime import datetime\n import pandas as pd\n\n firstday_month = datetime(year, month, 1)\n lastday_month = firstday_month + pd.offsets.MonthEnd(1)\n" }, { "answer_id": 69017505, "author": "José Florencio de Queiroz", "author_id": 3372135, "author_profile": "https://Stackoverflow.com/users/3372135", "pm_score": 3, "selected": false, "text": "from dateutil.relativedelta import relativedelta\n\ndef last_day_of_month(date):\n return date.replace(day=1) + relativedelta(months=1) - relativedelta(days=1)\n" }, { "answer_id": 70769732, "author": "RCN", "author_id": 16607636, "author_profile": "https://Stackoverflow.com/users/16607636", "pm_score": 0, "selected": false, "text": "df['daysinmonths'] = df['your_date_col'].apply(lambda t: pd.Period(t, freq='S').days_in_month)\n" }, { "answer_id": 71060677, "author": "J.Wei", "author_id": 6645051, "author_profile": "https://Stackoverflow.com/users/6645051", "pm_score": 3, "selected": false, "text": "dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)\n" }, { "answer_id": 71853719, "author": "Denis Savenko", "author_id": 5319874, "author_profile": "https://Stackoverflow.com/users/5319874", "pm_score": 0, "selected": false, "text": "import pytz\nfrom datetime import datetime, timedelta\n\n# get now time with timezone (optional)\nnow = datetime.now(pytz.UTC)\n\n# get first day on this month, get last day on prev month and after get first day on prev month with min time\nfist_day_with_time = datetime.combine((now.replace(day=1) - timedelta(days=1)).replace(day=1), datetime.min.time())\n" }, { "answer_id": 72643539, "author": "DanielHefti", "author_id": 12702595, "author_profile": "https://Stackoverflow.com/users/12702595", "pm_score": 0, "selected": false, "text": "from datetime import datetime, timedelta\n\nif (datetime.today()+timedelta(days=1)).day == 1:\n print(\"today is the last day of the month\")\nelse:\n print(\"today isn't the last day of the month\")\n" }, { "answer_id": 73032438, "author": "xor007", "author_id": 2436995, "author_profile": "https://Stackoverflow.com/users/2436995", "pm_score": 0, "selected": false, "text": "from datetime import timedelta as td\nfrom datetime import datetime as dt\ntoday = dt.now()\na_day_next_month = dt(today.year, today.month, 27) + td(days=5)\nfirst_day_next_month = dt(a_day_next_month.year, a_day_next_month.month, 1)\nlast_day_this_month = first_day_next_month - td(days=1)\n" }, { "answer_id": 73537730, "author": "Mr.TK", "author_id": 2002855, "author_profile": "https://Stackoverflow.com/users/2002855", "pm_score": 0, "selected": false, "text": "day=31" }, { "answer_id": 74011365, "author": "Amit Pathak", "author_id": 11608962, "author_profile": "https://Stackoverflow.com/users/11608962", "pm_score": 2, "selected": false, "text": "def get_last_day_of_month(mon: int, year: int) -> str:\n '''\n Returns last day of the month.\n '''\n\n ### Day 28 falls in every month\n res = datetime(month=mon, year=year, day=28)\n ### Go to next month\n res = res + timedelta(days=4)\n ### Subtract one day from the start of the next month\n res = datetime.strptime(res.strftime('%Y-%m-01'), '%Y-%m-%d') - timedelta(days=1)\n\n return res.strftime('%Y-%m-%d')\n" }, { "answer_id": 74060594, "author": "Zach Bateman", "author_id": 15312063, "author_profile": "https://Stackoverflow.com/users/15312063", "pm_score": 0, "selected": false, "text": "from datetime import timedelta\n\ndef last_day_of_month(date):\n if date.month != (date + timedelta(days=1)).month:\n return date\n else:\n return last_day_of_month(date + timedelta(days=1))\n" }, { "answer_id": 74284092, "author": "ramwin", "author_id": 3601654, "author_profile": "https://Stackoverflow.com/users/3601654", "pm_score": 0, "selected": false, "text": "$ pip install datetime-month\n$ python\n>>> from month import XMonth\n>>> Xmonth(2022, 11).last_date()\ndatetime.date(2022, 11, 30)\n" }, { "answer_id": 74355441, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 0, "selected": false, "text": "Timestamp.days_in_month" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
42,966
<p>What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.</p>
[ { "answer_id": 45067, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": true, "text": "namespace AutoComplete\n{\n public partial class Main : Form\n {\n //so you don't have to address \"txtMain.AutoCompleteCustomSource\" every time\n AutoCompleteStringCollection acsc;\n public Main()\n {\n InitializeComponent();\n\n //Set to use a Custom source\n txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;\n //Set to show drop down *and* append current suggestion to end\n txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\n //Init string collection.\n acsc = new AutoCompleteStringCollection();\n //Set txtMain's AutoComplete Source to acsc\n txtMain.AutoCompleteCustomSource = acsc;\n }\n\n private void txtMain_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.Enter)\n {\n //Only keep 10 AutoComplete strings\n if (acsc.Count < 10)\n {\n //Add to collection\n acsc.Add(txtMain.Text);\n }\n else\n {\n //remove oldest\n acsc.RemoveAt(0); \n //Add to collection\n acsc.Add(txtMain.Text);\n }\n }\n }\n\n private void Main_FormClosed(object sender, FormClosedEventArgs e)\n {\n //open stream to AutoComplete save file\n StreamWriter sw = new StreamWriter(\"AutoComplete.acs\");\n\n //Write AutoCompleteStringCollection to stream\n foreach (string s in acsc)\n sw.WriteLine(s);\n\n //Flush to file\n sw.Flush();\n\n //Clean up\n sw.Close();\n sw.Dispose();\n }\n\n private void Main_Load(object sender, EventArgs e)\n {\n //open stream to AutoComplete save file\n StreamReader sr = new StreamReader(\"AutoComplete.acs\");\n\n //initial read\n string line = sr.ReadLine();\n //loop until end\n while (line != null)\n {\n //add to AutoCompleteStringCollection\n acsc.Add(line);\n //read again\n line = sr.ReadLine();\n }\n\n //Clean up\n sr.Close();\n sr.Dispose();\n }\n }\n}\n" }, { "answer_id": 1441659, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": "[assembly: AssemblyProduct(\"...\")]" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066/" ]
42,980
<p>Does anyone know how to setup <a href="http://www.selenic.com/mercurial/wiki/index.cgi/Mercurial" rel="noreferrer">Mercurial</a> to use <a href="http://www.perforce.com/perforce/products/merge.html" rel="noreferrer">p4merge</a> as the merge/diff tool on OS X 10.5?</p>
[ { "answer_id": 54261, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#!/usr/bin/python\nimport sys\nimport os\n\nos.system('/Applications/p4merge.app/Contents/MacOS/p4merge \"%s\" \"%s\"' % (sys.argv[2], sys.argv[5]))\n" }, { "answer_id": 170637, "author": "Ry4an Brase", "author_id": 8992, "author_profile": "https://Stackoverflow.com/users/8992", "pm_score": 5, "selected": false, "text": "~/.hgrc" }, { "answer_id": 399092, "author": "Ivan", "author_id": 50135, "author_profile": "https://Stackoverflow.com/users/50135", "pm_score": 4, "selected": false, "text": "p4.args=$base $local $other $output\n" }, { "answer_id": 2311268, "author": "gnz", "author_id": 269335, "author_profile": "https://Stackoverflow.com/users/269335", "pm_score": 2, "selected": false, "text": "~/.hgrc/" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3547/" ]
42,984
<p>I'm behind a firewall at work at the moment and I was testing something that I had deployed to my website, and the work proxy seems to be blocking it somewhat.</p> <p>Basically I am getting a message of:</p> <blockquote> <p>Operation is not valid due to the current state of the object</p> </blockquote> <p>I've got it down to my proxy interferring, but I can't see any advanced settings or anything I can set up to go through my proxy to get to my service.</p> <p>I did a quick google for it, but no joy.</p> <p>Anyone found a quick way to get around it?</p>
[ { "answer_id": 314622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<system.net> \n <defaultProxy useDefaultCredentials=\"false\">\n <proxy usesystemdefault=\"true\" proxyaddress=\"10.0.0.1\" port=\"80\" bypassonlocal=\"true\" />\n </defaultProxy>\n</system.net>\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ]
42,990
<p>I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.</p> <p>Example:</p> <pre><code>// Updated to be correct, thanks @Apocalisp ^foo.*(?&lt;!bar)$ </code></pre> <p>Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. </p> <p>I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. </p> <p>Thanks to @Kibbee for verifying that this works in C# as well. </p>
[ { "answer_id": 43010, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 1, "selected": false, "text": "foo.*(?!bar) // not correct\n" }, { "answer_id": 43016, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "\"^first_string(?!.?second_string)\\\\z\"\n" }, { "answer_id": 43017, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 4, "selected": true, "text": "foo.*(?<!bar)\n" }, { "answer_id": 43030, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "import java.util.regex.Pattern;\npublic class Test {\n public static void main(String[] args) {\n Pattern p = Pattern.compile(\"^foo.*(?<!bar)$\");\n System.out.println(p.matcher(\"foobar\").matches());\n System.out.println(p.matcher(\"fooBLAHbar\").matches());\n System.out.println(p.matcher(\"1foo\").matches());\n System.out.println(p.matcher(\"fooBLAH-ar\").matches());\n System.out.println(p.matcher(\"foo\").matches());\n System.out.println(p.matcher(\"foobaz\").matches());\n }\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/42990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535/" ]
43,021
<p>Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?</p> <p>For instance, I currently do something like this depending on the circumstances:</p> <pre><code>int i = 0; foreach (Object o in collection) { // ... i++; } </code></pre>
[ { "answer_id": 43029, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 10, "selected": true, "text": "foreach" }, { "answer_id": 43035, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 7, "selected": false, "text": "public static class ForEachExtensions\n{\n public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)\n {\n int idx = 0;\n foreach (T item in enumerable)\n handler(item, idx++);\n }\n}\n\npublic class Example\n{\n public static void Main()\n {\n string[] values = new[] { \"foo\", \"bar\", \"baz\" };\n\n values.ForEachWithIndex((item, idx) => Console.WriteLine(\"{0}: {1}\", idx, item));\n }\n}\n" }, { "answer_id": 43103, "author": "crucible", "author_id": 3717, "author_profile": "https://Stackoverflow.com/users/3717", "pm_score": 4, "selected": false, "text": "IList<Object> collection = new List<Object> { \n new Object(), \n new Object(), \n new Object(), \n };\n\nforeach (Object o in collection)\n{\n Console.WriteLine(collection.IndexOf(o));\n}\n\nConsole.ReadLine();\n" }, { "answer_id": 77542, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 6, "selected": false, "text": "int" }, { "answer_id": 1046748, "author": "mike nelson", "author_id": 23616, "author_profile": "https://Stackoverflow.com/users/23616", "pm_score": 7, "selected": false, "text": "for" }, { "answer_id": 1984049, "author": "mat3", "author_id": 173472, "author_profile": "https://Stackoverflow.com/users/173472", "pm_score": 4, "selected": false, "text": "int index=0;\nforeach (var item in enumerable)\n{\n blah(item, index); // some code that depends on the index\n index++;\n}\n" }, { "answer_id": 1985112, "author": "Sachin", "author_id": 149656, "author_profile": "https://Stackoverflow.com/users/149656", "pm_score": 3, "selected": false, "text": "int index;\nforeach (Object o in collection)\n{\n index = collection.indexOf(o);\n}\n" }, { "answer_id": 3293486, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 5, "selected": false, "text": "foreach (var item in ForEachHelper.WithIndex(collection))\n{\n Console.Write(\"Index=\" + item.Index);\n Console.Write(\";Value= \" + item.Value);\n Console.Write(\";IsLast=\" + item.IsLast);\n Console.WriteLine();\n}\n" }, { "answer_id": 3535307, "author": "user426810", "author_id": 426810, "author_profile": "https://Stackoverflow.com/users/426810", "pm_score": 3, "selected": false, "text": "continue" }, { "answer_id": 3535362, "author": "Ian Henry", "author_id": 223274, "author_profile": "https://Stackoverflow.com/users/223274", "pm_score": 3, "selected": false, "text": "obj.Value" }, { "answer_id": 3691283, "author": "ulrichb", "author_id": 50890, "author_profile": "https://Stackoverflow.com/users/50890", "pm_score": 2, "selected": false, "text": "WithIndex()" }, { "answer_id": 4055002, "author": "Matt Towers", "author_id": 491656, "author_profile": "https://Stackoverflow.com/users/491656", "pm_score": 1, "selected": false, "text": "IEnumerator enumerator = myEnumerable.GetEnumerator();\nstring myDelimitedString;\nstring current = null;\n\nif( enumerator.MoveNext() )\n current = (string)enumerator.Current;\n\nwhile( null != current)\n{\n current = (string)enumerator.Current; }\n\n myDelimitedString += current;\n\n if( enumerator.MoveNext() )\n myDelimitedString += DELIMITER;\n else\n break;\n}\n" }, { "answer_id": 5405140, "author": "nicodemus13", "author_id": 26463, "author_profile": "https://Stackoverflow.com/users/26463", "pm_score": 2, "selected": false, "text": "var destinationList = new List<someObject>();\nforeach (var item in itemList)\n{\n var stringArray = item.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (stringArray.Length != 2)\n {\n //use the destinationList Count property to give us the index into the stringArray list\n throw new Exception(\"Item at row \" + (destinationList.Count + 1) + \" has a problem.\");\n }\n else\n {\n destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]});\n }\n}\n" }, { "answer_id": 5709974, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "public class IndexedItem<TModel> {\n public IndexedItem(int index, TModel item) {\n Index = index;\n Item = item;\n }\n\n public int Index { get; private set; }\n public TModel Item { get; private set; }\n}\n" }, { "answer_id": 7421615, "author": "Kasey Speakman", "author_id": 209133, "author_profile": "https://Stackoverflow.com/users/209133", "pm_score": 2, "selected": false, "text": "string[] names = { \"one\", \"two\", \"three\" };\nvar oddOrEvenByName = names\n .Select((name, index) => new KeyValuePair<string, int>(name, index % 2))\n .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);\n" }, { "answer_id": 11437562, "author": "bcahill", "author_id": 474902, "author_profile": "https://Stackoverflow.com/users/474902", "pm_score": 10, "selected": false, "text": "foreach (var item in Model.Select((value, i) => new { i, value }))\n{\n var value = item.value;\n var index = item.i;\n}\n" }, { "answer_id": 15572052, "author": "Bart Calixto", "author_id": 826568, "author_profile": "https://Stackoverflow.com/users/826568", "pm_score": 2, "selected": false, "text": "@foreach (var banner in Model.MainBanners) {\n @Model.MainBanners.IndexOf(banner)\n}\n" }, { "answer_id": 15889868, "author": "mike nelson", "author_id": 23616, "author_profile": "https://Stackoverflow.com/users/23616", "pm_score": 0, "selected": false, "text": "foreach" }, { "answer_id": 19236156, "author": "Gezim", "author_id": 32495, "author_profile": "https://Stackoverflow.com/users/32495", "pm_score": 5, "selected": false, "text": "//var list = new List<int> { 1, 2, 3, 4, 5, 6 }; // Your sample collection\n\nvar listEnumerator = list.GetEnumerator(); // Get enumerator\n\nfor (var i = 0; listEnumerator.MoveNext() == true; i++)\n{\n int currentItem = listEnumerator.Current; // Get current item.\n //Console.WriteLine(\"At index {0}, item is {1}\", i, currentItem); // Do as you wish with i and currentItem\n}\n" }, { "answer_id": 19594773, "author": "Warren LaFrance", "author_id": 1404405, "author_profile": "https://Stackoverflow.com/users/1404405", "pm_score": 2, "selected": false, "text": "var listOfNames = new List<string>(){\"John\",\"Steve\",\"Anna\",\"Chris\"};\n\nvar listCount = listOfNames.Count;\n\nvar NamesWithCommas = string.Empty;\n\nforeach (var element in listOfNames)\n{\n NamesWithCommas += element;\n if(listOfNames.IndexOf(element) != listCount -1)\n {\n NamesWithCommas += \", \";\n }\n}\n\nNamesWithCommas.Dump(); //LINQPad method to write to console.\n" }, { "answer_id": 22016592, "author": "David Bullock", "author_id": 463052, "author_profile": "https://Stackoverflow.com/users/463052", "pm_score": 6, "selected": false, "text": "for" }, { "answer_id": 27785300, "author": "ssaeed", "author_id": 3256077, "author_profile": "https://Stackoverflow.com/users/3256077", "pm_score": 2, "selected": false, "text": "foreach (Object o in collection)\n{\n // ...\n @collection.IndexOf(o)\n}\n" }, { "answer_id": 33508983, "author": "BenKoshy", "author_id": 4880924, "author_profile": "https://Stackoverflow.com/users/4880924", "pm_score": 0, "selected": false, "text": "// Untested\nfor (int i = 0; i < collection.Count; i++)\n{\n Console.WriteLine(\"My index is \" + i);\n}\n" }, { "answer_id": 37471479, "author": "Parsa", "author_id": 2116114, "author_profile": "https://Stackoverflow.com/users/2116114", "pm_score": 4, "selected": false, "text": "for (int i = 0 ; i < myList.Count ; i++)\n{\n // Do something...\n}\n" }, { "answer_id": 39105631, "author": "Satisfied", "author_id": 6748675, "author_profile": "https://Stackoverflow.com/users/6748675", "pm_score": 3, "selected": false, "text": "var s = \"ABCDEFG\";\nforeach (var item in s.GetEnumeratorWithIndex())\n{\n System.Console.WriteLine(\"Character: {0}, Position: {1}\", item.Value, item.Index);\n}\n" }, { "answer_id": 39997157, "author": "user1414213562", "author_id": 6659843, "author_profile": "https://Stackoverflow.com/users/6659843", "pm_score": 9, "selected": false, "text": "foreach" }, { "answer_id": 40540985, "author": "Kind Contributor", "author_id": 887092, "author_profile": "https://Stackoverflow.com/users/887092", "pm_score": 4, "selected": false, "text": "foreach (var item in collection with var index)\n{\n Console.WriteLine(\"Iteration {0} has value {1}\", index, item);\n}\n\n//or, building on @user1414213562's answer\nforeach (var (item, index) in collection)\n{\n Console.WriteLine(\"Iteration {0} has value {1}\", index, item);\n}\n" }, { "answer_id": 45239493, "author": "Paul Mitchell", "author_id": 38966, "author_profile": "https://Stackoverflow.com/users/38966", "pm_score": 4, "selected": false, "text": "static class Extensions\n{\n public static IEnumerable<(int, T)> Enumerate<T>(\n this IEnumerable<T> input,\n int start = 0\n )\n {\n int i = start;\n foreach (var t in input)\n {\n yield return (i++, t);\n }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var s = new string[]\n {\n \"Alpha\",\n \"Bravo\",\n \"Charlie\",\n \"Delta\"\n };\n\n foreach (var (i, t) in s.Enumerate())\n {\n Console.WriteLine($\"{i}: {t}\");\n }\n }\n}\n" }, { "answer_id": 46145503, "author": "Pavel", "author_id": 3553138, "author_profile": "https://Stackoverflow.com/users/3553138", "pm_score": 6, "selected": false, "text": "System.ValueTuple" }, { "answer_id": 50456510, "author": "conterio", "author_id": 4525819, "author_profile": "https://Stackoverflow.com/users/4525819", "pm_score": 5, "selected": false, "text": "int i = -1;\nforeach (var item in Collection)\n{\n ++i;\n item.index = i;\n}\n" }, { "answer_id": 53789000, "author": "Ahmed Fwela", "author_id": 4009642, "author_profile": "https://Stackoverflow.com/users/4009642", "pm_score": -1, "selected": false, "text": "IEnumerable" }, { "answer_id": 56218652, "author": "Marcos ruiz", "author_id": 11475011, "author_profile": "https://Stackoverflow.com/users/11475011", "pm_score": 2, "selected": false, "text": "ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element =>\n{\n // element.Index\n // element.Value\n});\n" }, { "answer_id": 62951790, "author": "usman tahir", "author_id": 5717287, "author_profile": "https://Stackoverflow.com/users/5717287", "pm_score": 3, "selected": false, "text": "// using foreach loop how to get index number:\n \nforeach (var result in results.Select((value, index) => new { index, value }))\n{\n // do something\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
43,044
<p>I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc. </p> <p>I've found solutions to this problem but they rely on alternative color palettes than RGB. I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors. </p> <p>Any ideas would be great.</p>
[ { "answer_id": 43081, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "brightness = sqrt(R^2+G^2+B^2)\n" }, { "answer_id": 43235, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 10, "selected": true, "text": "public Color generateRandomColor(Color mix) {\n Random random = new Random();\n int red = random.nextInt(256);\n int green = random.nextInt(256);\n int blue = random.nextInt(256);\n\n // mix the color\n if (mix != null) {\n red = (red + mix.getRed()) / 2;\n green = (green + mix.getGreen()) / 2;\n blue = (blue + mix.getBlue()) / 2;\n }\n\n Color color = new Color(red, green, blue);\n return color;\n}\n" }, { "answer_id": 12266311, "author": "motobói", "author_id": 25612, "author_profile": "https://Stackoverflow.com/users/25612", "pm_score": 5, "selected": false, "text": "function pastelColors(){\n var r = (Math.round(Math.random()* 127) + 127).toString(16);\n var g = (Math.round(Math.random()* 127) + 127).toString(16);\n var b = (Math.round(Math.random()* 127) + 127).toString(16);\n return '#' + r + g + b;\n}\n" }, { "answer_id": 14810261, "author": "ChilledFlame", "author_id": 2060983, "author_profile": "https://Stackoverflow.com/users/2060983", "pm_score": 2, "selected": false, "text": "function fnGetRandomColour(iDarkLuma, iLightLuma) \n{ \n for (var i=0;i<20;i++)\n {\n var sColour = ('ffffff' + Math.floor(Math.random() * 0xFFFFFF).toString(16)).substr(-6);\n\n var rgb = parseInt(sColour, 16); // convert rrggbb to decimal\n var r = (rgb >> 16) & 0xff; // extract red\n var g = (rgb >> 8) & 0xff; // extract green\n var b = (rgb >> 0) & 0xff; // extract blue\n\n var iLuma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709\n\n\n if (iLuma > iDarkLuma && iLuma < iLightLuma) return sColour;\n }\n return sColour;\n} \n" }, { "answer_id": 21361663, "author": "m1ch4ls", "author_id": 3024975, "author_profile": "https://Stackoverflow.com/users/3024975", "pm_score": 2, "selected": false, "text": "List<Color> ColorPalette = ColorGenerator.Generate(30).ToList();\n" }, { "answer_id": 22363008, "author": "Petr Bugyík", "author_id": 2875783, "author_profile": "https://Stackoverflow.com/users/2875783", "pm_score": 2, "selected": false, "text": "function pastelColors() {\n $r = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);\n $g = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);\n $b = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);\n\n return \"#\" . $r . $g . $b;\n}\n" }, { "answer_id": 22743973, "author": "LifeInTheTrees", "author_id": 2040877, "author_profile": "https://Stackoverflow.com/users/2040877", "pm_score": 0, "selected": false, "text": "int rand = a global color randomizer that you can control by script/ by a crossfader etc.\nfloat h = perlin(grey,23.3*rand)\nfloat s = perlin(grey,54,4*rand)\nfloat v = perlin(grey,12.6*rand)\n\nReturn float4 HSVtoRGB(h,s,v);\n" }, { "answer_id": 28500955, "author": "Dave_L", "author_id": 1163569, "author_profile": "https://Stackoverflow.com/users/1163569", "pm_score": 2, "selected": false, "text": "GetRandomColours <- function(num.of.colours, color.to.mix=c(1,1,1)) {\n return(rgb((matrix(runif(num.of.colours*3), nrow=num.of.colours)*color.to.mix)/2))\n}\n" }, { "answer_id": 31594284, "author": "Ephraim", "author_id": 599402, "author_profile": "https://Stackoverflow.com/users/599402", "pm_score": 0, "selected": false, "text": ".flat-color-gen" }, { "answer_id": 31629356, "author": "Sceptic", "author_id": 3340062, "author_profile": "https://Stackoverflow.com/users/3340062", "pm_score": 1, "selected": false, "text": "generateRandomComplementaryColor = function(r, g, b){\n //--- JavaScript code\n var red = Math.floor((Math.random() * 256));\n var green = Math.floor((Math.random() * 256));\n var blue = Math.floor((Math.random() * 256));\n //---\n\n //--- Extra check for Internet Explorers, its Math.random is not random enough.\n if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){\n red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));\n green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));\n blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));\n };\n //---\n\n //--- nodejs code\n /*\n crypto = Npm.require('crypto');\n red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);\n green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);\n blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);\n */\n //---\n\n red = (red + r)/2;\n green = (green + g)/2;\n blue = (blue + b)/2;\n\n return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')';\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
43,051
<p>I have the following C# code:</p> <pre><code>byte rule = 0; ... rule = rule | 0x80; </code></pre> <p>which produces the error: </p> <blockquote> <p><em>Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)</em></p> </blockquote> <p>[Update: first version of the question was wrong ... I misread the compiler output]</p> <p>Adding the cast <strong>doesn't</strong> fix the problem:</p> <pre><code>rule = rule | (byte) 0x80; </code></pre> <p>I need to write it as:</p> <pre><code>rule |= 0x80; </code></pre> <p>Which just seems weird. Why is the <code>|=</code> operator any different to the <code>|</code> operator?</p> <p>Is there any other way of telling the compiler to treat the constant as a byte?</p> <hr> <p><strong>@ Giovanni Galbo</strong> : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much!</p> <p><strong>@ Jonathon Holland</strong> : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces:</p> <blockquote> <p><em>The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type)</em> </p> </blockquote>
[ { "answer_id": 43064, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 4, "selected": false, "text": "rule = (byte)(rule | 0x80);\n" }, { "answer_id": 43074, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 4, "selected": true, "text": "int rule = 0;\nrule |= 0x80;\n" }, { "answer_id": 43090, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 0, "selected": false, "text": "rule | 0x80" }, { "answer_id": 16884882, "author": "arx", "author_id": 292432, "author_profile": "https://Stackoverflow.com/users/292432", "pm_score": 2, "selected": false, "text": "(byte1 | byte2)" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3631/" ]
43,111
<p>I have a self referencing Categories table. Each Category has a CategoryID, ParentCategoryID, CategoryName, etc. And each category can have any number of sub categories, and each of those sub categories can have any number of sub categories, and so and and so forth. So basically the tree can be X levels deep.</p> <p>Then Products are associated to leaf (sub) Categories. Is there a way to get all the Products for any given Category (which would be all the products associated to all its leaf descendants) using LINQ to SQL? </p> <p>This feels like a recursive problem. Is it better to used a Stored Procedure instead?</p>
[ { "answer_id": 43121, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "public IQueryable GetCategories(Category parent)\n{\n var cats = (parent.Categories);\n foreach (Category c in cats )\n {\n cats = cats .Concat(GetCategories(c));\n }\n return a;\n}\n" }, { "answer_id": 413555, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public IQueryable<Partner> GetPartners()\n {\n return from p in db.Partners\n select new Partner\n {\n PartnerId = p.PartnerId,\n CompanyName = p.CompanyName,\n Address1 = p.Address1,\n Address2 = p.Address2,\n Website = p.Website,\n City = p.City,\n State = p.State,\n County = p.County,\n Country = p.Country,\n Zip = p.Zip,\n ParentPartner = GetPartners().WithPartnerId(p.ParentPartnerId).ToList().SingleOrDefault(),\n SubPartners = GetPartners().WithParentPartnerId(p.PartnerId).ToList()\n };\n }\n\n\npublic static IQueryable<Partner> WithPartnerId(this IQueryable<Partner> qry, int? partnerId)\n {\n return from t in qry\n where t.PartnerId == partnerId\n select t;\n }\n\npublic static IQueryable<Partner> WithParentPartnerId(this IQueryable<Partner> qry, int? parentPartnerId)\n {\n return from p in qry\n where p.ParentPartner.PartnerId == parentPartnerId\n select p;\n }\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653/" ]
43,116
<p>I've got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same program?</p> <p>UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux. Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).</p>
[ { "answer_id": 43120, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 7, "selected": true, "text": "popen()" }, { "answer_id": 43122, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 3, "selected": false, "text": "commandThatOutputs.exe > someFileToStoreResults.txt\n" }, { "answer_id": 43136, "author": "Arktronic", "author_id": 4479, "author_profile": "https://Stackoverflow.com/users/4479", "pm_score": 2, "selected": false, "text": "popen()" }, { "answer_id": 17651740, "author": "dharmabook.ru", "author_id": 2583079, "author_profile": "https://Stackoverflow.com/users/2583079", "pm_score": -1, "selected": false, "text": "//execute external process and read exactly binary or text output\n//can read image from Zip file for example\nstring run(const char* cmd){\n FILE* pipe = popen(cmd, \"r\");\n if (!pipe) return \"ERROR\";\n char buffer[262144];\n string data;\n string result;\n int dist=0;\n int size;\n //TIME_START\n while(!feof(pipe)) {\n size=(int)fread(buffer,1,262144, pipe); //cout<<buffer<<\" size=\"<<size<<endl;\n data.resize(data.size()+size);\n memcpy(&data[dist],buffer,size);\n dist+=size;\n }\n //TIME_PRINT_\n pclose(pipe);\n return data;\n}\n" }, { "answer_id": 19907372, "author": "Prabhat Kumar Singh", "author_id": 2608019, "author_profile": "https://Stackoverflow.com/users/2608019", "pm_score": 1, "selected": false, "text": "system()" }, { "answer_id": 28971647, "author": "MestreLion", "author_id": 624066, "author_profile": "https://Stackoverflow.com/users/624066", "pm_score": 6, "selected": false, "text": "popen()" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830/" ]
43,126
<pre><code>public static IList&lt;T&gt; LoadObjectListAll&lt;T&gt;() { ISession session = CheckForExistingSession(); var cfg = new NHibernate.Cfg.Configuration().Configure(); var returnList = session.CreateCriteria(typeof(T)); var list = returnList.List(); var castList = list.Cast&lt;typeof(T)&gt;(); return castList; } </code></pre> <p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>
[ { "answer_id": 43128, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 3, "selected": false, "text": "var castList = list.Cast<typeof(T)>();\n" }, { "answer_id": 43131, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 0, "selected": false, "text": "IList<T>\n" }, { "answer_id": 43132, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": -1, "selected": false, "text": "IList" }, { "answer_id": 43141, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 4, "selected": true, "text": "T" }, { "answer_id": 43145, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 0, "selected": false, "text": "List<string>" }, { "answer_id": 43153, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 1, "selected": false, "text": "IList<T>" }, { "answer_id": 43160, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 1, "selected": false, "text": "typeof" }, { "answer_id": 43195, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "var returnList = session.CreateCriteria(typeof(T));\nvar list = returnList.List();\nvar castList = list.Cast<typeof(T)>();\nreturn castList;\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
43,134
<p>Simple question, but one that I've been curious about...is there a functional difference between the following two commands?</p> <pre><code>String::class String.class </code></pre> <p>They both do what I expect -- that is to say they return <code>Class</code> -- but what is the difference between using the <code>::</code> and the <code>.</code>?</p> <p>I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after <code>::</code> but not after <code>.</code>, but I don't know what the reason for this is...</p>
[ { "answer_id": 43146, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 6, "selected": true, "text": "." }, { "answer_id": 48046, "author": "Peeja", "author_id": 4937, "author_profile": "https://Stackoverflow.com/users/4937", "pm_score": 4, "selected": false, "text": "." } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4142/" ]
43,157
<p>I was surprised to find today that I couldn't track down any simple way to write the contents of an <code>InputStream</code> to an <code>OutputStream</code> in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).</p> <p>So, given an <code>InputStream</code> <code>in</code> and an <code>OutputStream</code> <code>out</code>, is there a simpler way to write the following?</p> <pre><code>byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); } </code></pre>
[ { "answer_id": 43163, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 7, "selected": false, "text": "byte[] buffer = new byte[1024];\nint len;\nwhile ((len = in.read(buffer)) != -1) {\n out.write(buffer, 0, len);\n}\n" }, { "answer_id": 51753, "author": "Mikezx6r", "author_id": 5382, "author_profile": "https://Stackoverflow.com/users/5382", "pm_score": 9, "selected": false, "text": "org.apache.commons.io.IOUtils" }, { "answer_id": 540772, "author": "Dilum Ranatunga", "author_id": 64967, "author_profile": "https://Stackoverflow.com/users/64967", "pm_score": 4, "selected": false, "text": "PipedInputStream" }, { "answer_id": 18788720, "author": "Alexander Volkov", "author_id": 2022586, "author_profile": "https://Stackoverflow.com/users/2022586", "pm_score": 2, "selected": false, "text": "byte[] buffer = new byte[4096];\nint n;\nwhile ((n = in.read(buffer)) > 0) {\n out.write(buffer, 0, n);\n}\nout.close();\n" }, { "answer_id": 18793899, "author": "Jordan LaPrise", "author_id": 2730161, "author_profile": "https://Stackoverflow.com/users/2730161", "pm_score": 5, "selected": false, "text": "InputStream" }, { "answer_id": 19194580, "author": "user1079877", "author_id": 1079877, "author_profile": "https://Stackoverflow.com/users/1079877", "pm_score": 8, "selected": false, "text": "/* You can get Path from file also: file.toPath() */\nFiles.copy(InputStream in, Path target)\nFiles.copy(Path source, OutputStream out)\n" }, { "answer_id": 19915774, "author": "DejanLekic", "author_id": 876497, "author_profile": "https://Stackoverflow.com/users/876497", "pm_score": 2, "selected": false, "text": "import org.apache.commons.net.io.Util;\n...\nUtil.copyStream(in, out);\n" }, { "answer_id": 22223001, "author": "Pranav", "author_id": 2991983, "author_profile": "https://Stackoverflow.com/users/2991983", "pm_score": -1, "selected": false, "text": "public static void copyStream(InputStream is, OutputStream os)\n {\n final int buffer_size=1024;\n try\n {\n byte[] bytes=new byte[buffer_size];\n for(;;)\n {\n int count=is.read(bytes, 0, buffer_size);\n if(count==-1)\n break;\n os.write(bytes, 0, count);\n }\n }\n catch(Exception ex){}\n }\n" }, { "answer_id": 22657697, "author": "Andrejs", "author_id": 1180621, "author_profile": "https://Stackoverflow.com/users/1180621", "pm_score": 6, "selected": false, "text": "ByteStreams.copy()" }, { "answer_id": 29420264, "author": "Nour Rteil", "author_id": 4654101, "author_profile": "https://Stackoverflow.com/users/4654101", "pm_score": -1, "selected": false, "text": "public static boolean copyFile(InputStream inputStream, OutputStream out) {\n byte buf[] = new byte[1024];\n int len;\n long startTime=System.currentTimeMillis();\n\n try {\n while ((len = inputStream.read(buf)) != -1) {\n out.write(buf, 0, len);\n }\n\n long endTime=System.currentTimeMillis()-startTime;\n Log.v(\"\",\"Time taken to transfer all bytes is : \"+endTime);\n out.close();\n inputStream.close();\n\n } catch (IOException e) {\n\n return false;\n }\n return true;\n}\n" }, { "answer_id": 32136196, "author": "Sivakumar", "author_id": 1879388, "author_profile": "https://Stackoverflow.com/users/1879388", "pm_score": 3, "selected": false, "text": "try(InputStream inputStream = new FileInputStream(\"C:\\\\mov.mp4\");\n OutputStream outputStream = new FileOutputStream(\"D:\\\\mov.mp4\")) {\n\n byte[] buffer = new byte[10*1024];\n\n for (int length; (length = inputStream.read(buffer)) != -1; ) {\n outputStream.write(buffer, 0, length);\n }\n} catch (FileNotFoundException exception) {\n exception.printStackTrace();\n} catch (IOException ioException) {\n ioException.printStackTrace();\n}\n" }, { "answer_id": 34191665, "author": "Bohemian", "author_id": 256196, "author_profile": "https://Stackoverflow.com/users/256196", "pm_score": 2, "selected": false, "text": "byte[] buffer = new byte[2048];\nfor (int n = in.read(buffer); n >= 0; n = in.read(buffer))\n out.write(buffer, 0, n);\n" }, { "answer_id": 39070240, "author": "Jin Kwon", "author_id": 330457, "author_profile": "https://Stackoverflow.com/users/330457", "pm_score": 3, "selected": false, "text": "private void copy(final InputStream in, final OutputStream out)\n throws IOException {\n final byte[] b = new byte[8192];\n for (int r; (r = in.read(b)) != -1;) {\n out.write(b, 0, r);\n }\n}\n" }, { "answer_id": 39440936, "author": "Ali Dehghani", "author_id": 1393484, "author_profile": "https://Stackoverflow.com/users/1393484", "pm_score": 9, "selected": true, "text": "InputStream" }, { "answer_id": 40019374, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 4, "selected": false, "text": "JDK" }, { "answer_id": 42004909, "author": "holmis83", "author_id": 1463522, "author_profile": "https://Stackoverflow.com/users/1463522", "pm_score": 4, "selected": false, "text": "StreamUtils.copy(in, out);\n" }, { "answer_id": 46348544, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": -1, "selected": false, "text": "new LengthOf(new TeeInput(input, output)).value();\n" }, { "answer_id": 54272980, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 2, "selected": false, "text": "BufferedInputStream" }, { "answer_id": 56980114, "author": "Daniel De León", "author_id": 980442, "author_profile": "https://Stackoverflow.com/users/980442", "pm_score": 2, "selected": false, "text": "inputStream.transferTo(...)" }, { "answer_id": 60788219, "author": "IPP Nerd", "author_id": 4504727, "author_profile": "https://Stackoverflow.com/users/4504727", "pm_score": 2, "selected": false, "text": "byte[] buffer=new byte[1024];\nfor(int n; (n=inputStream.read(buffer))!=-1; outputStream.write(buffer,0,n));\n" }, { "answer_id": 68497202, "author": "fullmoon", "author_id": 1143361, "author_profile": "https://Stackoverflow.com/users/1143361", "pm_score": 0, "selected": false, "text": "ByteStreamKt.copyTo(src, dst, buffer.length)" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
43,201
<p>I'm looking for some examples or samples of routing for the following sort of scenario:</p> <p>The general example of doing things is: {controller}/{action}/{id}</p> <p>So in the scenario of doing a product search for a store you'd have:</p> <pre><code>public class ProductsController: Controller { public ActionResult Search(string id) // id being the search string { ... } } </code></pre> <p>Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id}</p> <p>So that you could have a particular search for a particular store, but use a different search method for a different store?</p> <p>(If you required the store name to be a higher priority than the function itself in the url)</p> <p>Or would it come down to:</p> <pre><code>public class ProductsController: Controller { public ActionResult Search(int category, string id) // id being the search string { if(category == 1) return Category1Search(); if(category == 2) return Category2Search(); ... } } </code></pre> <p>It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories?</p> <p>Edit to add:</p> <p>The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories.</p> <p>IE:</p> <p>/this/search/items/search+term &lt;-- works</p> <p>/that/search/items/search+term &lt;-- won't work - because the search controller isn't allowed.</p>
[ { "answer_id": 45076, "author": "crucible", "author_id": 3717, "author_profile": "https://Stackoverflow.com/users/3717", "pm_score": 2, "selected": false, "text": " public static void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n var shop1namespace = new RouteValueDictionary();\n shop1namespace.Add(\"namespaces\", new HashSet<string>(new string[] \n { \n \"MyWebShop.Controllers.Shop1\"\n }));\n\n routes.Add(\"Shop1\", new Route(\"Shop1/{controller}/{action}/{id}\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new\n {\n action = \"Index\",\n id = (string)null\n }),\n DataTokens = shop1namespace\n });\n\n var shop2namespace = new RouteValueDictionary();\n shop2namespace.Add(\"namespaces\", new HashSet<string>(new string[] \n { \n \"MyWebShop.Controllers.Shop2\"\n }));\n\n routes.Add(\"Shop2\", new Route(\"Shop2/{controller}/{action}/{id}\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new\n {\n action = \"Index\",\n id = (string)null\n }),\n DataTokens = shop2namespace\n });\n\n var defaultnamespace = new RouteValueDictionary();\n defaultnamespace.Add(\"namespaces\", new HashSet<string>(new string[] \n { \n \"MyWebShop.Controllers\"\n }));\n\n routes.Add(\"Default\", new Route(\"{controller}/{action}/{id}\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new { controller = \"Home\", action = \"Index\", id = \"\" }),\n DataTokens = defaultnamespace \n });\n }\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ]
43,218
<p>I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.</p> <p>However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.</p> <p>Does anybody have any ideas for resolving this?</p>
[ { "answer_id": 43222, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": true, "text": "Page.ClientScript.RegisterClientScriptInclude(\"myJsFile\", Page.ResolveClientUrl(\"~/Javascript/jsfile.js\"))\n" }, { "answer_id": 43252, "author": "Jared", "author_id": 3442, "author_profile": "https://Stackoverflow.com/users/3442", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\" src=\"<%= Response.ApplyAppPathModifier(\"~/javascript/globaljs.aspx\") %>\"></script>\n" }, { "answer_id": 43734, "author": "Brad Tutterow", "author_id": 308, "author_profile": "https://Stackoverflow.com/users/308", "pm_score": 2, "selected": false, "text": "<asp:ScriptManager ID=\"ScriptManager1\" \n EnablePartialRendering=\"True\"\n runat=\"server\">\n <Scripts>\n <asp:ScriptReference \n Assembly=\"SampleControl\" \n Name=\"SampleControl.UpdatePanelAnimation.js\" />\n </Scripts>\n</asp:ScriptManager>\n" }, { "answer_id": 262558, "author": "Chris Zwiryk", "author_id": 734, "author_profile": "https://Stackoverflow.com/users/734", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"~/resources/stylesheet.css.ashx\" />\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
43,224
<p>Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)</p>
[ { "answer_id": 47286, "author": "matt", "author_id": 2646, "author_profile": "https://Stackoverflow.com/users/2646", "pm_score": 5, "selected": false, "text": "public class Statistics\n{\n public Trendline CalculateLinearRegression(int[] values)\n {\n var yAxisValues = new List<int>();\n var xAxisValues = new List<int>();\n\n for (int i = 0; i < values.Length; i++)\n {\n yAxisValues.Add(values[i]);\n xAxisValues.Add(i + 1);\n }\n\n return new Trendline(yAxisValues, xAxisValues);\n }\n}\n\npublic class Trendline\n{\n private readonly IList<int> xAxisValues;\n private readonly IList<int> yAxisValues;\n private int count;\n private int xAxisValuesSum;\n private int xxSum;\n private int xySum;\n private int yAxisValuesSum;\n\n public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)\n {\n this.yAxisValues = yAxisValues;\n this.xAxisValues = xAxisValues;\n\n this.Initialize();\n }\n\n public int Slope { get; private set; }\n public int Intercept { get; private set; }\n public int Start { get; private set; }\n public int End { get; private set; }\n\n private void Initialize()\n {\n this.count = this.yAxisValues.Count;\n this.yAxisValuesSum = this.yAxisValues.Sum();\n this.xAxisValuesSum = this.xAxisValues.Sum();\n this.xxSum = 0;\n this.xySum = 0;\n\n for (int i = 0; i < this.count; i++)\n {\n this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);\n this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);\n }\n\n this.Slope = this.CalculateSlope();\n this.Intercept = this.CalculateIntercept();\n this.Start = this.CalculateStart();\n this.End = this.CalculateEnd();\n }\n\n private int CalculateSlope()\n {\n try\n {\n return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));\n }\n catch (DivideByZeroException)\n {\n return 0;\n }\n }\n\n private int CalculateIntercept()\n {\n return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;\n }\n\n private int CalculateStart()\n {\n return (this.Slope*this.xAxisValues.First()) + this.Intercept;\n }\n\n private int CalculateEnd()\n {\n return (this.Slope*this.xAxisValues.Last()) + this.Intercept;\n }\n}\n" }, { "answer_id": 15799351, "author": "Thymine", "author_id": 356218, "author_profile": "https://Stackoverflow.com/users/356218", "pm_score": 4, "selected": false, "text": "decimal" }, { "answer_id": 48136019, "author": "Magn3144", "author_id": 7769419, "author_profile": "https://Stackoverflow.com/users/7769419", "pm_score": 1, "selected": false, "text": "class Program\n {\n public double CalculateTrendlineSlope(List<Point> graph)\n {\n int n = graph.Count;\n double a = 0;\n double b = 0;\n double bx = 0;\n double by = 0;\n double c = 0;\n double d = 0;\n double slope = 0;\n\n foreach (Point point in graph)\n {\n a += point.x * point.y;\n bx = point.x;\n by = point.y;\n c += Math.Pow(point.x, 2);\n d += point.x;\n }\n a *= n;\n b = bx * by;\n c *= n;\n d = Math.Pow(d, 2);\n\n slope = (a - b) / (c - d);\n return slope;\n }\n }\n\n class Point\n {\n public double x;\n public double y;\n }\n" }, { "answer_id": 51140331, "author": "Todd Skelton", "author_id": 1212994, "author_profile": "https://Stackoverflow.com/users/1212994", "pm_score": 1, "selected": false, "text": "public class DataPoint<T1,T2>\n{\n public DataPoint(T1 x, T2 y)\n {\n X = x;\n Y = y;\n }\n\n [JsonProperty(\"x\")]\n public T1 X { get; }\n\n [JsonProperty(\"y\")]\n public T2 Y { get; }\n}\n\npublic class Trendline\n{\n public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints)\n {\n int count = 0;\n long sumX = 0;\n long sumX2 = 0;\n decimal sumY = 0;\n decimal sumXY = 0;\n\n foreach (var dataPoint in dataPoints)\n {\n count++;\n sumX += dataPoint.X;\n sumX2 += dataPoint.X * dataPoint.X;\n sumY += dataPoint.Y;\n sumXY += dataPoint.X * dataPoint.Y;\n }\n\n Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));\n Intercept = (sumY / count) - (Slope * (sumX / count));\n }\n\n public decimal Slope { get; private set; }\n public decimal Intercept { get; private set; }\n public decimal Start { get; private set; }\n public decimal End { get; private set; }\n\n public decimal GetYValue(decimal xValue)\n {\n return Slope * xValue + Intercept;\n }\n}\n" }, { "answer_id": 59964271, "author": "jonyB", "author_id": 10564382, "author_profile": "https://Stackoverflow.com/users/10564382", "pm_score": 0, "selected": false, "text": "/**@typedef {{\n * x: Number;\n * y:Number;\n * }} Point\n * @param {Point[]} data\n * @returns {Function} */\nfunction _getTrendlineEq(data) {\n const xySum = data.reduce((acc, item) => {\n const xy = item.x * item.y\n acc += xy\n return acc\n }, 0)\n const xSum = data.reduce((acc, item) => {\n acc += item.x\n return acc\n }, 0)\n const ySum = data.reduce((acc, item) => {\n acc += item.y\n return acc\n }, 0)\n const aTop = (data.length * xySum) - (xSum * ySum)\n const xSquaredSum = data.reduce((acc, item) => {\n const xSquared = item.x * item.x\n acc += xSquared\n return acc\n }, 0)\n const aBottom = (data.length * xSquaredSum) - (xSum * xSum)\n const a = aTop / aBottom\n const bTop = ySum - (a * xSum)\n const b = bTop / data.length\n return function trendline(x) {\n return a * x + b\n }\n}" }, { "answer_id": 62789036, "author": "user13889781", "author_id": 13889781, "author_profile": "https://Stackoverflow.com/users/13889781", "pm_score": 0, "selected": false, "text": "// https://classroom.synonym.com/calculate-trendline-2709.html\npackage main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n\n graph := [][]float64{\n {1, 3},\n {2, 5},\n {3, 6.5},\n }\n\n n := len(graph)\n\n // get the slope\n var a float64\n var b float64\n var bx float64\n var by float64\n var c float64\n var d float64\n var slope float64\n\n for _, point := range graph {\n\n a += point[0] * point[1]\n bx += point[0]\n by += point[1]\n c += math.Pow(point[0], 2)\n d += point[0]\n\n }\n\n a *= float64(n) // 97.5\n b = bx * by // 87\n c *= float64(n) // 42\n d = math.Pow(d, 2) // 36\n slope = (a - b) / (c - d) // 1.75\n\n // calculating the y-intercept (b) of the Trendline\n var e float64\n var f float64\n\n e = by // 14.5\n f = slope * bx // 10.5\n intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3\n\n // output\n fmt.Println(slope)\n fmt.Println(intercept)\n\n}\n" }, { "answer_id": 67130721, "author": "Gregg Reno", "author_id": 264604, "author_profile": "https://Stackoverflow.com/users/264604", "pm_score": 2, "selected": false, "text": "ArrayList<Entry> yValues2 = new ArrayList<>();\n\nArrayList<Double > xAxisValues = new ArrayList<Double>();\nArrayList<Double> yAxisValues = new ArrayList<Double>();\n\nfor (int i = 0; i < readings.size(); i++)\n{\n r = readings.get(i);\n yAxisValues.add(r.value);\n xAxisValues.add((double)i + 1);\n}\n\nTrendLine tl = new TrendLine(yAxisValues, xAxisValues);\n\n//Create the y values for the trend line\ndouble currY = tl.Start;\nfor (int i = 0; i < readings.size(); ++ i) {\n yValues2.add(new Entry(i, (float) currY));\n currY = currY + tl.Slope;\n}\n\n...\n\npublic class TrendLine\n{\n private ArrayList<Double> xAxisValues = new ArrayList<Double>();\n private ArrayList<Double> yAxisValues = new ArrayList<Double>();\n\n private int count;\n private double xAxisValuesSum;\n private double xxSum;\n private double xySum;\n private double yAxisValuesSum;\n\n public TrendLine(ArrayList<Double> yAxisValues, ArrayList<Double> xAxisValues)\n {\n this.yAxisValues = yAxisValues;\n this.xAxisValues = xAxisValues;\n\n this.Initialize();\n }\n\n public double Slope;\n public double Intercept;\n public double Start;\n public double End;\n\n private double getArraySum(ArrayList<Double> arr) {\n double sum = 0;\n for (int i = 0; i < arr.size(); ++i) {\n sum = sum + arr.get(i);\n }\n return sum;\n }\n private void Initialize()\n {\n this.count = this.yAxisValues.size();\n this.yAxisValuesSum = getArraySum(this.yAxisValues);\n this.xAxisValuesSum = getArraySum(this.xAxisValues);\n this.xxSum = 0;\n this.xySum = 0;\n\n for (int i = 0; i < this.count; i++)\n {\n this.xySum += (this.xAxisValues.get(i)*this.yAxisValues.get(i));\n this.xxSum += (this.xAxisValues.get(i)*this.xAxisValues.get(i));\n }\n\n this.Slope = this.CalculateSlope();\n this.Intercept = this.CalculateIntercept();\n this.Start = this.CalculateStart();\n this.End = this.CalculateEnd();\n }\n\n private double CalculateSlope()\n {\n try\n {\n return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));\n }\n catch (Exception e)\n {\n return 0;\n }\n }\n\n private double CalculateIntercept()\n {\n return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;\n }\n\n private double CalculateStart()\n {\n return (this.Slope*this.xAxisValues.get(0)) + this.Intercept;\n }\n\n private double CalculateEnd()\n {\n return (this.Slope*this.xAxisValues.get(this.xAxisValues.size()-1)) + this.Intercept;\n }\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646/" ]
43,249
<p>Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure? </p> <p>For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it. </p> <p>SQL Server 2005 is my only applicable limitation I think.</p> <pre><code>create procedure getDepartments @DepartmentIds varchar(max) as declare @Sql varchar(max) select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')' exec(@Sql) </code></pre>
[ { "answer_id": 43260, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": false, "text": "SELECT d.[Name]\nFROM Department d\n JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId\n" }, { "answer_id": 43263, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 2, "selected": false, "text": "declare @xmlstring as varchar(100) \nset @xmlstring = '<args><arg value=\"42\" /><arg2>-1</arg2></args>' \n\ndeclare @docid int \n\nexec sp_xml_preparedocument @docid output, @xmlstring\n\nselect [id],parentid,nodetype,localname,[text]\nfrom openxml(@docid, '/args', 1) \n" }, { "answer_id": 44136, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 2, "selected": false, "text": "IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL\nBEGIN\n DROP TABLE #tmpDept\nEND\n\nSET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')\n\nCREATE TABLE #tmpDept (DeptID INT)\nDECLARE @DeptID INT\nIF IsNumeric(@DepartmentIDs)=1\nBEGIN\n SET @DeptID=@DepartmentIDs\n INSERT INTO #tmpDept (DeptID) SELECT @DeptID\nEND\nELSE\nBEGIN\n WHILE CHARINDEX(',',@DepartmentIDs)>0\n BEGIN\n SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)\n SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))\n INSERT INTO #tmpDept (DeptID) SELECT @DeptID\n END\nEND\n" }, { "answer_id": 15191592, "author": "Nishant", "author_id": 2089165, "author_profile": "https://Stackoverflow.com/users/2089165", "pm_score": 2, "selected": false, "text": "Declare @XMLList xml\nSET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)\nSELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
43,253
<p>What is the best way to measure exception handling overhead/performance in C++?</p> <p>Please give standalone code samples.</p> <p>I'm targeting Microsoft Visual C++ 2008 and gcc.</p> <p>I need to get results from the following cases:</p> <ol> <li>Overhead when there are no try/catch blocks</li> <li>Overhead when there are try/catch blocks but exceptions are not thrown</li> <li>Overhead when exceptions are thrown</li> </ol>
[ { "answer_id": 43292, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 3, "selected": false, "text": "g++ exception_handling.cpp -o exception_handling [ -O2 ]\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2948/" ]
43,289
<p>How can I do this fast?</p> <p>Sure I can do this:</p> <pre><code>static bool ByteArrayCompare(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; for (int i=0; i&lt;a1.Length; i++) if (a1[i]!=a2[i]) return false; return true; } </code></pre> <p>But I'm looking for either a <a href="https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library" rel="noreferrer">BCL</a> function or some highly optimized proven way to do this.</p> <pre><code>java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); </code></pre> <p>works nicely, but it doesn't look like that would work for x64.</p> <p>Note my super-fast answer <a href="https://stackoverflow.com/a/8808245/4489">here</a>.</p>
[ { "answer_id": 43300, "author": "gil", "author_id": 195, "author_profile": "https://Stackoverflow.com/users/195", "pm_score": 3, "selected": false, "text": "for" }, { "answer_id": 43305, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": false, "text": "public static bool equals(sbyte[] a1, sbyte[] a2)\n{\n if (a1 == a2)\n {\n return true;\n }\n if ((a1 != null) && (a2 != null))\n {\n if (a1.Length != a2.Length)\n {\n return false;\n }\n for (int i = 0; i < a1.Length; i++)\n {\n if (a1[i] != a2[i])\n {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n" }, { "answer_id": 43310, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 9, "selected": false, "text": "using System;\nusing System.Linq;\n...\nvar a1 = new int[] { 1, 2, 3};\nvar a2 = new int[] { 1, 2, 3};\nvar a3 = new int[] { 1, 2, 4};\nvar x = a1.SequenceEqual(a2); // true\nvar y = a1.SequenceEqual(a3); // false\n" }, { "answer_id": 811292, "author": "Milan Gardian", "author_id": 23843, "author_profile": "https://Stackoverflow.com/users/23843", "pm_score": 5, "selected": false, "text": "System.Data.Linq.Binary" }, { "answer_id": 1445280, "author": "Kevin Driedger", "author_id": 9587, "author_profile": "https://Stackoverflow.com/users/9587", "pm_score": 2, "selected": false, "text": "if(myByteArray1.Length != myByteArray2.Length) return false;\nif(myByteArray1.Length == 8)\n return BitConverter.ToInt64(myByteArray1, 0) == BitConverter.ToInt64(myByteArray2, 0); \nelse if(myByteArray.Length == 4)\n return BitConverter.ToInt32(myByteArray2, 0) == BitConverter.ToInt32(myByteArray2, 0); \n" }, { "answer_id": 1445405, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 8, "selected": false, "text": "[DllImport(\"msvcrt.dll\", CallingConvention=CallingConvention.Cdecl)]\nstatic extern int memcmp(byte[] b1, byte[] b2, long count);\n\nstatic bool ByteArrayCompare(byte[] b1, byte[] b2)\n{\n // Validate buffers are the same length.\n // This also ensures that the count does not exceed the length of either buffer. \n return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;\n}\n" }, { "answer_id": 4617030, "author": "user565710", "author_id": 565710, "author_profile": "https://Stackoverflow.com/users/565710", "pm_score": 4, "selected": false, "text": " using System.Linq; //SequenceEqual\n\n byte[] ByteArray1 = null;\n byte[] ByteArray2 = null;\n\n ByteArray1 = MyFunct1();\n ByteArray2 = MyFunct2();\n\n if (ByteArray1.SequenceEqual<byte>(ByteArray2) == true)\n {\n MessageBox.Show(\"Match\");\n }\n else\n {\n MessageBox.Show(\"Don't match\");\n }\n" }, { "answer_id": 8140664, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 7, "selected": false, "text": "static bool ByteArrayCompare(byte[] a1, byte[] a2) \n{\n return StructuralComparisons.StructuralEqualityComparer.Equals(a1, a2);\n}\n" }, { "answer_id": 8808245, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 7, "selected": true, "text": "a1.SequenceEquals(a2)" }, { "answer_id": 29831846, "author": "API_Base", "author_id": 4691027, "author_profile": "https://Stackoverflow.com/users/4691027", "pm_score": -1, "selected": false, "text": "SequenceEquals" }, { "answer_id": 30740076, "author": "Alon", "author_id": 2327376, "author_profile": "https://Stackoverflow.com/users/2327376", "pm_score": -1, "selected": false, "text": " public bool Compare(byte[] b1, byte[] b2)\n {\n return Encoding.ASCII.GetString(b1) == Encoding.ASCII.GetString(b2);\n }\n" }, { "answer_id": 33307903, "author": "ArekBulski", "author_id": 2375119, "author_profile": "https://Stackoverflow.com/users/2375119", "pm_score": 5, "selected": false, "text": "static unsafe bool EqualBytesLongUnrolled (byte[] data1, byte[] data2)\n{\n if (data1 == data2)\n return true;\n if (data1.Length != data2.Length)\n return false;\n\n fixed (byte* bytes1 = data1, bytes2 = data2) {\n int len = data1.Length;\n int rem = len % (sizeof(long) * 16);\n long* b1 = (long*)bytes1;\n long* b2 = (long*)bytes2;\n long* e1 = (long*)(bytes1 + len - rem);\n\n while (b1 < e1) {\n if (*(b1) != *(b2) || *(b1 + 1) != *(b2 + 1) || \n *(b1 + 2) != *(b2 + 2) || *(b1 + 3) != *(b2 + 3) ||\n *(b1 + 4) != *(b2 + 4) || *(b1 + 5) != *(b2 + 5) || \n *(b1 + 6) != *(b2 + 6) || *(b1 + 7) != *(b2 + 7) ||\n *(b1 + 8) != *(b2 + 8) || *(b1 + 9) != *(b2 + 9) || \n *(b1 + 10) != *(b2 + 10) || *(b1 + 11) != *(b2 + 11) ||\n *(b1 + 12) != *(b2 + 12) || *(b1 + 13) != *(b2 + 13) || \n *(b1 + 14) != *(b2 + 14) || *(b1 + 15) != *(b2 + 15))\n return false;\n b1 += 16;\n b2 += 16;\n }\n\n for (int i = 0; i < rem; i++)\n if (data1 [len - 1 - i] != data2 [len - 1 - i])\n return false;\n\n return true;\n }\n}\n" }, { "answer_id": 36291188, "author": "Zar Shardan", "author_id": 913845, "author_profile": "https://Stackoverflow.com/users/913845", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// \n /// </summary>\n /// <param name=\"array1\"></param>\n /// <param name=\"array2\"></param>\n /// <param name=\"bytesToCompare\"> 0 means compare entire arrays</param>\n /// <returns></returns>\n public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0)\n {\n if (array1.Length != array2.Length) return false;\n\n var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare;\n var tailIdx = length - length % sizeof(Int64);\n\n //check in 8 byte chunks\n for (var i = 0; i < tailIdx; i += sizeof(Int64))\n {\n if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false;\n }\n\n //check the remainder of the array, always shorter than 8 bytes\n for (var i = tailIdx; i < length; i++)\n {\n if (array1[i] != array2[i]) return false;\n }\n\n return true;\n }\n" }, { "answer_id": 38002854, "author": "Mr Anderson", "author_id": 6196648, "author_profile": "https://Stackoverflow.com/users/6196648", "pm_score": 3, "selected": false, "text": "memcmp()" }, { "answer_id": 39701555, "author": "Motlicek Petr", "author_id": 819843, "author_profile": "https://Stackoverflow.com/users/819843", "pm_score": 2, "selected": false, "text": "Host Process Environment Information:\nBenchmarkDotNet.Core=v0.9.9.0\nOS=Microsoft Windows NT 6.2.9200.0\nProcessor=Intel(R) Core(TM) i7-3770 CPU 3.40GHz, ProcessorCount=8\nFrequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC\nCLR=MS.NET 4.0.30319.42000, Arch=64-bit RELEASE [RyuJIT]\nGC=Concurrent Workstation\nJitModules=clrjit-v4.6.1590.0\n\nType=CompareMemoriesBenchmarks Mode=Throughput \n\n Method | Median | StdDev | Scaled | Scaled-SD |\n----------------------- |------------ |---------- |------- |---------- |\n NewMemCopy | 30.0443 ms | 1.1880 ms | 1.00 | 0.00 |\n EqualBytesLongUnrolled | 29.9917 ms | 0.7480 ms | 0.99 | 0.04 |\n msvcrt_memcmp | 30.0930 ms | 0.2964 ms | 1.00 | 0.03 |\n UnsafeCompare | 31.0520 ms | 0.7072 ms | 1.03 | 0.04 |\n ByteArrayCompare | 212.9980 ms | 2.0776 ms | 7.06 | 0.25 |\n" }, { "answer_id": 43191293, "author": "Eli Arbel", "author_id": 276083, "author_profile": "https://Stackoverflow.com/users/276083", "pm_score": 4, "selected": false, "text": "Unsafe.As<T>(object)" }, { "answer_id": 46005655, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "static bool ByteArrayEquals(byte[] a1, byte[] a2) \n{\n return a1.Zip(a2, (l, r) => l == r).All(x => x);\n}\n" }, { "answer_id": 46471559, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 3, "selected": false, "text": "StructuralComparison : 4.6 MiB/s\nfor : 274.5 MiB/s\nToUInt32 : 263.6 MiB/s\nToUInt64 : 474.9 MiB/s\nmemcmp : 8500.8 MiB/s\n" }, { "answer_id": 48577229, "author": "Zapnologica", "author_id": 1331971, "author_profile": "https://Stackoverflow.com/users/1331971", "pm_score": 2, "selected": false, "text": "linq" }, { "answer_id": 48599119, "author": "Joe Amenta", "author_id": 1083771, "author_profile": "https://Stackoverflow.com/users/1083771", "pm_score": 7, "selected": false, "text": "Span<T>" }, { "answer_id": 48666556, "author": "Raymond Osterbrink", "author_id": 2576585, "author_profile": "https://Stackoverflow.com/users/2576585", "pm_score": -1, "selected": false, "text": "public static bool CompareByteArrays(byte[] ba0, byte[] ba1) =>\n !(ba0.Length != ba1.Length || Enumerable.Range(1,ba0.Length)\n .FirstOrDefault(n => ba0[n] != ba1[n]) > 0);\n" }, { "answer_id": 48975665, "author": "Casey Chester", "author_id": 2726757, "author_profile": "https://Stackoverflow.com/users/2726757", "pm_score": 1, "selected": false, "text": "public enum CompareDirection { Forward, Backward }\n\nprivate static unsafe bool UnsafeEquals(byte[] a, byte[] b, CompareDirection direction = CompareDirection.Forward)\n{\n // returns when a and b are same array or both null\n if (a == b) return true;\n\n // if either is null or different lengths, can't be equal\n if (a == null || b == null || a.Length != b.Length)\n return false;\n\n const int UNROLLED = 16; // count of longs 'unrolled' in optimization\n int size = sizeof(long) * UNROLLED; // 128 bytes (min size for 'unrolled' optimization)\n int len = a.Length;\n int n = len / size; // count of full 128 byte segments\n int r = len % size; // count of remaining 'unoptimized' bytes\n\n // pin the arrays and access them via pointers\n fixed (byte* pb_a = a, pb_b = b)\n {\n if (r > 0 && direction == CompareDirection.Backward)\n {\n byte* pa = pb_a + len - 1;\n byte* pb = pb_b + len - 1;\n byte* phead = pb_a + len - r;\n while(pa >= phead)\n {\n if (*pa != *pb) return false;\n pa--;\n pb--;\n }\n }\n\n if (n > 0)\n {\n int nOffset = n * size;\n if (direction == CompareDirection.Forward)\n {\n long* pa = (long*)pb_a;\n long* pb = (long*)pb_b;\n long* ptail = (long*)(pb_a + nOffset);\n while (pa < ptail)\n {\n if (*(pa + 0) != *(pb + 0) || *(pa + 1) != *(pb + 1) ||\n *(pa + 2) != *(pb + 2) || *(pa + 3) != *(pb + 3) ||\n *(pa + 4) != *(pb + 4) || *(pa + 5) != *(pb + 5) ||\n *(pa + 6) != *(pb + 6) || *(pa + 7) != *(pb + 7) ||\n *(pa + 8) != *(pb + 8) || *(pa + 9) != *(pb + 9) ||\n *(pa + 10) != *(pb + 10) || *(pa + 11) != *(pb + 11) ||\n *(pa + 12) != *(pb + 12) || *(pa + 13) != *(pb + 13) ||\n *(pa + 14) != *(pb + 14) || *(pa + 15) != *(pb + 15)\n )\n {\n return false;\n }\n pa += UNROLLED;\n pb += UNROLLED;\n }\n }\n else\n {\n long* pa = (long*)(pb_a + nOffset);\n long* pb = (long*)(pb_b + nOffset);\n long* phead = (long*)pb_a;\n while (phead < pa)\n {\n if (*(pa - 1) != *(pb - 1) || *(pa - 2) != *(pb - 2) ||\n *(pa - 3) != *(pb - 3) || *(pa - 4) != *(pb - 4) ||\n *(pa - 5) != *(pb - 5) || *(pa - 6) != *(pb - 6) ||\n *(pa - 7) != *(pb - 7) || *(pa - 8) != *(pb - 8) ||\n *(pa - 9) != *(pb - 9) || *(pa - 10) != *(pb - 10) ||\n *(pa - 11) != *(pb - 11) || *(pa - 12) != *(pb - 12) ||\n *(pa - 13) != *(pb - 13) || *(pa - 14) != *(pb - 14) ||\n *(pa - 15) != *(pb - 15) || *(pa - 16) != *(pb - 16)\n )\n {\n return false;\n }\n pa -= UNROLLED;\n pb -= UNROLLED;\n }\n }\n }\n\n if (r > 0 && direction == CompareDirection.Forward)\n {\n byte* pa = pb_a + len - r;\n byte* pb = pb_b + len - r;\n byte* ptail = pb_a + len;\n while(pa < ptail)\n {\n if (*pa != *pb) return false;\n pa++;\n pb++;\n }\n }\n }\n\n return true;\n}\n" }, { "answer_id": 56553320, "author": "Mahmoud Al-Qudsi", "author_id": 17027, "author_profile": "https://Stackoverflow.com/users/17027", "pm_score": 3, "selected": false, "text": "memcmp" }, { "answer_id": 69280107, "author": "Antidisestablishmentarianism", "author_id": 13843929, "author_profile": "https://Stackoverflow.com/users/13843929", "pm_score": 0, "selected": false, "text": "public unsafe bool SIMDNoFallThrough() #requires System.Runtime.Intrinsics.X86\n{\n if (a1 == null || a2 == null)\n return false;\n\n int length0 = a1.Length;\n\n if (length0 != a2.Length) return false;\n\n fixed (byte* b00 = a1, b01 = a2)\n {\n byte* b0 = b00, b1 = b01, last0 = b0 + length0, last1 = b1 + length0, last32 = last0 - 31;\n\n if (length0 > 31)\n {\n while (b0 < last32)\n {\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != -1)\n return false;\n b0 += 32;\n b1 += 32;\n }\n return Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(last0 - 32), Avx.LoadVector256(last1 - 32))) == -1;\n }\n\n if (length0 > 15)\n {\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != 65535)\n return false;\n return Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(last0 - 16), Sse2.LoadVector128(last1 - 16))) == 65535;\n }\n\n if (length0 > 7)\n {\n if (*(ulong*)b0 != *(ulong*)b1)\n return false;\n return *(ulong*)(last0 - 8) == *(ulong*)(last1 - 8);\n }\n\n if (length0 > 3)\n {\n if (*(uint*)b0 != *(uint*)b1)\n return false;\n return *(uint*)(last0 - 4) == *(uint*)(last1 - 4);\n }\n\n if (length0 > 1)\n {\n if (*(ushort*)b0 != *(ushort*)b1)\n return false;\n return *(ushort*)(last0 - 2) == *(ushort*)(last1 - 2);\n }\n\n return *b0 == *b1;\n }\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4489/" ]
43,290
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
[ { "answer_id": 43312, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": true, "text": "{% url %}" }, { "answer_id": 55734, "author": "Garth Kidd", "author_id": 5700, "author_profile": "https://Stackoverflow.com/users/5700", "pm_score": 4, "selected": false, "text": "models.py" }, { "answer_id": 72249, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 2, "selected": false, "text": "reverse()" }, { "answer_id": 57151646, "author": "juan Isaza", "author_id": 2394901, "author_profile": "https://Stackoverflow.com/users/2394901", "pm_score": 3, "selected": false, "text": "from django.urls import reverse\n\nurl = reverse('my_app:endpoint', kwargs={'arg1': arg_1})\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
43,291
<p>I know that I can do something like</p> <pre><code>$int = (int)99; //(int) has a maximum or 99 </code></pre> <p>To set the variable <code>$int</code> to an integer and give it a value of <code>99</code>. </p> <p>Is there a way to set the type to something like <code>LongBlob</code> in MySQL for <code>LARGE</code> Integers in PHP?</p>
[ { "answer_id": 43295, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 4, "selected": true, "text": "$int = (int)123;\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
43,320
<p>One of the things that get me thoroughly confused is the use of <code>session.Flush</code>,in conjunction with <code>session.Commit</code>, and <code>session.Close</code>.</p> <p>Sometimes <code>session.Close</code> works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.</p> <p>But sometimes I really get stymied by the logic behind <code>session.Flush</code>. I have seen examples where you have a <code>session.SaveOrUpdate()</code> followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.</p> <p>Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.</p>
[ { "answer_id": 43567, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 9, "selected": true, "text": "Close()" }, { "answer_id": 44212, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 4, "selected": false, "text": "ITransaction.Commit()" }, { "answer_id": 22193504, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " using (var transaction = session.BeginTransaction())\n {\n transaction.Commit();\n }\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372/" ]
43,321
<p>The default shell in Mac OS X is <code>bash</code>, which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed <em>more stuff</em>, though, and I've heard good things about <code>zsh</code> in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad. </p> <p>(As I understand it, <code>bash</code> can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.)</p> <p>Will switching to <code>zsh</code>, even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn <em>why</em> it's better? (Examples would be nice, too <code>:)</code> )</p> <hr> <p>@<a href="https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43340">Rodney Amato</a> &amp; @<a href="https://stackoverflow.com/questions/43321/worth-switching-to-zsh-for-casual-use#43338">Vulcan Eager</a> give two good reasons to respectively stick to <code>bash</code> and switch to <code>zsh</code>. Looks like I'll have to investigate both! Oh well <code>:)</code></p> <p>Is there anyone with an opinion from both sides of the argument?</p>
[ { "answer_id": 43340, "author": "Rodney Amato", "author_id": 4342, "author_profile": "https://Stackoverflow.com/users/4342", "pm_score": 7, "selected": true, "text": "tar -xzvf bash-completion-20060301.tar.gz\n" }, { "answer_id": 83754, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 6, "selected": false, "text": "**/*.c" }, { "answer_id": 106317, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 4, "selected": false, "text": "autoload -U zutil # [1]\nautoload -U compinit # [2]\nautoload -U complist # [3]\ncompinit\n" }, { "answer_id": 909650, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "zmv" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
43,322
<p>Plug-in systems in C++ are hard because the ABI is not properly defined, and each compiler (or version thereof) follows its own rules. However, COM on Windows shows that it's possible to create a minimal plug-in system that allows programmers with different compilers to create plug-ins for a host application using a simple interface.</p> <p>Let's be practical, and leave the C++ standard, which is not very helpful in this respect, aside for a minute. If I want to write an app for Windows and Mac (and optionally Linux) that supports C++ plug-ins, and if I want to give plug-in authors a reasonably large choice of compilers (say less than 2 year old versions of Visual C++, GCC or Intel's C++ compiler), what features of C++ could I count on?</p> <p>Of course, I assume that plug-ins would be written for a specific platform.</p> <p>Off the top of my head, here are some C++ features I can think of, with what I think is the answer:</p> <ul> <li>vtable layout, to use objects through abstract classes? (yes)</li> <li>built-in types, pointers? (yes)</li> <li>structs, unions? (yes)</li> <li>exceptions? (no)</li> <li>extern "C" functions? (yes)</li> <li>stdcall non-extern "C" functions with built-in parameter types? (yes)</li> <li>non-stdcall non-extern "C" functions with user-defined parameter types? (no)</li> </ul> <p>I would appreciate any experience you have in that area that you could share. If you know of any moderately successful app that has a C++ plug-in system, that's cool too.</p> <p>Carl</p>
[ { "answer_id": 43373, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": false, "text": "#if defined(IN_THE_PLUGIN)\nvoid MyObject::somefunction() { MyObject_somefunction(this); }\n#endif\n" }, { "answer_id": 176893, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 3, "selected": false, "text": "Q_DECLARE_INTERFACE" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ]
43,324
<p>I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation:</p> <blockquote> <p>Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request.</p> </blockquote> <p>So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly:</p> <pre><code>Guid UploadID = Guid.NewGuid(); Application.Add(Guid.ToString(), User); </code></pre> <p>So, I'm creating a unique ID and using it as a key to store the <code>Page.User</code> object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly:</p> <pre><code>IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]]; </code></pre> <p>This actually works, but it has two glaring drawbacks: </p> <ul> <li><p>If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them.</p></li> <li><p>If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future.</p></li> </ul> <p>Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session?</p> <p>I know I can get the session ID through <code>Session.SessionID</code>, and I know how to use YUI to post it to the next page. What I don't know is how to use that <code>SessionID</code> to grab the session from the state server.</p> <p>Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario.</p>
[ { "answer_id": 43353, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "Session.SessionID" }, { "answer_id": 43356, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 1, "selected": false, "text": "string sessionId = HttpContext.Current.Session.SessionID;\n" }, { "answer_id": 237682, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "using System;\nusing System.Web;\n\npublic class Global_asax : System.Web.HttpApplication\n{\n private void Application_BeginRequest(object sender, EventArgs e)\n {\n /* \n Fix for the Flash Player Cookie bug in Non-IE browsers.\n Since Flash Player always sends the IE cookies even in FireFox\n we have to bypass the cookies by sending the values as part of the POST or GET\n and overwrite the cookies with the passed in values.\n\n The theory is that at this point (BeginRequest) the cookies have not been ready by\n the Session and Authentication logic and if we update the cookies here we'll get our\n Session and Authentication restored correctly\n */\n\n HttpRequest request = HttpContext.Current.Request;\n\n try\n {\n string sessionParamName = \"ASPSESSID\";\n string sessionCookieName = \"ASP.NET_SESSIONID\";\n\n string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName];\n if (sessionValue != null)\n {\n UpdateCookie(sessionCookieName, sessionValue);\n }\n }\n catch (Exception ex)\n {\n // TODO: Add logging here.\n }\n\n try\n {\n string authParamName = \"AUTHID\";\n string authCookieName = FormsAuthentication.FormsCookieName;\n\n string authValue = request.Form[authParamName] ?? request.QueryString[authParamName];\n if (authValue != null)\n {\n UpdateCookie(authCookieName, authValue);\n }\n }\n catch (Exception ex)\n {\n // TODO: Add logging here.\n }\n }\n\n private void UpdateCookie(string cookieName, string cookieValue)\n {\n HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);\n if (cookie == null)\n {\n HttpCookie newCookie = new HttpCookie(cookieName, cookieValue);\n Response.Cookies.Add(newCookie);\n }\n else\n {\n cookie.Value = cookieValue;\n HttpContext.Current.Request.Cookies.Set(cookie);\n }\n }\n}\n" }, { "answer_id": 25755712, "author": "Pluto", "author_id": 1507941, "author_profile": "https://Stackoverflow.com/users/1507941", "pm_score": 2, "selected": false, "text": "public SessionStateStoreData GetSessionById(string sessionId)\n{\n HttpApplication httpApplication = HttpContext.ApplicationInstance;\n\n // Black magic #1: getting to SessionStateModule\n HttpModuleCollection httpModuleCollection = httpApplication.Modules;\n SessionStateModule sessionHttpModule = httpModuleCollection[\"Session\"] as SessionStateModule;\n if (sessionHttpModule == null)\n {\n // Couldn't find Session module\n return null;\n }\n\n // Black magic #2: getting to SessionStateStoreProviderBase through reflection\n FieldInfo fieldInfo = typeof(SessionStateModule).GetField(\"_store\", BindingFlags.NonPublic | BindingFlags.Instance);\n SessionStateStoreProviderBase sessionStateStoreProviderBase = fieldInfo.GetValue(sessionHttpModule) as SessionStateStoreProviderBase;\n if (sessionStateStoreProviderBase == null)\n {\n // Couldn't find sessionStateStoreProviderBase\n return null;\n }\n\n // Black magic #3: generating dummy HttpContext out of the thin air. sessionStateStoreProviderBase.GetItem in #4 needs it.\n SimpleWorkerRequest request = new SimpleWorkerRequest(\"dummy.html\", null, new StringWriter());\n HttpContext context = new HttpContext(request);\n\n // Black magic #4: using sessionStateStoreProviderBase.GetItem to fetch the data from session with given Id.\n bool locked;\n TimeSpan lockAge;\n object lockId;\n SessionStateActions actions;\n SessionStateStoreData sessionStateStoreData = sessionStateStoreProviderBase.GetItem(\n context, sessionId, out locked, out lockAge, out lockId, out actions);\n return sessionStateStoreData;\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2527/" ]
43,349
<p>I know that default cron's behavior is to send normal and error output to cron's owner local email box.</p> <p>Is there other ways to get theses results (for example to send it by email to a bunch of people, to store them somewhere, and so on) ?</p>
[ { "answer_id": 43357, "author": "Vagnerr", "author_id": 3720, "author_profile": "https://Stackoverflow.com/users/3720", "pm_score": 2, "selected": false, "text": "* * * * * /path/my/command > /my/email/script 2&>1\n" }, { "answer_id": 43360, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": true, "text": "command > /tmp/log.txt 2>&1" }, { "answer_id": 43376, "author": "Rodney Amato", "author_id": 4342, "author_profile": "https://Stackoverflow.com/users/4342", "pm_score": 3, "selected": false, "text": "MAILTO=\"user@example.com\"\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
43,354
<p>How do you reference a bitmap on the stage in flash using actionscript 3?</p> <p>I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out.</p> <pre><code>layer 5 : mask2:MovieClip layer 4 : img2:Bitmap layer 3 : mask1:MovieClip layer 2 : img1:Bitmap layer 1 : background:Bitmap </code></pre> <p>at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images.</p> <p>but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this?</p> <p>The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3.</p> <p>Any help would be appreciated.</p> <p><strong>EDIT:</strong></p> <p>@<a href="https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#43735">81bronco</a> , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what <a href="https://stackoverflow.com/questions/43354/how-do-you-reference-a-bitmap-on-the-stage-in-actionscript#44347">vanhornRF</a> suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation.</p>
[ { "answer_id": 43477, "author": "bitbonk", "author_id": 4227, "author_profile": "https://Stackoverflow.com/users/4227", "pm_score": 1, "selected": false, "text": "imageHolder.removeChild( imageIndex )\n" }, { "answer_id": 44347, "author": "vanhornRF", "author_id": 1945, "author_profile": "https://Stackoverflow.com/users/1945", "pm_score": 0, "selected": false, "text": "for(var i:int=0; i<numChildren; i++){\n trace(getChildAt(i),\"This is the child at position \"+i);\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
43,368
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
[ { "answer_id": 48479, "author": "Jason", "author_id": 5036, "author_profile": "https://Stackoverflow.com/users/5036", "pm_score": 1, "selected": false, "text": "<table>" }, { "answer_id": 198348, "author": "massimo", "author_id": 24489, "author_profile": "https://Stackoverflow.com/users/24489", "pm_score": 3, "selected": false, "text": "db.table.field.widget=...\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4462/" ]
43,374
<p>What I have so far is </p> <pre><code>#!/bin/sh php_syntax_check() { retval=0 for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do if [ -f $i ]; then output=$(php -l $i) retval=$? if [ $retval -gt 0 ]; then echo "==============================================================================" echo "Unstaging $i for the commit due to the follow parse errors" echo "$output" git reset -q HEAD $i fi fi done if [ $retval -gt 0 ]; then exit $retval fi } php_syntax_check </code></pre>
[ { "answer_id": 547489, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#!/usr/bin/php\n<?php /* Your pre-commit check. */ ?>\n" }, { "answer_id": 3069175, "author": "LarryH", "author_id": 13923, "author_profile": "https://Stackoverflow.com/users/13923", "pm_score": 3, "selected": true, "text": "git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --\nfind $TMPDIR -name '*.php' -print | xargs -n 1 php -l\n" }, { "answer_id": 48700175, "author": "Sudheesh.M.S", "author_id": 1295321, "author_profile": "https://Stackoverflow.com/users/1295321", "pm_score": 0, "selected": false, "text": "#!/usr/local/bin/php\n<?php\n /**\n * Collect all files which have been added, copied or\n * modified and store them in an array - output\n */\n exec('git diff --cached --name-only --diff-filter=ACM', $output);\n\n $isViolated = 0;\n $violatedFiles = array();\n // $php_cs_path = \"/usr/local/bin/php-cs-fixer\";\n $php_cs_path = \"~/.composer/vendor/bin/phpcs\";\n\n foreach ($output as $fileName) {\n // Consider only PHP file for processing\n if (pathinfo($fileName, PATHINFO_EXTENSION) == \"php\") {\n $psr_output = array();\n\n // Put the changes to be made in $psr_output, if not as per PSR2 standard\n\n // php-cs-fixer\n // exec(\"{$php_cs_path} fix {$fileName} --rules=@PSR2 --dry-run --diff\", $psr_output, $return);\n\n // php-code-sniffer\n exec(\"{$php_cs_path} --standard=PSR2 --colors -n {$fileName}\", $psr_output, $return);\n\n if ($return != 0) {\n $isViolated = 1;\n $violatedFiles[] = $fileName;\n echo implode(\"\\n\", $psr_output), \"\\n\";\n }\n }\n }\n if ($isViolated == 1) {\n echo \"\\n---------------------------- IMPORTANT --------------------------------\\n\";\n echo \"\\nPlease use the suggestions above to fix the code in the following file: \\n\";\n echo \" => \" . implode(\"\\n => \", $violatedFiles);\n echo \"\\n-----------------------------------------------------------------------\\n\\n\\n\";\n exit(1);\n } else {\n echo \"\\n => Committed Successfully :-)\\n\\n\";\n exit(0);\n }\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4342/" ]
43,393
<p>I've come back to using NHibernate after using other technologies (<a href="http://www.lhotka.net/" rel="nofollow noreferrer">CSLA</a> and <a href="http://subsonicproject.com/" rel="nofollow noreferrer">Subsonic</a>) for a couple of years, and I'm finding the querying a bit frustrating, especially when compared to Subsonic. I was wondering what other approaches people are using?</p> <p>The Hibernate Query Language doesn't feel right to me, seems too much like writing SQL, which to my mind is one of the reason to use an ORM tools so I don't have to, furthermore it's all in XML, which means it's poor for refactoring, and errors will only be discovered at runtime?</p> <p>Criteria Queries, don't seem fluid enough.</p> <p>I've <a href="http://jhollingworth.wordpress.com/2008/03/28/subsonic-like-nhibernate-query-generator-button-in-visual-studio/" rel="nofollow noreferrer">read</a> that Ayende's <a href="http://www.ayende.com/projects/downloads/nhibernate-query-generator.aspx" rel="nofollow noreferrer">NHibernate Query Generator</a>, is a useful tool, is this what people are using? What else is out there?</p> <p>EDIT: Worth a read <a href="http://www.ayende.com/Blog/archive/2007/03/17/Implementing-Linq-for-NHibernate-A-How-To-Guide--Part.aspx" rel="nofollow noreferrer">http://www.ayende.com/Blog/archive/2007/03/17/Implementing-Linq-for-NHibernate-A-How-To-Guide--Part.aspx</a></p>
[ { "answer_id": 48097, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 2, "selected": false, "text": "GetProductsForOrder(Order order)" }, { "answer_id": 206242, "author": "tobinharris", "author_id": 1136215, "author_profile": "https://Stackoverflow.com/users/1136215", "pm_score": 1, "selected": false, "text": "public class CustomerRepostitory()\n{ \n //LINQ for NHibernate \n public Customer[] FindCustomerByEmail(string email)\n {\n return (from c in _session.Linq<Customer>() where c.Email == email).FirstOrDefault();\n }\n\n //HQL\n public Customer[] FindBestBuyers()\n {\n var q = _session.CreateQuery(\"...insert complex HQL here...\");\n return q.List<Customer>();\n }\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
43,422
<p>For example, I issued an ALTER TABLE statement to create an index on a MEDIUMTEXT field in an InnoDB table that has 134k rows where the size of the index was 255 bytes and the average size of the data in the field is 30k. This command has been running for the last 15 minutes or so (and is the only thing running on the database). Is there any way for me to determine if it is going to finish in closer to 5 minutes, 5 hours, or 5 days?</p>
[ { "answer_id": 7713657, "author": "Jay Binks", "author_id": 987797, "author_profile": "https://Stackoverflow.com/users/987797", "pm_score": 4, "selected": false, "text": "select count(*) from `myoriginalrable`;\nselect count(*) from `#sql-1e8_11ae5`;\n" }, { "answer_id": 12055272, "author": "Axel", "author_id": 1611966, "author_profile": "https://Stackoverflow.com/users/1611966", "pm_score": 4, "selected": false, "text": "SHOW ENGINE INNODB STATUS" }, { "answer_id": 17755072, "author": "aalku", "author_id": 270349, "author_profile": "https://Stackoverflow.com/users/270349", "pm_score": 2, "selected": false, "text": "select \nbeginsd, now(), qRuns, qTime, tName, trxStarted, trxTime, `rows`, modified, locked, hoursLeftL, estimatedEndL, modifiedPerSecL, avgRows, estimatedEndG, modifiedPerSecG, hoursLeftG\nfrom (\nselect \n (@tname:='<table>') tName,\n @beginsd:=sysdate() beginsd,\n @trxStarted:=(select trx_started from information_schema.innodb_trx where trx_query like concat('alter table %', @tname, '%')) trxStarted, \n @trxTime:=timediff(@beginsd, @trxStarted) trxTime,\n @rows:=(select table_rows from information_schema.tables where table_name like @tname) `rows`,\n @runs:=(ifnull(@runs, 0)+1) qRuns,\n @rowsSum:=(ifnull(@rowsSum, 0)+@rows),\n round(@avgRows:=(@rowsSum / @runs)) avgRows,\n @modified:=(select trx_rows_modified from information_schema.innodb_trx where trx_query like concat('alter table %', @tname, '%')) modified, \n @rowsLeftL:=(cast(@rows as signed) - cast(@modified as signed)) rowsLeftL,\n round(@rowsLeftG:=(cast(@avgRows as signed) - cast(@modified as signed)), 2) rowsLeftG,\n @locked:=(select trx_rows_locked from information_schema.innodb_trx where trx_query like concat('alter table %', @tname, '%')) locked,\n @endsd:=sysdate() endsd,\n --\n time_to_sec(timediff(@endsd, @beginsd)) qTime,\n @modifiedInc:=(cast(@modified as signed) - cast(@p_modified as signed)) modifiedInc,\n @timeInc:=time_to_sec(timediff(@beginsd, @p_beginsd)) timeInc,\n round(@modifiedPerSecL:=(@modifiedInc/@timeInc)) modifiedPerSecL,\n round(@modifiedPerSecG:=(@modified/time_to_sec(@trxTime))) modifiedPerSecG,\n round(@minutesLeftL := (@rowsLeftL / @modifiedPerSecL / 60)) minutesLeftL,\n round(@minutesLeftG := (@rowsLeftG / @modifiedPerSecG / 60)) minutesLeftG,\n round(@hoursLeftL := (@minutesLeftL / 60), 2) hoursLeftL,\n round(@hoursLeftG := (@minutesLeftG / 60), 2) hoursLeftG,\n (@beginsd + INTERVAL @minutesLeftL MINUTE) estimatedEndL,\n (@beginsd + INTERVAL @minutesLeftG MINUTE) estimatedEndG,\n --\n @p_rows:=@rows,\n @p_modified:=@modified,\n @p_beginsd:=@beginsd\n) sq;\n" }, { "answer_id": 54616646, "author": "mahemoff", "author_id": 18706, "author_profile": "https://Stackoverflow.com/users/18706", "pm_score": 2, "selected": false, "text": "ls -laShr /var/lib/mysql | sort -h" }, { "answer_id": 54816616, "author": "Shimon Doodkin", "author_id": 466363, "author_profile": "https://Stackoverflow.com/users/466363", "pm_score": 1, "selected": false, "text": "cd /var/lib/mysql/mydb\nTABLEFILE=\"MYTABLE.ibd\"\nTEMPFILE=\"\\#*ibd\"\n\nls -lah $TABLEFILE;\nls -lah $TEMPFILE; # make sure you have only one temp file or modify the above TEMPFILE\n\nSIZE_TOTAL=$(stat -c %s $TABLEFILE);\n\n# other ways to get 1st size and time\n#SIZE1=1550781106; TIME1=1550781106;\n#SIZE1=$(stat -c %s $TEMPFILE); TIME1=$(stat -c %Z $TEMPFILE); sleep 10;\nSIZE1=0; TIME1=$(stat -c %X $TEMPFILE); # use file create time\n\necho \"SIZE1=$TIME1; TIME1=$TIME1\";\n\nSIZE2=$(stat -c %s $TEMPFILE); TIME2=$(stat -c %Z $TEMPFILE);\n\nDELTA_SIZE=$(( $SIZE2 - $SIZE1 ))\nDELTA_TIME=$(( $TIME2 - $TIME1 ))\n\n# debug last numbers should not be zero:\n\necho $SIZE1 $SIZE2 $SIZE_TOTAL $DELTA_SIZE;\necho $TIME1 $TIME2 $DELTA_TIME;\n\nSIZE_PER_SECOND=$( awk \"BEGIN {print $DELTA_SIZE / $DELTA_TIME }\" );\nSIZE_LEFT=$(($SIZE_TOTAL - $SIZE2));\nTIME_LEFT_SECONDS=$( awk \"BEGIN { print ( $SIZE_LEFT / $SIZE_PER_SECOND) }\" );\nTIME_LEFT_MINUTES=$( awk \"BEGIN { print $TIME_LEFT_SECONDS /60 }\" );\nTIME_LEFT=$( awk \"BEGIN { printf \\\"%d:%02d:%2d\\\", int($TIME_LEFT_MINUTES /60), int($TIME_LEFT_MINUTES % 60), int($TIME_LEFT_SECONDS % 60 ) }\" );\n\necho \"TIME_LEFT = $TIME_LEFT\";\necho \"SIZE_LEFT = $SIZE_LEFT\" \"MB=\" $(( $SIZE_LEFT/1024/1024 )) ;\nawk \"BEGIN { if( $SIZE_TOTAL == $SIZE2 ) print \\\"mysql finished\\\" }\" ;\n\nfree -h # check free memory, sometimes it is full and it makes it slow\n" }, { "answer_id": 62174308, "author": "Gonzalo Cao", "author_id": 1222923, "author_profile": "https://Stackoverflow.com/users/1222923", "pm_score": 2, "selected": false, "text": "UPDATE performance_schema.setup_instruments\n SET ENABLED = 'YES'\n WHERE NAME LIKE 'stage/innodb/alter%';\nUPDATE performance_schema.setup_consumers\n SET ENABLED = 'YES'\n WHERE NAME LIKE '%stages%';\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
43,427
<p>Say I have a site on <a href="http://example.com" rel="noreferrer">http://example.com</a>. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words</p> <p><a href="http://example.com" rel="noreferrer">http://example.com</a> &amp; <a href="http://example.com/" rel="noreferrer">http://example.com/</a> should be allowed, but <a href="http://example.com/anything" rel="noreferrer">http://example.com/anything</a> and <a href="http://example.com/someendpoint.aspx" rel="noreferrer">http://example.com/someendpoint.aspx</a> should be blocked.</p> <p>Further it would be great if I can allow certain query strings to passthrough to the home page: <a href="http://example.com?okparam=true" rel="noreferrer">http://example.com?okparam=true</a> </p> <p>but not <a href="http://example.com?anythingbutokparam=true" rel="noreferrer">http://example.com?anythingbutokparam=true</a></p>
[ { "answer_id": 43436, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "Disallow: /subdir/\n" }, { "answer_id": 43454, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "Disallow: *\nAllow: index.ext\n" }, { "answer_id": 43838, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": false, "text": "robots.txt" }, { "answer_id": 44711, "author": "Boaz", "author_id": 2892, "author_profile": "https://Stackoverflow.com/users/2892", "pm_score": 7, "selected": true, "text": "User-Agent: *\nDisallow: /*\nAllow: /?okparam=\nAllow: /$\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892/" ]
43,459
<p>can anybody recommend some really good resources for how to get Apache authenticating users with Kerberos.</p> <p>Background reading on Kerberos would also be useful </p> <p>Thanks</p> <p>Peter</p>
[ { "answer_id": 18693599, "author": "Tomas Tomecek", "author_id": 909579, "author_profile": "https://Stackoverflow.com/users/909579", "pm_score": 1, "selected": false, "text": "mod_auth_kerb" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720/" ]
43,466
<p>I know 'best' is subjective, so according to you, what is the best solution for the following problem:</p> <p>Given a string of length n (say "abc"), generate all proper subsets of the string. So, for our example, the output would be {}, {a}, {b}, {c}, {ab}, {bc}, {ac}. {abc}.</p> <p>What do you think?</p>
[ { "answer_id": 43474, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "def subsets(s):\n r = []\n a = [False] * len(s)\n while True:\n r.append(\"\".join([s[i] for i in range(len(s)) if a[i]]))\n j = 0\n while a[j]:\n a[j] = False\n j += 1\n if j >= len(s):\n return r\n a[j] = True\n\nprint subsets(\"abc\")\n" }, { "answer_id": 43481, "author": "Tnilsson", "author_id": 4165, "author_profile": "https://Stackoverflow.com/users/4165", "pm_score": 0, "selected": false, "text": "int i = 0;\nResults.push({});\n\nWhile(i > Inset.Length) {\n Foreach(Set s in Results) {\n If(s.Length == i) {\n Foreach(character c in inSet)\n Results.push(s+c);\n }\n i++;\n}\n" }, { "answer_id": 145313, "author": "Sarp Centel", "author_id": 16622, "author_profile": "https://Stackoverflow.com/users/16622", "pm_score": 1, "selected": false, "text": " char str [] = \"abc\";\n int n = strlen(str); // n is number of elements in your set\n\n for(int i=0; i< (1 << n); i++) { // (1 << n) is equal to 2^n\n for(int j=0; j<n; j++) { // For each element in the set\n if((i & (1 << j)) > 0) { // Check if it's included in this subset. (1 << j) sets the jth bit\n cout << str[j];\n }\n }\n cout << endl;\n }\n" }, { "answer_id": 21300716, "author": "feliciafay", "author_id": 1315742, "author_profile": "https://Stackoverflow.com/users/1315742", "pm_score": 0, "selected": false, "text": "//recursive solution in C++\nset<string> power_set_recursive(string input_str)\n{\n set<string> res;\n if(input_str.size()==0) {\n res.insert(\"\");\n } else if(input_str.size()==1) {\n res.insert(input_str.substr(0,1));\n } else {\n for(int i=0;i<input_str.size();i++) {\n set<string> left_set=power_set_iterative(input_str.substr(0,i));\n set<string> right_set=power_set_iterative(input_str.substr(i,input_str.size()-i));\n for(set<string>::iterator it1=left_set.begin();it1!=left_set.end();it1++) {\n for(set<string>::iterator it2=right_set.begin();it2!=right_set.end();it2++) {\n string tmp=(*it1)+(*it2);\n sort(tmp.begin(),tmp.end());\n res.insert(tmp);\n }\n }\n }\n }\n return res;\n}\n\n\n//iterative solution in C++\nset<string> power_set_iterative(string input_str)\n{\n set<string> res;\n set<string> out_res;\n res.insert(\"\");\n set<string>::iterator res_it;\n for(int i=0;i<input_str.size();i++){\n for(res_it=res.begin();res_it!=res.end();res_it++){\n string tmp=*res_it+input_str.substr(i,1);\n sort(tmp.begin(),tmp.end());\n out_res.insert(tmp);\n }\n res.insert(input_str.substr(i,1));\n for(set<string>::iterator res_it2=out_res.begin();res_it2!=out_res.end();res_it2++){\n res.insert(*res_it2);\n }\n out_res.clear();\n }\n return res;\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
43,490
<p>When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during <code>wm_close</code> - is <code>DestroyHandle</code> the .net equivalent?</p> <hr> <p>I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:</p> <pre><code>void Dispose(bool disposing) { otherObject.Event -= myEventHandler; } </code></pre>
[ { "answer_id": 43499, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "DestroyHandle" }, { "answer_id": 43560, "author": "dan gibson", "author_id": 4495, "author_profile": "https://Stackoverflow.com/users/4495", "pm_score": 2, "selected": false, "text": "Dispose" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
43,500
<p>I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this?</p> <p>Edited: I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal.</p>
[ { "answer_id": 43505, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 9, "selected": true, "text": "Enumerable.SequenceEqual" }, { "answer_id": 43506, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "var dictionary = new Dictionary<int, string>() {{1, \"a\"}, {2, \"b\"}};\nvar intList = new List<int> {1, 2};\nvar stringList = new List<string> {\"a\", \"b\"};\nvar test1 = dictionary.Keys.SequenceEqual(intList);\nvar test2 = dictionary.Values.SequenceEqual(stringList);\n" }, { "answer_id": 43518, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 2, "selected": false, "text": " public static bool IsEqual(this List<int> InternalList, List<int> ExternalList)\n {\n if (InternalList.Count != ExternalList.Count)\n {\n return false;\n }\n else\n {\n for (int i = 0; i < InternalList.Count; i++)\n {\n if (InternalList[i] != ExternalList[i])\n return false;\n }\n }\n\n return true;\n\n }\n" }, { "answer_id": 2740552, "author": "user329244", "author_id": 329244, "author_profile": "https://Stackoverflow.com/users/329244", "pm_score": 2, "selected": false, "text": "var list1 = new[] { \"Bill\", \"Bob\", \"Sally\" };\nvar list2 = new[] { \"Bob\", \"Bill\", \"Sally\" };\nbool isequal = list1.Compare(list2).IsSame;\n" }, { "answer_id": 4655702, "author": "Allon Guralnek", "author_id": 149265, "author_profile": "https://Stackoverflow.com/users/149265", "pm_score": 6, "selected": false, "text": "SequenceEqual" }, { "answer_id": 9348579, "author": "Desty", "author_id": 664033, "author_profile": "https://Stackoverflow.com/users/664033", "pm_score": 4, "selected": false, "text": "Equals()" }, { "answer_id": 12470106, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 3, "selected": false, "text": " CollectionAssert.AreEquivalent\n" }, { "answer_id": 35963754, "author": "mbadeveloper", "author_id": 3752193, "author_profile": "https://Stackoverflow.com/users/3752193", "pm_score": 0, "selected": false, "text": "public bool CompareStringLists(List<string> list1, List<string> list2)\n{\n if (list1.Count != list2.Count) return false;\n\n foreach(string item in list1)\n {\n if (!list2.Contains(item)) return false;\n }\n\n return true;\n}\n" }, { "answer_id": 39720054, "author": "Chrono", "author_id": 1649245, "author_profile": "https://Stackoverflow.com/users/1649245", "pm_score": 1, "selected": false, "text": "Enumerable.Intersect" }, { "answer_id": 43353457, "author": "ispostback", "author_id": 5893015, "author_profile": "https://Stackoverflow.com/users/5893015", "pm_score": 1, "selected": false, "text": " static void Main()\n{\n // Create a dictionary and add several elements to it.\n var dict = new Dictionary<string, int>();\n dict.Add(\"cat\", 2);\n dict.Add(\"dog\", 3);\n dict.Add(\"x\", 4);\n\n // Create another dictionary.\n var dict2 = new Dictionary<string, int>();\n dict2.Add(\"cat\", 2);\n dict2.Add(\"dog\", 3);\n dict2.Add(\"x\", 4);\n\n // Test for equality.\n bool equal = false;\n if (dict.Count == dict2.Count) // Require equal count.\n {\n equal = true;\n foreach (var pair in dict)\n {\n int value;\n if (dict2.TryGetValue(pair.Key, out value))\n {\n // Require value be equal.\n if (value != pair.Value)\n {\n equal = false;\n break;\n }\n }\n else\n {\n // Require key be present.\n equal = false;\n break;\n }\n }\n }\n Console.WriteLine(equal);\n}\n" }, { "answer_id": 50775030, "author": "Ken Kin", "author_id": 927012, "author_profile": "https://Stackoverflow.com/users/927012", "pm_score": 0, "selected": false, "text": "{1, 2, 3, 4}\n{4, 3, 2, 1}\n" }, { "answer_id": 51903573, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": 1, "selected": false, "text": "SequenceEqual" }, { "answer_id": 63476151, "author": "Denis535", "author_id": 4805491, "author_profile": "https://Stackoverflow.com/users/4805491", "pm_score": 0, "selected": false, "text": "private static void Compare<T>(IEnumerable<T> actual, IEnumerable<T> expected, out IList<T> common, out IList<T> missing, out IList<T> extra) {\n common = new List<T>();\n missing = new List<T>();\n extra = new List<T>();\n\n var expected_ = new LinkedList<T>( expected );\n foreach (var item in actual) {\n if (expected_.Remove( item )) {\n common.Add( item );\n } else {\n extra.Add( item );\n }\n }\n foreach (var item in expected_) {\n missing.Add( item );\n }\n}\n" }, { "answer_id": 71462170, "author": "ErroneousFatality", "author_id": 1445435, "author_profile": "https://Stackoverflow.com/users/1445435", "pm_score": 0, "selected": false, "text": "Dictionary<K, V>" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2348/" ]
43,503
<p>Is there a way to detect if a flash movie contains any sound or is playing any music?<br> It would be nice if this could be done inside a webbrowser (actionscript <strong>from another flash object</strong>, javascript,..) and could be done <em>before</em> the flash movie starts playing.</p> <p>However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated</p>
[ { "answer_id": 43519, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 3, "selected": true, "text": "FIELD DATA TYPE EXAMPLE DESCRIPTION\n Signature byte[3] “FLV” Always “FLV”\n Version uint8 “\\x01” (1) Currently 1 for known FLV files\n Flags uint8 bitmask “\\x05” (5, audio+video) Bitmask: 4 is audio, 1 is video\n Offset uint32-be “\\x00\\x00\\x00\\x09” (9) Total size of header (always 9 for known FLV files) \n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ]
43,507
<p>I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not?</p> <p>Is there anything more to be added to the code that goes into a real world application?</p> <p>What all steps are to be taken to make the application more robust and secure?</p> <p>Here is a sample source code I got from the web:</p> <pre><code>function getChats() { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { return; } var url="getchat.php?latest="+latest; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </code></pre>
[ { "answer_id": 43515, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 0, "selected": false, "text": "new Ajax.Request('/some_url',\n {\n method:'get',\n onSuccess: function(transport){\n var response = transport.responseText || \"no response text\";\n alert(\"Success! \\n\\n\" + response);\n },\n onFailure: function(){ alert('Something went wrong...') }\n });\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
43,511
<p>I have some classes layed out like this</p> <pre><code>class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } class C : B { protected override void SpecialRender() { // Do some cool stuff } } </code></pre> <p>Is it possible to prevent the C class from overriding the Render method, without breaking the following code?</p> <pre><code>A obj = new C(); obj.Render(); // calls B.Render -&gt; c.SpecialRender </code></pre>
[ { "answer_id": 43516, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "public sealed override void Render()\n{\n // Prepare the object for rendering \n SpecialRender();\n // Do some cleanup \n}\n" }, { "answer_id": 43517, "author": "Matt Bishop", "author_id": 4301, "author_profile": "https://Stackoverflow.com/users/4301", "pm_score": 1, "selected": false, "text": "protected override sealed void Render() { ... }\n" }, { "answer_id": 43522, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 2, "selected": false, "text": "class B : A\n{\n public sealed override void Render()\n {\n // Prepare the object for rendering\n SpecialRender();\n // Do some cleanup\n }\n\n protected virtual void SpecialRender()\n {\n }\n}\n" }, { "answer_id": 43531, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "sealed" }, { "answer_id": 43547, "author": "bitbonk", "author_id": 4227, "author_profile": "https://Stackoverflow.com/users/4227", "pm_score": 0, "selected": false, "text": "class A\n{\n public virtual void Render()\n {\n }\n}\nclass B : A\n{\n public override void Render()\n {\n // Prepare the object for rendering \n SpecialRender();\n // Do some cleanup \n }\n protected virtual void SpecialRender()\n {\n }\n}\nclass B2 : B\n{\n public new void Render()\n {\n }\n}\nclass C : B2\n{\n protected override void SpecialRender()\n {\n }\n //public override void Render() // compiler error \n //{\n //}\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3602/" ]
43,524
<p>It is slow to load anything other than a small project. It is slow to quit; it can sometimes take minutes. It can be slow to open new files. The record macro feature used to be useful. It is now so slow to start up it's almost always quicker to do it manually!</p> <hr> <blockquote> <p>More info would be helpful. How big are your solutions? What platform are you on. What 3rd party plugins are you running? What else is running on your pc? </p> </blockquote> <p>3.2GHz P4 Hyperthreaded, 2GB RAM. Running Outlook, Perforce, IE7, directory browsers. Usually have 1-3 instances of VS running. It's much slower than VC6, say. It seems to take a long time to load projects and close down. I'm interested in if people know reasons why this happens, because of the way VS is written. Is it using .net internally and GC slows it down?</p>
[ { "answer_id": 260385, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <windows.h>\n\nint main(char argc, char *argv[])\n{\n printf(\"Hello World\\n\");\n return 0;\n}\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233/" ]
43,525
<p>For some strange, bizarre reason, my images in my website just will not display on webkit based languages (such as safari and chrome).</p> <p>This is the image tag</p> <pre><code>&lt;img src="images/dukkah.jpg" class="imgleft"/&gt; </code></pre> <p>Not only does it not display in the website, it wont display when accessed directly at <code>http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg</code></p> <p>...Why?</p>
[ { "answer_id": 37536836, "author": "Matt", "author_id": 1318694, "author_profile": "https://Stackoverflow.com/users/1318694", "pm_score": 0, "selected": false, "text": "$ curl -s http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg\n<html><head></head><body><!-- vbe --></body></html>\n" } ]
2008/09/04
[ "https://Stackoverflow.com/questions/43525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]