qid
int64
4
19.1M
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 [System.Data.Linq.Mapping.DatabaseAttribute(Name=\"MyDB\")]\npublic partial class MyDataContext : System.Data.Linq.DataContext\n{\n ...\n\n partial void OnCreated();\n partial void InsertMyTable(MyTable instance);\n partial void UpdateMyTable(MyTable instance);\n partial void DeleteMyTable(MyTable instance);\n\n ...\n public partial class MyDataContext\n{\n partial void OnCreated() {\n //do something on data context creation\n }\n}\n //this code will get optimised out if no body is implemented\npartial void DoSomethingIfCompFlag();\n\n#if COMPILER_FLAG\n//this code won't exist if the flag is off\npartial void DoSomethingIfCompFlag() {\n //your code\n}\n#endif\n" } ]
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 [Microsoft.SqlServer.Server.SqlFunction]\npublic static SqlString FormatNumber(SqlInt32 number)\n{\n return number.Value.ToString(\"N0\");\n}\n SELECT dbo.FormatNumber(value)\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 FILEa FILEc FILEf /\n|+-DIR1\n| |- FILEa\n|+-DIR2\n| |- FILEc\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 -r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)\n A revision argument can be one of:\n NUMBER revision number\n '{' DATE '}' revision at start of the date\n 'HEAD' latest in repository\n 'BASE' base rev of item's working copy\n 'COMMITTED' last commit at or before BASE\n 'PREV' revision just before COMMITTED\n svn export -r xxxx:HEAD http://svn/\n" }, { "answer_id": 262104, "author": "bolk", "author_id": 32764, "author_profile": "https://Stackoverflow.com/users/32764", "pm_score": 2, "selected": false, "text": "svn export svn diff --summarize -rXXX http://svn/...\n" } ]
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 about:config" }, { "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 continue throw" }, { "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 return {\n prop: 'yay!'\n}\n// The object literal gets returned as expected and all is well\nreturn\n{\n prop: 'nay!'\n}\n// Oops! return by itself is a perfectly valid statement, so a semicolon\n// is inserted and undefined is unexpectedly returned, rather than the object\n// literal. Note that no error occurred.\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 using System;\nusing System.ComponentModel.Composition;\nusing System.Reflection;\n\nnamespace HelloMEF\n{\n public interface IGreetings\n {\n void Hello();\n }\n\n [Export(typeof(IGreetings))]\n public class Greetings : IGreetings\n {\n public void Hello()\n {\n Console.WriteLine(\"Hello world!\");\n }\n }\n\n class HelloMEF : IDisposable\n {\n private readonly CompositionContainer _container;\n\n [Import(typeof(IGreetings))]\n private IGreetings greetings = null;\n\n public HelloMEF()\n {\n var catalog = new AggregateCatalog();\n catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));\n _container = new CompositionContainer(catalog);\n var batch = new CompositionBatch();\n batch.AddPart(this);\n container.Compose(batch);\n\n }\n\n public void Run()\n {\n greetings.Hello();\n }\n\n public void Dispose()\n {\n _container.Dispose();\n }\n\n static void Main()\n {\n using (var helloMef = new HelloMEF())\n helloMef.Run();\n }\n }\n}\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); $elem 5000 setTimeout()" }, { "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() var left = parseInt($('#element').css('marginLeft'));\n$('#element')\n .animate({ marginLeft: left ? left : 0 }, 5000)\n .fadeOut('fast');\n $('#element')\n .animate({ marginLeft: 0 }, 5000)\n .fadeOut('fast');\n $('#element').fadeOut({\n speed: 'fast',\n preDelay: 5000\n});\n" }, { "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() $('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();\n" }, { "answer_id": 3040106, "author": "thekingoftruth", "author_id": 241367, "author_profile": "https://Stackoverflow.com/users/241367", "pm_score": 1, "selected": false, "text": "remove() remove() $('#foo').fadeIn(500).delay(5000).fadeOut(500);\n" }, { "answer_id": 7735285, "author": "rjmoggach", "author_id": 586932, "author_profile": "https://Stackoverflow.com/users/586932", "pm_score": 0, "selected": false, "text": "fadeOut $('#foo').delay(2000).fadeOut(2000);\n" } ]
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 Response.Expires=-1" }, { "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> class=\"wrapper\" </div> wrapper <div class=\"push\"></div> </div> wrapper <div class=\"footer\"></div> * {\n margin: 0;\n}\nhtml, body {\n height: 100%;\n}\n.wrapper {\n min-height: 100%;\n height: auto !important;\n height: 100%;\n margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */\n}\n.footer, .push {\n height: 142px; /* .push must be the same height as .footer */\n}\n" }, { "answer_id": 42314, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 4, "selected": false, "text": "#footer position: absolute;\nbottom: 0;\n padding margin #sidebar #content #footer #footer bottom: 0" }, { "answer_id": 42315, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 5, "selected": false, "text": "position: absolute margin-bottom #footer {\n position: absolute;\n bottom: 0px;\n width: 100%;\n}\n#content, #sidebar { \n margin-bottom: 5em; \n}\n" }, { "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 css( 'margin-top', height_diff + 50 )\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; div position: relative; min-height: 100%; div z-index div <!doctype html>\n<html>\n <head>\n <title>Sticky Footer</title>\n <meta charset=\"utf-8\">\n <style>\n .wrapper { position: relative; min-height: 100%; }\n .footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; }\n .column { height: 2000px; padding-bottom: 300px; background-color: grxqeen; }\n /* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */\n </style>\n </head>\n <body>\n <div class=\"wrapper\">\n <div class=\"column\">\n <span>hello</span>\n </div>\n <div class=\"footer\">\n <p>This is a test. This is only a test...</p>\n </div>\n </div>\n </body>\n</html>" }, { "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 .content {\n min-height: calc(100vh - 120px);\n /* 80px header + 40px footer = 120px */\n}\n * {\n margin:0;\n padding:0;\n}\nheader {\n background: yellow;\n height: 80px;\n}\n.content {\n min-height: calc(100vh - 120px);\n /* 80px header + 40px footer = 120px */\n background: pink;\n}\nfooter {\n height: 40px;\n background: aqua;\n} <header>header goes here</header>\n<div class=\"content\">This page has little content</div>\n<footer>This is my footer</footer> * {\n margin:0;\n padding:0;\n}\nheader {\n background: yellow;\n height: 80px;\n}\n.content {\n min-height: calc(100vh - 120px);\n /* 80px header + 40px footer = 120px */\n background: pink;\n}\nfooter {\n height: 40px;\n background: aqua;\n} <header>header goes here</header>\n<div class=\"content\">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.\n</div>\n<footer>\n This is my footer\n</footer> * {\n margin:0;padding:0;\n}\nheader {\n background: yellow;\n height: 80px;\n position:relative;\n}\n.content {\n min-height: 100vh;\n background: pink;\n margin: -80px 0 -40px;\n padding: 80px 0 40px;\n box-sizing:border-box;\n}\nfooter {\n height: 40px;\n background: aqua;\n} <header>header goes here</header>\n<div class=\"content\">Lorem ipsum \n</div>\n<footer>\n This is my footer\n</footer>" }, { "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 <div id=\"container\">\n <div class=\"footer\">\n </div>\n </div>\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 flex flex-grow flow-direction column row vh 1vh 100vh ----------- body -----------\n----------------------------\n\n---------- footer ----------\n----------------------------\n ----------- body -----------\n----------------------------\n\n---------- spacer ----------\n <- This element must grow in height\n----------------------------\n\n---------- footer ----------\n----------------------------\n body {\n margin: 0;\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\n.spacer {\n flex: 1;\n}\n\n/* make it visible for the purposes of demo */\n.footer {\n height: 50px;\n background-color: red;\n} <body>\n <div class=\"content\">Hello World!</div>\n <div class=\"spacer\"></div>\n <footer class=\"footer\"></footer>\n</body> flex-shrink flex-shrink .content footer .content {\n flex-shrink: 0;\n}\n\n.footer {\n flex-shrink: 0;\n}\n flex spacer .spacer {\n flex: 1 0 auto;\n}\n .spacer {\n flex-grow: 1;\n flex-shrink: 0;\n flex-basis: auto;\n}\n" }, { "answer_id": 34823140, "author": "DevWL", "author_id": 2179965, "author_profile": "https://Stackoverflow.com/users/2179965", "pm_score": 0, "selected": false, "text": "auto fix $.footerBottom({target:\"footer\"}); //as html5 tag <footer>.\n// You can change it to your preferred \"div\" with for example class \"footer\" \n// by setting target to {target:\"div.footer\"}\n //import jQuery library before this script\n // Import jQuery library before this script\n\n// Our custom jQuery Plugin\n(function($) {\n $.footerBottom = function(options) { // Or use \"$.fn.footerBottom\" or \"$.footerBottom\" to call it globally directly from $.footerBottom();\n var defaults = {\n target: \"footer\",\n container: \"html\",\n innercontainer: \"body\",\n css: {\n footer: {\n position: \"absolute\",\n left: 0,\n bottom: 0,\n },\n\n html: {\n position: \"relative\",\n minHeight: \"100%\"\n }\n }\n };\n\n options = $.extend(defaults, options);\n\n // JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE\n $(options.target).css({\n \"position\": options.css.footer.position,\n \"left\": options.css.footer.left,\n \"bottom\": options.css.footer.bottom,\n });\n\n $(options.container).css({\n \"position\": options.css.html.position,\n \"min-height\": options.css.html.minHeight,\n });\n\n function logic() {\n var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height\n $(options.innercontainer).css('padding-bottom', footerOuterHeight + \"px\"); // Set padding equal to footer height on body element\n $(options.target).css('height', footerOuterHeight + \"!important\"); // Set outerHeight of footer element to ... footer\n console.log(\"jQ custom plugin footerBottom runs\"); // Display text in console so ou can check that it works in your browser. Delete it if you like.\n };\n\n // DEFINE WHEN TO RUN FUNCTION\n $(window).on('load resize', function() { // Run on page loaded and on window resized\n logic();\n });\n\n // RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE\n // return this.each(function() {\n // this.checked = true;\n // });\n // return this;\n };\n})(jQuery); // End of plugin\n\n\n// USE EXAMPLE\n$.footerBottom(); // Run our plugin with all default settings for HTML5 /* Set your footer CSS to what ever you like it will work anyway */\nfooter {\n box-sizing: border-box;\n height: auto;\n width: 100%;\n padding: 30px 0;\n background-color: black;\n color: white;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->\n<body>\n <div class=\"content\">\n <header>\n <nav>\n <ul>\n <li>link</li>\n <li>link</li>\n <li>link</li>\n <li>link</li>\n <li>link</li>\n <li>link</li>\n </ul>\n </nav>\n </header>\n\n <section>\n <p></p>\n <p>Lorem ipsum...</p>\n </section>\n </div>\n <footer>\n <p>Copyright 2009 Your name</p>\n <p>Copyright 2009 Your name</p>\n <p>Copyright 2009 Your name</p>\n </footer>" }, { "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} <body>\n <div class=\"body\">test as body</div>\n <div class=\"footer\">test as footer</div>\n</body>" }, { "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 footer.init(document.getElementById(\"ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER\"));\n @media only screen and (min-height: 768px) {/* or height/length of body content including footer*/\n /* For mobile phones: */\n #footer {\n width: 100%;\n position:fixed;\n bottom:0;\n }\n}\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 html {\n height: 100%;\n}\n\nbody {\n height: 100%;\n min-height: 100vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n margin: 0;\n display: flex;\n flex-direction: column;\n}\n\nmain {\n flex-grow: 1;\n flex-shrink: 0;\n}\n\nheader,\nfooter {\n flex: none;\n}\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 body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n margin:0;\n}\n\n.content {\n padding: 50px;\n background: red;\n}\n\n.footer {\n margin-top: auto;\n padding:10px;\n background: green;\n} <div class=\"content\">\n some content here\n</div>\n<footer class=\"footer\">\n some content\n</footer>" }, { "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% margin: 0 html, body {height: 100%}\n\nbody {\n display: grid; /* generates a block-level grid */\n align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */\n margin: 0;\n}\n\n.content {\n background: lightgreen;\n /* demo / for default snippet window */\n height: 1em;\n animation: height 2.5s linear alternate infinite;\n}\n\nfooter {background: lightblue}\n\n@keyframes height {to {height: 250px}} <div class=\"content\">Content</div>\n<footer>Footer</footer> align-content: space-between" }, { "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} <body style=\"height:1500px\">\n\n <h2>position: fixed;</h2>\n\n <p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>\n\n <div class=\"fixed\">\n This div element has position: fixed;\n </div>\n\n</body>" }, { "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 min-height: 100%; position: relative; position: absolute; bottom: 0; left: 0;" }, { "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;} <body>\n <div class=\"content\">Page Content - height expands to fill space</div>\n <footer class=\"footer\">Footer Content</footer>\n</body>" }, { "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 .parent {\n display: grid;\n height: 95vh; /* no scroll bars if few content */\n grid-template-rows: auto 1fr auto;\n}\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 body 100% html,\nbody {\n width: 100%;\n height: 100%;\n}\n flex column body { \n min-height: 100%;\n display: flex;\n flex-direction: column;\n}\n flex-grow: 1 main {\n flex-grow: 1;\n}\n flex-grow *, \n*::after,\n*::before{\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\nhtml,\nbody {\n width: 100%;\n height: 100%;\n}\n\nbody {\n min-height: 100%;\n display: flex;\n flex-direction: column;\n}\n\nmain {\n flex-grow: 1;\n}\n\nfooter{\n background-color: black;\n color: white;\n padding: 1rem 0;\n display: flex; \n justify-content: center;\n align-items: center;\n} <body> \n <main>\n <section >\n Hero\n </section>\n </main>\n\n <footer >\n <div>\n <p > &copy; Copyright 2021</p>\n </div>\n </footer>\n</body>" }, { "answer_id": 73325579, "author": "Shubham Sarda", "author_id": 7846238, "author_profile": "https://Stackoverflow.com/users/7846238", "pm_score": 0, "selected": false, "text": "<main> <body>\n <header>\n <!╌ nav, logo ╌> \n </header>\n <main>\n <!╌ section and div ╌> \n </main>\n <footer>\n <!╌ nav, logo ╌>\n </footer>\n</body>\n main{\n min-height: 90vh;\n}\n" } ]
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 function 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": 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 clientWidth // width in pixels\nfunction setImagesWidth(id, width)\n{\n var images = document.getElementById(id).getElementsByTagName(\"img\");\n var newWidth = width + \"px\";\n for (var i = 0; i < images.length; ++i)\n {\n if (images[i].clientWidth > width)\n {\n images[i].style.width = newWidth;\n } \n }\n}\n" }, { "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 var img = document.getElementById(\"img\");\n var width = img.naturalWidth;\n var height = img.naturalHeight;\n document.getElementById(\"info\").innerHTML = \"HTML Dimensions: \"+img.width+\" x \"+img.height + \n \"\\nReal pixel dimensions:\"+ \n width+\" x \"+height; <img id=\"img\" src=\"http://upload.wikimedia.org/wikipedia/commons/0/03/Circle-withsegments.svg\" width=\"100\">\n\n<pre id=\"info\">\n\n</pre>" } ]
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 VideoPlayer Video mx_internal videoDisplay.mx_internal::videoPlayer.attachNetStream(incomingStream);\nvideoDisplay.mx_internal::videoPlayer.visible = true;\n mx.core.mx_internal" }, { "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 2001:0db8:0000:0000:0000:0000:1428:57ab*\n2001:0db8:0000:0000:0000::1428:57ab*\n2001:0db8:0:0:0:0:1428:57ab*\n2001:0db8:0:0::1428:57ab\n2001:0db8::1428:57ab\n2001:db8::1428:57ab\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 CAST (0x SELECT UPDATE POST" }, { "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() node.addChildInternal() 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 object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;\n var a = b ?? c;\n var a = b != null ? b : c;\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 <?php\n//MySQL query stuff here\n$result = mysql_query($sql, $link) or die(\"Opps\");\nwhile($row = mysql_fetch_assoc($result))\n{\n$_SESSION['fName'] = $row['fName'];\n$_SESSION['lName'] = $row['lName'];\n//...\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 while ! = int i=0; \nwhile (i != 10)\n{ \n Console.WriteLine(i); \n i++; \n}\n i = 0\nwhile i != 10:\n print i\n i += 1\n" }, { "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 i" } ]
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 ItemCommand RepeaterCommandEventArgs void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)\n {\n // Stuff to databind\n Button myButton = (Button)e.Item.FindControl(\"myButton\");\n\n myButton.CommandName = \"Add\";\n myButton.CommandArgument = \"Some Identifying Argument\";\n }\n}\n\nvoid rptr_ItemCommand(object source, RepeaterCommandEventArgs e)\n{\n if (e.CommandName == \"Add\")\n {\n // Do your event\n }\n}\n" }, { "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 Description: Mono Mozilla library\n Mono is a platform for running and developing applications based on the\n ECMA/ISO Standards. Mono is an open source effort led by Novell.\n Mono provides a complete CLR (Common Language Runtime) including compiler and\n runtime, which can produce and execute CIL (Common Intermediate Language)\n bytecode (aka assemblies), and a class library.\n .\n This package contains the implementation of the WebControl class based on the\n Mozilla engine using libgluezilla.\nHomepage: http://www.mono-project.com/\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 Dispose" }, { "answer_id": 42501, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "IDisposable Dispose" }, { "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 Dispose" }, { "answer_id": 42501, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "IDisposable Dispose" }, { "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 SetWindowsHookEx() KeyPreview" } ]
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() MemoryStream IO.Stream 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 OpaqueFrame // OpaqueFrame\n//\n// OpaqueFrame is a CustomFrameWindow subclass that in conjunction with\n// OpaqueNonClientView provides the window frame on Windows XP and on Windows\n// Vista when DWM desktop compositing is disabled. The window title and\n// borders are provided with bitmaps. src\\chrome\\app\\theme" } ]
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 try:\n from xml.etree.cElementTree import XML\nexcept ImportError:\n from xml.etree.ElementTree import XML\nimport zipfile\n\n\n\"\"\"\nModule that extract text from MS XML Word document (.docx).\n(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)\n\"\"\"\n\nWORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'\nPARA = WORD_NAMESPACE + 'p'\nTEXT = WORD_NAMESPACE + 't'\n\n\ndef get_docx_text(path):\n \"\"\"\n Take the path of a docx file as argument, return the text in unicode.\n \"\"\"\n document = zipfile.ZipFile(path)\n xml_content = document.read('word/document.xml')\n document.close()\n tree = XML(xml_content)\n\n paragraphs = []\n for paragraph in tree.getiterator(PARA):\n texts = [node.text\n for node in paragraph.getiterator(TEXT)\n if node.text]\n if texts:\n paragraphs.append(''.join(texts))\n\n return '\\n\\n'.join(paragraphs)\n" }, { "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 #!/usr/bin/env python\nfrom tika import parser\nparsed = parser.from_file('/path/to/file')\nprint(parsed[\"metadata\"]) #To get the meta data of the file\nprint(parsed[\"content\"]) # To get the content of the file\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 import textractplus as tp\ntext=tp.process('path/to/yourfile.doc')\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 iter \ndef get_docx_text(path):\n \"\"\"\n Take the path of a docx file as argument, return the text in unicode.\n \"\"\"\n document = zipfile.ZipFile(path)\n xml_content = document.read('word/document.xml')\n document.close()\n tree = XML(xml_content)\n\n paragraphs = []\n for paragraph in tree.iter(PARA):\n texts = [node.text\n for node in paragraph.iter(TEXT)\n if node.text]\n if texts:\n paragraphs.append(''.join(texts))\n\n return '\\n\\n'.join(paragraphs)\n" } ]
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 public partial class updateProgressTest : System.Web.UI.Page\n{\n protected void btnTest_OnClick(object sender, EventArgs e)\n {\n System.Threading.Thread.Sleep(1000);\n this.lblTest.Text = \"I was changed on the server! Yay!\";\n }\n}\n" }, { "answer_id": 1433511, "author": "Adiel", "author_id": 85045, "author_profile": "https://Stackoverflow.com/users/85045", "pm_score": 0, "selected": false, "text": "float:left <style type=\"text/css\">\n.tbx \n{\n float:left;\n}\n <asp:TextBox CssClass=\"tbx\" .... />\n" }, { "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 .load-inline {display:inline-block}\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 <asp:UpdateProgress class=\"progress\" ID=\"UpdateProgress1\" runat=\"server\">\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 value" }, { "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 synchronized" }, { "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 // thread 1 is running this code\n if(value == 0) \n {\n value = 1; \n // RIGHT NOW, thread 2 steps in.\n // It sees value as 1, so runs the other branch, and changes it to 0\n // This causes your method to return 0 even though you actually want 1\n }\n else if(value == 1) \n { \n value = 0; \n }\n return value;\n something something // we read value here\n if(value == 0) \n {\n value = 1; \n }\n else if(value == 1) \n { \n value = 0; \n }\n // and we return it here\n return value;\n value return value lock( value )\n{\n if(value == 0) \n ... // all your code here\n return value;\n}\n" } ]
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 Storage IAM & Admin Service account" }, { "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 1 5 9 3 \n2 6 0 4 \n3 7 1 5 \n4 8 2 6 \n\n4 3 2 1 \n8 7 6 5 \n2 1 0 9 \n6 5 4 3\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 Matrix class RotatedMatrix : IReadableMatrix\n{\n private readonly IReadableMatrix _baseMatrix;\n\n public RotatedMatrix(IReadableMatrix baseMatrix)\n {\n _baseMatrix = baseMatrix;\n }\n\n int GetValue(int x, int y)\n {\n // transpose x and y dimensions\n return _baseMatrix(y, x);\n }\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 rotated_ccw = list(zip(*original))[::-1]\n zip(*original) * >>> list(zip(*[[1,2,3],[4,5,6],[7,8,9]]))\n[[1,4,7],[2,5,8],[3,6,9]]\n [::-1] >>> [[1,2,3],[4,5,6],[7,8,9]][::-1]\n[[7,8,9],[4,5,6],[1,2,3]]\n [::-1]" }, { "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 array_map() $array = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 0, 1, 2],\n [3, 4, 5, 6]\n];\n$transposed = array_map(null, ...$array);\n [\n [1, 5, 9, 3],\n [2, 6, 0, 4],\n [3, 7, 1, 5],\n [4, 8, 2, 6]\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 private int[][] rotate(int[][] arr) {\n int width = arr[0].length;\n int depth = arr.length;\n int[][] re = new int[width][depth];\n for (int i = 0; i < depth; i++) {\n for (int j = 0; j < width; j++) {\n re[j][depth - i - 1] = arr[i][j];\n }\n }\n return re;\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 dest[j][n-1-i] = src[i][j]\n function rotate(array, N)\n{\n Rotate outer-most data\n rotate a new array with N-2 or you can do the similar action following step1\n}\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 13 9 5 1\n14 10 6 2 \n15 11 7 3\n16 12 8 4\n 1 4\n\n\n13 16\n 2\n 8\n9 \n 15\n 3\n5 \n 12\n 14\n 6 7\n10 11\n [0,0] -> [0,n-1], [0,n-1] -> [n-1,n-1], [n-1,n-1] -> [n-1,0], and [n-1,0] -> [0,0]\n[0,1] -> [1,n-1], [1,n-2] -> [n-1,n-2], [n-1,n-2] -> [n-2,0], and [n-2,0] -> [0,1]\n[0,2] -> [2,n-2], [2,n-2] -> [n-1,n-3], [n-1,n-3] -> [n-3,0], and [n-3,0] -> [0,2]\n [0,i] -> [i,n-i], [i,n-i] -> [n-1,n-(i+1)], [n-1,n-(i+1)] -> [n-(i+1),0], and [n-(i+1),0] to [0,i]\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 original = [ [7,8,9],\n [4,5,6],\n [1,2,3] ]\n original = [[7,8,9],\n [4,5,6],\n [1,2,3]]\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 $array = array_reverse($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 1 4 7\nA' = 2 5 8\n 3 6 9\n 7 4 1 3 6 9\nA'B = 8 5 2 BA' = 2 5 8\n 9 6 3 1 4 7\n void swapInSpace(int** mat, int r1, int c1, int r2, int c2)\n{\n mat[r1][c1] ^= mat[r2][c2];\n mat[r2][c2] ^= mat[r1][c1];\n mat[r1][c1] ^= mat[r2][c2];\n}\n\nvoid transpose(int** mat, int size)\n{\n for (int i = 0; i < size; i++)\n {\n for (int j = (i + 1); j < size; j++)\n {\n swapInSpace(mat, i, j, j, i);\n }\n }\n}\n\nvoid rotate(int** mat, int size)\n{\n //Get transpose\n transpose(mat, size);\n\n //Swap columns\n for (int i = 0; i < size / 2; i++)\n {\n for (int j = 0; j < size; j++)\n {\n swapInSpace(mat, i, j, size - (i + 1), j);\n }\n }\n}\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); // Get an array element rotated 90 degrees clockwise\nfunction getArray2dCW(a, x, y) {\n var t = x;\n x = y;\n y = a.length - t - 1;\n return a[y][x];\n}\n\n//demo\nvar arr = [\n [5, 4, 6],\n [1, 7, 9],\n [-2, 11, 0],\n [8, 21, -3],\n [3, -1, 2]\n];\n\nvar newarr = [];\narr[0].forEach(() => newarr.push(new Array(arr.length)));\n\nfor (var i = 0; i < newarr[0].length; i++) {\n for (var j = 0; j < newarr.length; j++) {\n newarr[j][i] = getArray2dCW(arr, i, j);\n }\n}\nconsole.log(newarr); // Get an array element rotated 90 degrees counter-clockwise\nfunction getArray2dCCW(a, x, y) {\n var t = x;\n x = a[0].length - y - 1;\n y = t;\n return a[y][x];\n}\n\n//demo\nvar arr = [\n [5, 4, 6],\n [1, 7, 9],\n [-2, 11, 0],\n [8, 21, -3],\n [3, -1, 2]\n];\n\nvar newarr = [];\narr[0].forEach(() => newarr.push(new Array(arr.length)));\n\nfor (var i = 0; i < newarr[0].length; i++) {\n for (var j = 0; j < newarr.length; j++) {\n newarr[j][i] = getArray2dCCW(arr, i, j);\n }\n}\nconsole.log(newarr); // Get an array element rotated 180 degrees\nfunction getArray2d180(a, x, y) {\n x = a[0].length - x - 1;\n y = a.length - y - 1;\n return a[y][x];\n}\n\n//demo\nvar arr = [\n [5, 4, 6],\n [1, 7, 9],\n [-2, 11, 0],\n [8, 21, -3],\n [3, -1, 2]\n];\n\nvar newarr = [];\narr.forEach(() => newarr.push(new Array(arr[0].length)));\n\nfor (var i = 0; i < newarr[0].length; i++) {\n for (var j = 0; j < newarr.length; j++) {\n newarr[j][i] = getArray2d180(arr, i, j);\n }\n}\nconsole.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 Enter matrix elements:\n element[0,0]=1\n element[0,1]=2\n element[0,2]=3\n element[0,3]=4\n element[1,0]=5\n element[1,1]=6\n element[1,2]=7\n element[1,3]=8\n element[2,0]=9\n element[2,1]=10\n element[2,2]=11\n element[2,3]=12\n Matrix elements are:\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n Matrix rotated at 90 deg are:\n 9 5 1\n 10 6 2\n 11 7 3\n 12 8 4\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 Input:\n M A C P \n B N L D \n Y E T S \n I W R Z \n\n Output:\n I Y B M \n W E N A \n R T L C \n Z S D P \n\n/**\n * (c) @author \"G A N MOHIM\"\n * Oct 3, 2015\n * RotateArrayNintyDegree.java\n */\npackage rotatearray;\n\npublic class RotateArrayNintyDegree {\n\n public char[][] rotateArrayNinetyDegree(char[][] input) {\n int k; // k is used to generate index for output array\n\n char[][] output = new char[input.length] [input[0].length];\n\n for (int i = 0; i < input.length; i++) {\n k = 0;\n for (int j = input.length-1; j >= 0; j--) {\n output[i][k] = input[j][i]; // note how i is used as column index, and j as row\n k++;\n }\n }\n\n return output;\n }\n\n public void printArray(char[][] charArray) {\n for (int i = 0; i < charArray.length; i++) {\n for (int j = 0; j < charArray[0].length; j++) {\n System.out.print(charArray[i][j] + \" \");\n }\n System.out.println();\n }\n\n\n }\n\n public static void main(String[] args) {\n char[][] input = \n { {'M', 'A', 'C', 'P'},\n {'B', 'N', 'L', 'D'},\n {'Y', 'E', 'T', 'S'},\n {'I', 'W', 'R', 'Z'}\n };\n\n char[][] output = new char[input.length] [input[0].length];\n\n RotateArrayNintyDegree rotationObj = new RotateArrayNintyDegree();\n rotationObj.printArray(input);\n\n System.out.println(\"\\n\");\n output = rotationObj.rotateArrayNinetyDegree(input);\n rotationObj.printArray(output);\n\n }\n\n}\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 1 4 7\n 2 5 8\n 3 6 9\n 3 6 9\n 2 5 8\n 1 4 7\n public class MyClass {\n\n public static void main(String args[]) {\n Demo obj = new Demo();\n /*initial matrix to rotate*/\n int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };\n int[][] transpose = new int[3][3]; // matrix to store transpose\n\n obj.display(matrix); // initial matrix\n\n obj.rotate(matrix, transpose); // call rotate method\n System.out.println();\n obj.display(transpose); // display the rotated matix\n }\n}\n\nclass Demo { \n public void rotate(int[][] mat, int[][] tran) {\n\n /* First take the transpose of the matrix */\n for (int i = 0; i < mat.length; i++) {\n for (int j = 0; j < mat.length; j++) {\n tran[i][j] = mat[j][i]; \n }\n }\n\n /*\n * Interchange the rows of the transpose matrix to get rotated\n * matrix\n */\n for (int i = 0, j = tran.length - 1; i != j; i++, j--) {\n for (int k = 0; k < tran.length; k++) {\n swap(i, k, j, k, tran);\n }\n }\n }\n\n public void swap(int a, int b, int c, int d, int[][] arr) {\n int temp = arr[a][b];\n arr[a][b] = arr[c][d];\n arr[c][d] = temp; \n }\n\n /* Method to display the matrix */\n public void display(int[][] arr) {\n for (int i = 0; i < arr.length; i++) {\n for (int j = 0; j < arr.length; j++) {\n System.out.print(arr[i][j] + \" \");\n }\n System.out.println();\n }\n }\n}\n 1 2 3 \n4 5 6 \n7 8 9 \n\n3 6 9 \n2 5 8 \n1 4 7 \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": ". . .\n. .\n . . .\n. . .\n. . .\n . . . .\n. . . .\n. . . .\n. . . .\n 0 1\n2 3\n 2 0\n3 1\n def rotate(matrix):\n # Algorithm goes here.\n matrix = [\n [0,1],\n [2,3]\n]\n matrix[row][column]\n def print_matrix(matrix):\n for row in matrix:\n print row\n . .\n. .\n . . .\n. x .\n. . .\n . . . .\n. x x .\n. x x .\n. . . .\n . . . . .\n. x x x .\n. x O x .\n. x x x .\n. . . . .\n . . . . . .\n. x x x x .\n. x O O x .\n. x O O x .\n. x x x x .\n. . . . . .\n . . . . . . .\n. x x x x x .\n. x O O O x .\n. x O - O x .\n. x O O O x .\n. x x x x x .\n. . . . . . .\n +-----+--------+\n| N×N | Layers |\n+-----+--------+\n| 1×1 | 1 |\n| 2×2 | 1 |\n| 3×3 | 2 |\n| 4×4 | 2 |\n| 5×5 | 3 |\n| 6×6 | 3 |\n| 7×7 | 4 |\n+-----+--------+\n +-----+--------+------------------+\n| N×N | Layers | Rotatable Layers |\n+-----+--------+------------------+\n| 1×1 | 1 | 0 |\n| 2×2 | 1 | 1 |\n| 3×3 | 2 | 1 |\n| 4×4 | 2 | 2 |\n| 5×5 | 3 | 2 |\n| 6×6 | 3 | 3 |\n| 7×7 | 4 | 3 |\n+-----+--------+------------------+\n +-----+--------+------------------+---------+\n| N×N | Layers | Rotatable Layers | N/2 |\n+-----+--------+------------------+---------+\n| 1×1 | 1 | 0 | 1/2 = 0 |\n| 2×2 | 1 | 1 | 2/2 = 1 |\n| 3×3 | 2 | 1 | 3/2 = 1 |\n| 4×4 | 2 | 2 | 4/2 = 2 |\n| 5×5 | 3 | 2 | 5/2 = 2 |\n| 6×6 | 3 | 3 | 6/2 = 3 |\n| 7×7 | 4 | 3 | 7/2 = 3 |\n+-----+--------+------------------+---------+\n N/2 def rotate(matrix):\n size = len(matrix)\n # Rotatable layers only.\n layer_count = size / 2\n . . . . .\n. x x x .\n. x O x .\n. x x x .\n. . . . .\n +--------+-----------+\n| Column | 0 1 2 3 4 |\n+--------+-----------+\n| | . . . . . |\n| | . x x x . |\n| | . x O x . |\n| | . x x x . |\n| | . . . . . |\n+--------+-----------+\n +-----+-----------+\n| Row | |\n+-----+-----------+\n| 0 | . . . . . |\n| 1 | . x x x . |\n| 2 | . x O x . |\n| 3 | . x x x . |\n| 4 | . . . . . |\n+-----+-----------+\n +-----------+---------+---------+---------+\n| Layer | Rows | Columns | Rotate? |\n+-----------+---------+---------+---------+\n| Outermost | 0 and 4 | 0 and 4 | Yes |\n| Inner | 1 and 3 | 1 and 3 | Yes |\n| Innermost | 2 | 2 | No |\n+-----------+---------+---------+---------+\n def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n\n for layer in range(0, layer_count):\n first = layer\n last = size - first - 1\n print 'Layer %d: first: %d, last: %d' % (layer, first, last)\n\n# 5x5 matrix\nmatrix = [\n [ 0, 1, 2, 3, 4],\n [ 5, 6, 6, 8, 9],\n [10,11,12,13,14],\n [15,16,17,18,19],\n [20,21,22,23,24]\n]\n\nrotate(matrix)\n Layer 0: first: 0, last: 4\nLayer 1: first: 1, last: 3\n first last +--------+-----------+\n| Column | 0 1 2 3 4 |\n+--------+-----------+\n| | . . . . . |\n| | . x x x . |\n| | . x O x . |\n| | . x x x . |\n| | . . . . . |\n+--------+-----------+\n\n+-----+-----------+\n| Row | |\n+-----+-----------+\n| 0 | . . . . . |\n| 1 | . x x x . |\n| 2 | . x O x . |\n| 3 | . x x x . |\n| 4 | . . . . . |\n+-----+-----------+\n 0 1 2\n3 4 5\n6 7 8\n +-----+-------+\n| Col | 0 1 2 |\n+-----+-------+\n| | 0 1 2 |\n| | 3 4 5 |\n| | 6 7 8 |\n+-----+-------+\n\n+-----+-------+\n| Row | |\n+-----+-------+\n| 0 | 0 1 2 |\n| 1 | 3 4 5 |\n| 2 | 6 7 8 |\n+-----+-------+\n first last def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n\n # Our layer loop i=0, i=1, i=2\n for layer in range(0, layer_count):\n\n first = layer\n last = size - first - 1\n \n # We want to move within a layer here.\n first last +---------------+-------------------+-------------+\n| Corner | Position | 3x3 Values |\n+---------------+-------------------+-------------+\n| top left | (first, first) | (0,0) |\n| top right | (first, last) | (0,2) |\n| bottom right | (last, last) | (2,2) |\n| bottom left | (last, first) | (2,0) |\n+---------------+-------------------+-------------+\n * * 1 *\n3 4 5\n* 7 *\n * * first last def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n for layer in range(0, layer_count):\n\n first = layer\n last = size - first - 1\n\n top_left = (first, first)\n top_right = (first, last)\n bottom_right = (last, last)\n bottom_left = (last, first)\n\n print 'top_left: %s' % (top_left)\n print 'top_right: %s' % (top_right)\n print 'bottom_right: %s' % (bottom_right)\n print 'bottom_left: %s' % (bottom_left)\n\nmatrix = [\n[0, 1, 2],\n[3, 4, 5],\n[6, 7, 8]\n]\n\nrotate(matrix)\n top_left: (0, 0)\ntop_right: (0, 2)\nbottom_right: (2, 2)\nbottom_left: (2, 0)\n def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n for layer in range(0, layer_count):\n \n first = layer\n last = size - first - 1\n\n top_left = matrix[first][first]\n top_right = matrix[first][last]\n bottom_right = matrix[last][last]\n bottom_left = matrix[last][first]\n\n # bottom_left -> top_left\n matrix[first][first] = bottom_left\n # top_left -> top_right\n matrix[first][last] = top_left\n # top_right -> bottom_right\n matrix[last][last] = top_right\n # bottom_right -> bottom_left\n matrix[last][first] = bottom_right\n\n\nprint_matrix(matrix)\nprint '---------'\nrotate(matrix)\nprint_matrix(matrix)\n [0, 1, 2]\n[3, 4, 5]\n[6, 7, 8]\n [6, 1, 0]\n[3, 4, 5]\n[8, 7, 2]\n matrix = [\n[0, 1, 2, 3, 4],\n[5, 6, 7, 8, 9],\n[10, 11, 12, 13, 14],\n[15, 16, 17, 18, 19],\n[20, 21, 22, 23, 24]\n]\nprint_matrix(matrix)\nprint '--------------------'\nrotate(matrix)\nprint_matrix(matrix)\n [20, 1, 2, 3, 0]\n[ 5, 16, 7, 6, 9]\n[10, 11, 12, 13, 14]\n[15, 18, 17, 8, 19]\n[24, 21, 22, 23, 4]\n first last first last def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n \n # Move through layers (i.e. layer loop).\n for layer in range(0, layer_count):\n \n first = layer\n last = size - first - 1\n\n # Move within a single layer (i.e. element loop).\n for element in range(first, last):\n \n offset = element - first\n\n # 'element' increments column (across right)\n top = (first, element)\n # 'element' increments row (move down)\n right_side = (element, last)\n # 'last-offset' decrements column (across left)\n bottom = (last, last-offset)\n # 'last-offset' decrements row (move up)\n left_side = (last-offset, first)\n\n print 'top: %s' % (top)\n print 'right_side: %s' % (right_side)\n print 'bottom: %s' % (bottom)\n print 'left_side: %s' % (left_side)\n def rotate(matrix):\n size = len(matrix)\n layer_count = size / 2\n\n for layer in range(0, layer_count):\n first = layer\n last = size - first - 1\n\n for element in range(first, last):\n offset = element - first\n\n top = matrix[first][element]\n right_side = matrix[element][last]\n bottom = matrix[last][last-offset]\n left_side = matrix[last-offset][first]\n\n matrix[first][element] = left_side\n matrix[element][last] = top\n matrix[last][last-offset] = right_side\n matrix[last-offset][first] = bottom\n 0, 1, 2 \n3, 4, 5 \n6, 7, 8 \n rotate 6, 3, 0 \n7, 4, 1 \n8, 5, 2 \n" }, { "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 _values Matrix<TValue> [][] result = new TValue[Columns, Rows] Matrix<TValue> Columns Rows public uint Columns \n => (uint)_values[0].Length;\n\npublic uint Rows \n => (uint)_values.Length;\n public Matrix<TValue> Rotate(int rotation)\n{\n var _rotation = (double)rotation / 90d;\n\n if (_rotation - Math.Floor(_rotation) > 0)\n {\n throw new NotSupportedException(\"A matrix may only be rotated by multiples of 90.\").\n }\n\n rotation = (int)_rotation;\n ...\n}\n double int int double" }, { "answer_id": 50540508, "author": "Crashalot", "author_id": 144088, "author_profile": "https://Stackoverflow.com/users/144088", "pm_score": 0, "selected": false, "text": "matrix func rotate(matrix: [[Int]]) -> [[Int]] {\n let transposedPoints = transpose(input: matrix)\n let rotatedPoints = transposedPoints.map{ Array($0.reversed()) }\n return rotatedPoints\n}\n\n\nfileprivate func transpose<T>(input: [[T]]) -> [[T]] {\n if input.isEmpty { return [[T]]() }\n let count = input[0].count\n var out = [[T]](repeating: [T](), count: count)\n for outer in input {\n for (index, inner) in outer.enumerated() {\n out[index].append(inner)\n }\n }\n\n return out\n}\n" }, { "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 [0,1,2,3,4,5,6,7,8] [2,5,8,1,4,7,0,3,6] indexes rotated //n=3\nrotate([\n 1, 2, 3,\n 4, 5, 6,\n 7, 8, 9], 3))\n\n//result:\n[7, 4, 1,\n 8, 5, 2,\n 9, 6, 3]\n\n\n//n=4\nrotate([\n 1, 2, 3, 4,\n 5, 6, 7, 8,\n 9, 10, 11, 12,\n 13, 14, 15, 16], 4))\n\n//result:\n[13, 9, 5, 1,\n 14, 10, 6, 2,\n 15, 11, 7, 3,\n 16, 12, 8, 4]\n\n\n//n=5\nrotate([\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], 5))\n\n//result:\n[21, 16, 11, 6, 1, \n 22, 17, 12, 7, 2, \n 23, 18, 13, 8, 3, \n 24, 19, 14, 9, 4, \n 25, 20, 15, 10, 5]\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 1 2\n3 4\n\n3 1\n4 2\n\n2 4\n1 3\n\n4 3\n2 1\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 void rotate(vector<vector<int> > &matrix) {\n reverse(matrix.begin(), matrix.end());\n for (int i = 0; i < matrix.size(); ++i) {\n for (int j = i + 1; j < matrix[i].size(); ++j)\n swap(matrix[i][j], matrix[j][i]);\n }\n}\n 1 2 3 3 2 1 3 6 9\n4 5 6 => 6 5 4 => 2 5 8\n7 8 9 9 8 7 1 4 7\n void anti_rotate(vector<vector<int> > &matrix) {\n for (auto vi : matrix) reverse(vi.begin(), vi.end());\n for (int i = 0; i < matrix.size(); ++i) {\n for (int j = i + 1; j < matrix[i].size(); ++j)\n swap(matrix[i][j], matrix[j][i]);\n }\n}\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] #include <windows.h>\n#include <stdio.h>\n#include <tchar.h>\n\nvoid _tmain( int argc, TCHAR *argv[] )\n{\n STARTUPINFO si;\n PROCESS_INFORMATION pi;\n\n ZeroMemory( &si, sizeof(si) );\n si.cb = sizeof(si);\n ZeroMemory( &pi, sizeof(pi) );\n\n if( argc != 2 )\n {\n printf(\"Usage: %s [cmdline]\\n\", argv[0]);\n return;\n }\n\n // Start the child process. \n if( !CreateProcess( NULL, // No module name (use command line)\n argv[1], // Command line\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 return;\n }\n\n // Wait until child process exits.\n WaitForSingleObject( pi.hProcess, INFINITE );\n\n // Close process and thread handles. \n CloseHandle( pi.hProcess );\n CloseHandle( pi.hThread );\n}\n" }, { "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 //-- wait for the process to finish\nwhile (true)\n{\n //-- see if the task has terminated\n DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);\n\n if ( (dwExitCode == WAIT_FAILED )\n || (dwExitCode == WAIT_OBJECT_0 )\n || (dwExitCode == WAIT_ABANDONED) )\n {\n DWORD dwExitCode;\n\n //-- get the process exit code\n GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);\n\n //-- the task has ended so close the handle\n CloseHandle(ProcessInfo.hThread);\n CloseHandle(ProcessInfo.hProcess);\n\n //-- save the exit code\n lExitCode = dwExitCode;\n\n return;\n }\n else\n {\n //-- see if there are any message that need to be processed\n while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))\n {\n if (message.msg.message == WM_QUIT)\n {\n return;\n }\n\n //-- process the message queue\n if (GetMessage(&message.msg, 0, 0, 0))\n {\n //-- process the message\n TranslateMessage(&pMessage->msg);\n DispatchMessage(&pMessage->msg);\n }\n }\n }\n}\n" }, { "answer_id": 340042, "author": "Bob Moore", "author_id": 9368, "author_profile": "https://Stackoverflow.com/users/9368", "pm_score": 2, "selected": false, "text": "WaitForSingleObject MsgWaitForMultipleObjects" }, { "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 STARTUPINFOW initInfo = { 0 };\ninitInfo.cb = sizeof(initInfo);\nPROCESS_INFORMATION procInfo = { 0 };\n\nCreateProcessA(PATH_FOR_EXE, NULL, NULL, NULL, FALSE, 0, NULL, NULL, (LPSTARTUPINFOA)&initInfo, &procInfo);\n" }, { "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 gethostname uname hostname ip_address_list require 'socket'\nip_address = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address\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 request.host" }, { "answer_id": 3246800, "author": "Salil", "author_id": 297087, "author_profile": "https://Stackoverflow.com/users/297087", "pm_score": 3, "selected": false, "text": "host_with_port host_port= request.host_with_port\n" }, { "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() require 'socket'\n\ndef my_first_private_ipv4\n Socket.ip_address_list.detect{|intf| intf.ipv4_private?}\nend\n\ndef my_first_public_ipv4\n Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}\nend\n ip_address() ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?\n" }, { "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 require 'socket' ifconfig" }, { "answer_id": 12632929, "author": "Tilo", "author_id": 677684, "author_profile": "https://Stackoverflow.com/users/677684", "pm_score": 2, "selected": false, "text": "hostname uname hostname = `uname -n`.chomp.sub(/\\..*/,'') # stripping off \"\\n\" and the network name if present\n # on a Mac:\n ip_addresses = `ifconfig | grep 'inet ' | grep -v 127.0.0.1 | cut -d' ' -f 2`.split\n => ['10.2.21.122','10.8.122.12']\n\n # on Linux:\n ip_addresses = `ifconfig -a | grep 'inet ' | grep -v 127.0.0.1 | cut -d':' -f 2 | cut -d' ' -f 1`.split\n => ['10.2.21.122','10.8.122.12']\n" } ]
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 re.sub(pattern, repl, string[, count, flags])\n re.MULTILINE re.sub('^//', '', s, flags=re.MULTILINE)\n re.sub(re.compile('^//', re.MULTILINE), '', s)\n" }, { "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 re.sub(pattern, repl, string[, count, flags])\n flags count re.sub('^//', '', s, flags=re.MULTILINE)\n re.sub('^//', '', s, flags=re.M)\n" } ]
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 class C { }\n\nstatic void Foo(C x) => Console.WriteLine(nameof(Foo));\nstatic void Foo(object x) => Console.WriteLine(nameof(Object));\n\npublic static void Main(string[] args)\n{\n object x = new C();\n\n Foo((dynamic)x); // prints: \"Foo\"\n Foo(x); // prints: \"Object\"\n}\n dynamic 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 string myfile = Path.Combine(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 SCOPE_IDENTITY() IDENT_CURRENT('tableName') OUTPUT INSERT" }, { "answer_id": 42669, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": false, "text": "@@IDENTITY SCOPE_IDENTITY() IDENT_CURRENT SCOPE_IDENTITY() @@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 create table TableWithIdentity\n ( IdentityColumnName int identity(1, 1) not null primary key,\n ... )\n\n-- type of this table's column must match the type of the\n-- identity column of the table you'll be inserting into\ndeclare @IdentityOutput table ( ID int )\n\ninsert TableWithIdentity\n ( ... )\noutput inserted.IdentityColumnName into @IdentityOutput\nvalues\n ( ... )\n\nselect @IdentityValue = (select ID from @IdentityOutput)\n" }, { "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 NewId = command.ExecuteScalar()\n" }, { "answer_id": 40425907, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": false, "text": "OUTPUT DECLARE @generated_keys table([Id] uniqueidentifier)\n\nINSERT INTO TurboEncabulators(StatorSlots)\nOUTPUT inserted.TurboEncabulatorID INTO @generated_keys\nVALUES('Malleable logarithmic casing');\n\nSELECT t.[TurboEncabulatorID ]\nFROM @generated_keys AS g \n JOIN dbo.TurboEncabulators AS t \n ON g.Id = t.TurboEncabulatorID \nWHERE @@ROWCOUNT > 0\n OUTPUT OUTPUT rowversion Timestamp public class TurboEncabulator\n{\n public String StatorSlots)\n\n [Timestamp]\n public byte[] RowVersion { get; set; }\n}\n rowversion DECLARE @generated_keys table([Id] uniqueidentifier)\n\nINSERT INTO TurboEncabulators(StatorSlots)\nOUTPUT inserted.TurboEncabulatorID INTO @generated_keys\nVALUES('Malleable logarithmic casing');\n\nSELECT t.[TurboEncabulatorID], t.[RowVersion]\nFROM @generated_keys AS g \n JOIN dbo.TurboEncabulators AS t \n ON g.Id = t.TurboEncabulatorID \nWHERE @@ROWCOUNT > 0\n Timetsamp OUTPUT Timestamp SELECT SELECT rowversion DECLARE @generated_keys table([Id] uniqueidentifier, [Rowversion] timestamp)\n\nINSERT INTO TurboEncabulators(StatorSlots)\nOUTPUT inserted.TurboEncabulatorID, inserted.Rowversion INTO @generated_keys\nVALUES('Malleable logarithmic casing');\n UPDATE OUTPUT UPDATE OUTPUT SELECT UPDATE TurboEncabulators\nSET StatorSlots = 'Lotus-O deltoid type'\nWHERE ((TurboEncabulatorID = 1) AND (RowVersion = 792))\n\nSELECT RowVersion\nFROM TurboEncabulators\nWHERE @@ROWCOUNT > 0 AND TurboEncabulatorID = 1\n" }, { "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 INSERT INTO MyTable\nOUTPUT INSERTED.ID\nVALUES\n (...),\n (...),\n (...)\n ID\n2\n3\n4\n" }, { "answer_id": 55142419, "author": "Frank Roth", "author_id": 1073330, "author_profile": "https://Stackoverflow.com/users/1073330", "pm_score": 2, "selected": false, "text": "uuid INSERT INTO table (uuid, name, street, zip) \n VALUES ('2f802845-447b-4caa-8783-2086a0a8d437', 'Peter', 'Mainstreet 7', '88888');\n SELECT * FROM table WHERE uuid='2f802845-447b-4caa-8783-2086a0a8d437';\n" }, { "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 OFF CREATE TABLE #foo \n ( \n fooid INT IDENTITY NOT NULL, \n fooname VARCHAR(20) \n ) \n\nSELECT @@Identity AS [@@Identity], \n Scope_identity() AS [SCOPE_IDENTITY()], \n Ident_current('#Foo') AS [IDENT_CURRENT] \n\nSET IDENTITY_INSERT #foo ON \n\nINSERT INTO #foo \n (fooid, \n fooname) \nVALUES (1, \n 'one'), \n (2, \n 'Two') \n\nSET IDENTITY_INSERT #foo OFF \n\nSELECT @@Identity AS [@@Identity], \n Scope_identity() AS [SCOPE_IDENTITY()], \n Ident_current('#Foo') AS [IDENT_CURRENT] \n\nINSERT INTO #foo \n (fooname) \nVALUES ('Three') \n\nSELECT @@Identity AS [@@Identity], \n Scope_identity() AS [SCOPE_IDENTITY()], \n Ident_current('#Foo') AS [IDENT_CURRENT] \n\n-- YOU CAN INSERT \nSET IDENTITY_INSERT #foo ON \n\nINSERT INTO #foo \n (fooid, \n fooname) \nVALUES (10, \n 'Ten'), \n (11, \n 'Eleven') \n\nSET IDENTITY_INSERT #foo OFF \n\nSELECT @@Identity AS [@@Identity], \n Scope_identity() AS [SCOPE_IDENTITY()], \n Ident_current('#Foo') AS [IDENT_CURRENT] \n\nSELECT * \nFROM #foo \n" }, { "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 SELECT NEXT VALUE FOR CountBy1 AS SequenceID\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 switch (toupper(input))\n{\n case 'A':\n" }, { "answer_id": 48627, "author": "dmityugov", "author_id": 3232, "author_profile": "https://Stackoverflow.com/users/3232", "pm_score": 3, "selected": true, "text": "getchar() cgetc()" } ]
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 = '[email protected]' , @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 @ANSI_Attachment BIT = 0 @mailitem_id INT = NULL OUTPUT,\n @ANSI_Attachment BIT = 0\n WITH EXECUTE AS 'dbo'\n @ansi_attachment = 1\n" }, { "answer_id": 14670451, "author": "Gena", "author_id": 2036703, "author_profile": "https://Stackoverflow.com/users/2036703", "pm_score": 4, "selected": false, "text": "sp_send_dbmail @ANSI_Attachment BIT = 0\nWITH EXECUTE AS 'dbo'\n IF(@AttachmentsExist = 1)\n BEGIN\n.......\n END\n IF(@AttachmentsExist = 1)\nBEGIN\n if (@ANSI_Attachment = 1) \n begin\n --Copy temp attachments to sysmail_attachments \n INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)\n SELECT @mailitem_id, filename, filesize, \n convert(varbinary(max), \n substring( -- remove BOM mark from unicode\n convert(varchar(max), CONVERT (nvarchar(max), attachment)), \n 2, DATALENGTH(attachment)/2\n )\n )\n\n FROM sysmail_attachments_transfer\n WHERE uid = @temp_table_uid\n end else begin\n --Copy temp attachments to sysmail_attachments \n INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)\n SELECT @mailitem_id, filename, filesize, attachment\n FROM sysmail_attachments_transfer\n WHERE uid = @temp_table_uid\n end\nEND\n" } ]
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} <a>Testing Select</a>\n<select id=\"list\"></select>" }, { "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 DBI DBI DBI DBIx::Simple # DBI\nmy $rows = $dbh->selectall_arrayref($sql, { Slice => {} });\n # tell it we want \"hashes\" (yuck!) ^^^^\n\n# DBIx::Simple\nmy $rows = $db->query($sql)->hashes; # does the same as the above code underneath!\n 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 Would you like to save?\n Save Don't Save \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> FacesContext FacesServlet" }, { "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 textBoxHasFocus if (textBoxHasFocus) {\n $get(\"MainSearchBox_SearchTextBox\").blur();\n $get(\"MainSearchBox_SearchTextBox\").focus();\n} \n" }, { "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 unset($area);\n$area = array();\n\nunset($section);\n$section = array();\n $area $section $root" }, { "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 cite" }, { "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> <p> <div>" }, { "answer_id": 42979, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 4, "selected": true, "text": "<h1> <p> <em>" }, { "answer_id": 43847, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 0, "selected": false, "text": "blockquote div 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 (defun quicksort (lis) (if (null lis) nil\n (let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))\n (append (quicksort (remove-if-not fn r)) (list x)\n (quicksort (remove-if fn r))))))\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 (defun quicksort (lis) (if (null lis) nil\n (let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))\n (append (quicksort (remove-if-not fn r)) (list x)\n (quicksort (remove-if fn r))))))\n if len(L) <= 1: return L\nreturn qsort([lt for lt in L[1:] if lt < L[0]]) + [L[0]] + qsort([ge for ge in L[1:] if ge >= L[0]])\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 function printStuff(args)\n for key,value in pairs(args) do\n print value .. \" \"\n end\nend\nstrings = {\n \"hello\",\n \"world\",\n \"from lua\"\n}\nprintStuff(strings)\n" }, { "answer_id": 1629064, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 0, "selected": false, "text": "auto dmdr Python > Java w = \"my string here\".split()[1]" }, { "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 >>> import calendar\n>>> calendar.monthrange(2002, 1)\n(1, 31)\n>>> calendar.monthrange(2008, 2) # leap years are handled correctly\n(4, 29)\n>>> calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years\n(0, 28)\n calendar.monthrange(year, month)[1]\n" }, { "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 >>> \n>>> last_day_of_month(2008, 2)\ndatetime.date(2008, 2, 29)\n>>> last_day_of_month(2009, 2)\ndatetime.date(2009, 2, 28)\n>>> last_day_of_month(2008, 11)\ndatetime.date(2008, 11, 30)\n>>> last_day_of_month(2008, 12)\ndatetime.date(2008, 12, 31)\n" }, { "answer_id": 13386470, "author": "ely", "author_id": 567620, "author_profile": "https://Stackoverflow.com/users/567620", "pm_score": 2, "selected": false, "text": "calendar.monthcalendar # Some random date.\nsome_date = datetime.date(2012, 5, 23)\n\n# Get last weekday\nlast_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()\n\nprint last_weekday\n31\n [0:-2] numpy.ravel numpy.ndarray.max" }, { "answer_id": 13565185, "author": "augustomen", "author_id": 317971, "author_profile": "https://Stackoverflow.com/users/317971", "pm_score": 8, "selected": false, "text": "calendar import datetime\n\ndef last_day_of_month(any_day):\n # The day 28 exists in every month. 4 days later, it's always next month\n next_month = any_day.replace(day=28) + datetime.timedelta(days=4)\n # subtracting the number of the current day brings us back one month\n return next_month - datetime.timedelta(days=next_month.day)\n >>> for month in range(1, 13):\n... print(last_day_of_month(datetime.date(2022, month, 1)))\n...\n2022-01-31\n2022-02-28\n2022-03-31\n2022-04-30\n2022-05-31\n2022-06-30\n2022-07-31\n2022-08-31\n2022-09-30\n2022-10-31\n2022-11-30\n2022-12-31\n" }, { "answer_id": 14994380, "author": "Vince Spicer", "author_id": 272313, "author_profile": "https://Stackoverflow.com/users/272313", "pm_score": 7, "selected": false, "text": "dateutil.relativedelta day=31 import datetime\nfrom dateutil.relativedelta import relativedelta\n\ndate_in_feb = datetime.datetime(2013, 2, 21)\nprint(datetime.datetime(2013, 2, 21) + relativedelta(day=31)) # End-of-month\n# datetime.datetime(2013, 2, 28, 0, 0)\n dateutil pip install python-datetutil\n" }, { "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 from dateutil.relativedelta import relativedelta\nlast_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)\n 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 31\n import calendar\nfrom time import gmtime, strftime\nlastDay = calendar.monthrange(int(strftime(\"%Y\", gmtime())), int(strftime(\"%m\", gmtime())))[1]\ntoday = strftime(\"%d\", gmtime())\nlastDay == today\n False\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 calendar.monthrange(date.today().year, date.today().month)[1]\n >>> date.today()\ndatetime.date(2017, 1, 3)\n>>> date.today().replace(day=31)\ndatetime.date(2017, 1, 31)\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 end_date_of_a_month(datetime.datetime.now().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 datetime.datetime(2017, 11, 30, 0, 0)\n import calendar import datetime as dt\nimport calendar\nfrom dateutil.relativedelta import relativedelta\n\nsomeDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]\n\nstart1 = dt.datetime.now()\nfor thisDate in someDates:\n lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)\n\nprint ('Time Spent= ', dt.datetime.now() - start1)\n\n\nstart2 = dt.datetime.now()\nfor thisDate in someDates:\n lastDay = dt.datetime(thisDate.year, \n thisDate.month, \n calendar.monthrange(thisDate.year, thisDate.month)[1])\n\nprint ('Time Spent= ', dt.datetime.now() - start2)\n Time Spent= 0:00:00.097814\nTime Spent= 0:00:00.109791\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 next_month month_end dte next_month timedelta(days=1)" }, { "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) >>> calendar.monthlen(2002, 1)\n31\n>>> calendar.monthlen(2008, 2)\n29\n>>> calendar.monthlen(2100, 2)\n28\n calendar.monthrange(year, month)[1]" }, { "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 import datetime\n\ndef last_day_of_month(d: datetime.date) -> datetime.date:\n return (\n datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -\n datetime.timedelta(days=1)\n )\n calendar.monthrange() import calendar, datetime\n\ndef last_day_of_month(d: datetime.date) -> datetime.date:\n return d.replace(day=calendar.monthrange(d.year, d.month)[1])\n In [14]: today = datetime.date.today()\n\nIn [15]: %timeit last_day_of_month_dt(today)\n918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [16]: %timeit last_day_of_month_calendar(today)\n1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n" }, { "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 from datetime import datetime\n import pandas as pd\n\n firstday_month = datetime(year, month, 1)\n lastday_month = firstday_month + pd.DateOffset(months=1) - pd.DateOffset(days=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 from datetime import date\n\nprint(last_day_of_month(date.today()))\n>> 2021-09-30\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 months=1 day=1 dt days=-1" }, { "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 from datetime import datetime, timedelta\nimport pytz\n\nset(pytz.all_timezones_set)\ntz = pytz.timezone(\"Europe/Berlin\")\n\ndt = datetime.today().astimezone(tz=tz)\n\nif (dt+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 days=+1 import datetime\nfrom dateutil.relativedelta import relativedelta\n\nday_of_febuary = datetime.datetime(2022, 2, 21)\nlast_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)\nprint(last_day_of_febuary)\n# Output: 2022-02-28 23:59:59\n" }, { "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 >>> get_last_day_of_month(mon=10, year=2022)\n... '2022-10-31'\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 import pandas as pd\n\n> pd.Timestamp(year=2020, month=2, day=1).days_in_month\n\n29\n" } ]
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(\"...\")] [assembly: AssemblyCompany(\"...\")] namespace Ionic.ExampleCode\n{\n public partial class NameOfYourForm\n {\n private void SaveFormToRegistry()\n {\n if (AppCuKey != null)\n {\n // the completion list\n var converted = _completions.ToList().ConvertAll(x => x.XmlEscapeIexcl());\n string completionString = String.Join(\"¡\", converted.ToArray());\n AppCuKey.SetValue(_rvn_Completions, completionString);\n }\n }\n\n private void FillFormFromRegistry()\n {\n if (!stateLoaded)\n {\n if (AppCuKey != null)\n {\n // get the MRU list of .... whatever\n _completions = new System.Windows.Forms.AutoCompleteStringCollection();\n string c = (string)AppCuKey.GetValue(_rvn_Completions, \"\");\n if (!String.IsNullOrEmpty(c))\n {\n string[] items = c.Split('¡');\n if (items != null && items.Length > 0)\n {\n //_completions.AddRange(items);\n foreach (string item in items)\n _completions.Add(item.XmlUnescapeIexcl());\n }\n }\n\n // Can also store/retrieve items in the registry for\n // - textbox contents\n // - checkbox state\n // - splitter state\n // - and so on\n //\n stateLoaded = true;\n }\n }\n }\n\n private Microsoft.Win32.RegistryKey AppCuKey\n {\n get\n {\n if (_appCuKey == null)\n {\n _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegistryPath, true);\n if (_appCuKey == null)\n _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegistryPath);\n }\n return _appCuKey;\n }\n set { _appCuKey = null; }\n }\n\n private string _appRegistryPath;\n private string AppRegistryPath\n {\n get\n {\n if (_appRegistryPath == null)\n {\n // Use a registry path that depends on the assembly attributes,\n // that are presumed to be elsewhere. Example:\n // \n // [assembly: AssemblyCompany(\"Dino Chiesa\")]\n // [assembly: AssemblyProduct(\"XPathVisualizer\")]\n\n var a = System.Reflection.Assembly.GetExecutingAssembly();\n object[] attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true);\n var p = attr[0] as System.Reflection.AssemblyProductAttribute;\n attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true);\n var c = attr[0] as System.Reflection.AssemblyCompanyAttribute;\n\n _appRegistryPath = String.Format(\"Software\\\\{0}\\\\{1}\",\n p.Product, c.Company);\n }\n return _appRegistryPath;\n }\n }\n\n private Microsoft.Win32.RegistryKey _appCuKey;\n private string _rvn_Completions = \"Completions\";\n private readonly int _MaxMruListSize = 14;\n private System.Windows.Forms.AutoCompleteStringCollection _completions;\n private bool stateLoaded;\n }\n\n public static class Extensions\n {\n public static string XmlEscapeIexcl(this String s)\n {\n while (s.Contains(\"¡\"))\n {\n s = s.Replace(\"¡\", \"&#161;\");\n }\n return s;\n }\n public static string XmlUnescapeIexcl(this String s)\n {\n while (s.Contains(\"&#161;\"))\n {\n s = s.Replace(\"&#161;\", \"¡\");\n }\n return s;\n }\n\n public static List<String> ToList(this System.Windows.Forms.AutoCompleteStringCollection coll)\n {\n var list = new List<String>();\n foreach (string item in coll)\n {\n list.Add(item);\n }\n return list;\n }\n }\n}\n" } ]
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 Mercurial.ini [merge-tools]\np4.priority = 100\np4.premerge = True # change this to False if you're don't trust hg's internal merge\np4.executable = /Applications/p4merge.app/Contents/MacOS/p4merge\np4.gui = True\np4.args = $base $local $other $output\n hg diff extdiff hg pdiff" }, { "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/ Mercurial.ini [extensions]\nhgext.extdiff =\n [extdiff]\ncmd.p4diff = p4merge\n [tortoisehg]\nvdiff = p4diff\n" } ]
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 false\nfalse\nfalse\ntrue\ntrue\ntrue\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 IEnumerable GetEnumerator Enumerator MoveNext() Current Current MoveNext Current" }, { "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 IndexOf System.Collections.IEnumerable collection = Enumerable.Range(100, 10);\n\nforeach (var o in collection.OfType<object>().Select((x, i) => new {x, i}))\n{\n Console.WriteLine(\"{0} {1}\", o.i, o.x);\n}\n" }, { "answer_id": 1046748, "author": "mike nelson", "author_id": 23616, "author_profile": "https://Stackoverflow.com/users/23616", "pm_score": 7, "selected": false, "text": "for foreach for foreach Dispose" }, { "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 enumerable.ForEach((item, index) => blah(item, index));\n public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action)\n {\n var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void\n enumerable.Select((item, i) => \n {\n action(item, i);\n return unit;\n }).ToList();\n\n return pSource;\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 IList" }, { "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 ForEachHelper public static class ForEachHelper\n{\n public sealed class Item<T>\n {\n public int Index { get; set; }\n public T Value { get; set; }\n public bool IsLast { get; set; }\n }\n\n public static IEnumerable<Item<T>> WithIndex<T>(IEnumerable<T> enumerable)\n {\n Item<T> item = null;\n foreach (T value in enumerable)\n {\n Item<T> next = new Item<T>();\n next.Index = 0;\n next.Value = value;\n next.IsLast = false;\n if (item != null)\n {\n next.Index = item.Index + 1;\n yield return item;\n }\n item = next;\n }\n if (item != null)\n {\n item.IsLast = true;\n yield return item;\n } \n }\n}\n" }, { "answer_id": 3535307, "author": "user426810", "author_id": 426810, "author_profile": "https://Stackoverflow.com/users/426810", "pm_score": 3, "selected": false, "text": "continue int i=-1;\nforeach (Object o in collection)\n{\n ++i;\n //...\n continue; //<--- safe to call, index will be increased\n //...\n}\n" }, { "answer_id": 3535362, "author": "Ian Henry", "author_id": 223274, "author_profile": "https://Stackoverflow.com/users/223274", "pm_score": 3, "selected": false, "text": "obj.Value foreach(var obj in collection.Select((item, index) => new { Index = index, Value = item }) {\n string foo = string.Format(\"Something[{0}] = {1}\", obj.Index, obj.Value);\n ...\n}\n" }, { "answer_id": 3691283, "author": "ulrichb", "author_id": 50890, "author_profile": "https://Stackoverflow.com/users/50890", "pm_score": 2, "selected": false, "text": "WithIndex() var list = new List<int> { 1, 2, 3, 4, 5, 6 }; \n\nvar odd = list.WithIndex().Where(i => (i.Item & 1) == 1);\nCollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i => i.Index));\nCollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i => i.Item));\n" }, { "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 item.value item.i Select new { i, value } ValueTuple foreach (var item in Model.Select((value, i) => ( value, i )))\n{\n var value = item.value;\n var index = item.i;\n}\n item. foreach (var (value, i) in Model.Select((value, i) => ( value, i )))\n{\n // Access `value` and `i` directly here.\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 <%int i=0;\n foreach (var review in Model.ReviewsList) { %>\n <div id=\"review_<%=i%>\">\n <h3><%:review.Title%></h3> \n </div>\n <%i++;\n } %>\n <%foreach (var review in Model.ReviewsList.WithIndex()) { %>\n <div id=\"review_<%=LoopHelper.Index()%>\">\n <h3><%:review.Title%></h3> \n </div>\n <%} %>\n public static class LoopHelper {\n public static int Index() {\n return (int)HttpContext.Current.Items[\"LoopHelper_Index\"];\n } \n}\n\npublic static class LoopHelperExtensions {\n public static IEnumerable<T> WithIndex<T>(this IEnumerable<T> that) {\n return new EnumerableWithIndex<T>(that);\n }\n\n public class EnumerableWithIndex<T> : IEnumerable<T> {\n public IEnumerable<T> Enumerable;\n\n public EnumerableWithIndex(IEnumerable<T> enumerable) {\n Enumerable = enumerable;\n }\n\n public IEnumerator<T> GetEnumerator() {\n for (int i = 0; i < Enumerable.Count(); i++) {\n HttpContext.Current.Items[\"LoopHelper_Index\"] = i;\n yield return Enumerable.ElementAt(i);\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator() {\n return GetEnumerator();\n }\n }\n static HttpContext.Current.Items" }, { "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 GetEnumerator for listEnumerator.MoveNext() == true MoveNext" }, { "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 string.join var joinResult = string.Join(\",\", listOfNames);\n" }, { "answer_id": 22016592, "author": "David Bullock", "author_id": 463052, "author_profile": "https://Stackoverflow.com/users/463052", "pm_score": 6, "selected": false, "text": "for foreach while do var i = 0;\nforeach (var e in collection) {\n // Do stuff with 'e' and 'i'\n i++;\n}\n Array List<T> LinkedList // Hope the JIT compiler optimises read of the 'Count' property!\nfor (var i = 0; i < collection.Count; i++) {\n var e = collection[i];\n // Do stuff with 'e' and 'i'\n}\n IEnumerator MoveNext() Current foreach continue // First, filter 'e' based on 'i',\n// then apply an action to remaining 'e'\ncollection\n .AsParallel()\n .Where((e,i) => /* filter with e,i */)\n .ForAll(e => { /* use e, but don't modify it */ });\n\n// Using 'e' and 'i', produce a new collection,\n// where each element incorporates 'i'\ncollection\n .AsParallel()\n .Select((e, i) => new MyWrapper(e, i));\n AsParallel() ForEach() List<T> Array foreach" }, { "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 foreach (string m in myList)\n{\n // Do something...\n}\n myList.indexOf(m)\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 public struct ValueWithIndex<T>\n{\n public readonly T Value;\n public readonly int Index;\n\n public ValueWithIndex(T value, int index)\n {\n this.Value = value;\n this.Index = index;\n }\n\n public static ValueWithIndex<T> Create(T value, int index)\n {\n return new ValueWithIndex<T>(value, index);\n }\n}\n\npublic static class ExtensionMethods\n{\n public static IEnumerable<ValueWithIndex<T>> GetEnumeratorWithIndex<T>(this IEnumerable<T> enumerable)\n {\n return enumerable.Select(ValueWithIndex<T>.Create);\n }\n}\n" }, { "answer_id": 39997157, "author": "user1414213562", "author_id": 6659843, "author_profile": "https://Stackoverflow.com/users/6659843", "pm_score": 9, "selected": false, "text": "foreach foreach (var (item, index) in collection.WithIndex())\n{\n Debug.WriteLine($\"{index}: {item}\");\n}\n using System.Collections.Generic;\n\npublic static class EnumExtension {\n public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self) \n => self.Select((item, index) => (item, index));\n}\n" }, { "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 foreach () with var index IIndexedEnumerable interface IIndexedEnumerable<T> : IEnumerable<T>\n{\n //Not index, because sometimes source IEnumerables are transient\n public long IterationNumber { get; }\n}\n with IIndexedEnumerable" }, { "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 foreach (var (value, index) in collection.Select((v, i)=>(v, i))) {\n Console.WriteLine(value + \" is at index \" + index);\n}\n foreach 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 IEnumerator //\n// Summary:\n// Exposes an enumerator, which supports a simple iteration over a non-generic collection.\npublic interface IEnumerable\n{\n //\n // Summary:\n // Returns an enumerator that iterates through a collection.\n //\n // Returns:\n // An System.Collections.IEnumerator object that can be used to iterate through\n // the collection.\n IEnumerator GetEnumerator();\n}\n\n//\n// Summary:\n// Supports a simple iteration over a non-generic collection.\npublic interface IEnumerator\n{\n //\n // Summary:\n // Gets the element in the collection at the current position of the enumerator.\n //\n // Returns:\n // The element in the collection at the current position of the enumerator.\n object Current { get; }\n\n //\n // Summary:\n // Advances the enumerator to the next element of the collection.\n //\n // Returns:\n // true if the enumerator was successfully advanced to the next element; false if\n // the enumerator has passed the end of the collection.\n //\n // Exceptions:\n // T:System.InvalidOperationException:\n // The collection was modified after the enumerator was created.\n bool MoveNext();\n //\n // Summary:\n // Sets the enumerator to its initial position, which is before the first element\n // in the collection.\n //\n // Exceptions:\n // T:System.InvalidOperationException:\n // The collection was modified after the enumerator was created.\n void Reset();\n}\n IEnumerator foreach IEnumerable IList<T> IEnumerable IEnumerable foreach GetEnumerator MoveNext foreach IEnumerator foreach public static class Ext\n{\n public static void FE<T>(this IEnumerable<T> l, Action<int, T> act)\n {\n int counter = 0;\n foreach (var item in l)\n {\n act(counter, item);\n counter++;\n }\n }\n}\n var x = new List<string>() { \"hello\", \"world\" };\nx.FE((ind, ele) =>\n{\n Console.WriteLine($\"{ind}: {ele}\");\n});\n" }, { "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 List<Color> ColorsPalette = ColorGenerator\n .Generate(30)\n .Skip(2) // skip white and black\n .ToList(); \n public static class ColorGenerator\n{\n\n // RYB color space\n private static class RYB\n {\n private static readonly double[] White = { 1, 1, 1 };\n private static readonly double[] Red = { 1, 0, 0 };\n private static readonly double[] Yellow = { 1, 1, 0 };\n private static readonly double[] Blue = { 0.163, 0.373, 0.6 };\n private static readonly double[] Violet = { 0.5, 0, 0.5 };\n private static readonly double[] Green = { 0, 0.66, 0.2 };\n private static readonly double[] Orange = { 1, 0.5, 0 };\n private static readonly double[] Black = { 0.2, 0.094, 0.0 };\n\n public static double[] ToRgb(double r, double y, double b)\n {\n var rgb = new double[3];\n for (int i = 0; i < 3; i++)\n {\n rgb[i] = White[i] * (1.0 - r) * (1.0 - b) * (1.0 - y) +\n Red[i] * r * (1.0 - b) * (1.0 - y) +\n Blue[i] * (1.0 - r) * b * (1.0 - y) +\n Violet[i] * r * b * (1.0 - y) +\n Yellow[i] * (1.0 - r) * (1.0 - b) * y +\n Orange[i] * r * (1.0 - b) * y +\n Green[i] * (1.0 - r) * b * y +\n Black[i] * r * b * y;\n }\n\n return rgb;\n }\n }\n\n private class Points : IEnumerable<double[]>\n {\n private readonly int pointsCount;\n private double[] picked;\n private int pickedCount;\n\n private readonly List<double[]> points = new List<double[]>();\n\n public Points(int count)\n {\n pointsCount = count;\n }\n\n private void Generate()\n {\n points.Clear();\n var numBase = (int)Math.Ceiling(Math.Pow(pointsCount, 1.0 / 3.0));\n var ceil = (int)Math.Pow(numBase, 3.0);\n for (int i = 0; i < ceil; i++)\n {\n points.Add(new[]\n {\n Math.Floor(i/(double)(numBase*numBase))/ (numBase - 1.0),\n Math.Floor((i/(double)numBase) % numBase)/ (numBase - 1.0),\n Math.Floor((double)(i % numBase))/ (numBase - 1.0),\n });\n }\n }\n\n private double Distance(double[] p1)\n {\n double distance = 0;\n for (int i = 0; i < 3; i++)\n {\n distance += Math.Pow(p1[i] - picked[i], 2.0);\n }\n\n return distance;\n }\n\n private double[] Pick()\n {\n if (picked == null)\n {\n picked = points[0];\n points.RemoveAt(0);\n pickedCount = 1;\n return picked;\n }\n\n var d1 = Distance(points[0]);\n int i1 = 0, i2 = 0;\n foreach (var point in points)\n {\n var d2 = Distance(point);\n if (d1 < d2)\n {\n i1 = i2;\n d1 = d2;\n }\n\n i2 += 1;\n }\n\n var pick = points[i1];\n points.RemoveAt(i1);\n\n for (int i = 0; i < 3; i++)\n {\n picked[i] = (pickedCount * picked[i] + pick[i]) / (pickedCount + 1.0);\n }\n\n pickedCount += 1;\n return pick;\n }\n\n public IEnumerator<double[]> GetEnumerator()\n {\n Generate();\n for (int i = 0; i < pointsCount; i++)\n {\n yield return Pick();\n }\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n\n public static IEnumerable<Color> Generate(int numOfColors)\n {\n var points = new Points(numOfColors);\n\n foreach (var point in points)\n {\n var rgb = RYB.ToRgb(point[0], point[1], point[2]);\n yield return Color.FromArgb(\n (int)Math.Floor(255 * rgb[0]),\n (int)Math.Floor(255 * rgb[1]),\n (int)Math.Floor(255 * rgb[2]));\n }\n }\n}\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 function zig ( xx : float ): float{ //lfo nz -1,1\n xx= xx+32;\n var x0 = Mathf.Floor(xx);\n var x1 = x0+1;\n var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;\n var v1 = (Mathf.Sin (x1*.014686)*31718.927)%1;\n return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;\n}\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 generateFlatColorWithOrder() (function($) {\n function generateFlatColorWithOrder(num, rr, rg, rb) {\n var colorBase = 256;\n var red = 0;\n var green = 0;\n var blue = 0;\n num = Math.round(num);\n num = num + 1;\n if (num != null) {\n\n red = (num*rr) % 256;\n green = (num*rg) % 256;\n blue = (num*rb) % 256;\n }\n var redString = Math.round((red + colorBase) / 2).toString();\n var greenString = Math.round((green + colorBase) / 2).toString();\n var blueString = Math.round((blue + colorBase) / 2).toString();\n return \"rgb(\"+redString+\", \"+greenString+\", \"+blueString+\")\";\n //return '#' + redString + greenString + blueString;\n }\n\n function generateRandomFlatColor() {\n return generateFlatColorWithOrder(Math.round(Math.random()*127));\n }\n\n var rr = Math.round(Math.random()*1000);\n var rg = Math.round(Math.random()*1000);\n var rb = Math.round(Math.random()*1000);\n console.log(\"random red: \"+ rr);\n console.log(\"random green: \"+ rg);\n console.log(\"random blue: \"+ rb);\n console.log(\"----------------------------------------------------\");\n $('.flat-color-gen').each(function(i, obj) {\n console.log(generateFlatColorWithOrder(i));\n $(this).css(\"background-color\",generateFlatColorWithOrder(i, rr, rg, rb).toString());\n });\n})(window.jQuery);\n" }, { "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 generateRandomComplementaryColor(240, 240, 240);\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) int (23b | 32b) int operator| operator| byte int byte rule = (byte)(rule | 0x80);\n rule |= 0x80; x op= y x = (T)(x op y)" } ]
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 commandThatOutputs.exe | yourProgramToProcessInput.exe\n #include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n FILE * fptr; // file holder\n char c; // char buffer\n\n\n system(\"dir >> temp.txt\"); // call dir and put it's contents in a temp using redirects.\n fptr = fopen(\"temp.txt\", \"r\"); // open said file for reading.\n // oh, and check for fptr being NULL.\n while(1){\n c = fgetc(fptr);\n if(c!= EOF)\n printf(\"%c\", c); // do what you need to.\n else\n break; // exit when you hit the end of the file.\n }\n fclose(fptr); // don't call this is fptr is NULL. \n remove(\"temp.txt\"); // clean up\n\n getchar(); // stop so I can see if it worked.\n}\n /tmp C:\\Users\\username\\Local Settings\\Temp C:\\Documents and Settings\\username\\Local Settings\\Temp in 2K/XP /tmp" }, { "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() system(\"ls song > song.txt\");\n ls song song.txt" }, { "answer_id": 28971647, "author": "MestreLion", "author_id": 624066, "author_profile": "https://Stackoverflow.com/users/624066", "pm_score": 6, "selected": false, "text": "popen() #include <stdio.h>\n\n#define BUFSIZE 128\n\nint parse_output(void) {\n char *cmd = \"ls -l\"; \n \n char buf[BUFSIZE];\n FILE *fp;\n\n if ((fp = popen(cmd, \"r\")) == NULL) {\n printf(\"Error opening pipe!\\n\");\n return -1;\n }\n\n while (fgets(buf, BUFSIZE, fp) != NULL) {\n // Do whatever you want here...\n printf(\"OUTPUT: %s\", buf);\n }\n\n if (pclose(fp)) {\n printf(\"Command not found or exited with error status\\n\");\n return -1;\n }\n\n return 0;\n}\n OUTPUT: total 16\nOUTPUT: -rwxr-xr-x 1 14077 14077 8832 Oct 19 04:32 a.out\nOUTPUT: -rw-r--r-- 1 14077 14077 1549 Oct 19 04:32 main.c\n" } ]
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 var castList = list.Cast<T>();\n IList IList<T> IList ArrayList IList<T>" }, { "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 public static IList<T> LoadObjectListAll()\n{\n ISession session = CheckForExistingSession();\n // Not sure if you can configure a session after retrieving it. CheckForExistingSession should have this logic.\n // var cfg = new NHibernate.Cfg.Configuration().Configure();\n var criteria = session.CreateCriteria(typeof(T));\n return criteria.List<T>();\n}\n" }, { "answer_id": 43132, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": -1, "selected": false, "text": "IList IList<T> IList ArrayList public static IList<T> LoadObjectListAll()\n" }, { "answer_id": 43141, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 4, "selected": true, "text": "T System.Type T typeof(T) T typeof Type ISessionFactory ISession public static T[] LoadObjectListAll()\n{\n var session = GetNewSession();\n var criteria = session.CreateCriteria(typeof(T));\n var results = criteria.List<T>();\n return results.ToArray(); \n}\n" }, { "answer_id": 43145, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 0, "selected": false, "text": "List<string> List<object>" }, { "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 System.Type" }, { "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 return session.CreateCriteria(typeof(T)).List().Cast<T>();\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": ". #methods Object.methods >> def Object.methods; [\"foo\", \"bar\"]; end\n=> nil\n>> Object.[TAB]\nObject.foo Object.bar\n>> Object.\n . #methods [continuing from above...]\n>> def Object.baz; Object; end\n=> nil\n>> Object.baz.[TAB]\nDisplay all 1022 possibilities? (y or n)\n #baz Object Object Object.baz Object.baz.methods Object.methods :: . HTTP Net:: Net. Net.HTTP Net::HTTP" } ]
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 copy(InputStream,OutputStream) InputStream in;\nOutputStream out;\nIOUtils.copy(in,out);\nin.close();\nout.close();\n IOUtils" }, { "answer_id": 540772, "author": "Dilum Ranatunga", "author_id": 64967, "author_profile": "https://Stackoverflow.com/users/64967", "pm_score": 4, "selected": false, "text": "PipedInputStream PipedOutputStream IOException byte[] buffer = new byte[1024];\nint len = in.read(buffer);\nwhile (len != -1) {\n out.write(buffer, 0, len);\n len = in.read(buffer);\n if (Thread.interrupted()) {\n throw new InterruptedException();\n }\n}\n" }, { "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 File private void copyInputStreamToFile( InputStream in, File file ) {\n try {\n OutputStream out = new FileOutputStream(file);\n byte[] buf = new byte[1024];\n int len;\n while((len=in.read(buf))>0){\n out.write(buf,0,len);\n }\n out.close();\n in.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n}\n" }, { "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 file.toPath() File.createTempFile() REPLACE_EXISTING FileAlreadyExistsException Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)\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() ByteStreams.copy(inputStream, outputStream);\n" }, { "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 for while" }, { "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 transferTo public long transferTo(OutputStream out) throws IOException\n transferTo InputStream OutputStream input.transferTo(output);\n" }, { "answer_id": 40019374, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 4, "selected": false, "text": "JDK java.nio.file.Files.java // buffer size used for reading and writing\nprivate static final int BUFFER_SIZE = 8192;\n\n/**\n * Reads all bytes from an input stream and writes them to an output stream.\n */\nprivate static long copy(InputStream source, OutputStream sink) throws IOException {\n long nread = 0L;\n byte[] buf = new byte[BUFFER_SIZE];\n int n;\n while ((n = source.read(buf)) > 0) {\n sink.write(buf, 0, n);\n nread += n;\n }\n return nread;\n}\n" }, { "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 FileCopyUtils.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 BufferedOutputStream try (OutputStream out = new BufferedOutputStream(...);\n InputStream in = new BufferedInputStream(...))) {\n int ch;\n while ((ch = in.read()) != -1) {\n out.write(ch);\n }\n}\n" }, { "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(...) public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException {\n byte[] read = new byte[buffer]; // Your buffer size.\n while (0 < (buffer = in.read(read)))\n out.write(read, 0, buffer);\n}\n public static void transfer(int size, InputStream in, OutputStream out) throws IOException {\n transfer(in, out,\n size > 0xFFFF ? 0xFFFF // 16bits 65,536\n : size > 0xFFF ? 0xFFF// 12bits 4096\n : size < 0xFF ? 0xFF // 8bits 256\n : size\n );\n}\n" }, { "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) public static void replaceCurrentDb(Context context, Uri newDbUri) {\n try {\n File currentDb = context.getDatabasePath(DATABASE_NAME);\n if (currentDb.exists()) {\n InputStream src = context.getContentResolver().openInputStream(newDbUri);\n FileOutputStream dst = new FileOutputStream(currentDb);\n final byte[] buffer = new byte[8 * 1024];\n ByteStreamsKt.copyTo(src, dst, buffer.length);\n src.close();\n dst.close();\n Toast.makeText(context, \"SUCCESS! Your selected file is set as current menu.\", Toast.LENGTH_LONG).show();\n }\n else\n Log.e(\"DOWNLOAD:::: Database\", \" fail, database not found\");\n }\n catch (IOException e) {\n Toast.makeText(context, \"Data Download FAIL.\", Toast.LENGTH_LONG).show();\n Log.e(\"DOWNLOAD FAIL!!!\", \"fail, reason:\", e);\n }\n}\n" } ]
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 int Slope b Intercept a public class Trendline\n{\n public Trendline(IList<decimal> yAxisValues, IList<decimal> xAxisValues)\n : this(yAxisValues.Select((t, i) => new Tuple<decimal, decimal>(xAxisValues[i], t)))\n { }\n public Trendline(IEnumerable<Tuple<Decimal, Decimal>> data)\n {\n var cachedData = data.ToList();\n\n var n = cachedData.Count;\n var sumX = cachedData.Sum(x => x.Item1);\n var sumX2 = cachedData.Sum(x => x.Item1 * x.Item1);\n var sumY = cachedData.Sum(x => x.Item2);\n var sumXY = cachedData.Sum(x => x.Item1 * x.Item2);\n\n //b = (sum(x*y) - sum(x)sum(y)/n)\n // / (sum(x^2) - sum(x)^2/n)\n Slope = (sumXY - ((sumX * sumY) / n))\n / (sumX2 - (sumX * sumX / n));\n\n //a = sum(y)/n - b(sum(x)/n)\n Intercept = (sumY / n) - (Slope * (sumX / n));\n\n Start = GetYValue(cachedData.Min(a => a.Item1));\n End = GetYValue(cachedData.Max(a => a.Item1));\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 Intercept + Slope * xValue;\n }\n}\n" }, { "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 id parentid nodetype localname text\n0 NULL 1 args NULL\n2 0 1 arg NULL\n3 2 2 value NULL\n5 3 3 #text 42\n4 0 1 arg2 NULL\n6 4 3 #text -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 SELECT Dept.Name \nFROM Departments \nJOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID\nORDER BY Dept.Name\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 g++ exception_handling.cpp -o exception_handling [ -O2 ] -fno-exceptions -DNO_EXCEPTIONS\n #include <stdio.h>\n\n// Timer code\n\n#if defined(__linux__)\n#include <sys/time.h>\n#include <time.h>\n\ndouble time()\n{\n timeval tv;\n gettimeofday(&tv, 0);\n return 1.0 * tv.tv_sec + 0.000001 * tv.tv_usec;\n}\n#elif defined(_WIN32)\n#include <windows.h>\n\ndouble get_performance_frequency()\n{\n unsigned _int64 frequency;\n QueryPerformanceFrequency((LARGE_INTEGER*) &frequency); // just assume it works\n return double(frequency);\n}\n\ndouble performance_frequency = get_performance_frequency();\n\ndouble time()\n{\n unsigned _int64 counter;\n QueryPerformanceCounter((LARGE_INTEGER*) &counter);\n return double(counter) / performance_frequency;\n}\n#else\n# error time() not implemented for your platform\n#endif\n\n// How many times to repeat the whole test\nconst int repeats = 10;\n\n// How many times to iterate one case\nconst int times = 1000000;\n\n// Trick optimizer to not remove code\nint result = 0;\n\n\n\n// Case 1. No exception thrown nor handled.\n\nvoid do_something()\n{\n ++result;\n}\n\nvoid case1()\n{\n do_something();\n}\n\n\n\n// Case 2. No exception thrown, but handler installed\n\n#ifndef NO_EXCEPTIONS\nvoid do_something_else()\n{\n --result;\n}\n\nvoid case2()\n{\n try\n {\n do_something();\n }\n catch (int exception)\n {\n do_something_else();\n }\n}\n\n\n\n// Case 3. Exception thrown and caught\n\nvoid do_something_and_throw()\n{\n throw ++result;\n}\n\nvoid case3()\n{\n try\n {\n do_something_and_throw();\n }\n catch (int exception)\n {\n result = exception;\n }\n}\n#endif // !NO_EXCEPTIONS\n\nvoid (*tests[])() =\n{\n case1,\n#ifndef NO_EXCEPTIONS\n case2,\n case3\n#endif // !NO_EXCEPTIONS\n};\n\nint main()\n{\n#ifdef NO_EXCEPTIONS\n printf(\"case0\\n\");\n#else\n printf(\"case1\\tcase2\\tcase3\\n\");\n#endif\n for (int repeat = 0; repeat < repeats; ++repeat)\n {\n for (int test = 0; test < sizeof(tests)/sizeof(tests[0]); ++test)\n {\n double start = time();\n\n for (int i = 0; i < times; ++i)\n tests[test]();\n\n double end = time();\n\n printf(\"%f\\t\", (end - start) * 1000000.0 / times);\n }\n printf(\"\\n\");\n }\n\n return result; // optimizer is happy - we produce a result\n}\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 byte[] IEquatable<Binary> System.Data.Linq.Binary byte[] private bool EqualsTo(Binary binary)\n{\n if (this != binary)\n {\n if (binary == null)\n {\n return false;\n }\n if (this.bytes.Length != binary.bytes.Length)\n {\n return false;\n }\n if (this.hashCode != binary.hashCode)\n {\n return false;\n }\n int index = 0;\n int length = this.bytes.Length;\n while (index < length)\n {\n if (this.bytes[index] != binary.bytes[index])\n {\n return false;\n }\n index++;\n }\n }\n return true;\n}\n Binary for 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) // Copyright (c) 2008-2013 Hafthor Stefansson\n// Distributed under the MIT/X11 software license\n// Ref: http://www.opensource.org/licenses/mit-license.php.\nstatic unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {\n unchecked {\n if(a1==a2) return true;\n if(a1==null || a2==null || a1.Length!=a2.Length)\n return false;\n fixed (byte* p1=a1, p2=a2) {\n byte* x1=p1, x2=p2;\n int l = a1.Length;\n for (int i=0; i < l/8; i++, x1+=8, x2+=8)\n if (*((long*)x1) != *((long*)x2)) return false;\n if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }\n if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }\n if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;\n return true;\n }\n }\n}\n" }, { "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 private unsafe static bool EqualsHelper(String strA, String strB)\n{\n Contract.Requires(strA != null);\n Contract.Requires(strB != null);\n Contract.Requires(strA.Length == strB.Length);\n\n int length = strA.Length;\n\n fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)\n {\n char* a = ap;\n char* b = bp;\n\n // Unroll the loop\n\n #if AMD64\n // For the AMD64 bit platform we unroll by 12 and\n // check three qwords at a time. This is less code\n // than the 32 bit case and is shorter\n // pathlength.\n\n while (length >= 12)\n {\n if (*(long*)a != *(long*)b) return false;\n if (*(long*)(a+4) != *(long*)(b+4)) return false;\n if (*(long*)(a+8) != *(long*)(b+8)) return false;\n a += 12; b += 12; length -= 12;\n }\n #else\n while (length >= 10)\n {\n if (*(int*)a != *(int*)b) return false;\n if (*(int*)(a+2) != *(int*)(b+2)) return false;\n if (*(int*)(a+4) != *(int*)(b+4)) return false;\n if (*(int*)(a+6) != *(int*)(b+6)) return false;\n if (*(int*)(a+8) != *(int*)(b+8)) return false;\n a += 10; b += 10; length -= 10;\n }\n #endif\n\n // This depends on the fact that the String objects are\n // always zero terminated and that the terminating zero is not included\n // in the length. For odd string sizes, the last compare will include\n // the zero terminator.\n while (length > 0)\n {\n if (*(int*)a != *(int*)b) break;\n a += 2; b += 2; length -= 2;\n }\n\n return (length <= 0);\n }\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 UnsafeCompare : 86,8784 ms\nEqualBytesSimd : 71,5125 ms\nEqualBytesSimdUnrolled : 73,1917 ms\nEqualBytesLongUnrolled : 39,8623 ms\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() EqualBytesLongUnrolled() #if NETCOREAPP3_0\nusing System.Runtime.Intrinsics.X86;\n#endif\n…\n\npublic static unsafe bool Compare(byte[] arr0, byte[] arr1)\n{\n if (arr0 == arr1)\n {\n return true;\n }\n if (arr0 == null || arr1 == null)\n {\n return false;\n }\n if (arr0.Length != arr1.Length)\n {\n return false;\n }\n if (arr0.Length == 0)\n {\n return true;\n }\n fixed (byte* b0 = arr0, b1 = arr1)\n {\n#if NETCOREAPP3_0\n if (Avx2.IsSupported)\n {\n return Compare256(b0, b1, arr0.Length);\n }\n else if (Sse2.IsSupported)\n {\n return Compare128(b0, b1, arr0.Length);\n }\n else\n#endif\n {\n return Compare64(b0, b1, arr0.Length);\n }\n }\n}\n#if NETCOREAPP3_0\npublic static unsafe bool Compare256(byte* b0, byte* b1, int length)\n{\n byte* lastAddr = b0 + length;\n byte* lastAddrMinus128 = lastAddr - 128;\n const int mask = -1;\n while (b0 < lastAddrMinus128) // unroll the loop so that we are comparing 128 bytes at a time.\n {\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != mask)\n {\n return false;\n }\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 32), Avx.LoadVector256(b1 + 32))) != mask)\n {\n return false;\n }\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 64), Avx.LoadVector256(b1 + 64))) != mask)\n {\n return false;\n }\n if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 96), Avx.LoadVector256(b1 + 96))) != mask)\n {\n return false;\n }\n b0 += 128;\n b1 += 128;\n }\n while (b0 < lastAddr)\n {\n if (*b0 != *b1) return false;\n b0++;\n b1++;\n }\n return true;\n}\npublic static unsafe bool Compare128(byte* b0, byte* b1, int length)\n{\n byte* lastAddr = b0 + length;\n byte* lastAddrMinus64 = lastAddr - 64;\n const int mask = 0xFFFF;\n while (b0 < lastAddrMinus64) // unroll the loop so that we are comparing 64 bytes at a time.\n {\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != mask)\n {\n return false;\n }\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 16), Sse2.LoadVector128(b1 + 16))) != mask)\n {\n return false;\n }\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 32), Sse2.LoadVector128(b1 + 32))) != mask)\n {\n return false;\n }\n if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 48), Sse2.LoadVector128(b1 + 48))) != mask)\n {\n return false;\n }\n b0 += 64;\n b1 += 64;\n }\n while (b0 < lastAddr)\n {\n if (*b0 != *b1) return false;\n b0++;\n b1++;\n }\n return true;\n}\n#endif\npublic static unsafe bool Compare64(byte* b0, byte* b1, int length)\n{\n byte* lastAddr = b0 + length;\n byte* lastAddrMinus32 = lastAddr - 32;\n while (b0 < lastAddrMinus32) // unroll the loop so that we are comparing 32 bytes at a time.\n {\n if (*(ulong*)b0 != *(ulong*)b1) return false;\n if (*(ulong*)(b0 + 8) != *(ulong*)(b1 + 8)) return false;\n if (*(ulong*)(b0 + 16) != *(ulong*)(b1 + 16)) return false;\n if (*(ulong*)(b0 + 24) != *(ulong*)(b1 + 24)) return false;\n b0 += 32;\n b1 += 32;\n }\n while (b0 < lastAddr)\n {\n if (*b0 != *b1) return false;\n b0++;\n b1++;\n }\n return true;\n}\n" }, { "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 OS=Windows\nProcessor=?, ProcessorCount=8\nFrequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC\nCLR=CORE, Arch=64-bit ? [RyuJIT]\nGC=Concurrent Workstation\ndotnet cli version: 1.0.0-preview2-003131\n\nType=CompareMemoriesBenchmarks Mode=Throughput \n\n Method | Median | StdDev | Scaled | Scaled-SD |\n----------------------- |------------ |---------- |------- |---------- |\n NewMemCopy | 30.1789 ms | 0.0437 ms | 1.00 | 0.00 |\n EqualBytesLongUnrolled | 30.1985 ms | 0.1782 ms | 1.00 | 0.01 |\n msvcrt_memcmp | 30.1084 ms | 0.0660 ms | 1.00 | 0.00 |\n UnsafeCompare | 31.1845 ms | 0.4051 ms | 1.03 | 0.01 |\n ByteArrayCompare | 212.0213 ms | 0.1694 ms | 7.03 | 0.01 |\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) byte[] long[] bool CompareWithUnsafeLibrary(byte[] a1, byte[] a2)\n{\n if (a1.Length != a2.Length) return false;\n\n var longSize = (int)Math.Floor(a1.Length / 8.0);\n var long1 = Unsafe.As<long[]>(a1);\n var long2 = Unsafe.As<long[]>(a2);\n\n for (var i = 0; i < longSize; i++)\n {\n if (long1[i] != long2[i]) return false;\n }\n\n for (var i = longSize * 8; i < a1.Length; i++)\n {\n if (a1[i] != a2[i]) return false;\n }\n\n return true;\n}\n long1.Length BenchmarkDotNet=v0.10.3.0, OS=Microsoft Windows NT 6.2.9200.0\nProcessor=Intel(R) Core(TM) i7-4870HQ CPU 2.50GHz, ProcessorCount=8\nFrequency=2435775 Hz, Resolution=410.5470 ns, Timer=TSC\n [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0\n DefaultJob : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0\n\n Method | Mean | StdDev |\n----------------------- |-------------- |---------- |\n UnsafeLibrary | 125.8229 ns | 0.3588 ns |\n UnsafeCompare | 89.9036 ns | 0.8243 ns |\n JSharpEquals | 1,432.1717 ns | 1.3161 ns |\n EqualBytesLongUnrolled | 43.7863 ns | 0.8923 ns |\n NewMemCmp | 65.4108 ns | 0.2202 ns |\n ArraysEqual | 910.8372 ns | 2.6082 ns |\n PInvokeMemcmp | 52.7201 ns | 0.1105 ns |\n" }, { "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 memcmp for Buffer.Compare using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace memcmp\n{\n class Program\n {\n static byte[] TestVector(int size)\n {\n var data = new byte[size];\n using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())\n {\n rng.GetBytes(data);\n }\n return data;\n }\n\n static TimeSpan Measure(string testCase, TimeSpan offset, Action action, bool ignore = false)\n {\n var t = Stopwatch.StartNew();\n var n = 0L;\n while (t.Elapsed < TimeSpan.FromSeconds(10))\n {\n action();\n n++;\n }\n var elapsed = t.Elapsed - offset;\n if (!ignore)\n {\n Console.WriteLine($\"{testCase,-16} : {n / elapsed.TotalSeconds,16:0.0} MiB/s\");\n }\n return elapsed;\n }\n\n [DllImport(\"msvcrt.dll\", CallingConvention = CallingConvention.Cdecl)]\n static extern int memcmp(byte[] b1, byte[] b2, long count);\n\n static void Main(string[] args)\n {\n // how quickly can we establish if two sequences of bytes are equal?\n\n // note that we are testing the speed of different comparsion methods\n\n var a = TestVector(1024 * 1024); // 1 MiB\n var b = (byte[])a.Clone();\n\n // was meant to offset the overhead of everything but copying but my attempt was a horrible mistake... should have reacted sooner due to the initially ridiculous throughput values...\n // Measure(\"offset\", new TimeSpan(), () => { return; }, ignore: true);\n var offset = TimeZone.Zero\n\n Measure(\"StructuralComparison\", offset, () =>\n {\n StructuralComparisons.StructuralEqualityComparer.Equals(a, b);\n });\n\n Measure(\"for\", offset, () =>\n {\n for (int i = 0; i < a.Length; i++)\n {\n if (a[i] != b[i]) break;\n }\n });\n\n Measure(\"ToUInt32\", offset, () =>\n {\n for (int i = 0; i < a.Length; i += 4)\n {\n if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) break;\n }\n });\n\n Measure(\"ToUInt64\", offset, () =>\n {\n for (int i = 0; i < a.Length; i += 8)\n {\n if (BitConverter.ToUInt64(a, i) != BitConverter.ToUInt64(b, i)) break;\n }\n });\n\n Measure(\"memcmp\", offset, () =>\n {\n memcmp(a, b, a.Length);\n });\n }\n }\n}\n" }, { "answer_id": 48577229, "author": "Zapnologica", "author_id": 1331971, "author_profile": "https://Stackoverflow.com/users/1331971", "pm_score": 2, "selected": false, "text": "linq public bool CompareTwoArrays(byte[] array1, byte[] array2)\n {\n return !array1.Where((t, i) => t != array2[i]).Any();\n }\n public bool CompareTwoArrays(byte[] array1, byte[] array2)\n {\n if (array1.Length != array2.Length) return false;\n return !array1.Where((t, i) => t != array2[i]).Any();\n }\n" }, { "answer_id": 48599119, "author": "Joe Amenta", "author_id": 1083771, "author_profile": "https://Stackoverflow.com/users/1083771", "pm_score": 7, "selected": false, "text": "Span<T> // byte[] is implicitly convertible to ReadOnlySpan<byte>\nstatic bool ByteArrayCompare(ReadOnlySpan<byte> a1, ReadOnlySpan<byte> a2)\n{\n return a1.SequenceEqual(a2);\n}\n SpansEqual SpansEqual SpansEqual | Method | ByteCount | Mean | StdDev | Ratio | RatioSD |\n|-------------- |----------- |-------------------:|----------------:|------:|--------:|\n| SpansEqual | 15 | 2.074 ns | 0.0233 ns | 1.00 | 0.00 |\n| LongPointers | 15 | 2.854 ns | 0.0632 ns | 1.38 | 0.03 |\n| Unrolled | 15 | 12.449 ns | 0.2487 ns | 6.00 | 0.13 |\n| PInvokeMemcmp | 15 | 7.525 ns | 0.1057 ns | 3.63 | 0.06 |\n| | | | | | |\n| SpansEqual | 1026 | 15.629 ns | 0.1712 ns | 1.00 | 0.00 |\n| LongPointers | 1026 | 46.487 ns | 0.2938 ns | 2.98 | 0.04 |\n| Unrolled | 1026 | 23.786 ns | 0.1044 ns | 1.52 | 0.02 |\n| PInvokeMemcmp | 1026 | 28.299 ns | 0.2781 ns | 1.81 | 0.03 |\n| | | | | | |\n| SpansEqual | 1048585 | 17,920.329 ns | 153.0750 ns | 1.00 | 0.00 |\n| LongPointers | 1048585 | 42,077.448 ns | 309.9067 ns | 2.35 | 0.02 |\n| Unrolled | 1048585 | 29,084.901 ns | 428.8496 ns | 1.62 | 0.03 |\n| PInvokeMemcmp | 1048585 | 30,847.572 ns | 213.3162 ns | 1.72 | 0.02 |\n| | | | | | |\n| SpansEqual | 2147483591 | 124,752,376.667 ns | 552,281.0202 ns | 1.00 | 0.00 |\n| LongPointers | 2147483591 | 139,477,269.231 ns | 331,458.5429 ns | 1.12 | 0.00 |\n| Unrolled | 2147483591 | 137,617,423.077 ns | 238,349.5093 ns | 1.10 | 0.00 |\n| PInvokeMemcmp | 2147483591 | 138,373,253.846 ns | 288,447.8278 ns | 1.11 | 0.01 |\n SpansEqual SpansEqual BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000\nAMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores\n.NET SDK=6.0.202\n [Host] : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT\n DefaultJob : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT\n" }, { "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 int Span.SequenceCompareTo(...) Span.SequenceEqualTo ReadOnlySpan<T> where T: IComparable<T> byte[] long[] memcmp Span<byte> byte[] Enumerable.SequenceEqual #if NETCOREAPP3_0_OR_GREATER\n// Using the platform-native Span<T>.SequenceEqual<T>(..)\npublic static int Compare(byte[] range1, int offset1, byte[] range2, int offset2, int count)\n{\n var span1 = range1.AsSpan(offset1, count);\n var span2 = range2.AsSpan(offset2, count);\n\n return span1.SequenceCompareTo(span2);\n // or, if you don't care about ordering\n // return span1.SequenceEqual(span2);\n}\n#else\n// The most basic implementation, in platform-agnostic, safe C#\npublic static bool Compare(byte[] range1, int offset1, byte[] range2, int offset2, int count)\n{\n // Working backwards lets the compiler optimize away bound checking after the first loop\n for (int i = count - 1; i >= 0; --i)\n {\n if (range1[offset1 + i] != range2[offset2 + i])\n {\n return false;\n }\n }\n\n return true;\n}\n#endif\n" }, { "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 public unsafe bool LongPointersNoFallThrough()\n{\n if (a1 == null || a2 == null || a1.Length != a2.Length)\n return false;\n fixed (byte* p1 = a1, p2 = a2)\n {\n byte* x1 = p1, x2 = p2;\n int l = a1.Length;\n if ((l & 8) != 0)\n {\n for (int i = 0; i < l / 8; i++, x1 += 8, x2 += 8)\n if (*(long*)x1 != *(long*)x2) return false;\n return *(long*)(x1 + (l - 8)) == *(long*)(x2 + (l - 8));\n }\n if ((l & 4) != 0)\n {\n if (*(int*)x1 != *(int*)x2) return false; x1 += 4; x2 += 4;\n return *(int*)(x1 + (l - 4)) == *(int*)(x2 + (l - 4));\n }\n if ((l & 2) != 0)\n {\n if (*(short*)x1 != *(short*)x2) return false; x1 += 2; x2 += 2;\n return *(short*)(x1 + (l - 2)) == *(short*)(x2 + (l - 2));\n }\n return *x1 == *x2;\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 %} django.core.urlresolvers.reverse() reverse reverse(viewname, urlconf=None, args=None, kwargs=None)\n django.urls import reverse" }, { "answer_id": 55734, "author": "Garth Kidd", "author_id": 5700, "author_profile": "https://Stackoverflow.com/users/5700", "pm_score": 4, "selected": false, "text": "models.py permalink from django.db.models import permalink\n\ndef get_absolute_url(self): \n \"\"\"Construct the absolute URL for this Item.\"\"\"\n return ('project.app.views.view_name', [str(self.id)])\nget_absolute_url = permalink(get_absolute_url)\n reverse from django.core.urlresolvers import reverse\n\ndef get_absolute_url(self): \n \"\"\"Construct the absolute URL for this Item.\"\"\"\n return reverse('project.app.views.view_name', None, [str(self.id)])\n" }, { "answer_id": 72249, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 2, "selected": false, "text": "reverse() ViewDoesNotExist NoReverseMatch None" }, { "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() ISession using ISession Find() Enumerable() NHibernate.ITransaction.Commit() ISession.Flush() ISession.Save() ISession.Delete() Flush() ISession.Find(..) FlushMode ITransaction Flush() ISession ITransaction ISession.Flush() tx.Commit(); // flush the session and commit the transaction\n Commit() sess.Flush();\ncurrentTransaction.Commit();\n tx.Rollback(); // rollback the transaction\n currentTransaction.Rollback();\n ISession.Close() tx.Commit();\nsess.Close();\n\nsess.Flush();\ncurrentTransaction.Commit();\nsess.Close();\n Close() 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 sudo cp bash_completion/bash_completion /etc\n if [ -f /etc/bash_completion ]; then\n . /etc/bash_completion \nfi\n" }, { "answer_id": 83754, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 6, "selected": false, "text": "**/*.c ./my_program.c vim ./my_program.c alias -s c=vim print *(e:age today now:)" }, { "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 zmv '(*).mp3' '$1.wma' zcalc bc zparseopts autopushd popd cd" } ]
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 MAILTO=nameofmailinglist" }, { "answer_id": 43376, "author": "Rodney Amato", "author_id": 4342, "author_profile": "https://Stackoverflow.com/users/4342", "pm_score": 3, "selected": false, "text": "MAILTO=\"[email protected]\"\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 imageHolder.removeChildByName( imageName )\n imageHolder.addChild( newImage )\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> <tr> #for $field in $dbObject.c: <th>$field.name</th> #end for </tr> <tr> #for $field in dbObject.c: <td>$field.type.toHtml($field.name, $field.value)</td> #end for </tr> </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 IS_EMPTY_OR(...) db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here'))\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) GetCustomersThatPurchasedProduct(Product product)" }, { "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 -rw-r----- 1 mysql mysql 3.3G Feb 9 13:21 sql-#2088_10fa.ibd\n-rw-r----- 1 mysql mysql 10.2G Feb 9 13:21 posts.ibd\n ls" }, { "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 SELECT EVENT_NAME, WORK_COMPLETED, WORK_ESTIMATED\n FROM performance_schema.events_stages_current;\n+------------------------------------------------------+----------------+----------------+\n| EVENT_NAME | WORK_COMPLETED | WORK_ESTIMATED |\n+------------------------------------------------------+----------------+----------------+\n| stage/innodb/alter table (read PK and internal sort) | 280 | 1245 |\n+------------------------------------------------------+----------------+----------------+\n1 row in set (0.01 sec)\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 noindex,nofollow META" }, { "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 LoadModule auth_kerb_module modules/mod_auth_kerb.so\n <Location /> \n AuthName \"Kerberos Authentication -- this will be showed to users via BasicAuth\"\n AuthType Kerberos\n KrbMethodNegotiate On\n KrbMethodK5Passwd Off\n # this is the principal from your keytab (you may lose the FQDN part)\n KrbServiceName HTTP/$FQDN\n KrbAuthRealms KERBEROS_DOMAIN\n Krb5KeyTab /path/to/http.keytab\n Require valid-user\n\n Order Deny,Allow\n Deny from all\n</Location>\n REMOTE_USER" } ]
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 Dispose" }, { "answer_id": 43560, "author": "dan gibson", "author_id": 4495, "author_profile": "https://Stackoverflow.com/users/4495", "pm_score": 2, "selected": false, "text": "Dispose DestroyHandle Dispose DestroyHandle DestroyHandle OnHandleDestroyed Dispose 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 var list1 = new[] { \"Billy\", \"Bob\" };\nvar list2 = new[] { \"Bob\", \"Sally\" };\nvar diff = list1.Compare(list2);\nvar onlyinlist1 = diff.Removed; //Billy\nvar onlyinlist2 = diff.Added; //Sally\nvar inbothlists = diff.Equal; //Bob\n var original = new Dictionary<int, string>() { { 1, \"a\" }, { 2, \"b\" } };\nvar changed = new Dictionary<int, string>() { { 1, \"aaa\" }, { 2, \"b\" } };\nvar diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);\nforeach (var item in diff.Different)\n Console.Write(\"{0} changed to {1}\", item.Key.Value, item.Value.Value);\n//Will output: a changed to aaa\n" }, { "answer_id": 4655702, "author": "Allon Guralnek", "author_id": 149265, "author_profile": "https://Stackoverflow.com/users/149265", "pm_score": 6, "selected": false, "text": "SequenceEqual SequenceEqual dictionary1.OrderBy(kvp => kvp.Key).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key))\n IComparer<T> IEqualityComparer<T> IComparer<T> dictionary1.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key, StringComparer.Ordinal))\n" }, { "answer_id": 9348579, "author": "Desty", "author_id": 664033, "author_profile": "https://Stackoverflow.com/users/664033", "pm_score": 4, "selected": false, "text": "Equals() ISet ISet HashSet" }, { "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 (dict1.Count == dict2.Count) && dict1.Intersect(dict2).Count() == dict1.Count\n dict2 dict1 Enumerable.Except Enumerable.Union" }, { "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 {1, 2, 3, 4}\n{1, 1, 1, 2, 2, 3, 4}\n Dictionary<TKey, TValue> Enumerable.SequenceEqual var a = new Dictionary<String, int> { { \"2\", 2 }, { \"1\", 1 }, };\nvar b = new Dictionary<String, int> { { \"1\", 1 }, { \"2\", 2 }, };\nDebug.Print(\"{0}\", a.SequenceEqual(b)); // false\n public static class CollectionExtensions {\n public static bool Represents<T>(this IEnumerable<T> first, IEnumerable<T> second) {\n if(object.ReferenceEquals(first, second)) {\n return true;\n }\n\n if(first is IOrderedEnumerable<T> && second is IOrderedEnumerable<T>) {\n return Enumerable.SequenceEqual(first, second);\n }\n\n if(first is ICollection<T> && second is ICollection<T>) {\n if(first.Count()!=second.Count()) {\n return false;\n }\n }\n\n first=first.OrderBy(x => x.GetHashCode());\n second=second.OrderBy(x => x.GetHashCode());\n return CollectionExtensions.Represents(first, second);\n }\n}\n GetHashCode() Count() ICollection<T>.Count" }, { "answer_id": 51903573, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": 1, "selected": false, "text": "SequenceEqual SetEquals namespace System.Collections.Generic {\n public static class ExtensionMethods {\n public static bool DictionaryEquals<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> d1, IReadOnlyDictionary<TKey, TValue> d2) {\n if (object.ReferenceEquals(d1, d2)) return true; \n if (d2 is null || d1.Count != d2.Count) return false;\n foreach (var (d1key, d1value) in d1) {\n if (!d2.TryGetValue(d1key, out TValue d2value)) return false;\n if (!d1value.Equals(d2value)) return false;\n }\n return true;\n }\n }\n}\n IComparable<TValue>" }, { "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> Dictionary<K, V> dictionaryA, dictionaryB;\nbool areDictionaryContentsEqual = new HashSet<K>(dictionaryA.Keys).SetEquals(dictionaryB.Keys);\n ICollection<T> T public static bool AreCollectionContentsEqual<T>(ICollection<T> collectionA, ICollection<T> collectionB)\n where T : notnull\n{\n if (collectionA.Count != collectionB.Count)\n {\n return false;\n }\n Dictionary<T, int> countByValueDictionary = new(collectionA.Count);\n foreach(T item in collectionA)\n {\n countByValueDictionary[item] = countByValueDictionary.TryGetValue(item, out int count) \n ? count + 1 \n : 1;\n }\n foreach (T item in collectionB)\n {\n if (!countByValueDictionary.TryGetValue(item, out int count) || count < 1)\n {\n return false;\n }\n countByValueDictionary[item] = count - 1;\n }\n return true;\n}\n O(n) O(n)" } ]
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 class B : A\n{\n protected sealed override void SpecialRender()\n {\n // do stuff\n }\n}\n\nclass C : B\n protected override void SpecialRender()\n {\n // not valid\n }\n}\n new" }, { "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 ~2.5 secs with ADVAPI32.DLL, CryptGetHashParam()\n ~1.5 secs with OLE2.DLL, StringFromGUID2()\n ~1.0 secs with C2.DLL, _AbortCompilerPass() \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/" ]