qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
168,924
<p>Let's say I've got two strings in JavaScript:</p> <pre><code>var date1 = '2008-10-03T20:24Z' var date2 = '2008-10-04T12:24Z' </code></pre> <p>How would I come to a result like so:</p> <pre><code>'4 weeks ago' </code></pre> <p>or</p> <pre><code>'in about 15 minutes' </code></pre> <p>(should support past and future).</p> <p>There are solutions out there for the past diffs, but I've yet to find one with support for future time diffs as well.</p> <p>These are the solutions I tried:</p> <p><a href="http://ejohn.org/blog/javascript-pretty-date/#postcomment" rel="nofollow noreferrer">John Resig's Pretty Date</a> and <a href="http://www.zachleat.com/web/2008/03/23/yet-another-pretty-date-javascript/" rel="nofollow noreferrer">Zach Leatherman's modification</a></p> <p>Bonus points for a jQuery solution.</p>
[ { "answer_id": 169009, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 4, "selected": true, "text": " function humane_date(date_str){\n var time_formats = [\n [60, 'Just Now'],\n [90, '1 Minute'], // 60*1.5\n [3600, 'Minutes', 60], // 60*60, 60\n [5400, '1 Hour'], // 60*60*1.5\n [86400, 'Hours', 3600], // 60*60*24, 60*60\n [129600, '1 Day'], // 60*60*24*1.5\n [604800, 'Days', 86400], // 60*60*24*7, 60*60*24\n [907200, '1 Week'], // 60*60*24*7*1.5\n [2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7\n [3942000, '1 Month'], // 60*60*24*(365/12)*1.5\n [31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)\n [47304000, '1 Year'], // 60*60*24*365*1.5\n [3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365\n [4730400000, '1 Century'], // 60*60*24*365*100*1.5\n ];\n\n var time = ('' + date_str).replace(/-/g,\"/\").replace(/[TZ]/g,\" \"),\n dt = new Date,\n seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),\n token = ' Ago',\n prepend = '',\n i = 0,\n format;\n\n if (seconds < 0) {\n seconds = Math.abs(seconds);\n token = '';\n prepend = 'In ';\n }\n\n while (format = time_formats[i++]) {\n if (seconds < format[0]) {\n if (format.length == 2) {\n return (i>1?prepend:'') + format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago\n } else {\n return prepend + Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');\n }\n }\n }\n\n // overflow for centuries\n if(seconds > 4730400000)\n return Math.round(seconds / 4730400000) + ' Centuries' + token;\n\n return date_str;\n };\n" }, { "answer_id": 169883, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "Date.prototype.toRelativeTime = function(otherTime) {\n // if no parameter is passed, use the current date.\n if (otherTime == undefined) otherTime = new Date();\n\n var diff = Math.abs(this.getTime() - otherTime.getTime()) / 1000;\n\n var MIN = 60, // some \"constants\" just \n HOUR = 3600, // for legibility\n DAY = 86400\n ;\n var out, temp;\n if (diff < MIN) {\n out = \"Less than a minute\";\n\n } else if (diff < 15 * MIN) {\n // less than fifteen minutes, show how many minutes\n temp = Math.round(diff / MIN);\n out = temp + \" minute\" + (temp == 1 ? \"\" : \"s\");\n // eg: 12 minutes\n } else if (diff < HOUR) {\n // less than an hour, round down to the nearest 5 minutes\n out = (Math.floor(diff / (5 * MIN)) * 5) + \" minutes\";\n } else if (diff < DAY) {\n // less than a day, just show hours\n temp = Math.round(diff / HOUR);\n out = temp + \" hour\" + (temp == 1 ? \"\" : \"s\");\n } else if (diff < 30 * DAY) {\n // show how many days ago\n temp = Math.round(diff / DAY);\n out = temp + \" day\" + (temp == 1 ? \"\" : \"s\");\n } else if (diff < 90 * DAY) {\n // more than 30 days, but less than 3 months, show the day and month\n return this.getDate() + \" \" + this.getShortMonth(); // see below\n } else {\n // more than three months difference, better show the year too\n return this.getDate() + \" \" + this.getShortMonth() + \" \" + this.getFullYear();\n }\n return out + (this.getTime() > otherTime.getTime() ? \" from now\" : \" ago\");\n\n};\n\nDate.prototype.getShortMonth = function() {\n return [\"Jan\", \"Feb\", \"Mar\",\n \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\",\n \"Oct\", \"Nov\", \"Dec\"][this.getMonth()];\n};\n\n// sample usage:\nvar x = new Date(2008, 9, 4, 17, 0, 0);\nalert(x.toRelativeTime()); // 9 minutes from now\n\nx = new Date(2008, 9, 4, 16, 45, 0, 0);\nalert(x.toRelativeTime()); // 6 minutes ago\n\nx = new Date(2008, 11, 1); // 1 Dec\n\nx = new Date(2009, 11, 1); // 1 Dec 2009\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22468/" ]
168,926
<p>Ok, I'm using the term "Progressive Enhancement" kind of loosely here but basically I have a Flash-based website that supports deep linking and loads content dynamically - what I'd like to do is provide alternate content (text) for those either not having Flash and for search engine bots. So, for a user with flash they would navigate to:</p> <pre><code>http://www.samplesite.com/#specific_page </code></pre> <p>and they would see a flash site that would navigate to the "<code>specific_page</code>." Those without flash would see the "<code>specific_page</code>" rendered in text in the alternative content section.</p> <p>Basically, I would use php/mysql to create a backend to handle all of this since the swf is also using dynamic data. The question is, does something out there that does this already exist?</p>
[ { "answer_id": 169009, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 4, "selected": true, "text": " function humane_date(date_str){\n var time_formats = [\n [60, 'Just Now'],\n [90, '1 Minute'], // 60*1.5\n [3600, 'Minutes', 60], // 60*60, 60\n [5400, '1 Hour'], // 60*60*1.5\n [86400, 'Hours', 3600], // 60*60*24, 60*60\n [129600, '1 Day'], // 60*60*24*1.5\n [604800, 'Days', 86400], // 60*60*24*7, 60*60*24\n [907200, '1 Week'], // 60*60*24*7*1.5\n [2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7\n [3942000, '1 Month'], // 60*60*24*(365/12)*1.5\n [31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)\n [47304000, '1 Year'], // 60*60*24*365*1.5\n [3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365\n [4730400000, '1 Century'], // 60*60*24*365*100*1.5\n ];\n\n var time = ('' + date_str).replace(/-/g,\"/\").replace(/[TZ]/g,\" \"),\n dt = new Date,\n seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),\n token = ' Ago',\n prepend = '',\n i = 0,\n format;\n\n if (seconds < 0) {\n seconds = Math.abs(seconds);\n token = '';\n prepend = 'In ';\n }\n\n while (format = time_formats[i++]) {\n if (seconds < format[0]) {\n if (format.length == 2) {\n return (i>1?prepend:'') + format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago\n } else {\n return prepend + Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');\n }\n }\n }\n\n // overflow for centuries\n if(seconds > 4730400000)\n return Math.round(seconds / 4730400000) + ' Centuries' + token;\n\n return date_str;\n };\n" }, { "answer_id": 169883, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "Date.prototype.toRelativeTime = function(otherTime) {\n // if no parameter is passed, use the current date.\n if (otherTime == undefined) otherTime = new Date();\n\n var diff = Math.abs(this.getTime() - otherTime.getTime()) / 1000;\n\n var MIN = 60, // some \"constants\" just \n HOUR = 3600, // for legibility\n DAY = 86400\n ;\n var out, temp;\n if (diff < MIN) {\n out = \"Less than a minute\";\n\n } else if (diff < 15 * MIN) {\n // less than fifteen minutes, show how many minutes\n temp = Math.round(diff / MIN);\n out = temp + \" minute\" + (temp == 1 ? \"\" : \"s\");\n // eg: 12 minutes\n } else if (diff < HOUR) {\n // less than an hour, round down to the nearest 5 minutes\n out = (Math.floor(diff / (5 * MIN)) * 5) + \" minutes\";\n } else if (diff < DAY) {\n // less than a day, just show hours\n temp = Math.round(diff / HOUR);\n out = temp + \" hour\" + (temp == 1 ? \"\" : \"s\");\n } else if (diff < 30 * DAY) {\n // show how many days ago\n temp = Math.round(diff / DAY);\n out = temp + \" day\" + (temp == 1 ? \"\" : \"s\");\n } else if (diff < 90 * DAY) {\n // more than 30 days, but less than 3 months, show the day and month\n return this.getDate() + \" \" + this.getShortMonth(); // see below\n } else {\n // more than three months difference, better show the year too\n return this.getDate() + \" \" + this.getShortMonth() + \" \" + this.getFullYear();\n }\n return out + (this.getTime() > otherTime.getTime() ? \" from now\" : \" ago\");\n\n};\n\nDate.prototype.getShortMonth = function() {\n return [\"Jan\", \"Feb\", \"Mar\",\n \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\",\n \"Oct\", \"Nov\", \"Dec\"][this.getMonth()];\n};\n\n// sample usage:\nvar x = new Date(2008, 9, 4, 17, 0, 0);\nalert(x.toRelativeTime()); // 9 minutes from now\n\nx = new Date(2008, 9, 4, 16, 45, 0, 0);\nalert(x.toRelativeTime()); // 6 minutes ago\n\nx = new Date(2008, 11, 1); // 1 Dec\n\nx = new Date(2009, 11, 1); // 1 Dec 2009\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
168,931
<p>When you guys are unit testing an application that relies on values from an app.config file? How do you test that those values are read in correctly and how your program reacts to incorrect values entered into a config file?</p> <p>It would be ridiculous to have to modify the config file for the NUnit app, but I can't read in the values from the app.config I want to test.</p> <p>Edit: I think I should clarify perhaps. I'm not worried about the ConfigurationManager failing to read the values, but I am concerned with testing how my program reacts to the values read in.</p>
[ { "answer_id": 168936, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": false, "text": "app.config ConfigurationManager" }, { "answer_id": 255712, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "// setup\nSystem.Configuration.Configuration config = \n ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nconfig.Sections.Add(\"sectionname\", new ConfigSectionType());\nConfigSectionType section = (ConfigSectionType)config.GetSection(\"sectionname\");\nsection.SomeProperty = \"value_you_want_to_test_with\";\nconfig.Save(ConfigurationSaveMode.Modified);\nConfigurationManager.RefreshSection(\"sectionname\");\n\n// carry out test ...\n" }, { "answer_id": 883328, "author": "Tuomas Hietanen", "author_id": 17791, "author_profile": "https://Stackoverflow.com/users/17791", "pm_score": 4, "selected": false, "text": "public class MyClass {\n\npublic static Func<string, string> \n GetConfigValue = s => ConfigurationManager.AppSettings[s];\n\n//...\n\n}\n string connectionString = MyClass.GetConfigValue(\"myConfigValue\");\n MyClass.GetConfigValue = s => s == \"myConfigValue\" ? \"Hi\", \"string.Empty\";\n" }, { "answer_id": 2528410, "author": "yonexbat", "author_id": 288291, "author_profile": "https://Stackoverflow.com/users/288291", "pm_score": 2, "selected": false, "text": " public static void BasicSetup()\n {\n ConnectionStringSettings connectionStringSettings = \n new ConnectionStringSettings();\n connectionStringSettings.Name = \"testmasterconnection\";\n connectionStringSettings.ConnectionString = \n \"server=localhost;user=some;database=some;port=3306;\";\n ConfigurationManager.ConnectionStrings.Clear();\n ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);\n }\n" }, { "answer_id": 4511031, "author": "Pervez Choudhury", "author_id": 41673, "author_profile": "https://Stackoverflow.com/users/41673", "pm_score": 5, "selected": false, "text": "[SetUp]\npublic void SetUp()\n{\n ConfigurationManager.AppSettings.Set(\"SettingKey\" , \"SettingValue\");\n // rest of unit test code follows\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
168,946
<p>Here's my scenario. I created an application which uses Integrated Windows Authentication in order to work. In <code>Application_AuthenticateRequest()</code>, I use <code>HttpContext.Current.User.Identity</code> to get the current <code>WindowsPrincipal</code> of the user of my website.</p> <p>Now here's the funny part. Some of our users have recently gotten married, and their names change. (i.e. the user's NT Login changes from <code>jsmith</code> to <code>jjones</code>) and when my application authenticates them, IIS passes me their OLD LOGIN . I continue to see <code>jsmith</code> passed to my application until I reboot my SERVER! Logging off the client does not work. Restarting the app pool does not work. Only a full reboot. </p> <p>Does anyone know what's going on here? Is there some sort of command I can use to flush whatever cache is giving me this problem? Is my server misconfigured?</p> <p>Note: I definitely do NOT want to restart IIS, my application pools, or the machine. As this is a production box, these are not really viable options.</p> <hr> <p>AviD -</p> <p>Yes, their UPN was changed along with their login name. And Mark/Nick... This is a production enterprise server... It can't just be rebooted or have IIS restarted. </p> <hr> <p><strong>Follow up (for posterity):</strong></p> <p>Grhm's answer was spot-on. This problem pops up in low-volume servers where you don't have a lot of people using your applications, but enough requests are made to keep the users' identity in the cache. The key part of the <a href="http://support.microsoft.com/kb/946358" rel="noreferrer">KB</a> which seems to describe why the cache item is not refreshed after the default of 10 minutes is:</p> <blockquote> <p>The cache entries do time out, however chances are that recurring queries by applications keep the existing cache entry alive for the maximum lifetime of the cache entry.</p> </blockquote> <p>I'm not exactly sure what in our code was causing this (the recurring queries), but the resolution which worked for us was to cut the <code>LsaLookupCacheExpireTime</code> value from the seemingly obscene default of 1 week to just a few hours. This, for us, cut the probability that a user would be impacted in the real world to essentially zero, and yet at the same time doesn't cause an extreme number of SID-Name lookups against our directory servers. An even better solution IMO would be if applications looked up user information by SID instead of mapping user data to textual login name. (Take note, vendors! If you're relying on AD authentication in your application, you'll want to put the SID in your authentication database!)</p>
[ { "answer_id": 7685602, "author": "Grhm", "author_id": 204690, "author_profile": "https://Stackoverflow.com/users/204690", "pm_score": 6, "selected": true, "text": "LookupAccountName()\n\nLookupAccountSid()\n\nLsaOpenPolicy()\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24995/" ]
168,951
<hr /> <p><strong> The <a href="http://docs.php.net/manual/en/class.httprequestpool.php" rel="noreferrer">HttpRequestPool</a> class provides a solution. Many thanks to those who pointed this out.</p> <p>A brief tutorial can be found at: <a href="http://www.phptutorial.info/?HttpRequestPool-construct" rel="noreferrer">http://www.phptutorial.info/?HttpRequestPool-construct</a></strong></p> <hr /> <p><strong>Problem</strong></p> <p>I'd like to make concurrent/parallel/simultaneous HTTP requests in PHP. I'd like to avoid consecutive requests as:</p> <ul> <li>a set of requests will take too long to complete; the more requests the longer</li> <li>the timeout of one request midway through a set may cause later requests to not be made (if a script has an execution time limit)</li> </ul> <p>I have managed to find details for making <a href="http://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/" rel="noreferrer">simultaneuos [sic] HTTP requests in PHP with cURL</a>, however I'd like to explicitly use PHP's <a href="http://php.net/manual/en/book.http.php" rel="noreferrer">HTTP functions</a> if at all possible.</p> <p>Specifically, I need to POST data concurrently to a set of URLs. The URLs to which data are posted are beyond my control; they are user-set.</p> <p>I don't mind if I need to wait for all requests to finish before the responses can be processed. If I set a timeout of 30 seconds on each request and requests are made concurrently, I know I must wait a maximum of 30 seconds (perhaps a little more) for all requests to complete.</p> <p>I can find no details of how this might be achieved. However, I did recently notice a mention in the PHP manual of PHP5+ being able to handle concurrent HTTP requests - I intended to make a note of it at the time, forgot, and cannot find it again.</p> <p><strong>Single request example (works fine)</strong></p> <pre><code>&lt;?php $request_1 = new HttpRequest($url_1, HTTP_METH_POST); $request_1-&gt;setRawPostData($dataSet_1); $request_1-&gt;send(); ?&gt; </code></pre> <p><strong>Concurrent request example (incomplete, clearly)</strong></p> <pre><code>&lt;?php $request_1 = new HttpRequest($url_1, HTTP_METH_POST); $request_1-&gt;setRawPostData($dataSet_1); $request_2 = new HttpRequest($url_2, HTTP_METH_POST); $request_2-&gt;setRawPostData($dataSet_2); // ... $request_N = new HttpRequest($url_N, HTTP_METH_POST); $request_N-&gt;setRawPostData($dataSet_N); // Do something to send() all requests at the same time ?&gt; </code></pre> <p>Any thoughts would be most appreciated!</p> <p><strong>Clarification 1</strong>: I'd like to stick to the PECL HTTP functions as:</p> <ul> <li>they offer a nice OOP interface</li> <li>they're used extensively in the application in question and sticking to what's already in use should be beneficial from a maintenance perspective</li> <li>I generally have to write fewer lines of code to make an HTTP request using the PECL HTTP functions compared to using cURL - fewer lines of code should also be beneficial from a maintenance perspective</li> </ul> <p><strong>Clarification 2</strong>: I realise PHP's HTTP functions aren't built in and perhaps I worded things wrongly there, which I shall correct. I have no concerns about people having to install extra stuff - this is not an application that is to be distributed, it's a web app with a server to itself.</p> <p><strong>Clarification 3</strong>: I'd be perfectly happy if someone authoritatively states that the PECL HTTP cannot do this.</p>
[ { "answer_id": 195806, "author": "Willem", "author_id": 15447, "author_profile": "https://Stackoverflow.com/users/15447", "pm_score": 2, "selected": false, "text": "$request_list = array(\n # address => http request string\n #\n '127.0.0.1' => \"HTTP/1.1 GET /index.html\\nServer: website.com\\n\\n\",\n '192.169.2.3' => \"HTTP/1.1 POST /form.dat\\nForm-data: ...\",\n );\n\nforeach($request_list as $addr => $http_request) {\n # first, create a socket and fire request to every host\n $socklist[$addr] = socket_create();\n socket_set_nonblock($socklist[$addr]); # Make operation asynchronious\n\n if (! socket_connect($socklist[$addr], $addr, 80))\n trigger_error(\"Cannot connect to remote address\");\n\n # the http header is send to this host\n socket_send($socklist[$addr], $http_request, strlen($http_request), MSG_EOF);\n}\n\n$results = array();\n\nforeach(array_keys($socklist) as $host_ip) {\n # Now loop and read every socket until it is exhausted\n $str = socket_read($socklist[$host_ip], 512, PHP_NORMAL_READ);\n if ($str != \"\") \n # add to previous string\n $result[$host_ip] .= $str;\n else\n # Done reading this socket, close it\n socket_close($socklist[$host_ip]);\n}\n# $results now contains an array with the full response (including http-headers)\n# of every connected host.\n" }, { "answer_id": 526426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\n$curlbase = new CurlBase;\n$curlbase->defaultOptions[ CURLOPT_TIMEOUT ] = 30;\n$curlbase->add( new HttpPost($url, array('name'=> 'value', 'a' => 'b')));\n$curlbase->add( new HttpPost($url2, array('name'=> 'value', 'a' => 'b')));\n$curlbase->add( new HttpPost($url3, array('name'=> 'value', 'a' => 'b')));\n$curlbase->perform(); \n\n foreach($curlbase->requests as $request) {\n...\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5343/" ]
168,956
<p>I need a (php) regex to match Yahoo's username rules:</p> <blockquote> <p>Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.).</p> </blockquote>
[ { "answer_id": 168965, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "[A-Za-z][A-Za-z0-9_.]{3,31}\n" }, { "answer_id": 168971, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 3, "selected": false, "text": "/[a-zA-Z][a-zA-Z0-9_]*\\.?[a-zA-Z0-9_]*/\n" }, { "answer_id": 169138, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "^(?=[A-Za-z](?:\\w*(?:\\.\\w*)?$))(\\S{4,32})$\n (?: ... )" }, { "answer_id": 169141, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 5, "selected": true, "text": "/^[A-Za-z](?=[A-Za-z0-9_.]{3,31}$)[a-zA-Z0-9_]*\\.?[a-zA-Z0-9_]*$/\n /^[a-z](?=[\\w.]{3,31}$)\\w*\\.?\\w*$/i\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24999/" ]
168,961
<p>I'm trying to add the lucene sandbox contribution called <a href="http://lucene.apache.org/java/docs/lucene-sandbox/index.html#Term%20Highlighter" rel="nofollow noreferrer">term-highlighter</a> to my pom.xml. I'm not really that familiar with Maven, but the code has a <a href="http://svn.apache.org/repos/asf/lucene/java/trunk/contrib/highlighter/pom.xml.template" rel="nofollow noreferrer">pom.xml.template</a> which seems to imply if I add a dependency that looks like:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt; &lt;artifactId&gt;lucene-highlighter&lt;/artifactId&gt; &lt;/dependency&gt; </code></pre> <p>It might work. Can someone help me out in adding a lucene-community project to my pom.xml file?</p> <p>Thanks for the comments, it turns out that adding the version was all I needed, and I just guessed it should match the lucene-core version I was using.:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt; &lt;artifactId&gt;lucene-highlighter&lt;/artifactId&gt; &lt;version&gt;2.3.1&lt;/version&gt; &lt;/dependency&gt; </code></pre>
[ { "answer_id": 168990, "author": "Sam Merrell", "author_id": 782, "author_profile": "https://Stackoverflow.com/users/782", "pm_score": 1, "selected": false, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.mycompany.app</groupId>\n <artifactId>my-app</artifactId>\n <packaging>jar</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>Maven Quick Start Archetype</name>\n <url>http://maven.apache.org</url>\n\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n</project>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
168,963
<p>I have the following code making a GET request on a URL:</p> <pre><code>$('#searchButton').click(function() { $('#inquiry').load('/portal/?f=searchBilling&amp;pid=' + $('#query').val()); }); </code></pre> <p>But the returned result is not always reflected. For example, I made a change in the response that spit out a stack trace but the stack trace did not appear when I clicked on the search button. I looked at the underlying PHP code that controls the ajax response and it had the correct code and visiting the page directly showed the correct result but the output returned by .load was old.</p> <p>If I close the browser and reopen it it works once and then starts to return the stale information. Can I control this by jQuery or do I need to have my PHP script output headers to control caching?</p>
[ { "answer_id": 168972, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": false, "text": "$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());\n" }, { "answer_id": 168977, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 10, "selected": true, "text": "$.ajax() $.ajaxSetup ({\n // Disable caching of AJAX responses\n cache: false\n});\n" }, { "answer_id": 169503, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "header(\"cache-control: no-cache\");\n \"/portal/?f=searchBilling&x=\" + (new Date()).getTime()\n" }, { "answer_id": 1713433, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$(\"#Search_Result\").load(\"AJAX-Search.aspx?q=\" + $(\"#q\").val() + \"&rnd=\" + String((new Date()).getTime()).replace(/\\D/gi, ''));\n" }, { "answer_id": 2158535, "author": "Marshall", "author_id": 234138, "author_profile": "https://Stackoverflow.com/users/234138", "pm_score": 7, "selected": false, "text": "$.ajax({\n url: \"/YourController\",\n cache: false,\n dataType: \"html\",\n success: function(data) {\n $(\"#content\").html(data);\n }\n});\n" }, { "answer_id": 3149499, "author": "Sasha", "author_id": 380087, "author_profile": "https://Stackoverflow.com/users/380087", "pm_score": 3, "selected": false, "text": "/**\n * Use this function as jQuery \"load\" to disable request caching in IE\n * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });\n **/\n$.fn.loadWithoutCache = function (){\n var elem = $(this);\n var func = arguments[1];\n $.ajax({\n url: arguments[0],\n cache: false,\n dataType: \"html\",\n success: function(data, textStatus, XMLHttpRequest) {\n elem.html(data);\n if(func != undefined){\n func(data, textStatus, XMLHttpRequest);\n }\n }\n });\n return elem;\n}\n" }, { "answer_id": 6616200, "author": "NGRAUPEN", "author_id": 219560, "author_profile": "https://Stackoverflow.com/users/219560", "pm_score": 3, "selected": false, "text": "LoadWithoutCache: function (url, source) {\n $.ajax({\n url: url,\n cache: false,\n dataType: \"html\",\n success: function (data) {\n $(\"#\" + source).html(data);\n return false;\n }\n });\n}\n Init: function (actionUrl1, actionUrl2, actionUrl3) ExampleJS.LoadWithoutCache(actionUrl1, \"div1\");\n" }, { "answer_id": 11609008, "author": "user1545320", "author_id": 1545320, "author_profile": "https://Stackoverflow.com/users/1545320", "pm_score": 2, "selected": false, "text": "$jqm(document).bind('pagebeforeload', function(event, data) {\n var url = data.url;\n var savePageInDOM = true;\n\n if (url.toLowerCase().indexOf(\"vacancies\") >= 0) {\n savePageInDOM = false;\n }\n\n $jqm.mobile.cache = savePageInDOM;\n})\n" }, { "answer_id": 23930553, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var sr = $(\"#Search Result\");\nsr.load(\"AJAX-Search.aspx?q=\" + $(\"#q\")\n.val() + \"&rnd=\" + String((new Date).getTime())\n.replace(/\\D/gi, \"\"));\n" }, { "answer_id": 24655541, "author": "NickStees", "author_id": 1943033, "author_profile": "https://Stackoverflow.com/users/1943033", "pm_score": 2, "selected": false, "text": "$('#searchButton').click(function() {\n$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime()); \n});\n" }, { "answer_id": 40810038, "author": "Adam Gordon Bell", "author_id": 135202, "author_profile": "https://Stackoverflow.com/users/135202", "pm_score": 1, "selected": false, "text": "(function($) {\n var _load = jQuery.fn.load;\n $.fn.load = function(url, params, callback) {\n if ( typeof url !== \"string\" && _load ) {\n return _load.apply( this, arguments );\n }\n var selector, type, response,\n self = this,\n off = url.indexOf(\" \");\n\n if (off > -1) {\n selector = stripAndCollapse(url.slice(off));\n url = url.slice(0, off);\n }\n\n // If it's a function\n if (jQuery.isFunction(params)) {\n\n // We assume that it's the callback\n callback = params;\n params = undefined;\n\n // Otherwise, build a param string\n } else if (params && typeof params === \"object\") {\n type = \"POST\";\n }\n\n // If we have elements to modify, make the request\n if (self.length > 0) {\n jQuery.ajax({\n url: url,\n\n // If \"type\" variable is undefined, then \"GET\" method will be used.\n // Make value of this field explicit since\n // user can override it through ajaxSetup method\n type: type || \"GET\",\n dataType: \"html\",\n cache: false,\n data: params\n }).done(function(responseText) {\n\n // Save response for use in complete callback\n response = arguments;\n\n self.html(selector ?\n\n // If a selector was specified, locate the right elements in a dummy div\n // Exclude scripts to avoid IE 'Permission Denied' errors\n jQuery(\"<div>\").append(jQuery.parseHTML(responseText)).find(selector) :\n\n // Otherwise use the full result\n responseText);\n\n // If the request succeeds, this function gets \"data\", \"status\", \"jqXHR\"\n // but they are ignored because response was set above.\n // If it fails, this function gets \"jqXHR\", \"status\", \"error\"\n }).always(callback && function(jqXHR, status) {\n self.each(function() {\n callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);\n });\n });\n }\n\n return this;\n }\n})(jQuery);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
168,979
<p>In C++, static library A is linked into dynamic libraries B and C. If a class, Foo, is used in A which is defined in B, will C link if it doesn't use Foo?</p> <p>I thought the answer was yes, but I am now running into a problem with xlc_r7 where library C says Foo is an undefined symbol, which it is as far as C is concerned. My problem with that is Library C isn't using the class referencing it. This links in Win32 (VC6) and OpenVMS.</p> <p>Is this a linker discrepancy or a PBCAK?</p> <p><strong>New info:</strong> </p> <ol> <li><p>B depends on C, but not visa-versa.</p></li> <li><p>I'm not using /OPT:REF to link on Windows and it links without issue. </p></li> </ol>
[ { "answer_id": 170163, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "__declspec( dllexport )" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24638/" ]
168,991
<p>I'd like to be able to (effectively) sort a database view - I know that conceptually order in a db view is invalid, but I have the following scenario to deal with:</p> <ul> <li>a third-party legacy application, that reads data from database tables using a select(*) from tablename statement</li> <li>the legacy application is very sensitive to the order of the records</li> <li>an application I've written to allow users to manage the data in the tables more easily, but inserts and deletes from the table naturally upset the order of the records.</li> </ul> <p>Changing the statement in the legacy application to select (*) from tablename order by field would fix my problem, but isn't an option.</p> <p>So - I've set up a staging table into which the data can be exported in the right order, but this is a resource-hungry option, means that the data isn't 'live' in the legacy application and is additional work for users.</p> <p>I'd like to be able to get at an ordered version of the table with these contraints. Any ideas how?</p> <hr> <p>Update - I'm working with Sybase 12.5, but I'd like to avoid a tightly coupled solution with a specific RDBMS - it might change.</p> <p>I cannot add an 'order by' clause to a view, because of SQL standards as referred to in <a href="http://en.wikipedia.org/wiki/View_(database)" rel="nofollow noreferrer">this Wikipedia entry</a></p>
[ { "answer_id": 168995, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 1, "selected": false, "text": "CREATE VIEW OrderedTable\nAS SELECT TOP (Select Count(*) from UnorderedTable) *\nFROM UnorderedTable Order By field\n" }, { "answer_id": 169024, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION orderedTable() \nRETURNS @returnTable TABLE \n (val varchar(100)) AS\nBEGIN\n insert @returnTable (val)\n select val from MyTable\n order by val desc\n RETURN \nEND\n\nGO\n\nSELECT * FROM orderedTable\n" }, { "answer_id": 169167, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "SELECT TOP 100 PERCENT * FROM TABLE ORDER BY 1\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2362/" ]
168,992
<p>I'm trying to display a series of titles varying from 60 characters to 160 or so and the capitalization varies, some of it all caps, some half caps. When it's mostly lowercase the whole 160 characters of text fits in the width I want, but when it starts getting more caps (they must be wider), it starts over flowing.</p> <p>Is there a way to use an attractive fixed witdh font (upper and lowercase widths the same too), or dynamically shrink the text to fit, or otherwise recognize how much space the text is going to take on the server side, and cut off the end dynamically? Or do you folks have a better solution?</p>
[ { "answer_id": 168997, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 1, "selected": false, "text": "style=\"width: Xpx; overflow: hidden;\"" }, { "answer_id": 169000, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 2, "selected": false, "text": "h1 {\n width: 400px; /* or whatever width */\n overflow: hidden;\n}\n" }, { "answer_id": 169054, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 4, "selected": true, "text": "<html>\n<head>\n<title>h1 stackoverflow question</title>\n<style type=\"text/css\">\n\n* { margin:0; padding:0 }\n\nh3 { \n display: block;\n width: 250px;\n height: 20px;\n margin-bottom: 5px;\n overflow: hidden;\n font-family: Courier, Lucidatypewriter, monospace;\n font: normal 20px/20px Courier;\n border: 1px solid red;\n}\n\n</style>\n</head>\n<body>\n\n<h3>Hello, World</h3>\n<h3>Lorem Ipsum dolor sit Amet</h3>\n<h3>Adipiscing Lorem dolor sit lorem ipsum</h3>\n<h3>&quot;C&quot; is for Cookie, that's good enough for lorem ipsum</h3>\n<h3>Oh, it's a lorem ipsum dolor sit amet. Adipiscing elit.</h3>\n\n</body>\n</html>\n" }, { "answer_id": 169083, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "var fontSize = \"200%\"; // your regular heading font size\nvar h1 = document.getElementById(\"myHeading\");\nwhile (h1.offsetHeight > oneLine) {\n fontSize *= (parseInt(fontSize) - 5) + \"%\";\n h1.style.fontSize = fontSize;\n}\n" }, { "answer_id": 178221, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 0, "selected": false, "text": "body {\n font:62.5%/140% Courier, Lucidatypewriter, monospace;\n}\n h1, h3 {\n ....\n height:2em;\n ....\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
169,008
<p>I'm trying to write a regex that will parse out the <strong>directory and filename</strong> of a fully qualified path using matching groups.</p> <p>so...</p> <pre><code>/var/log/xyz/10032008.log </code></pre> <p>would recognize <code>group 1 to be "/var/log/xyz"</code> and <code>group 2 to be "10032008.log"</code></p> <p>Seems simple but I can't get the matching groups to work for the life of me.</p> <p>NOTE: As pointed out by some of the respondents this is probably not a good use of regular expressions. Generally I'd prefer to use the file API of the language I was using. What I'm actually trying to do is a little more complicated than this but would have been much more difficult to explain, so I chose a domain that everyone would be familiar with in order to most succinctly describe the root problem.</p>
[ { "answer_id": 169014, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "^(.*)/([^/]*)$\n ^\\(.*\\)/\\([^/]*\\)$\n" }, { "answer_id": 169021, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 7, "selected": true, "text": "^(.+)\\/([^\\/]+)$\n" }, { "answer_id": 169033, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "/^(\\/([^/]+\\/)*)(.*)$/\n" }, { "answer_id": 169056, "author": "Travis Illig", "author_id": 8116, "author_profile": "https://Stackoverflow.com/users/8116", "pm_score": 4, "selected": false, "text": "^(.*/)([^/]*)$\n" }, { "answer_id": 8369774, "author": "Aurélien Ooms", "author_id": 1079252, "author_profile": "https://Stackoverflow.com/users/1079252", "pm_score": 2, "selected": false, "text": "[/]{0,1}([^/]+[/])*([^/]*)\n ((/)|())([^/]+/)*([^/]*)\n ^[/]{0,1}([^/]+[/])*([^/]*)$\n^((/)|())([^/]+/)*([^/]*)$\n" }, { "answer_id": 26635619, "author": "Suganthan Madhavan Pillai", "author_id": 2534236, "author_profile": "https://Stackoverflow.com/users/2534236", "pm_score": 1, "selected": false, "text": "^(.+?)/([\\w]+\\.log)$\n /" }, { "answer_id": 33021907, "author": "Chad Nouis", "author_id": 1078068, "author_profile": "https://Stackoverflow.com/users/1078068", "pm_score": 5, "selected": false, "text": "((?:[^/]*/)*)(.*)\n (\n (?:\n [^/]*\n /\n )\n *\n)\n(.*)\n ( -- capture group 1 starts\n (?: -- non-capturing group starts\n [^/]* -- greedily match as many non-directory separators as possible\n / -- match a single directory-separator character\n ) -- non-capturing group ends\n * -- repeat the non-capturing group zero-or-more times\n) -- capture group 1 ends\n(.*) -- capture all remaining characters in group 2\n #!/usr/bin/perl -w\n\nuse strict;\nuse warnings;\n\nsub test {\n my $str = shift;\n my $testname = shift;\n\n $str =~ m#((?:[^/]*/)*)(.*)#;\n\n print \"$str -- $testname\\n\";\n print \" 1: $1\\n\";\n print \" 2: $2\\n\\n\";\n}\n\ntest('/var/log/xyz/10032008.log', 'absolute path');\ntest('var/log/xyz/10032008.log', 'relative path');\ntest('10032008.log', 'filename-only');\ntest('/10032008.log', 'file directly under root');\n /var/log/xyz/10032008.log -- absolute path\n 1: /var/log/xyz/\n 2: 10032008.log\n\nvar/log/xyz/10032008.log -- relative path\n 1: var/log/xyz/\n 2: 10032008.log\n\n10032008.log -- filename-only\n 1:\n 2: 10032008.log\n\n/10032008.log -- file directly under root\n 1: /\n 2: 10032008.log\n" }, { "answer_id": 55600175, "author": "theBuzzyCoder", "author_id": 2147023, "author_profile": "https://Stackoverflow.com/users/2147023", "pm_score": 2, "selected": false, "text": "/ . touch . a-z A-Z 0-9 - _ / /(?:(?P<dir>(?:[/]?)(?:[^\\/]+/)+)(?P<filename>[^/]+))/\n root / / /(?P<filepath>(?P<root>[/]?)(?P<rest_of_the_path>.+))/\n / / /(?P<filepath>(?P<first_directory>(?P<root>[/]?)[^\\/]+/)(?P<rest_of_the_path>.+))/\n /(?P<filepath>(?P<dir>(?P<root>[/]?)(?P<single_dir>[^\\/]+/)+)(?P<rest_of_the_path>.+))/\n yz/ var/ log/ yz/ / [^/] /(?:(?P<dir>(?:[/]?)(?:[^\\/]+/)+)(?P<filename>[^/]+))/\n ^ (?P<dir>pattern) dir file (?:pattern) ? + [^\\/] / [/]? / [^\\/]+/ / / var/ xyz/" }, { "answer_id": 68665097, "author": "rpmathur 12", "author_id": 11573816, "author_profile": "https://Stackoverflow.com/users/11573816", "pm_score": 0, "selected": false, "text": "https://drive.google.com/drive/folders/14Q6d-KiwgTKE-qm5EOZvHeX86-Wf9Q5f?usp=sharing\n [-\\w]{25,} \n =REGEXEXTRACT(N2,\"[-\\w]{25,}\")\n 14Q6d-KiwgTKE-qm5EOZvHeX86-Wf9Q5f" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
169,034
<p>Every time I call this method my NSMutableData is leaking and I cannot figure out how to plug it. theData's retain count is upped by one after the decoder is allocated and initialized and I have no idea why. I am stuck with a retain count of 2 at the end of the method and attempting to release it causes an app crash.</p> <pre><code>- (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey { NSMutableData *theData; NSKeyedUnarchiver *decoder; theData = [NSData dataWithContentsOfFile:inFile]; decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData]; venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy]; [decoder finishDecoding]; [decoder release]; } </code></pre>
[ { "answer_id": 169247, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 2, "selected": false, "text": "venueIOList -autorelease -release" }, { "answer_id": 169709, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 3, "selected": true, "text": "venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy];\n ListClassName *decodedList = [decoder decodeObjectForKey:inKey];\nself.venueIOList = decodedList;\n decodedList readVenueArchiveFile: decodedList" }, { "answer_id": 169742, "author": "titaniumdecoy", "author_id": 18091, "author_profile": "https://Stackoverflow.com/users/18091", "pm_score": 0, "selected": false, "text": "theData = [NSData dataWithContentsOfFile:inFile]; theData = [[[NSData alloc] initWithContentsOfFile:inFile] autorelease]; decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];" }, { "answer_id": 174835, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 2, "selected": false, "text": "theData = [NSData dataWithContentsOfFile:inFile];\n theData = [[NSData alloc] initWithContentsOfFile:inFile];\n [theData release];\n theData - (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey\n{\n NSMutableData *theData;\n NSKeyedUnarchiver *decoder;\n\n theData = [[NSData alloc] initWithContentsOfFile:inFile];\n decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];\n ListClassName *decodedList = [decoder decodeObjectForKey:inKey];\n self.venueIOList = decodedList;\n [decoder finishDecoding];\n [decoder release];\n [theData release];\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25004/" ]
169,044
<p>My development environment is running in JDK1.6, and I need to compile some classes so they are compatible with a client running JDK1.5. How would I do this with the 'javac' ant target?</p>
[ { "answer_id": 169055, "author": "Tom Feiner", "author_id": 13523, "author_profile": "https://Stackoverflow.com/users/13523", "pm_score": 2, "selected": false, "text": "< javac srcdir=\"${src} destdir=\"${build}\" target=\"1.5\" />" }, { "answer_id": 169065, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 1, "selected": false, "text": "<javac source=\"1.5\"... />\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,058
<p>I've got a Win32 C++ app with a suite of unit tests. After the unit tests have finished running, I'd like a human-readable report on any unfreed memory to be automatically generated. Ideally, the report will have a stack with files &amp; line number info for each unfreed allocation. It would be nice to have them generated in a consistent order to make it easy to diff it from one run to the next. (Basically, I would like the results of valgrind --leak-check=full, but on windows). </p> <p>I've had success with UMDH getting this kind of info from running processes, but that tool only seems to work if you attach to an existing process. I want this to happen automatically every time I run my unit tests.</p> <p>Is there a tool that can do this? If so, how do I use it? </p> <p>Thanks!</p>
[ { "answer_id": 169088, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "_CrtSetReportMode\n_CrtSetReportFile\n_CrtMemState \n_CrtMemCheckpoint\n_CrtMemDumpStatistics\n_CrtSetReportFile\n_CrtSetDbgFlag\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23524/" ]
169,070
<p>How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an <code>os.chdir()</code>, the cwd will not be changed after the function is called.</p>
[ { "answer_id": 169079, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 2, "selected": false, "text": "def preserve_cwd(function):\n def decorator(*args, **kwargs):\n cwd = os.getcwd()\n result = function(*args, **kwargs)\n os.chdir(cwd)\n return result\n return decorator\n @preserve_cwd\ndef test():\n print 'was:',os.getcwd()\n os.chdir('/')\n print 'now:',os.getcwd()\n\n>>> print os.getcwd()\n/Users/dspitzer\n>>> test()\nwas: /Users/dspitzer\nnow: /\n>>> print os.getcwd()\n/Users/dspitzer\n" }, { "answer_id": 169112, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": false, "text": "from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6\nimport contextlib, os\n\n@contextlib.contextmanager\ndef remember_cwd():\n curdir= os.getcwd()\n try: yield\n finally: os.chdir(curdir)\n print \"getcwd before:\", os.getcwd()\nwith remember_cwd():\n walk_around_the_filesystem()\nprint \"getcwd after:\", os.getcwd()\n" }, { "answer_id": 170174, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 5, "selected": false, "text": "def preserve_cwd(function):\n @functools.wraps(function)\n def decorator(*args, **kwargs):\n cwd = os.getcwd()\n try:\n return function(*args, **kwargs)\n finally:\n os.chdir(cwd)\n return decorator\n @contextlib.contextmanager\ndef remember_cwd():\n curdir = os.getcwd()\n try:\n yield\n finally:\n os.chdir(curdir)\n" }, { "answer_id": 14019583, "author": "CharlesB", "author_id": 11343, "author_profile": "https://Stackoverflow.com/users/11343", "pm_score": 6, "selected": true, "text": "subdir = d / 'subdir' #subdir is a path object, in the path.py module\nwith subdir:\n # here current dir is subdir\n\n#not anymore\n" }, { "answer_id": 72163496, "author": "Machinexa", "author_id": 11332999, "author_profile": "https://Stackoverflow.com/users/11332999", "pm_score": 3, "selected": false, "text": "import contextlib\nwith contextlib.chdir('/path/to/cwd/to'):\n pass\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
169,080
<p>I'd like to be able to toggle easily between two values for "maximum number of parallel project builds" in Visual Studio 2008 (in Tools->Options->Projects and Solutions->Build and Run). (When I'm planning on doing concurrent work I'd like to reduce it from 4 to 3.) I'm not too well versed in writing macros for the IDE. When I try recording a macro, and perform all the actions (open the dialog, change the setting, click OK), the only thing that gets recorded is this:</p> <pre><code>DTE.ExecuteCommand ("Tools.Options") </code></pre> <p>Is my goal unattainable?</p>
[ { "answer_id": 169093, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "Dim p = DTE.Properties(\"ProjectsAndSolutions\",\"BuildAndRun\")\np.Item(\"MaxNumParallelBuilds\")\n" }, { "answer_id": 6443508, "author": "Coder_Dan", "author_id": 449295, "author_profile": "https://Stackoverflow.com/users/449295", "pm_score": 1, "selected": false, "text": "Sub EditConcurrentBuilds()\n Dim p As EnvDTE.Properties = DTE.Properties(\"Environment\", \"ProjectsAndSolution\")\n Dim item As EnvDTE.Property = p.Item(\"ConcurrentBuilds\")\n Dim text As String = InputBox(\"Enter number of concurrent builds\", \"Concurrent Build Option\")\n Dim v As Integer = Val(text)\n\n If (v > 0 And v < 5) Then\n item.Value = text\n End If\nEnd Sub\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
169,107
<p>I'm in a situation where I would to generate a script for a database that I could run on another server and get a database identical to the original one, but without any of the data. In essence, I want to end up with a big create script that captures the database schema. </p> <p>I am working in an environment that has SQL Server 2000 installed, and I am unable to install the 2005 client tools (in the event that they would help). I can't afford RedGate, but I really would like to have a database with identical schema on another server.</p> <p>Any suggestions? Any simple .exe (no installation required) tools, tips, or T-SQL tricks would be much appreciated.</p> <p><strong>Update:</strong> The database I'm working with has 200+ tables and several foreign-key relationships and constraints, so manually scripting each table and pasting together the script is not a viable option. I'm looking for something better than this manual solution</p> <p><strong>Additional Update</strong> Unless I'm completely missing something, this is not a viable solution using the SQL 2000 tools. When I select the option to generate a create script on a database. I end up with a script that contains a CREATE DATABASE command, and creates none of the objects - the tables, the constraints, etc. SQL 2005's Management studio may handle the objects as well, but the database is in an environment where there is no way for me to connect an installation of Management Studio to it.</p>
[ { "answer_id": 169135, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 5, "selected": true, "text": "Script Database as > Create to > file > All Tasks > Generate Scripts" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19452/" ]
169,116
<p>I have a type (System.Type) of an enum and a string containing enumeration value to set.</p> <p>E.g. given: </p> <pre><code>enum MyEnum { A, B, C }; </code></pre> <p>I have typeof(MyEnum) and "B".</p> <p>How do I create MyEnum object set to MyEnum.B?</p>
[ { "answer_id": 169120, "author": "Yuval", "author_id": 23202, "author_profile": "https://Stackoverflow.com/users/23202", "pm_score": 4, "selected": false, "text": "MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), \"B\");\n" }, { "answer_id": 169181, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 2, "selected": false, "text": "void foo(Type t)\n{\n Object o = Enum.Parse(t, \"B\");\n}\n" }, { "answer_id": 13733479, "author": "Brad Patton", "author_id": 27989, "author_profile": "https://Stackoverflow.com/users/27989", "pm_score": 1, "selected": false, "text": "public static class Utils {\n public static T ParseEnum<T>(string value) {\n return (T)Enum.Parse(typeof(T), value, true);\n }\n string s = \"B\";\nMyEnum enumValue = Utils.ParseEnum<MyEnum>(s);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,121
<p>When I try to bind port 80 to a socket in c, i always get the error, that I don't have permission to use this port. is there an easy way to get this permission?</p>
[ { "answer_id": 169147, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": false, "text": "winsock" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25017/" ]
169,146
<p>I'm getting an unexpected T_CONCAT_EQUAL error on a line of the following form:</p> <pre><code>$arg1 .= "arg2".$arg3."arg4"; </code></pre> <p>I'm using PHP5. I could simply go an do the following:</p> <pre><code>$arg1 = $arg1."arg2".$arg3."arg4"; </code></pre> <p>but I'd like to know whats going wrong in the first place. Any ideas?</p> <p>Thanks, sweeney</p>
[ { "answer_id": 169187, "author": "Brian Sweeney", "author_id": 2170994, "author_profile": "https://Stackoverflow.com/users/2170994", "pm_score": 1, "selected": false, "text": "$arg1 .= \"arg2\".$arg3.\"arg4\";\n arg1 .= \"arg2\".$arg3.\"arg4\";\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2170994/" ]
169,150
<p>How can I configure an application, or even an entire machine, to use either the server or workstation flavor of the CLR's garbage collection? </p>
[ { "answer_id": 260139, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 0, "selected": false, "text": "GCSettings.LatencyMode" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593/" ]
169,155
<p>I am using SetCursor to set the system cursor to my own image. The code looks something like this:</p> <pre><code>// member on some class HCURSOR _cursor; // at init time _cursor = LoadCursorFromFile("somefilename.cur"); // in some function SetCursor(_cursor); </code></pre> <p>When I do this the cursor does change, but on the first mouse move message it changes back to the default system arrow cursor. This is the only code in the project that is setting the cursor. What do I need to do to make the cursor stay the way I set it?</p>
[ { "answer_id": 169280, "author": "Joe Ludwig", "author_id": 1031, "author_profile": "https://Stackoverflow.com/users/1031", "pm_score": 4, "selected": true, "text": "WM_SETCURSOR WM_SETCURSOR SetCursor WM_SETCURSOR // defined somewhere\nHWND windowHandle;\nHCURSOR cursor;\n\nSetCursor(cursor);\nSetClassLong(windowHandle, GCL_HCURSOR, (DWORD)cursor);\n SetCursor SetClassLong" }, { "answer_id": 1592563, "author": "Heinz Traub", "author_id": 192841, "author_profile": "https://Stackoverflow.com/users/192841", "pm_score": 1, "selected": false, "text": "RegisterClass || RegisterClassEx WNDCLASS.hCursor || WNDCLASSEX.hCursor NULL" }, { "answer_id": 40096492, "author": "sergiol", "author_id": 383779, "author_profile": "https://Stackoverflow.com/users/383779", "pm_score": 0, "selected": false, "text": "RegisterClass RegisterClassEx BOOL CMyWnd::RegisterWindowClass()\n{\n WNDCLASS wndcls;\n // HINSTANCE hInst = AfxGetInstanceHandle();\n HINSTANCE hInst = AfxGetResourceHandle();\n\n if (!(::GetClassInfo(hInst, _T(\"MyCtrl\"), &wndcls)))\n {\n // otherwise we need to register a new class\n wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;\n wndcls.lpfnWndProc = ::DefWindowProc;\n wndcls.cbClsExtra = wndcls.cbWndExtra = 0;\n wndcls.hInstance = hInst;\n wndcls.hIcon = NULL;\n wndcls.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);\n wndcls.hbrBackground = (HBRUSH) (COLOR_3DFACE + 1);\n wndcls.lpszMenuName = NULL;\n wndcls.lpszClassName = _T(\"MyCtrl\");\n\n if (!AfxRegisterClass(&wndcls))\n {\n AfxThrowResourceException();\n return FALSE;\n }\n }\n\n return TRUE;\n}\n wndcls.hCursor WM_SETCURSOR WM_SETCURSOR BEGIN_MESSAGE_MAP(CMyWnd, CWnd)\n //... other messages\n ON_WM_SETCURSOR()\nEND_MESSAGE_MAP()\n OnSetCursor BOOL CMyWnd::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)\n{\n if (SomeCondition())\n return FALSE;\n\n return __super::OnSetCursor(pWnd, nHitTest, message);\n}\n SomeCondition() BOOL CMyWnd::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)\n{\n return FALSE;\n}\n afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031/" ]
169,170
<p>I am looking for a way to do a keep alive check in .NET. The scenario is for both UDP and TCP.</p> <p>Currently in TCP what I do is that one side connects and when there is no data to send it sends a keep alive every X seconds.</p> <p>I want the other side to check for data, and if non was received in X seconds, to raise an event or so.</p> <p>One way i tried to do was do a blocking receive and set the socket's RecieveTimeout to X seconds. But the problem was whenever the Timeout happened, the socket's Receive would throw an SocketExeception and the socket on this side would close, is this the correct behaviour ? why does the socket close/die after the timeout instead of just going on ?</p> <p>A check if there is data and sleep isn't acceptable (since I might be lagging on receiving data while sleeping).</p> <p>So what is the best way to go about this, and why is the method i described on the other side failing ?</p>
[ { "answer_id": 171344, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 4, "selected": false, "text": " public static void SetTcpKeepAlive(Socket socket, uint keepaliveTime, uint keepaliveInterval)\n {\n /* the native structure\n struct tcp_keepalive {\n ULONG onoff;\n ULONG keepalivetime;\n ULONG keepaliveinterval;\n };\n */\n\n // marshal the equivalent of the native structure into a byte array\n uint dummy = 0;\n byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];\n BitConverter.GetBytes((uint)(keepaliveTime)).CopyTo(inOptionValues, 0);\n BitConverter.GetBytes((uint)keepaliveTime).CopyTo(inOptionValues, Marshal.SizeOf(dummy));\n BitConverter.GetBytes((uint)keepaliveInterval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);\n\n // write SIO_VALS to Socket IOControl\n socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);\n }\n" }, { "answer_id": 69497010, "author": "Guillermo Ruffino", "author_id": 229052, "author_profile": "https://Stackoverflow.com/users/229052", "pm_score": 2, "selected": false, "text": "tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);\ntcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 2);\ntcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 2);\ntcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,186
<p>I am having a very hard time finding a standard pattern / best practice that deals with rendering child controls inside a composite based on a property value.</p> <p>Here is a basic scenario. I have a Composite Control that has two child controls, a textbox and a dropdown. Lets say there is a property that toggles which child to render.</p> <p>so:</p> <pre><code>myComposite.ShowDropdown = true; </code></pre> <p>If true, it shows a dropdown, otherwise it shows the textbox.</p> <p>The property value should be saved across postbacks, and the the correct control should be displayed based on the postback value. </p> <p>Any good examples out there?</p>
[ { "answer_id": 169205, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 0, "selected": false, "text": "public bool ShowDropDown\n{\n get{ return (bool)ViewState[\"ShowDropDown\"]; }\n set{ ViewState[\"ShowDropDown\"]; }\n}\n\n\nprivate void Page_Load(object sender, EventArgs e)\n{\n DropDaownControl.Visible = ShowDropDown;\n TextBoxControl.Visible = !ShowDropDown;\n} \n/* some more code */\n" }, { "answer_id": 169353, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 3, "selected": true, "text": "public virtual bool ShowDropdown\n{\n get\n {\n object o = ViewState[\"ShowDropdown\"];\n if (o != null)\n return (bool)o;\n return false; // Default value\n }\n set\n {\n bool oldValue = ShowDropdown;\n if (value != oldValue)\n {\n ViewState[\"ShowDropdown\"] = value;\n }\n }\n}\n dropDown.Visible = ShowDropDown;\ntextBox.Visible = !ShowDropDown;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25020/" ]
169,193
<p>There is a way to keep the scroll on bottom for a multi line textbox?</p> <p>Something like in the vb6 </p> <pre><code>txtfoo.selstart=len(txtfoo.text) </code></pre> <p>I'm trying with txtfoo.selectionstart=txtfoo.text.length without success.</p> <p>Regards.</p>
[ { "answer_id": 169210, "author": "MazarD", "author_id": 22672, "author_profile": "https://Stackoverflow.com/users/22672", "pm_score": 4, "selected": true, "text": "txtfoo.AppendText \n txtfoo.text+=\"something\"\n" }, { "answer_id": 169219, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "txtfoo.Text += \"something\";\ntxtfoo.SelectionStart = txtfoo.Text.Length;\ntxtfoo.ScrollToCaret();\n" }, { "answer_id": 169264, "author": "RodgerB", "author_id": 20900, "author_profile": "https://Stackoverflow.com/users/20900", "pm_score": 0, "selected": false, "text": "Public Class Form1\n\n Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click\n ScrollTextbox()\n End Sub\n\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n ScrollTextbox()\n End Sub\n\n Private Sub ScrollTextbox()\n TextBox1.SelectionStart = TextBox1.TextLength\n TextBox1.ScrollToCaret()\n End Sub\n\nEnd Class\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22672/" ]
169,201
<p>In ActionScript 3.0, is there an automatic way to calculate the number of days, hours, minutes and seconds between two specified dates?</p> <p>Basicly, what I need is the ActionScript equivalent of the .NET Timespan class.</p> <p>Any idea?</p>
[ { "answer_id": 169218, "author": "Russell Myers", "author_id": 18194, "author_profile": "https://Stackoverflow.com/users/18194", "pm_score": 4, "selected": false, "text": "var someDate:Date = new Date(...);\nvar anotherDate:Date = new Date(...);\nvar millisecondDifference:int = anotherDate.valueOf() - someDate.valueOf();\nvar seconds:int = millisecondDifference / 1000;\n....\n" }, { "answer_id": 457213, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 5, "selected": false, "text": "TimeSpan.fromDates(later, earlier).totalDays;\n /**\n * Represents an interval of time \n */ \npublic class TimeSpan\n{\n private var _totalMilliseconds : Number;\n\n public function TimeSpan(milliseconds : Number)\n {\n _totalMilliseconds = Math.floor(milliseconds);\n }\n\n /**\n * Gets the number of whole days\n * \n * @example In a TimeSpan created from TimeSpan.fromHours(25), \n * totalHours will be 1.04, but hours will be 1 \n * @return A number representing the number of whole days in the TimeSpan\n */\n public function get days() : int\n {\n return int(_totalMilliseconds / MILLISECONDS_IN_DAY);\n }\n\n /**\n * Gets the number of whole hours (excluding entire days)\n * \n * @example In a TimeSpan created from TimeSpan.fromMinutes(1500), \n * totalHours will be 25, but hours will be 1 \n * @return A number representing the number of whole hours in the TimeSpan\n */\n public function get hours() : int\n {\n return int(_totalMilliseconds / MILLISECONDS_IN_HOUR) % 24;\n }\n\n /**\n * Gets the number of whole minutes (excluding entire hours)\n * \n * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), \n * totalSeconds will be 65.5, but seconds will be 5 \n * @return A number representing the number of whole minutes in the TimeSpan\n */\n public function get minutes() : int\n {\n return int(_totalMilliseconds / MILLISECONDS_IN_MINUTE) % 60; \n }\n\n /**\n * Gets the number of whole seconds (excluding entire minutes)\n * \n * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), \n * totalSeconds will be 65.5, but seconds will be 5 \n * @return A number representing the number of whole seconds in the TimeSpan\n */\n public function get seconds() : int\n {\n return int(_totalMilliseconds / MILLISECONDS_IN_SECOND) % 60;\n }\n\n /**\n * Gets the number of whole milliseconds (excluding entire seconds)\n * \n * @example In a TimeSpan created from TimeSpan.fromMilliseconds(2123), \n * totalMilliseconds will be 2001, but milliseconds will be 123 \n * @return A number representing the number of whole milliseconds in the TimeSpan\n */\n public function get milliseconds() : int\n {\n return int(_totalMilliseconds) % 1000;\n }\n\n /**\n * Gets the total number of days.\n * \n * @example In a TimeSpan created from TimeSpan.fromHours(25), \n * totalHours will be 1.04, but hours will be 1 \n * @return A number representing the total number of days in the TimeSpan\n */\n public function get totalDays() : Number\n {\n return _totalMilliseconds / MILLISECONDS_IN_DAY;\n }\n\n /**\n * Gets the total number of hours.\n * \n * @example In a TimeSpan created from TimeSpan.fromMinutes(1500), \n * totalHours will be 25, but hours will be 1 \n * @return A number representing the total number of hours in the TimeSpan\n */\n public function get totalHours() : Number\n {\n return _totalMilliseconds / MILLISECONDS_IN_HOUR;\n }\n\n /**\n * Gets the total number of minutes.\n * \n * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), \n * totalSeconds will be 65.5, but seconds will be 5 \n * @return A number representing the total number of minutes in the TimeSpan\n */\n public function get totalMinutes() : Number\n {\n return _totalMilliseconds / MILLISECONDS_IN_MINUTE;\n }\n\n /**\n * Gets the total number of seconds.\n * \n * @example In a TimeSpan created from TimeSpan.fromMilliseconds(65500), \n * totalSeconds will be 65.5, but seconds will be 5 \n * @return A number representing the total number of seconds in the TimeSpan\n */\n public function get totalSeconds() : Number\n {\n return _totalMilliseconds / MILLISECONDS_IN_SECOND;\n }\n\n /**\n * Gets the total number of milliseconds.\n * \n * @example In a TimeSpan created from TimeSpan.fromMilliseconds(2123), \n * totalMilliseconds will be 2001, but milliseconds will be 123 \n * @return A number representing the total number of milliseconds in the TimeSpan\n */\n public function get totalMilliseconds() : Number\n {\n return _totalMilliseconds;\n }\n\n /**\n * Adds the timespan represented by this instance to the date provided and returns a new date object.\n * @param date The date to add the timespan to\n * @return A new Date with the offseted time\n */ \n public function add(date : Date) : Date\n {\n var ret : Date = new Date(date.time);\n ret.milliseconds += totalMilliseconds;\n\n return ret;\n }\n\n /**\n * Creates a TimeSpan from the different between two dates\n * \n * Note that start can be after end, but it will result in negative values. \n * \n * @param start The start date of the timespan\n * @param end The end date of the timespan\n * @return A TimeSpan that represents the difference between the dates\n * \n */ \n public static function fromDates(start : Date, end : Date) : TimeSpan\n {\n return new TimeSpan(end.time - start.time);\n }\n\n /**\n * Creates a TimeSpan from the specified number of milliseconds\n * @param milliseconds The number of milliseconds in the timespan\n * @return A TimeSpan that represents the specified value\n */ \n public static function fromMilliseconds(milliseconds : Number) : TimeSpan\n {\n return new TimeSpan(milliseconds);\n }\n\n /**\n * Creates a TimeSpan from the specified number of seconds\n * @param seconds The number of seconds in the timespan\n * @return A TimeSpan that represents the specified value\n */ \n public static function fromSeconds(seconds : Number) : TimeSpan\n {\n return new TimeSpan(seconds * MILLISECONDS_IN_SECOND);\n }\n\n /**\n * Creates a TimeSpan from the specified number of minutes\n * @param minutes The number of minutes in the timespan\n * @return A TimeSpan that represents the specified value\n */ \n public static function fromMinutes(minutes : Number) : TimeSpan\n {\n return new TimeSpan(minutes * MILLISECONDS_IN_MINUTE);\n }\n\n /**\n * Creates a TimeSpan from the specified number of hours\n * @param hours The number of hours in the timespan\n * @return A TimeSpan that represents the specified value\n */ \n public static function fromHours(hours : Number) : TimeSpan\n {\n return new TimeSpan(hours * MILLISECONDS_IN_HOUR);\n }\n\n /**\n * Creates a TimeSpan from the specified number of days\n * @param days The number of days in the timespan\n * @return A TimeSpan that represents the specified value\n */ \n public static function fromDays(days : Number) : TimeSpan\n {\n return new TimeSpan(days * MILLISECONDS_IN_DAY);\n }\n\n /**\n * The number of milliseconds in one day\n */ \n public static const MILLISECONDS_IN_DAY : Number = 86400000;\n\n /**\n * The number of milliseconds in one hour\n */ \n public static const MILLISECONDS_IN_HOUR : Number = 3600000;\n\n /**\n * The number of milliseconds in one minute\n */ \n public static const MILLISECONDS_IN_MINUTE : Number = 60000;\n\n /**\n * The number of milliseconds in one second\n */ \n public static const MILLISECONDS_IN_SECOND : Number = 1000;\n}\n" }, { "answer_id": 6990505, "author": "kam", "author_id": 885083, "author_profile": "https://Stackoverflow.com/users/885083", "pm_score": 2, "selected": false, "text": "public function timeDifference(startTime:Date, endTime:Date) : String\n{\nif (startTime == null) { return \"startTime empty.\"; }\nif (endTime == null) { return \"endTime empty.\"; }\nvar aTms = Math.floor(endTime.valueOf() - startTime.valueOf());\nreturn \"Time taken: \" \n + String( int(aTms/(24*60*+60*1000)) ) + \" days, \"\n + String( int(aTms/( 60*60*1000)) %24 ) + \" hours, \"\n + String( int(aTms/( 60*1000)) %60 ) + \" minutes, \"\n + String( int(aTms/( 1*1000)) %60 ) + \" seconds.\";\n}\n" }, { "answer_id": 10957282, "author": "kumling", "author_id": 1256559, "author_profile": "https://Stackoverflow.com/users/1256559", "pm_score": 1, "selected": false, "text": "var timeDiff:Number = endDate - startDate;\nvar days:Number = timeDiff / (24*60*60*1000);\nvar rem:Number = int(timeDiff % (24*60*60*1000));\nvar hours:Number = int(rem / (60*60*1000));\nrem = int(rem % (60*60*1000));\nvar minutes:Number = int(rem / (60*1000));\nrem = int(rem % (60*1000));\nvar seconds:Number = int(rem / 1000);\n\ntrace(days + \" << >> \" +hours+ \" << >> \" +minutes+ \" << >> \" +seconds);\n var time:Number = targetDate - currentDate;\nvar secs:Number = time/1000;\nvar mins:Number = secs/60; \nvar hrs:Number = mins/60;\nvar days:Number = int(hrs/24);\n\nsecs = int(secs % 60);\nmins = int(mins % 60);\nhrs = int(hrs % 24);\n\ntrace(secs + \" << >> \" + mins + \" << >> \" + hrs + \" << >> \" + days);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
169,216
<p>As kind of a follow up to <a href="https://stackoverflow.com/questions/111605/what-kind-of-prefix-do-you-use-for-member-variables">this question about prefixes</a>, I agree with most people on the thread that prefixes are bad. But what about if you are using getters and setters? Then you need to differeniate the publicly accessible getter name from the privately stored variable. I normally just use an underscore, but is there a better way?</p>
[ { "answer_id": 169238, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 1, "selected": false, "text": "private int myValue;\n\npublic int MyValue\n{\n get { return myValue; }\n}\n Private _myValue As Integer\n\nPublic ReadOnly Property MyValue As Integer\n Get\n Return _myValue\n End Get\nEnd Property\n" }, { "answer_id": 169243, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "Foo" }, { "answer_id": 169246, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 4, "selected": true, "text": "private int _x;\npublic get x():int { return _x; }\npublic set x(int val):void { _x = val; }\n private int x;\npublic get X():int { return x; }\npublic set X(int val):void { x = val; }\n" }, { "answer_id": 169282, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 3, "selected": false, "text": "private int _x;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911/" ]
169,217
<p>In SQL Server you can use the <code>IsNull()</code> function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#.</p> <p>For example, I want to do something like:</p> <pre><code>myNewValue = IsNull(myValue, new MyValue()); </code></pre> <p>instead of:</p> <pre><code>if (myValue == null) myValue = new MyValue(); myNewValue = myValue; </code></pre> <p>Thanks.</p>
[ { "answer_id": 169226, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 9, "selected": true, "text": "?? myNewValue = myValue ?? new MyValue();\n" }, { "answer_id": 169415, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 4, "selected": false, "text": "newValue = (oldValue is DBNull) ? null : oldValue;\n" }, { "answer_id": 169782, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "public static bool IsNull (this System.Object o)\n{\n return (o == null);\n}\n if (foo.IsNull())\n if (foo == null)\n" }, { "answer_id": 8118670, "author": "serializer", "author_id": 256268, "author_profile": "https://Stackoverflow.com/users/256268", "pm_score": 2, "selected": false, "text": "object value2 = null;\nConsole.WriteLine(object.Equals(value2,null));\n" }, { "answer_id": 31188861, "author": "Rudy", "author_id": 5074534, "author_profile": "https://Stackoverflow.com/users/5074534", "pm_score": 3, "selected": false, "text": "public static T isNull<T>(this T v1, T defaultValue)\n{\n return v1 == null ? defaultValue : v1;\n}\n\nmyValue.isNull(new MyValue())\n" }, { "answer_id": 50535628, "author": "Mansoor Bozorgmehr", "author_id": 4145647, "author_profile": "https://Stackoverflow.com/users/4145647", "pm_score": 0, "selected": false, "text": " //When Expression is Number\n public static double? isNull(double? Expression, double? Value)\n {\n if (Expression ==null)\n {\n return Value;\n }\n else\n {\n return Expression;\n }\n }\n\n\n //When Expression is string (Can not send Null value in string Expression\n public static string isEmpty(string Expression, string Value)\n {\n if (Expression == \"\")\n {\n return Value;\n }\n else\n {\n return Expression;\n }\n }\n" }, { "answer_id": 53874663, "author": "Denis M. Kitchen", "author_id": 120638, "author_profile": "https://Stackoverflow.com/users/120638", "pm_score": 0, "selected": false, "text": " public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = \"\")\n {\n string val = defaultValue;\n if (row.Table.Columns.Contains(colName))\n {\n if (row[colName] != DBNull.Value)\n {\n val = row[colName]?.ToString();\n }\n }\n return val;\n }\n MyControl.Text = MyDataTable.Rows[0].ColumnIsNull(\"MyColumn\");\nMyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull(\"AnotherCol\", \"Doh! I'm null\");\n" }, { "answer_id": 54180643, "author": "sushil suthar", "author_id": 4195533, "author_profile": "https://Stackoverflow.com/users/4195533", "pm_score": 0, "selected": false, "text": " /// <summary>\n /// Returns replacement value if expression is null\n /// </summary>\n /// <param name=\"expression\"></param>\n /// <param name=\"replacement\"></param>\n /// <returns></returns>\n public static long? IsNull(long? expression, long? replacement)\n {\n if (expression.HasValue)\n return expression;\n else\n return replacement;\n }\n\n /// <summary>\n /// Returns replacement value if expression is null\n /// </summary>\n /// <param name=\"expression\"></param>\n /// <param name=\"replacement\"></param>\n /// <returns></returns>\n public static string IsNull(string expression, string replacement)\n {\n if (string.IsNullOrWhiteSpace(expression))\n return replacement;\n else\n return expression;\n }\n" }, { "answer_id": 58693434, "author": "Mansoor Bozorgmehr", "author_id": 4145647, "author_profile": "https://Stackoverflow.com/users/4145647", "pm_score": 0, "selected": false, "text": " public static T IsNull<T>(this T DefaultValue, T InsteadValue)\n {\n\n object obj=\"kk\";\n\n if((object) DefaultValue == DBNull.Value)\n {\n obj = null;\n }\n\n if (obj==null || DefaultValue==null || DefaultValue.ToString()==\"\")\n {\n return InsteadValue;\n }\n else\n {\n return DefaultValue;\n }\n\n }\n\n//This method can work with DBNull and null value. This method is question's answer\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
169,220
<p>I'm used to writing classes like this:</p> <pre><code>public class foo { private string mBar = "bar"; public string Bar { get { return mBar; } set { mBar = value; } } //... other methods, no constructor ... } </code></pre> <p>Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?</p> <pre><code>public class foo2theRevengeOfFoo { //private string mBar = "bar"; public string Bar { get; set; } //... other methods, no constructor ... //behavior has changed. } </code></pre> <p>You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.</p> <p>Something like this would make more sense to me:</p> <pre><code>public string Bar { get; set; } = "bar"; </code></pre>
[ { "answer_id": 169232, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "public foo() {\n Bar = \"bar\";\n}\n" }, { "answer_id": 169237, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 5, "selected": false, "text": "public class foo {\n public foo(){\n Bar = \"bar\";\n }\n public string Bar {get;set;}\n}\n public class foo {\n private foo(){\n Bar = \"bar\";\n Baz = \"baz\";\n }\n public foo(int something) : this(){\n //do specialized initialization here\n Baz = string.Format(\"{0}Baz\", something);\n }\n public string Bar {get; set;}\n public string Baz {get; set;}\n}\n" }, { "answer_id": 169872, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "public class Foo\n{\n public string Bar { get; set; } = \"bar\";\n}\n public class Foo\n{\n public string Bar { get; }\n\n public Foo(string bar)\n {\n Bar = bar;\n }\n}\n" }, { "answer_id": 25576131, "author": "romanoza", "author_id": 3901618, "author_profile": "https://Stackoverflow.com/users/3901618", "pm_score": 5, "selected": false, "text": "public int Y { get; } = 2;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
169,233
<p><a href="http://thedailywtf.com/Articles/The-Hot-Room.aspx" rel="noreferrer">http://thedailywtf.com/Articles/The-Hot-Room.aspx</a></p> <p>You see how at the bottom there're links to the next and previous articles ("Unprepared For Divide_By_Zero" and "A Completely Different Game")? How do I do that, but selecting the next and previous non-private articles? This works for selecting the next article:</p> <pre><code>SELECT * FROM articles WHERE id &gt; ? AND private IS NULL </code></pre> <p>But I cannot find a way to select the previous article.</p> <p>What is the proper/efficient way to do this, preferably in one query?</p>
[ { "answer_id": 169270, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "-- next\nSELECT * FROM articles WHERE id > ? AND private IS NULL ORDER BY id ASC LIMIT 1\n\n-- previous\nSELECT * FROM articles WHERE id < ? AND private IS NULL ORDER BY id DESC LIMIT 1\n" }, { "answer_id": 169299, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 4, "selected": true, "text": "(SELECT * FROM articles WHERE id > ? \n AND private IS NULL \n ORDER BY id ASC LIMIT 1) \nUNION \n(SELECT * FROM articles WHERE id < ? \n AND private IS NULL \n ORDER BY id DESC LIMIT 1)\n" }, { "answer_id": 169301, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 2, "selected": false, "text": "SELECT * FROM articles WHERE id IN (\n SELECT id FROM articles WHERE id > ? AND private IS NULL ORDER BY id ASC LIMIT 1)\n)\nOR id IN (\n SELECT id FROM articles WHERE id < ? AND private IS NULL ORDER BY id DESC LIMIT 1\n);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23107/" ]
169,240
<p>I have two databases with the same structure. The tables have an integer as a primary key as used in Rails.</p> <p>If I have a patients table, I will have one patient using primary key 123 in one database and another patient using the same primary key in the other database.</p> <p>What would you suggest for merging the data from both databases?</p>
[ { "answer_id": 169606, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 3, "selected": false, "text": "def self.up\n ActiveRecord::Base.establish_connection :development\n patients = Patient.find(:all)\n ActiveRecord::Base.establish_connection :production\n patients.each { |patient| Patient.create patient.attributes.except(\"id\") }\nend\n" }, { "answer_id": 169865, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 3, "selected": false, "text": "#All models and their foreign keys\ntales = {Patients => [:doctor_id, :hospital_id],\n Doctors => [:hospital_id],\n Hospitals}\n\nActiveRecord::Base.establish_connection :development\n\nmax_id = tables.map do |model| \n model.maximum(:id)\nend.max + 1000\n\n\ntables.each do |model, fks| \n ActiveRecord::Base.establish_connection :development\n records = model.find(:all)\n\n ActiveRecord::Base.establish_connection :production\n records.each do |record|\n #update the foreign keys\n fks.each do |attr|\n record[attr] += max_id if not record[attr].nil?\n end\n record.id += max_id\n\n model.create record.attributes\n end\nend\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
169,276
<p>After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of "make work" for the programmer. It's work to PUT the dang things into the code, and then they make searching and reading code very annoying.</p> <p>What are the benefits? Why do coders go to the extra trouble to put this in their code.</p> <p>Make me a believer!</p>
[ { "answer_id": 169471, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 3, "selected": false, "text": "#region Properties\n\n#region Update Section\n\n#region Accessors\n #Sweep under carpet\n" }, { "answer_id": 287371, "author": "Jeff", "author_id": 23902, "author_profile": "https://Stackoverflow.com/users/23902", "pm_score": 2, "selected": false, "text": "#region Declaring variables for fields and object properties\n\n#region Getting the fields in scope\n\n#region Getting the properties of the object\n\n#region Setting Fields\n" }, { "answer_id": 287438, "author": "Enes", "author_id": 2921654, "author_profile": "https://Stackoverflow.com/users/2921654", "pm_score": 1, "selected": false, "text": "/// <example>\n /// The following code sample is an implementation of LoadPublishedVersion() for XmlPageProvider.\n /// <code source=\"../CodeSamples/EPiServerNET/PageProvider/XmlPageProvider.cs\" region=\"LoadPublishedVersion\" lang=\"cs\"/>\n /// </example>\n" }, { "answer_id": 11730161, "author": "Paul Williams", "author_id": 420400, "author_profile": "https://Stackoverflow.com/users/420400", "pm_score": 2, "selected": false, "text": " #region public int ObjectDepthThreshold\n\n public int ObjectDepthThreshold\n {\n get { return (int)GetValue(ObjectDepthThresholdProperty); }\n set { SetValue(ObjectDepthThresholdProperty, value); }\n }\n\n public static readonly DependencyProperty ObjectDepthThresholdProperty = DependencyProperty.Register(\n &quot;ObjectDepthThreshold&quot;,\n typeof(int),\n typeof(GotoXControls),\n new FrameworkPropertyMetadata((int)GotoXServiceState.OBJECT_DEPTH_THRESHOLD_DEFAULT,\n FrameworkPropertyMetadataOptions.AffectsRender,\n new PropertyChangedCallback(OnControlValueChanged)\n )\n );\n\n #endregion\n public int ObjectDepthThreshold\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
169,277
<p>Is there a Generics Friendly way of using Collection.EMPTY_LIST in my Java Program.</p> <p>I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this.</p> <p>Something like <code>users = Collections&lt;User&gt;.EMPTY_LIST;</code></p>
[ { "answer_id": 169286, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 6, "selected": true, "text": "List<User> users = Collections.emptyList();\n Collections.emptyList(); String List<User> users = Collections.<User>emptyList(); \n void doStuff(List<String> users) doStuff() doStuff(Collections.<String>emptyList());\n" }, { "answer_id": 169290, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 1, "selected": false, "text": "List<User> users = Collections.emptyList();\n" }, { "answer_id": 210588, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 1, "selected": false, "text": "Collections.emptyList() new ArrayList(0)" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
169,278
<p>How do I get modrewrite to ENTIRELY ignore the /vip/ directory so that all requests pass directly to the folder?</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^vip/.$ - [PT] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; </code></pre> <p>See also <a href="https://stackoverflow.com/questions/163302/how-do-i-ignore-a-directory-in-modrewrite">How do I ignore a directory in mod_rewrite?</a> -- reposting because I wasn't sufficiently clear about the problem first time around. </p>
[ { "answer_id": 169347, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": false, "text": "RewriteRule ^vip/.$ - [PT]\n RewriteRule ^vip/.*$ - [PT,L]\n" }, { "answer_id": 11918202, "author": "aron.duby", "author_id": 518064, "author_profile": "https://Stackoverflow.com/users/518064", "pm_score": 0, "selected": false, "text": "RewriteEngine Off\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24557/" ]
169,287
<p>Does anyone have a good resource on dlls and how they are used / generated in Visual Studio? A few questions I'm rather hazy on specifically are:</p> <ul> <li>How refresh files work</li> <li>How dll version numbers are generated</li> <li>The difference between adding a reference by project vs browsing for the specific dll</li> </ul> <p>Any other tips are welcome as well.</p>
[ { "answer_id": 169314, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n" }, { "answer_id": 169668, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "* *" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
169,293
<p>I'm looking for a make utility for building large java programs. I'm aware of ANT already, but want to see what else is available.</p> <p>Ideally, it should be able to handle the .java->.class package directory weirdness that fouls up GNU Make.</p> <p>Win32, but cross platform is a plus.</p> <p><strong>EDIT:</strong> I see some cons to using ANT, which is why I wanted to see other options, though I'll probably end up using it anyway, just because it works.</p> <ul> <li>requires nontrivial XML makefiles, "HelloWorld" is already 25 lines, and any more reasonable program gets large quickly. <ul> <li>The ant tutorials show comparisons of ant build.xml files that are roughly identical to big .bat files that just run all the java commands, only longer. <a href="http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html" rel="noreferrer">http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html</a>, I've already got one of those.</li> <li>Xml means that every single dependency, variable, target, rule and project has extra cruft on it, it just makes lines hard to read. <a href="http://www.codinghorror.com/blog/archives/001114.html" rel="noreferrer">The Angle Bracket Tax</a></li> </ul></li> <li>solves all the wrong problems for me. <ul> <li>ant makes writing jar and javac command lines easier, generating manifests easier, specifying .java source files easier, specifying jvm/java properties easier, writing custom build tools easier.</li> <li>ant does not make java class dependencies easier, and does not seem to have a more powerful variable system, both things usually solved by make utilities.</li> </ul></li> </ul> <p>I'd use gnu make, but it can't figure out where the .class file for a .java file with a package declaration is going to end up.</p>
[ { "answer_id": 170060, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 1, "selected": false, "text": "war" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
169,303
<p>I want to be able to run unstrusted ruby code. I want to be able to pass variables to said untrusted code that it may use. I also want said code to return a result to me. Here is a conceptual example of what I am thinking</p> <pre><code>input = "sweet" output = nil Thread.start { $SAFE = 4 #... untrusted code goes here, it uses the input variable(s) #to calculate some result that it places in the output variable } #parse the output variable as a string. </code></pre> <p>Just to clarify, I am basically using the untrusted code as a function. I want to provide its some inputs, and then allow it to write to the output. That is all I really want, I don't care how it is done, I just want the ability to use untrusted Ruby code as a sort of function. The solution does not have to look anything like the code I wrote above, I am just using it to illustrate what I want.</p> <p>Now, I can currently think of 3 ways to do this:</p> <ol> <li>Use the $SAFE level construct above.</li> <li>whytheluckystiff has a Sandbox plugin for ruby</li> <li>I could run each function in its own virtual machine, using some sort of os virtualization software like vmware or Xen or something.</li> </ol> <p>I am wondering if anyone has any recommendations for running untrusted ruby code in a functional way? What option would you recomend? How would you go about it? Thanks.</p>
[ { "answer_id": 26594052, "author": "fearless_fool", "author_id": 558639, "author_profile": "https://Stackoverflow.com/users/558639", "pm_score": 2, "selected": false, "text": "$SAFE" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21317/" ]
169,330
<p>Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI.</p> <p>I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want.</p> <p><strong><em>To clarify....</em></strong></p> <p>I'd like to script out the stored procedures. The list via the <code>Select * from sys.procedures</code> is helpful, but in the end I need to script out each of these.</p>
[ { "answer_id": 169339, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "select * from sys.procedures\n" }, { "answer_id": 169340, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 0, "selected": false, "text": "Select * from sys.procedures\n" }, { "answer_id": 169410, "author": "Andy S", "author_id": 3759, "author_profile": "https://Stackoverflow.com/users/3759", "pm_score": 0, "selected": false, "text": "select SPECIFIC_NAME,ROUTINE_DEFINITION from information_schema.routines\n" }, { "answer_id": 169455, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing Microsoft.SqlServer.Management.Smo;\n\nclass Program\n{\n static void Main(string[] args)\n {\n Server server = new Server(@\".\\SQLEXPRESS\");\n Database db = server.Databases[\"Northwind\"];\n List<SqlSmoObject> list = new List<SqlSmoObject>();\n DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure);\n foreach (DataRow row in dataTable.Rows)\n {\n string sSchema = (string)row[\"Schema\"];\n if (sSchema == \"sys\" || sSchema == \"INFORMATION_SCHEMA\")\n continue;\n StoredProcedure sp = (StoredProcedure)server.GetSmoObject(\n new Urn((string)row[\"Urn\"]));\n if (!sp.IsSystemObject)\n list.Add(sp);\n }\n Scripter scripter = new Scripter();\n scripter.Server = server;\n scripter.Options.IncludeHeaders = true;\n scripter.Options.SchemaQualify = true;\n scripter.Options.ToFileOnly = true;\n scripter.Options.FileName = @\"C:\\StoredProcedures.sql\";\n scripter.Script(list.ToArray());\n }\n}\n" }, { "answer_id": 174652, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": ";WITH ROUTINES AS (\n -- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit\n SELECT o.type_desc AS ROUTINE_TYPE\n ,o.[name] AS ROUTINE_NAME\n ,m.definition AS ROUTINE_DEFINITION\n FROM sys.sql_modules AS m\n INNER JOIN sys.objects AS o\n ON m.object_id = o.object_id\n)\nSELECT *\nFROM ROUTINES\n" }, { "answer_id": 183398, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 2, "selected": false, "text": "DataTable dtProcs = sqlConn.GetSchema(\"Procedures\", new string[] { databaseName });\nDataTable dtProcParams = sqlConn.GetSchema(\"ProcedureParameters\", new string[] { databaseName });\n" }, { "answer_id": 1011945, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "begin\n--select column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Products' \n--Declare the Table variable \nDECLARE @GeneratedStoredProcedures TABLE\n(\n Number INT IDENTITY(1,1), --Auto incrementing Identity column\n name VARCHAR(300) --The string value\n)\n\n--Decalre a variable to remember the position of the current delimiter\nDECLARE @CurrentDelimiterPositionVar INT \ndeclare @sqlCode varchar(max)\n--Decalre a variable to remember the number of rows in the table\nDECLARE @Count INT\n\n--Populate the TABLE variable using some logic\nINSERT INTO @GeneratedStoredProcedures SELECT name FROM sys.procedures where name like 'procGen_%'\n\n--Initialize the looper variable\nSET @CurrentDelimiterPositionVar = 1\n\n--Determine the number of rows in the Table\nSELECT @Count=max(Number) from @GeneratedStoredProcedures\n\n--A variable to hold the currently selected value from the table\nDECLARE @CurrentValue varchar(300);\n\n--Loop through until all row processing is done\nWHILE @CurrentDelimiterPositionVar <= @Count\nBEGIN\n --Load current value from the Table\n SELECT @CurrentValue = name FROM @GeneratedStoredProcedures WHERE Number = @CurrentDelimiterPositionVar \n --Process the current value\n --print @CurrentValue\n set @sqlCode = 'drop procedure ' + @CurrentValue\n print @sqlCode\n --exec (@sqlCode)\n\n\n --Increment loop counter\n SET @CurrentDelimiterPositionVar = @CurrentDelimiterPositionVar + 1;\nEND\n\nend\n" }, { "answer_id": 11673537, "author": "Nag", "author_id": 1555346, "author_profile": "https://Stackoverflow.com/users/1555346", "pm_score": 2, "selected": false, "text": "public static void GenerateTableScript()\n {\n Server databaseServer = default(Server);//DataBase Server Name\n databaseServer = new Server(\"yourDatabase Server Name\");\n string strFileName = @\"C:\\Images\\Your FileName_\" + DateTime.Today.ToString(\"yyyyMMdd\") + \".sql\"; //20120720`enter code here\n if (System.IO.File.Exists(strFileName))\n System.IO.File.Delete(strFileName);\n List<SqlSmoObject> list = new List<SqlSmoObject>();\n Scripter scripter = new Scripter(databaseServer);\n Database dbUltimateSurvey = databaseServer.Databases[\"YourDataBaseName\"];//DataBase Name\n //Table scripting Writing\n DataTable dataTable1 = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.Table);\n foreach (DataRow drTable in dataTable1.Rows)\n {\n //string strTableSchema = (string)drTable[\"Schema\"];\n //if (strTableSchema == \"dbo\")\n // continue;\n Table dbTable = (Table)databaseServer.GetSmoObject(new Urn((string)drTable[\"Urn\"]));\n if (!dbTable.IsSystemObject)\n if (dbTable.Name.Contains(\"SASTool_\"))\n list.Add(dbTable);\n }\n scripter.Server = databaseServer;\n scripter.Options.IncludeHeaders = true;\n scripter.Options.SchemaQualify = true;\n scripter.Options.ToFileOnly = true;\n scripter.Options.FileName = strFileName;\n scripter.Options.DriAll = true;\n scripter.Options.AppendToFile = true;\n scripter.Script(list.ToArray());//Table Script completed\n //Store Procedures scripting Writing\n list = new List<SqlSmoObject>();\n DataTable dataTable = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.StoredProcedure);\n foreach (DataRow row in dataTable.Rows)\n {\n string sSchema = (string)row[\"Schema\"];\n if (sSchema == \"sys\" || sSchema == \"INFORMATION_SCHEMA\")\n continue;\n StoredProcedure sp = (StoredProcedure)databaseServer.GetSmoObject(\n new Urn((string)row[\"Urn\"]));\n if (!sp.IsSystemObject)\n if (sp.Name.Contains(\"custom_\"))\n list.Add(sp);\n }\n scripter.Server = databaseServer;\n scripter.Options.IncludeHeaders = true;\n scripter.Options.SchemaQualify = true;\n scripter.Options.ToFileOnly = true;\n scripter.Options.FileName = strFileName;\n scripter.Options.DriAll = true;\n scripter.Options.AppendToFile = true;\n scripter.Script(list.ToArray()); // Stored procedure Script completed\n }\n" }, { "answer_id": 28810219, "author": "George", "author_id": 2209907, "author_profile": "https://Stackoverflow.com/users/2209907", "pm_score": -1, "selected": false, "text": "SqlConnection" }, { "answer_id": 34272463, "author": "Mauricio Gracia Gutierrez", "author_id": 1461862, "author_profile": "https://Stackoverflow.com/users/1461862", "pm_score": 0, "selected": false, "text": "SELECT NAME from SYS.PROCEDURES \norder by name\n SELECT NAME from SYS.PROCEDURES \nwhere name like '%<TEXT_TO_LOOK_FOR>%'\norder by name\n SELECT NAME from SYS.PROCEDURES \nwhere name like '%CUSTOMER%'\norder by name\n EXEC sp_HelpText SPNAME \n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5678/" ]
169,332
<p>I want to use a timer in my simple <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application. </p> <p>Is there a C# timer (or timer like) class for use in console applications?</p>
[ { "answer_id": 169337, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "Timer System.Timers Timer System.Threading using System;\nusing System.Timers;\n\npublic class Timer1\n{\n private static Timer aTimer = new System.Timers.Timer(10000);\n\n public static void Main()\n {\n aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n aTimer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit the program.\");\n Console.ReadLine();\n }\n\n // Specify what you want to happen when the Elapsed event is \n // raised.\n private static void OnTimedEvent(object source, ElapsedEventArgs e)\n {\n Console.WriteLine(\"The Elapsed event was raised at {0}\", e.SignalTime);\n }\n}\n" }, { "answer_id": 3381560, "author": "Sucharit", "author_id": 407871, "author_profile": "https://Stackoverflow.com/users/407871", "pm_score": -1, "selected": false, "text": "System.Timer" }, { "answer_id": 3381586, "author": "theburningmonk", "author_id": 55074, "author_profile": "https://Stackoverflow.com/users/55074", "pm_score": 3, "selected": false, "text": "System.Threading System.Timers using System.Threading;\nusing Timer = System.Timers.Timer;\n" }, { "answer_id": 29351760, "author": "Stéphane Gourichon", "author_id": 1429390, "author_profile": "https://Stackoverflow.com/users/1429390", "pm_score": -1, "selected": false, "text": "System.Timers.Timer SynchronizingObject System.Threading.Timer System.Reactive.Linq" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
169,342
<p>I have a solution that contains two projects. One project is an ASP.NET Web Application Project, and one is a class library. The web application has a project reference to the class library. Neither of these is strongly-named.</p> <p>In the class library, which I'll call &quot;Framework,&quot; I have an endpoint behavior (an IEndpointBehavior implementation) and a configuration element (a class derived from BehaviorExtensionsElement). The configuration element is so I can attach the endpoint behavior to a service via configuration.</p> <p>In the web application, I have an AJAX-enabled WCF service. In web.config, I have the AJAX service configured to use my custom behavior. The system.serviceModel section of the configuration is pretty standard and looks like this:</p> <pre><code>&lt;system.serviceModel&gt; &lt;behaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior name=&quot;MyEndpointBehavior&quot;&gt; &lt;enableWebScript /&gt; &lt;customEndpointBehavior /&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;/behaviors&gt; &lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot; /&gt; &lt;services&gt; &lt;service name=&quot;WebSite.AjaxService&quot;&gt; &lt;endpoint address=&quot;&quot; behaviorConfiguration=&quot;MyEndpointBehavior&quot; binding=&quot;webHttpBinding&quot; contract=&quot;WebSite.AjaxService&quot; /&gt; &lt;/service&gt; &lt;/services&gt; &lt;extensions&gt; &lt;behaviorExtensions&gt; &lt;add name=&quot;customEndpointBehavior&quot; type=&quot;Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot;/&gt; &lt;/behaviorExtensions&gt; &lt;/extensions&gt; &lt;/system.serviceModel&gt; </code></pre> <p>At runtime, this works perfectly. The AJAX enabled WCF service correctly uses my custom configured endpoint behavior.</p> <p>The problem is when I try to add a new AJAX WCF service. If I do Add -&gt; New Item... and select &quot;AJAX-enabled WCF Service,&quot; I can watch it add the .svc file and codebehind, but when it gets to updating the web.config file, I get this error:</p> <blockquote> <p>The configuration file is not a valid configuration file for WCF Service Library.</p> <p>The type 'Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' registered for extension 'customEndpointBehavior' could not be loaded.</p> </blockquote> <p>Obviously the configuration is entirely valid since it works perfectly at runtime. If I remove the element from my behavior configuration temporarily and then add the AJAX-enabled WCF Service, everything goes without a hitch.</p> <p>Unfortunately, in a larger project where we will have multiple services with various configurations, removing all of the custom behaviors temporarily is going to be error prone. While I realize I could go without using the wizard and do everything manually, not everyone can, and it'd be nice to be able to just use the product as it was meant to be used - wizards and all.</p> <p><strong>Why isn't my custom WCF behavior extension element type being found?</strong></p> <p>Updates/clarifications:</p> <ul> <li>It does work at runtime, just not design time.</li> <li>The Framework assembly is in the web project's bin folder when I attempt to add the service.</li> <li>While I could add services manually (&quot;without configuration&quot;), I need the out-of-the-box item template to work - that's the whole goal of the question.</li> <li>This issue is being seen in Visual Studio 2008. <strong>In VS 2010 this appears to be resolved.</strong></li> </ul> <p><a href="https://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=386511" rel="noreferrer">I filed this issue on Microsoft Connect</a> and it turns out you either have to put your custom configuration element in the GAC or put it in the IDE folder. They won't be fixing it, at least for now. I've posted the workaround they provided as the &quot;answer&quot; to this question.</p>
[ { "answer_id": 3332155, "author": "cdmdotnet", "author_id": 178840, "author_profile": "https://Stackoverflow.com/users/178840", "pm_score": 3, "selected": false, "text": "<system.serviceModel>\n <extensions>\n <behaviorExtensions>\n <add name=\"clientCredential\" type=\"Client.ClientCredentialElement, Client\" />\n </behaviorExtensions>\n </extensions>\n <system.serviceModel>\n <extensions>\n <behaviorExtensions>\n <add name=\"clientCredential\" type=\"Client.ClientCredentialElement, Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" />\n </behaviorExtensions>\n </extensions>\n" }, { "answer_id": 10738636, "author": "NoWar", "author_id": 196919, "author_profile": "https://Stackoverflow.com/users/196919", "pm_score": 3, "selected": false, "text": "[assembly: AssemblyVersion(\"1.0.*\")]\n//[assembly: AssemblyVersion(\"1.0.0.0\")]\n//[assembly: AssemblyFileVersion(\"1.0.0.0\")] \n <add name=\"clientCredential\" type=\"Client.ClientCredentialElement, Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" />\n //[assembly: AssemblyVersion(\"1.0.*\")] \n[assembly: AssemblyVersion(\"1.0.0.0\")] Keep it manually.\n[assembly: AssemblyFileVersion(\"1.0.0.0\")] \n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8116/" ]
169,355
<p>Would anyone know why MSVC++ 2008 always returns error 5 on GetLastError() when I try to call OpenProcess with PROCESS_ALL_ACCESS as my desired access? PROCESS_VM_READ works just fine. I'm an administrator on this computer and it is working fine in Dev C++.</p> <p>Do I need to set an option somewhere?</p>
[ { "answer_id": 169394, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "DELETE READ_CONTROL WRITE_DAC WRITE_OWNER" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,362
<p>I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python? </p>
[ { "answer_id": 169406, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 5, "selected": true, "text": "homework import smtplib\nimport zipfile\nimport tempfile\nfrom email import encoders\nfrom email.message import Message\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart \n\ndef send_file_zipped(the_file, recipients, sender='you@you.com'):\n zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')\n zip = zipfile.ZipFile(zf, 'w')\n zip.write(the_file)\n zip.close()\n zf.seek(0)\n\n # Create the message\n themsg = MIMEMultipart()\n themsg['Subject'] = 'File %s' % the_file\n themsg['To'] = ', '.join(recipients)\n themsg['From'] = sender\n themsg.preamble = 'I am not using a MIME-aware mail reader.\\n'\n msg = MIMEBase('application', 'zip')\n msg.set_payload(zf.read())\n encoders.encode_base64(msg)\n msg.add_header('Content-Disposition', 'attachment', \n filename=the_file + '.zip')\n themsg.attach(msg)\n themsg = themsg.as_string()\n\n # send the message\n smtp = smtplib.SMTP()\n smtp.connect()\n smtp.sendmail(sender, recipients, themsg)\n smtp.close()\n\n \"\"\"\n # alternative to the above 4 lines if you're using gmail\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.login(\"username\", \"password\")\n server.sendmail(sender,recipients,themsg)\n server.quit()\n \"\"\"\n send_file_zipped('result.txt', ['me@me.org'])\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/169362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,377
<p>As a hobby I'm interesting in programming an Ethernet-connected LED sign to scroll messages across a screen. But I'm having trouble making a UDP sender in <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a> (I am using 2008 currently).</p> <p>Now the sign is nice enough to have <a href="http://support.favotech.com/protocol.specs.2.4.jetfile.pdf" rel="nofollow noreferrer">a specifications sheet on programming for it</a>.</p> <p>But an example of a line to send to it (page 3):</p> <pre><code>&lt;0x01&gt;Z30&lt;0x02&gt;AA&lt;0x06&gt;&lt;0x1B&gt;0b&lt;0x1C&gt;1&lt;0x1A&gt;1This message will show up on the screen&lt;0x04&gt; </code></pre> <p>With codes such as &lt;0x01> representing the hex character.</p> <p>Now, to send this to the sign I need to use <a href="http://en.wikipedia.org/wiki/User_Datagram_Protocol" rel="nofollow noreferrer">UDP</a>. However, the examples I have all encode the message as <a href="http://en.wikipedia.org/wiki/ASCII" rel="nofollow noreferrer">ASCII</a> before sending, like this one (from <em><a href="http://www.java2s.com/Code/VB/Network-Remote/UDPClientsendspacketstoandreceivespacketsfromaserver.htm" rel="nofollow noreferrer">UDP: Client sends packets to, and receives packets from, a server</a></em>):</p> <pre><code>Imports System.Threading Imports System.Net.Sockets Imports System.IO Imports System.Net Public Class MainClass Shared Dim client As UdpClient Shared Dim receivePoint As IPEndPoint Public Shared Sub Main() receivePoint = New IPEndPoint(New IPAddress(0), 0) client = New UdpClient(8888) Dim thread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets)) thread.Start() Dim packet As String = "client" Console.WriteLine("Sending packet containing: ") ' ' Note the following line below, would appear to be my problem. ' Dim data As Byte() = System.Text.Encoding.ASCII.GetBytes(packet) client.Send(data, data.Length, "localhost", 5000) Console.WriteLine("Packet sent") End Sub Shared Public Sub WaitForPackets() While True Dim data As Byte() = client.Receive(receivePoint) Console.WriteLine("Packet received:" &amp; _ vbCrLf &amp; "Length: " &amp; data.Length &amp; vbCrLf &amp; _ System.Text.Encoding.ASCII.GetString(data)) End While End Sub ' WaitForPackets End Class </code></pre> <p>To output a hexcode in VB.NET, I think the syntax may possibly be &amp;H1A - to send what the specifications would define as &lt;0x1A>.</p> <p>Could I modify that code, to correctly send a correctly formated packet to this sign?</p> <p>The answers from Grant (after sending a packet with hex in it), Hamish Smith (using a function to get hex values), and Hafthor (hardcoded chr() message into example) when attempted all did not work. So I'll research to see what else could go wrong. In theory, if this string is sent successfully, I should have a message containing "OK" back, which will help to know when it works.</p> <p>I have tried and am now able to monitor the packets going through. A working packet example is this (in raw hex): <a href="http://www.brettjamesonline.com/misc/forums/other/working.raw" rel="nofollow noreferrer">http://www.brettjamesonline.com/misc/forums/other/working.raw</a> vs my version: <a href="http://www.brettjamesonline.com/misc/forums/other/failed.raw" rel="nofollow noreferrer">http://www.brettjamesonline.com/misc/forums/other/failed.raw</a>. The difference is my hex codes are still not encoded correctly, seen in this side-by-side image: <a href="http://www.brettjamesonline.com/misc/forums/other/snapshotcoding.png" rel="nofollow noreferrer">http://www.brettjamesonline.com/misc/forums/other/snapshotcoding.png</a>.</p> <p>I have used this code to generate the packet and send it:</p> <pre><code>container = &amp;H1 &amp; "Z" &amp; &amp;H30 &amp; &amp;H2 &amp; "temp.nrg" &amp; &amp;H1C &amp; "1Something" &amp; &amp;H4 ' This did not appear to work neither 'container = Chr(&amp;H1) &amp; "Z" &amp; Chr(&amp;H30) &amp; Chr(&amp;H2) &amp; Chr(&amp;H1C) &amp; "1Something" &amp; Chr(&amp;H4) '&lt;0x01&gt;Z00&lt;0x02&gt;FILENAME&lt;0x1C&gt;1Test to display&lt;0x04&gt; &lt;- the "official" spec to send Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(container) </code></pre> <p>(Full snippet: <a href="http://pastebin.com/f44417743" rel="nofollow noreferrer">http://pastebin.com/f44417743</a>.)</p>
[ { "answer_id": 169422, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 0, "selected": false, "text": "Public Function HexFromIP(ByVal sIP As String)\n Dim aIP As String()\n Dim sHexCode As String = \"\"\n aIP = sIP.Split(\".\")\n\n For Each IPOct As String In aIP\n sHexCode += Hex(Val(IPOct)).PadLeft(2, \"0\")\n Next\n\n Return sHexCode\nEnd Function\n hexSomething = Hex(Val(number)).PadLeft(2,\"0\")" }, { "answer_id": 169437, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 2, "selected": false, "text": "Function HexCodeToHexChar(ByVal m as System.Text.RegularExpressions.Match) As String\n Return Chr(Integer.Parse(m.Value.Substring(\"<0x\".Length, 2), _\n Globalization.NumberStyles.HexNumber))\nEnd Function\n Dim r As New System.Text.RegularExpressions.Regex(\"<0x[0-9a-fA-F]{2}>\")\nDim s As String = r.Replace(\"abc<0x44>efg\", AddressOf HexCodeToHexChar)\n' s should now be \"abcDefg\"\n Function HexCharToHexCode(ByVal m As Match) As String\n If m.Value.StartsWith(\"<0x\") And m.Value.EndsWith(\">\") And m.Value.Length = \"<0x??>\".Length Then\n Return \"<0<0x78>\" + m.Value.Substring(\"<0x\".Length)\n ElseIf Asc(m.Value) >= 0 And Asc(m.Value) <= &HFF Then\n Return \"<0x\" + Right(\"0\" + Hex(Asc(m.Value)), 2) + \">\"\n Else\n Throw New ArgumentException(\"Non-SBCS ANSI characters not supported\")\n End If\nEnd Function\n Dim r As New Regex(\"[^ -~]|<0x[0-9a-fA-F]{2}>\")\nDim s As String = r.Replace(\"abc\"+chr(4)+\"efg\", AddressOf HexCharToHexCode)\n' s should now be \"abc<0x04>efg\"\n Dim packet As String = Chr(&H01) + \"Z30\" + Chr(&H02) + \"AA\" + Chr(&H06) + _\n Chr(&H1B) + \"0b\" + Chr(&H1C) + \"1\" + Chr(&H1A) + _\n \"1This message will show up on the screen\" + Chr(&H04)\n Dim i As New IPEndPoint(IPAddress.Parse(\"192.168.0.5\"), 3001) ''//Target IP:port\nDim u As New UdpClient()\nDim b As Byte() = Encoding.UTF8.GetBytes(s) ''//Where s is the decoded string\nu.Send(b, b.Length, i)\n" }, { "answer_id": 169449, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 0, "selected": false, "text": "Public Class MainClass\n Shared client As UdpClient\n Shared receivePoint As IPEndPoint\n\n\n Public Shared Sub Main()\n receivePoint = New IPEndPoint(New IPAddress(0), 0)\n client = New UdpClient(8888)\n Dim thread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))\n thread.Start()\n\n\n Dim packet As Packet = New Packet(\"client\")\n Console.WriteLine(\"Sending packet containing: \")\n Dim data As Byte() = packet.Data\n\n client.Send(data, data.Length, \"localhost\", 5000)\n Console.WriteLine(\"Packet sent\")\n\n End Sub\n\n Public Shared Sub WaitForPackets()\n While True\n Dim data As Byte() = client.Receive(receivePoint)\n Console.WriteLine(\"Packet received:\" & _\n vbCrLf & \"Length: \" & data.Length & vbCrLf & _\n System.Text.Encoding.ASCII.GetString(data))\n\n End While\n\n End Sub ' WaitForPackets \n\nEnd Class \n\nPublic Class Packet \n Private _message As String \n\n Public Sub New(ByVal message As String)\n _message = message\n End Sub\n\n Public Function Data() As Byte()\n\n Dim ret(13 + _message.Length) As Byte\n\n Dim ms As New MemoryStream(ret, True)\n\n ms.WriteByte(&H1)\n\n '<0x01>Z30<0x02>AA<0x06><0x1B>0b<0x1C>1<0x1A>1This message will show up on the screen<0x04> \n ms.Write(System.Text.Encoding.ASCII.GetBytes(\"Z30\"), 0, 3)\n\n ms.WriteByte(&H2)\n\n ms.Write(System.Text.Encoding.ASCII.GetBytes(\"AA\"), 0, 2)\n\n ms.WriteByte(&H6)\n\n ms.Write(System.Text.Encoding.ASCII.GetBytes(\"0b\"), 0, 2)\n\n ms.WriteByte(&H1C)\n\n ms.Write(System.Text.Encoding.ASCII.GetBytes(\"1\"), 0, 1)\n\n ms.WriteByte(&H1A)\n\n ms.Write(System.Text.Encoding.ASCII.GetBytes(_message), 0, _message.Length)\n\n ms.WriteByte(&H4)\n\n ms.Close()\n\n Data = ret\n End Function\nEnd Class\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25031/" ]
169,378
<p>ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?</p>
[ { "answer_id": 169384, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 3, "selected": false, "text": "this" }, { "answer_id": 169399, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 9, "selected": true, "text": "ToRadians(double degrees)" }, { "answer_id": 169469, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": false, "text": "static" }, { "answer_id": 40593096, "author": "Joseph Morgan", "author_id": 1440294, "author_profile": "https://Stackoverflow.com/users/1440294", "pm_score": 0, "selected": false, "text": "using static className; \n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
169,404
<p>In a <a href="https://stackoverflow.com/questions/168408/c-alternatives-to-void-pointers-that-isnt-templates">related question</a> I asked about creating a generic container. Using polymorphic templates seems like the right way to go.</p> <p>However, I can't for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of <code>T</code> (along with its dimensions), allocated at some other point.</p> <p>I would like to be able to do something like</p> <pre><code>MyContainer&lt;float&gt; blah(); ... delete blah; </code></pre> <p>and</p> <pre><code>MyContainer&lt;ComplexObjectType*&gt; complexBlah(); ... delete complexBlah;` </code></pre> <p>Can I do something like this? Can I do it without smart pointers?</p> <p>Again, thanks for your input.</p>
[ { "answer_id": 169439, "author": "Scott Langham", "author_id": 11898, "author_profile": "https://Stackoverflow.com/users/11898", "pm_score": 3, "selected": true, "text": "MyContainer<shared_ptr<SomeComplexType> > MyContainer<float> shared_ptr shared_ptr shared_ptr" }, { "answer_id": 169986, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 1, "selected": false, "text": "typedef char YesType;\ntypedef char NoType[2];\n\ntemplate<typename T>\nstruct IsPointer\n{\ntypedef NoType Result;\n};\ntemplate<typename T>\nstruct IsPointer<T*>\n{\ntypedef YesType Result;\n};\n\ntemplate<typename T>\nstruct MyContainer\n{\n~MyContainer()\n{\n IsPointer<T>::Result r;\n Clear(&r);\n delete[] data;\n}\nvoid Clear(YesType*)\n{\n for (int i = 0; i < numElements; ++i)\n delete data[i];\n}\nvoid Clear(NoType*) {}\n\nT* data;\nint numElements;\n" }, { "answer_id": 192322, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "new" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14621/" ]
169,419
<p>I like having my warning level set at W4 but all new projects start at W3. Is there some way to change the default value for warning levels for new projects?</p>
[ { "answer_id": 169434, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 2, "selected": false, "text": "%PROGRAM_FILES%\\Microsoft Visual Studio 9.0\\Common7\\IDE\\ProjectTemplates\\\n %PROGRAM_FILES%\\Microsoft Visual Studio 9.0\\Common7\\IDE\\{Version}\\ProjectTemplates\\\n <WarningLevel>3</WarningLevel>\n <WarningLevel>4</WarningLevel>\n" }, { "answer_id": 169489, "author": "Brian Paden", "author_id": 3176, "author_profile": "https://Stackoverflow.com/users/3176", "pm_score": 0, "selected": false, "text": "%\\Microsoft Visual Studio 9.0\\VC\\VCWizards\\1033\n CLTool.WarningLevel = WarningLevel_3;\n CLTool.WarningLevel = WarningLevel_4;\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176/" ]
169,420
<p>I've been looking for a generic way to deal with bidirectional associations and a way to handle the inverse updates in manual written Java code.</p> <p>For those who don't know what I'm talking about, here is an example. Below it are my current results of (unsatisfying) solutions.</p> <pre><code>public class A { public B getB(); public void setB(B b); } public class B { public List&lt;A&gt; getAs(); } </code></pre> <p>Now, when updating any end of the association, in order to maintain consistency, the other end must be updated as well. Either manually each time </p> <pre><code>a.setB(b); b.getA().add(a); </code></pre> <p>or by putting matching code in the setter / getter and use a custom List implementation.</p> <p>I've found an outdated, unmaintained project whose dependencies are no longer available (<a href="https://e-nspire-gemini.dev.java.net/" rel="nofollow noreferrer">https://e-nspire-gemini.dev.java.net/</a>). It deals with the problem by using annotations that are used to inject the necessary code automatically.</p> <p>Does anyone know of another framework that deals with this in a generic, unobtrusive way ala gemini?</p> <p>ciao, Elmar</p>
[ { "answer_id": 169758, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 0, "selected": false, "text": "AssociationBuilder.createAssociation(A a, Connector< A> ca, B b, Connector< B> cb, Synchronizer< A,B> sync)\n sync(ChangeInfo info, A a, B b) // make sure that b reflects current state of a and vice-versa. \n" }, { "answer_id": 170371, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "public final class A {\n private B b;\n public B getB() {\n return b;\n }\n public void setB(final B b) {\n if (b == this.b) {\n // Important!!\n return;\n }\n // Be a member of both Bs (hence check in getAs).\n if (b != null) {\n b.addA(this);\n }\n // Atomic commit to change.\n this.b = b;\n // Remove from old B.\n if (this.b != null) {\n this.b.removeA(this);\n }\n }\n}\n\npublic final class B {\n private final List<A> as;\n /* pp */ void addA(A a) {\n if (a == null) {\n throw new NullPointerException();\n }\n // LinkedHashSet may be better under more demanding usage patterns.\n if (!as.contains(a)) {\n as.add(a);\n }\n }\n /* pp */ void removeA(A a) {\n if (a == null) {\n throw new NullPointerException();\n }\n as.removeA(a);\n }\n public List<A> getAs() {\n // Copy only those that really are associated with us.\n List<A> copy = new ArrayList<A>(as.size());\n for (A a : as) {\n if (a.getB() == this) {\n copy.add(a);\n }\n }\n return Collection.unmodifiableList(copy);\n }\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19935/" ]
169,428
<p>this code always returns 0 in PHP 5.2.5 for microseconds:</p> <pre><code>&lt;?php $dt = new DateTime(); echo $dt-&gt;format("Y-m-d\TH:i:s.u") . "\n"; ?&gt; </code></pre> <p>Output:</p> <pre><code>[root@www1 ~]$ php date_test.php 2008-10-03T20:31:26.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:27.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:27.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:28.000000 </code></pre> <p>Any ideas?</p>
[ { "answer_id": 169458, "author": "eydelber", "author_id": 25039, "author_profile": "https://Stackoverflow.com/users/25039", "pm_score": 6, "selected": true, "text": "function getTimestamp()\n{\n return date(\"Y-m-d\\TH:i:s\") . substr((string)microtime(), 1, 8);\n}\n" }, { "answer_id": 169499, "author": "jmccartie", "author_id": 24708, "author_profile": "https://Stackoverflow.com/users/24708", "pm_score": 4, "selected": false, "text": "function udate($format, $utimestamp = null)\n{\n if (is_null($utimestamp))\n $utimestamp = microtime(true);\n\n $timestamp = floor($utimestamp);\n $milliseconds = round(($utimestamp - $timestamp) * 1000000);\n\n return date(preg_replace('`(?<!\\\\\\\\)u`', $milliseconds, $format), $timestamp);\n}\n\necho udate('H:i:s.u'); // 19:40:56.78128\n" }, { "answer_id": 4329809, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 1, "selected": false, "text": "class ExtendedDateTime extends DateTime {\n /**\n * Returns new DateTime object. Adds microtime for \"now\" dates\n * @param string $sTime\n * @param DateTimeZone $oTimeZone \n */\n public function __construct($sTime = 'now', DateTimeZone $oTimeZone = NULL) {\n // check that constructor is called as current date/time\n if (strtotime($sTime) == time()) {\n $aMicrotime = explode(' ', microtime());\n $sTime = date('Y-m-d H:i:s.' . $aMicrotime[0] * 1000000, $aMicrotime[1]);\n }\n\n // DateTime throws an Exception with a null TimeZone\n if ($oTimeZone instanceof DateTimeZone) {\n parent::__construct($sTime, $oTimeZone);\n } else {\n parent::__construct($sTime);\n }\n }\n}\n\n$oDate = new ExtendedDateTime();\necho $oDate->format('Y-m-d G:i:s.u');\n 2010-12-01 18:12:10.146625\n" }, { "answer_id": 4414060, "author": "dbwebtek", "author_id": 538362, "author_profile": "https://Stackoverflow.com/users/538362", "pm_score": 4, "selected": false, "text": "$t = microtime(true);\n$micro = sprintf(\"%06d\",($t - floor($t)) * 1000000);\n$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );\n\nprint $d->format(\"Y-m-d H:i:s.u\");\n" }, { "answer_id": 6604836, "author": "tr0y", "author_id": 832634, "author_profile": "https://Stackoverflow.com/users/832634", "pm_score": 4, "selected": false, "text": "DateTime microtime(true) . sprintf .0 date_create_from_format(\n 'U.u', sprintf('%.f', microtime(true))\n)->format('Y-m-d\\TH:i:s.uO');\n DateTime::createFromFormat(\n 'U.u', sprintf('%.f', microtime(true))\n)->format('Y-m-d\\TH:i:s.uO');\n" }, { "answer_id": 10880637, "author": "f.ardelian", "author_id": 492130, "author_profile": "https://Stackoverflow.com/users/492130", "pm_score": -1, "selected": false, "text": "date('Y-m-d H:i:s.') . str_pad(substr((float)microtime(), 2), 6, '0', STR_PAD_LEFT)\n 2012-06-01 12:00:13.036613\n" }, { "answer_id": 16468901, "author": "crashmaxed", "author_id": 2367551, "author_profile": "https://Stackoverflow.com/users/2367551", "pm_score": 0, "selected": false, "text": "// Return DateTime object including microtime for \"now\"\nfunction dto_now()\n{\n list($usec, $sec) = explode(' ', microtime());\n $usec = substr($usec, 2, 6);\n $datetime_now = date('Y-m-d H:i:s\\.', $sec).$usec;\n return new DateTime($datetime_now, new DateTimeZone(date_default_timezone_get()));\n}\n" }, { "answer_id": 16922855, "author": "KyleFarris", "author_id": 83304, "author_profile": "https://Stackoverflow.com/users/83304", "pm_score": 2, "selected": false, "text": "function udate($format='Y-m-d H:i:s.', $microtime=NULL) {\n if(NULL === $microtime) $microtime = microtime();\n list($microseconds,$unix_time) = explode(' ', $microtime);\n return date($format,$unix_time) . array_pop(explode('.',$microseconds));\n}\n function udate($format='Y-m-d H:i:s.', $microtime=NULL) {\n if(NULL === $microtime) $microtime = microtime(true);\n list($unix_time,$microseconds) = explode('.', $microtime);\n return date($format,$unix_time) . $microseconds;\n}\n" }, { "answer_id": 17695036, "author": "Nadeem", "author_id": 2389988, "author_profile": "https://Stackoverflow.com/users/2389988", "pm_score": 1, "selected": false, "text": "$micro_date = microtime();\n$date_array = explode(\" \",$micro_date);\n$date = date(\"Y-m-d H:i:s\",$date_array[1]);\necho \"Date: $date:\" . $date_array[0].\"<br>\";\n" }, { "answer_id": 18502608, "author": "Manu Manjunath", "author_id": 495598, "author_profile": "https://Stackoverflow.com/users/495598", "pm_score": 0, "selected": false, "text": "date() function date_with_micro($format, $timestamp = null) {\n if (is_null($timestamp) || $timestamp === false) {\n $timestamp = microtime(true);\n }\n $timestamp_int = (int) floor($timestamp);\n $microseconds = (int) round(($timestamp - floor($timestamp)) * 1000000.0, 0);\n $format_with_micro = str_replace(\"u\", $microseconds, $format);\n return date($format_with_micro, $timestamp_int);\n}\n" }, { "answer_id": 28515980, "author": "mgutt", "author_id": 318765, "author_profile": "https://Stackoverflow.com/users/318765", "pm_score": 1, "selected": false, "text": "function udate($format, $timestamp=null) {\n if (!isset($timestamp)) $timestamp = microtime();\n // microtime(true)\n if (count($t = explode(\" \", $timestamp)) == 1) {\n list($timestamp, $usec) = explode(\".\", $timestamp);\n $usec = \".\" . $usec;\n }\n // microtime (much more precise)\n else {\n $usec = $t[0];\n $timestamp = $t[1];\n }\n // 7 decimal places for \"u\" is maximum\n $date = new DateTime(date('Y-m-d H:i:s' . substr(sprintf('%.7f', $usec), 1), $timestamp));\n return $date->format($format);\n}\necho udate(\"Y-m-d\\TH:i:s.u\") . \"\\n\";\necho udate(\"Y-m-d\\TH:i:s.u\", microtime(true)) . \"\\n\";\necho udate(\"Y-m-d\\TH:i:s.u\", microtime()) . \"\\n\";\n/* returns:\n2015-02-14T14:10:30.472647\n2015-02-14T14:10:30.472700\n2015-02-14T14:10:30.472749\n*/\n" }, { "answer_id": 28937386, "author": "Ryan", "author_id": 563394, "author_profile": "https://Stackoverflow.com/users/563394", "pm_score": 3, "selected": false, "text": "\\DateTime::createFromFormat('U.u', microtime(true));\n object(DateTime)(\n 'date' => '2015-03-09 17:27:39.456200',\n 'timezone_type' => 3,\n 'timezone' => 'Australia/Darwin'\n)\n createFromFormat() \\DateTime::createFromFormat('0.u00 U', microtime());\n $time = gettimeofday(); \n\\DateTime::createFromFormat('U.u', sprintf('%d.%06d', $time['sec'], $time['usec']));\n" }, { "answer_id": 30109661, "author": "JScarry", "author_id": 791470, "author_profile": "https://Stackoverflow.com/users/791470", "pm_score": 0, "selected": false, "text": "// Create a unique message ID using the time and microseconds\n list($usec, $sec) = explode(\" \", microtime());\n $messageID = date(\"Y-m-d H:i:s \", $sec) . substr($usec, 2, 8);\n $fname = \"./Messages/$messageID\";\n\n $fp = fopen($fname, 'w');\n 2015-05-07 12:03:17 65468400\n" }, { "answer_id": 32552994, "author": "Gras Double", "author_id": 289317, "author_profile": "https://Stackoverflow.com/users/289317", "pm_score": 0, "selected": false, "text": "21:15:05.999 21:15:06.000 21:15:05.000 DateTime::createFromFormat() U.u function udate($format, $time = null) {\n\n if (!$time) {\n $time = microtime(true);\n }\n\n // Avoid missing dot on full seconds: (string)42 and (string)42.000000 give '42'\n $time = number_format($time, 6, '.', '');\n\n return DateTime::createFromFormat('U.u', $time)->format($format);\n}\n" }, { "answer_id": 38334226, "author": "hozza", "author_id": 614616, "author_profile": "https://Stackoverflow.com/users/614616", "pm_score": 3, "selected": false, "text": "date() date('Y-m-d H:i:s').\".$milliseconds\"; list($sec, $usec) = explode('.', microtime(true));\necho date('Y-m-d H:i:s.', $sec) . $usec;\n 2016-07-12 16:27:08.5675 date('Y-m-d H:i:s').\".$microseconds\"; date('Y-m-d H:i:s.u') microtime() list($usec, $sec) = explode(' ', microtime());\necho date('Y-m-d H:i:s', $sec) . substr($usec, 1);\n 2016-07-12 16:27:08.56752900" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25039/" ]
169,435
<p>How can I view the intermediate translation done to JSP and JSPX pages by WTP? I'm getting weird syntax errors in my Problems tab of Eclipse in a project that has plenty of .jspx pages. They don't affect anything in the running application (Tomcat 6.0) and they appeared only over the last 2 weeks, after an update.</p> <p>The reason why I'd like to view the output is that I'm using the Stripes framework at <a href="http://stripesframework.org" rel="nofollow noreferrer">http://stripesframework.org</a> and the errors disappear for a particular .jspx file after I remove the &lt;stripes:errors /&gt; line of that file. At the same time, the syntax errors only appeared after I did recent fresh install of Eclipse at work, but then an update of Eclipse at home shortly therafter. I'd like to see the output to determine whose problem this should be (WTP, Stripes, or maybe just me :).</p> <p>Remember that this issue is somewhat cosmetic, as it doesn't affect anything functionally. It simply spams my Problems tab in Eclipse and shows the little red X icons in the project explorer.</p>
[ { "answer_id": 200594, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<stripes:errors/>" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269754/" ]
169,450
<p><em>Information-Expert</em>, <em>Tell-Don't-Ask</em>, and <em>SRP</em> are often mentioned together as best practices. But I think they are at odds. Here is what I'm talking about.</p> <p>Code that favors SRP but violates Tell-Don't-Ask &amp; Info-Expert:</p> <pre><code>Customer bob = ...; // TransferObjectFactory has to use Customer's accessors to do its work, // violates Tell Don't Ask CustomerDTO dto = TransferObjectFactory.createFrom(bob); </code></pre> <p>Code that favors Tell-Don't-Ask &amp; Info-Expert but violates SRP:</p> <pre><code>Customer bob = ...; // Now Customer is doing more than just representing the domain concept of Customer, // violates SRP CustomerDTO dto = bob.toDTO(); </code></pre> <p>Please fill me in on how these practices can co-exist peacefully.</p> <p>Definitions of the terms,</p> <ul> <li><p>Information Expert: objects that have the data needed for an operation should host the operation.</p></li> <li><p>Tell Don't Ask: don't ask objects for data in order to do work; tell the objects to do the work.</p></li> <li><p>Single Responsibility Principle: each object should have a narrowly defined responsibility.</p></li> </ul>
[ { "answer_id": 13421639, "author": "Michael Parker", "author_id": 1554346, "author_profile": "https://Stackoverflow.com/users/1554346", "pm_score": 1, "selected": false, "text": " List<Bill> bills = Customer.GetOutstandingBills();\n PaymentReminder.RemindCustomer(customer, bills);\n Customer.RemindAboutOutstandingBills() \n" }, { "answer_id": 43689140, "author": "Matthew Flynn", "author_id": 243314, "author_profile": "https://Stackoverflow.com/users/243314", "pm_score": 1, "selected": false, "text": "CustomerDTO dto = new CustomerDTO(bob);\n CustomerDTO dto = CustomerDTO.buildFor(bob);\n public abstract class DTOFactory<D, E> {\n public abstract D createDTO(E entity);\n}\n\n\npublic class CustomerDTOFactory extends DTOFactory<CustomerDTO, Customer> {\n @Override\n public CustomerDTO createDTO(Customer entity) {\n return new CustomerDTO(entity);\n }\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10759/" ]
169,453
<p>We're running a web app on Tomcat 6 and Apache mod_proxy 2.2.3. Seeing a lot of 502 errors like this:</p> <blockquote> <p>Bad Gateway! The proxy server received an invalid response from an upstream server.</p> <p>The proxy server could not handle the request GET /the/page.do.</p> <p>Reason: Error reading from remote server</p> <p>If you think this is a server error, please contact the webmaster.</p> <p>Error 502 </p> </blockquote> <p>Tomcat has plenty of threads, so it's not thread-constrained. We're pushing 2400 users via JMeter against the app. All the boxes are sitting inside our firewall on a fast unloaded network, so there shouldn't be any network problems. </p> <p>Anyone have any suggestions for things to look at or try? We're heading to tcpdump next.</p> <p>UPDATE 10/21/08: Still haven't figured this out. Seeing only a very small number of these under load. The answers below haven't provided any magical answers...yet. :)</p>
[ { "answer_id": 1287662, "author": "Janning", "author_id": 351758, "author_profile": "https://Stackoverflow.com/users/351758", "pm_score": 4, "selected": false, "text": "SetEnv proxy-nokeepalive 1\nSetEnv proxy-initial-not-pooled 1\n keepAlive" }, { "answer_id": 1837936, "author": "sibnick", "author_id": 159923, "author_profile": "https://Stackoverflow.com/users/159923", "pm_score": 2, "selected": false, "text": "#Default value is 2 minutes\n**Timeout 600**\nProxyRequests off\nProxyPass /app balancer://MyApp stickysession=JSESSIONID lbmethod=bytraffic nofailover=On\nProxyPassReverse /app balancer://MyApp\nProxyTimeout 600\n<Proxy balancer://MyApp>\n BalancerMember http://node1:8080/ route=node1 retry=1 max=25 timeout=600\n .........\n</Proxy>\n" }, { "answer_id": 2388463, "author": "Neil Salter", "author_id": 36385, "author_profile": "https://Stackoverflow.com/users/36385", "pm_score": 6, "selected": false, "text": "Timeout 5400\nProxyTimeout 5400\n" }, { "answer_id": 40425665, "author": "bhantol", "author_id": 2103767, "author_profile": "https://Stackoverflow.com/users/2103767", "pm_score": 2, "selected": false, "text": "ProxyPass /svc http://example.com/svc timeout=600\nProxyPassReverse /svc http://example.com/svc timeout=600\n timeout=600 <Proxy \"balancer://mycluster\">\n BalancerMember \"http://member1:8080/svc\" timeout=600\n BalancerMember \"http://member2:8080/svc\" timeout=600\n</Proxy> \n\nProxyPass /svc \"balancer://mycluster\" timeout=600\nProxyPassReverse /svc \"balancer://mycluster\" timeout=600\n timeout=600 ProxyPass ProxyPass ProxyPass BalancerMember" }, { "answer_id": 56000520, "author": "Muhammad Dyas Yaskur", "author_id": 2671470, "author_profile": "https://Stackoverflow.com/users/2671470", "pm_score": 2, "selected": false, "text": "/ ProxyPass / http://192.168.1.1:3001\nProxyPassReverse / http://192.168.1.1:3001\n ProxyPass / http://192.168.1.1:3001/\nProxyPassReverse / http://192.168.1.1:3001/\n" }, { "answer_id": 64805009, "author": "dr0i", "author_id": 1579915, "author_profile": "https://Stackoverflow.com/users/1579915", "pm_score": 0, "selected": false, "text": "timeout mod_proxy failonstatus/failontimeout failontimeout balancer timeout balancer balancer timeout BalancerMember timeout BalanceMember <Proxy balancer://mycluster>\n BalancerMember http://member1:8080/svc timeout=6 \n ... more BalanceMembers here\n</Proxy>\n failontimeout balancer ProxyPass /svc balancer://mycluster failontimeout=on\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671/" ]
169,470
<p>I have a function in which I get en external resource from the web using cocoa's Url object. And it works fine on the simulator, but occasionally fails on the device itself (it's a google query so the resource obviously does exist). Which leads me to believe that there is some internal timeout barrier on the hardware, but haven't read that such a barrier exists or not.</p> <p>Anyone else encountered similar issues? Or knows if the timeout is documented or can be changed?</p>
[ { "answer_id": 173275, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 1, "selected": false, "text": "+ (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval\n\nParameters\ntheURL\nThe URL for the new request.\n\ncachePolicy\nThe cache policy for the new request.\n\ntimeoutInterval\nThe timeout interval for the new request, in seconds.\n\nReturn Value\nThe newly created URL request.\n" }, { "answer_id": 600220, "author": "Andrew Raphael", "author_id": 72499, "author_profile": "https://Stackoverflow.com/users/72499", "pm_score": 2, "selected": false, "text": "Sun Mar 1 10:41:03 unknown SpringBoard[22] <Warning>: <myappid>.* failed to launch in time\n performSelector: withObject: afterDelay: 0.0" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
169,477
<p>I'm trying to implement a server control that frobs a couple of files inside the web directory of an ASP.NET site. I'm using VS Web Dev Express 2008 as my IDE. When I call <code>HttpContext.Current.Request.ApplicationPath</code> to get a path to the web root so I can find those files, it returns C:. What the heck?</p> <p>Absolute paths work just fine, but I'd like to be able to feed the server control a relative directory and just let it do it's thing. What have I done wrong?</p> <pre><code>public String Target { get { return _target; } set { if (value.StartsWith("~")) { // WTF? Gives me C:\? Why? _target = HttpContext.Current.Request.ApplicationPath + value.Substring(1); } else { _target = value; } } } private String _target; protected override void Render(HtmlTextWriter writer) { HtmlControl wrapper = new HtmlGenericControl("div"); int fileCount = 0; try { DirectoryInfo dir = new DirectoryInfo(_target); foreach (FileInfo f in dir.GetFiles()) { fileCount++; a = new HtmlAnchor(); a.Attributes.Add("href", f.FullName); a.InnerHtml = f.Name; wrapper.Controls.Add(a); } } catch (IOException e) { throw e; } Controls.Add(wrapper); base.Render(writer); } </code></pre>
[ { "answer_id": 169490, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "HTTPContext.Current.Request.ServerVariables(\"APPL_PHYSICAL_PATH\")\n" }, { "answer_id": 169510, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "Server.MapPath(ResolveUrl(\"~/filename\"))\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
169,506
<p>I have a form with many input fields.</p> <p>When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?</p>
[ { "answer_id": 169553, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "var items = new Array();\n\n$('#form_id:input').each(function (el) {\n items[el.name] = el;\n});\n" }, { "answer_id": 169554, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 10, "selected": true, "text": "$('#myForm').submit(function() {\n // get all the inputs into an array.\n var $inputs = $('#myForm :input');\n\n // not sure if you wanted this, but I thought I'd add it.\n // get an associative array of just the values.\n var values = {};\n $inputs.each(function() {\n values[this.name] = $(this).val();\n });\n\n});\n serializeArray var values = {};\n$.each($('#myForm').serializeArray(), function(i, field) {\n values[field.name] = field.value;\n});\n <select multiple> serializeArray" }, { "answer_id": 169961, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 4, "selected": false, "text": "$('#myForm').bind('submit', function () {\n var elements = this.elements;\n});" }, { "answer_id": 1443005, "author": "Lance Rushing", "author_id": 150463, "author_profile": "https://Stackoverflow.com/users/150463", "pm_score": 8, "selected": false, "text": "$('#myForm').submit(function() {\n // Get all the forms elements and their values in one step\n var values = $(this).serialize();\n\n});\n" }, { "answer_id": 3863951, "author": "slarti42uk", "author_id": 429740, "author_profile": "https://Stackoverflow.com/users/429740", "pm_score": 0, "selected": false, "text": "$.extend($.expr[':'],{\n submitable: function(a){\n if($(a).is(':checkbox:not(:checked)'))\n {\n return false;\n }\n else if($(a).is(':input'))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n});\n $('#form_id :submitable');\n" }, { "answer_id": 4892057, "author": "Man Called Haney", "author_id": 139062, "author_profile": "https://Stackoverflow.com/users/139062", "pm_score": 2, "selected": false, "text": "var inputs = $(\"#myForm :input\");\nvar obj = $.map(inputs, function(n, i) {\n var o = {};\n if (n.type == \"radio\" || n.type == \"checkbox\")\n o[n.id] = $(n).attr(\"checked\");\n else\n o[n.id] = $(n).val();\n return o;\n});\nreturn obj\n" }, { "answer_id": 7305864, "author": "suizo", "author_id": 836948, "author_profile": "https://Stackoverflow.com/users/836948", "pm_score": 2, "selected": false, "text": "var arr = new Array();\n$(':input').each(function() {\n arr.push($(this).val());\n});\narr;\n $(':input')" }, { "answer_id": 7650082, "author": "Itako", "author_id": 500921, "author_profile": "https://Stackoverflow.com/users/500921", "pm_score": 2, "selected": false, "text": "<input type=\"text\" name=\"array[]\" /> values = {};\n$(\"#something :input\").each(function() {\n if (this.name.search(/\\[\\]/) > 0) //search for [] in name\n {\n if (typeof values[this.name] != \"undefined\") {\n values[this.name] = values[this.name].concat([$(this).val()])\n } else {\n values[this.name] = [$(this).val()];\n }\n } else {\n values[this.name] = $(this).val();\n }\n});\n" }, { "answer_id": 8433722, "author": "Chris", "author_id": 1088085, "author_profile": "https://Stackoverflow.com/users/1088085", "pm_score": 3, "selected": false, "text": "$('form:input') var dataValues = {};\n form.find('input').each(\n function(unusedIndex, child) {\n dataValues[child.name] = child.value;\n });\n" }, { "answer_id": 9891143, "author": "Sarah Vessels", "author_id": 38743, "author_profile": "https://Stackoverflow.com/users/38743", "pm_score": 3, "selected": false, "text": "serializeArray var data = {};\n$('form.my-form').find('input, textarea, select').each(function(i, field) {\n data[field.name] = field.value;\n});\n" }, { "answer_id": 10264676, "author": "Malachi", "author_id": 287545, "author_profile": "https://Stackoverflow.com/users/287545", "pm_score": 4, "selected": false, "text": "var input_name = \"firstname\";\nvar input = $(\"#form_id :input[name='\"+input_name+\"']\"); \n" }, { "answer_id": 11098341, "author": "Jason Norwood-Young", "author_id": 493510, "author_profile": "https://Stackoverflow.com/users/493510", "pm_score": 1, "selected": false, "text": "$('#contentform').find('input, textarea, select').each(function(x, field) {\n if (field.name) {\n if (field.name.indexOf('[]')>0) {\n if (!$.isArray(data[field.name])) {\n data[field.name]=new Array();\n }\n data[field.name].push(field.value);\n } else {\n data[field.name]=field.value;\n }\n } \n});\n" }, { "answer_id": 20450781, "author": "Julian", "author_id": 3013580, "author_profile": "https://Stackoverflow.com/users/3013580", "pm_score": 0, "selected": false, "text": "// This html:\n// <form id=\"someCoolForm\">\n// <input type=\"text\" class=\"form-control\" name=\"username\" value=\"....\" />\n// \n// <input type=\"text\" class=\"form-control\" name=\"profile.first_name\" value=\"....\" />\n// <input type=\"text\" class=\"form-control\" name=\"profile.last_name\" value=\"....\" />\n// \n// <input type=\"text\" class=\"form-control\" name=\"emails[]\" value=\"...\" />\n// <input type=\"text\" class=\"form-control\" name=\"emails[]\" value=\"..\" />\n// <input type=\"text\" class=\"form-control\" name=\"emails[]\" value=\".\" />\n// </form>\n// \n// With this js:\n// \n// var form1 = parseForm($('#someCoolForm'));\n// console.log(form1);\n// \n// Will output something like:\n// {\n// username: \"test2\"\n// emails:\n// 0: \".@....com\"\n// 1: \"...@........com\"\n// profile: Object\n// first_name: \"...\"\n// last_name: \"...\"\n// }\n// \n// So, function below:\n\nvar parseForm = function (form) {\n\n var formdata = form.serializeArray();\n\n var data = {};\n\n _.each(formdata, function (element) {\n\n var value = _.values(element);\n\n // Parsing field arrays.\n if (value[0].indexOf('[]') > 0) {\n var key = value[0].replace('[]', '');\n\n if (!data[key])\n data[key] = [];\n\n data[value[0].replace('[]', '')].push(value[1]);\n } else\n\n // Parsing nested objects.\n if (value[0].indexOf('.') > 0) {\n\n var parent = value[0].substring(0, value[0].indexOf(\".\"));\n var child = value[0].substring(value[0].lastIndexOf(\".\") + 1);\n\n if (!data[parent])\n data[parent] = {};\n\n data[parent][child] = value[1];\n } else {\n data[value[0]] = value[1];\n }\n });\n\n return data;\n};\n" }, { "answer_id": 26843102, "author": "Chris Wheeler", "author_id": 2747260, "author_profile": "https://Stackoverflow.com/users/2747260", "pm_score": 3, "selected": false, "text": "$('#form').on('submit', function() {\n var data = $(this).serializeArray();\n});\n var data = new FormData([form])\n" }, { "answer_id": 27176157, "author": "Ole Aldric", "author_id": 4301060, "author_profile": "https://Stackoverflow.com/users/4301060", "pm_score": 4, "selected": false, "text": "$('.form').on('submit', function( e )){ \n var form = $( this ), // this will resolve to the form submitted\n action = form.attr( 'action' ),\n type = form.attr( 'method' ),\n data = {};\n\n // Make sure you use the 'name' field on the inputs you want to grab. \n form.find( '[name]' ).each( function( i , v ){\n var input = $( this ), // resolves to current input element.\n name = input.attr( 'name' ),\n value = input.val();\n data[name] = value;\n });\n\n // Code which makes use of 'data'.\n\n e.preventDefault();\n}\n function sendRequest(action, type, data) {\n $.ajax({\n url: action,\n type: type,\n data: data\n })\n .done(function( returnedHtml ) {\n $( \"#responseDiv\" ).append( returnedHtml );\n })\n .fail(function() {\n $( \"#responseDiv\" ).append( \"This failed\" );\n });\n}\n" }, { "answer_id": 36668583, "author": "Marcelo Rocha", "author_id": 5905467, "author_profile": "https://Stackoverflow.com/users/5905467", "pm_score": 0, "selected": false, "text": "<input type=\"text\" name=\"some_name\" ignore_this>\n if(!$(name).prop('ignorar')){\n do_your_thing;\n}\n" }, { "answer_id": 41141152, "author": "Roman Grinev", "author_id": 2834876, "author_profile": "https://Stackoverflow.com/users/2834876", "pm_score": 1, "selected": false, "text": "$('.subscribe-form').submit(function(e){\n var arr=$(this).serializeArray();\n var values={};\n for(i in arr){values[arr[i]['name']]=arr[i]['value']}\n console.log(values);\n return false;\n});\n" }, { "answer_id": 43871489, "author": "Ryanman", "author_id": 1214741, "author_profile": "https://Stackoverflow.com/users/1214741", "pm_score": 2, "selected": false, "text": "var formData = $('#formId').serializeArray().reduce(function (obj, item) {\n if (obj[item.name] == null) {\n obj[item.name] = [];\n } \n obj[item.name].push(item.value);\n return obj;\n}, {});\n" }, { "answer_id": 44493957, "author": "sparsh turkane", "author_id": 7113702, "author_profile": "https://Stackoverflow.com/users/7113702", "pm_score": 3, "selected": false, "text": "$(document).ready(function(){\n $(\"#form_id\").submit(function(event){\n event.preventDefault();\n var name = $(\"input[name='name']\",this).val();\n var email = $(\"input[name='email']\",this).val();\n });\n});\n" }, { "answer_id": 45824035, "author": "T.Liu", "author_id": 3574916, "author_profile": "https://Stackoverflow.com/users/3574916", "pm_score": 1, "selected": false, "text": "$('#myForm').submit( function( event ) {\n var values = $(this).serializeArray();\n // In my case, I need to fetch these data before custom actions\n event.preventDefault();\n});\n [{name: \"start-time\", value: \"11:01\"}, {name: \"end-time\", value: \"11:11\"}]\n var inputs = {};\n$.each(values, function(k, v){\n inputs[v.name]= v.value;\n});\n {\"start-time\":\"11:01\", \"end-time\":\"11:01\"}\n" }, { "answer_id": 57202528, "author": "dipenparmar12", "author_id": 8592918, "author_profile": "https://Stackoverflow.com/users/8592918", "pm_score": 2, "selected": false, "text": " $(\"#form\").submit(function (e) { \n e.preventDefault();\n input_values = $(this).serializeArray();\n });\n" }, { "answer_id": 60259912, "author": "Teodor Rautu", "author_id": 12911767, "author_profile": "https://Stackoverflow.com/users/12911767", "pm_score": 0, "selected": false, "text": "jQuery(\"#form\").serializeArray().filter(obje => \nobje.value!='').map(aobj=>aobj.name+\"=\"+aobj.value).join(\"&\")\n" }, { "answer_id": 60342733, "author": "tzazo", "author_id": 12718345, "author_profile": "https://Stackoverflow.com/users/12718345", "pm_score": 1, "selected": false, "text": "<select multiple=\"multiple\"> data function _get_values(form) {\n let data = {};\n $(form).find('input, textarea, select').each(function(x, field) {\n if (field.name) {\n if (field.name.indexOf('[]') > 0) {\n if (!$.isArray(data[field.name])) {\n data[field.name] = new Array();\n }\n for (let i = 0; i < field.selectedOptions.length; i++) {\n data[field.name].push(field.selectedOptions[i].value);\n }\n\n } else {\n data[field.name] = field.value;\n }\n }\n\n });\n return data\n}\n _get_values($('#form'))\n name [] <select name=\"favorite_colors[]\" multiple=\"multiple\">\n <option value=\"red\">Red</option>\n <option value=\"green\">Green</option>\n <option value=\"blue\">Blue</option>\n</select>\n" }, { "answer_id": 61876539, "author": "Raushan", "author_id": 12119519, "author_profile": "https://Stackoverflow.com/users/12119519", "pm_score": 2, "selected": false, "text": "$(\"#form-id\").submit(function (e) { \n e.preventDefault();\n inputs={};\n input_serialized = $(this).serializeArray();\n input_serialized.forEach(field => {\n inputs[field.name] = field.value;\n })\n console.log(inputs)\n});\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
169,511
<p>How do I iterate over a range of numbers in Bash when the range is given by a variable?</p> <p>I know I can do this (called "sequence expression" in the Bash <a href="http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion" rel="noreferrer">documentation</a>):</p> <pre><code> for i in {1..5}; do echo $i; done </code></pre> <p>Which gives:</p> <blockquote> <p>1 <br/> 2 <br/> 3 <br/> 4 <br/> 5</p> </blockquote> <p>Yet, how can I replace either of the range endpoints with a variable? This doesn't work:</p> <pre><code>END=5 for i in {1..$END}; do echo $i; done </code></pre> <p>Which prints:</p> <blockquote> <p>{1..5}</p> </blockquote>
[ { "answer_id": 169515, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 5, "selected": false, "text": "for i in $(seq $END); do echo $i; done\n" }, { "answer_id": 169517, "author": "Jiaaro", "author_id": 2908, "author_profile": "https://Stackoverflow.com/users/2908", "pm_score": 12, "selected": true, "text": "for i in $(seq 1 $END); do echo $i; done seq" }, { "answer_id": 169518, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "bash END=5\ni=1 ; while [[ $i -le $END ]] ; do\n echo $i\n ((i = i + 1))\ndone\n" }, { "answer_id": 169602, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 8, "selected": false, "text": "seq i typeset -i i END\nlet END=5 i=1\nwhile ((i<=END)); do\n echo $i\n …\n let i++\ndone\n echo echo $((i++)) for ((expr;expr;expr)) ksh typeset -i i END # Let's be explicit\nfor ((i=1;i<=END;++i)); do echo $i; done\n seq fork() exec() seq for i in $(eval echo \"{1..$END}\"); do\n eval echo fork() $(…)" }, { "answer_id": 171041, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 9, "selected": false, "text": "seq END=5\nfor ((i=1;i<=END;i++)); do\n echo $i\ndone\n# ==> outputs 1 2 3 4 5 on separate lines\n for ((expr1;expr2;expr3)); for (expr1;expr2;expr3) ((expr))" }, { "answer_id": 5303675, "author": "bobbogo", "author_id": 470195, "author_profile": "https://Stackoverflow.com/users/470195", "pm_score": 5, "selected": false, "text": "for i in $(eval echo {1..$END}); do\n ∶\n" }, { "answer_id": 5319280, "author": "jefeveizen", "author_id": 659754, "author_profile": "https://Stackoverflow.com/users/659754", "pm_score": 4, "selected": false, "text": "for i in $(jot $END); do echo $i; done\n" }, { "answer_id": 5723526, "author": "DigitalRoss", "author_id": 140740, "author_profile": "https://Stackoverflow.com/users/140740", "pm_score": 7, "selected": false, "text": "for i in <list>; do while seq #!/bin/sh\n\nlimit=4\n\ni=1; while [ $i -le $limit ]; do\n echo $i\n i=$(($i + 1))\ndone\n# Or -----------------------\nfor i in $(seq 1 $limit); do\n echo $i\ndone\n" }, { "answer_id": 7085147, "author": "SuperBob", "author_id": 897533, "author_profile": "https://Stackoverflow.com/users/897533", "pm_score": 3, "selected": false, "text": "$i RANGE_START=a\nRANGE_END=z\necho -e \"for i in {$RANGE_START..$RANGE_END}; do echo \\\\${i}; done\" | bash\n VAR=`echo -e \"for i in {$RANGE_START..$RANGE_END}; do echo \\\\${i}; done\" | bash`\n" }, { "answer_id": 18894729, "author": "Adrian Frühwirth", "author_id": 612462, "author_profile": "https://Stackoverflow.com/users/612462", "pm_score": 3, "selected": false, "text": "bash ksh93 $ ksh -c 'i=5; for x in {1..$i}; do echo \"$x\"; done'\n1\n2\n3\n4\n5\n$ ksh -c 'echo $KSH_VERSION'\nVersion JM 93u+ 2012-02-29\n\n$ bash -c 'i=5; for x in {1..$i}; do echo \"$x\"; done'\n{1..5}\n" }, { "answer_id": 22339375, "author": "BashTheKeyboard", "author_id": 3408346, "author_profile": "https://Stackoverflow.com/users/3408346", "pm_score": 3, "selected": false, "text": "{} (( )) tmpstart=0;\ntmpend=4;\n\nfor (( i=$tmpstart; i<=$tmpend; i++ )) ; do \necho $i ;\ndone\n 0\n1\n2\n3\n4\n" }, { "answer_id": 31365662, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 7, "selected": false, "text": "i=2\nend=5\nwhile [ $i -le $end ]; do\n echo $i\n i=$(($i+1))\ndone\n 2\n3\n4\n5\n (( )) [[ [ for ((;;)) seq {start..end} let i=i+1 let bash --posix i=$i+1 $((x+1)) x+1" }, { "answer_id": 31367827, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 3, "selected": false, "text": "end=5\nfor i in $(bash -c \"echo {1..${end}}\"); do echo $i; done\n" }, { "answer_id": 43054927, "author": "Alex Spangher", "author_id": 2056246, "author_profile": "https://Stackoverflow.com/users/2056246", "pm_score": 3, "selected": false, "text": "seq 1 $END | xargs -I {} echo {}" }, { "answer_id": 44348183, "author": "hossbear", "author_id": 4413742, "author_profile": "https://Stackoverflow.com/users/4413742", "pm_score": 5, "selected": false, "text": " for ((i=7;i<=12;i++)); do echo `printf \"%2.0d\\n\" $i |sed \"s/ /0/\"`;done\n 07\n08\n09\n10\n11\n12\n" }, { "answer_id": 45352296, "author": "Zac B", "author_id": 249199, "author_profile": "https://Stackoverflow.com/users/249199", "pm_score": 3, "selected": false, "text": "range range.bash echo {1..10} source range.bash\none=1\nten=10\n\nrange {$one..$ten}\nrange $one $ten\nrange {1..$ten}\nrange {1..10}\n for i in {1..a}; do echo $i; done seq {a..z} {1..10} $END END=a {1..a}" }, { "answer_id": 49765602, "author": "Ethan Post", "author_id": 4527, "author_profile": "https://Stackoverflow.com/users/4527", "pm_score": 0, "selected": false, "text": "function num_range {\n # Return a range of whole numbers from beginning value to ending value.\n # >>> num_range start end\n # start: Whole number to start with.\n # end: Whole number to end with.\n typeset s e v\n s=${1}\n e=${2}\n if (( ${e} >= ${s} )); then\n v=${s}\n while (( ${v} <= ${e} )); do\n echo ${v}\n ((v=v+1))\n done\n elif (( ${e} < ${s} )); then\n v=${s}\n while (( ${v} >= ${e} )); do\n echo ${v}\n ((v=v-1))\n done\n fi\n}\n\nfunction test_num_range {\n num_range 1 3 | egrep \"1|2|3\" | assert_lc 3\n num_range 1 3 | head -1 | assert_eq 1\n num_range -1 1 | head -1 | assert_eq \"-1\"\n num_range 3 1 | egrep \"1|2|3\" | assert_lc 3\n num_range 3 1 | head -1 | assert_eq 3\n num_range 1 -1 | tail -1 | assert_eq \"-1\"\n}\n" }, { "answer_id": 54770805, "author": "Bruno Bronosky", "author_id": 117471, "author_profile": "https://Stackoverflow.com/users/117471", "pm_score": 5, "selected": false, "text": "seq {..} for while $( ) for (( ; ; )) $(( )) for (( i=1; i<=1000000; i++ )) for i in $(seq 1 1000000) # show that seq is fast\n$ time (seq 1 1000000 | wc)\n 1000000 1000000 6888894\n\nreal 0m0.227s\nuser 0m0.239s\nsys 0m0.008s\n\n# show that {..} is fast\n$ time (echo {1..1000000} | wc)\n 1 1000000 6888896\n\nreal 0m1.778s\nuser 0m1.735s\nsys 0m0.072s\n\n# Show that for loops (even with a : noop) are slow\n$ time (for i in {1..1000000} ; do :; done | wc)\n 0 0 0\n\nreal 0m3.642s\nuser 0m3.582s\nsys 0m0.057s\n\n# show that echo is slow\n$ time (for i in {1..1000000} ; do echo $i; done | wc)\n 1000000 1000000 6888896\n\nreal 0m7.480s\nuser 0m6.803s\nsys 0m2.580s\n\n$ time (for i in $(seq 1 1000000) ; do echo $i; done | wc)\n 1000000 1000000 6888894\n\nreal 0m7.029s\nuser 0m6.335s\nsys 0m2.666s\n\n# show that C-style for loops are slower\n$ time (for (( i=1; i<=1000000; i++ )) ; do echo $i; done | wc)\n 1000000 1000000 6888896\n\nreal 0m12.391s\nuser 0m11.069s\nsys 0m3.437s\n\n# show that arithmetic expansion is even slower\n$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; i=$(($i+1)); done | wc)\n 1000000 1000000 6888896\n\nreal 0m19.696s\nuser 0m18.017s\nsys 0m3.806s\n\n$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; ((i=i+1)); done | wc)\n 1000000 1000000 6888896\n\nreal 0m18.629s\nuser 0m16.843s\nsys 0m3.936s\n\n$ time (i=1; e=1000000; while [ $i -le $e ]; do echo $((i++)); done | wc)\n 1000000 1000000 6888896\n\nreal 0m17.012s\nuser 0m15.319s\nsys 0m3.906s\n\n# even a noop is slow\n$ time (i=1; e=1000000; while [ $((i++)) -le $e ]; do :; done | wc)\n 0 0 0\n\nreal 0m12.679s\nuser 0m11.658s\nsys 0m1.004s\n" }, { "answer_id": 56329737, "author": "theBuzzyCoder", "author_id": 2147023, "author_profile": "https://Stackoverflow.com/users/2147023", "pm_score": 4, "selected": false, "text": "seq man seq $ seq [-w] [-f format] [-s string] [-t string] [first [incr]] last\n seq first incr last $ seq 1 2 10\n1 3 5 7 9\n $ seq 1 5\n1 2 3 4 5\n $ seq 5\n1 2 3 4 5\n {first..last..incr} $ echo {1..5}\n1 2 3 4 5\n $ echo {1..10..2}\n1 3 5 7 9\n $ echo {a..z}\na b c d e f g h i j k l m n o p q r s t u v w x y z\n" }, { "answer_id": 56653812, "author": "Zimba", "author_id": 5958708, "author_profile": "https://Stackoverflow.com/users/5958708", "pm_score": 2, "selected": false, "text": "seq eval jot for ((i=1;i<=END;i++)) while printf echo a=1; b=5; d='for i in {'$a'..'$b'}; do echo -n \"$i\"; done;' echo \"$d\" | bash seq" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24923/" ]
169,512
<p>I recently began using <a href="http://www.eclipse.org/birt/phoenix/deploy/" rel="noreferrer">BIRT</a> and have developed a report to use with my <a href="http://developer.mozilla.org/en/XULRunner" rel="noreferrer">xulrunner</a> application. What I haven't yet figured out is how I should deploy the viewer. It seems like BIRT mostly targets Java applications, so there are instructions for deploying on J2EE, JBoss, and other technologies -- with which I am not familiar (but I'm not developing in Java anyway).</p> <p>Reviewing <a href="http://www.onjava.com/pub/a/onjava/2006/07/26/deploying-birt.html" rel="noreferrer">this article</a> on deploying BIRT and reviewing the <a href="http://www.eclipse.org/birt/phoenix/deploy/" rel="noreferrer">deployment details</a> on BIRT's web site, I'm not sure where to go. I wasn't expecting to have to add some large Java dependency for the xulrunner application --is there no way I can drop an executable in with my xulrunner app, call it from my app, and pass it a report document? (Or something else that would be simpler than learning and using J2EE, JBoss, tomcat?)</p>
[ { "answer_id": 27257220, "author": "McCoy", "author_id": 2816092, "author_profile": "https://Stackoverflow.com/users/2816092", "pm_score": 2, "selected": false, "text": "genReport.bat -f PDF -o PATH/GENERATED_REPORTS/REPORT.pdf -F \"PATH/TO/REPORT.rptdesign\"" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525/" ]
169,520
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/795746/warning-mysql-fetch-array-supplied-argument-is-not-a-valid-mysql-result">Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result</a> </p> </blockquote> <p>When I run my php page, I get this error and do not know what's wrong, can anyone help? If anyone needs more infomation, I'll post the whole code.</p> <pre>Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in H:\Program Files\EasyPHP 2.0b1\www\test\info.php on line 16</pre> <pre><code>&lt;?PHP $user_name = "root"; $password = ""; $database = "addressbook"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "SELECT * FROM tb_address_book"; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . "&lt;BR&gt;"; print $db_field['First_Name'] . "&lt;BR&gt;"; print $db_field['Surname'] . "&lt;BR&gt;"; print $db_field['Address'] . "&lt;BR&gt;"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?&gt; </code></pre>
[ { "answer_id": 169527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?PHP\n\n $user_name = \"root\";\n $password = \"\";\n $database = \"addressbook\";\n $server = \"127.0.0.1\";\n\n$db_handle = mysql_connect($server, $user_name, $password);\n$db_found = mysql_select_db($database, $db_handle);\n\nif ($db_found) {\n\n $SQL = \"SELECT * FROM tb_address_book\";\n $result = mysql_query($SQL);\n\n while ($db_field = mysql_fetch_assoc($result)) {\n print $db_field['ID'] . \"<BR>\";\n print $db_field['First_Name'] . \"<BR>\";\n print $db_field['Surname'] . \"<BR>\";\n print $db_field['Address'] . \"<BR>\";\n } \n\n mysql_close($db_handle);\n\n}\nelse {\n print \"Database NOT Found \";\n mysql_close($db_handle);\n}\n\n?>\n" }, { "answer_id": 169528, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": false, "text": "$sql = \"SELECT * FROM myTable\"; // table name only do not add tb\n$result = mysql_query($sql);\nvar_dump($result); // bool(false)\n false while if (!$result) {\n echo \"Error. \" . mysql_error();\n} else {\n while ( ... ) {\n ...\n }\n}\n tb_address_book" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,529
<p>So I have a ListView with an upper limit of about 1000 items. I need to be able to filter these items using a textbox's TextChanged event. I have some code that works well for a smaller number of items (~400), but when I need to re-display a full list of all 1000 items, it takes about 4 seconds.</p> <p>I am not creating new ListViewItems every time. Instead, I keep a list of the full item collection and then add from that. It seems that the .Add method is taking a long time regardless. Here is a little sample:</p> <pre><code>this.BeginUpdate(); foreach (ListViewItem item in m_cachedItems) { MyListView.Add(item); } this.EndUpdate; </code></pre> <p>I have tried only adding the missing items (i.e., the difference between the items currently being displayed and the total list of items), but this doesn't work either. There can be a situation in which there is only one item currently displayed, the user clears the textbox, and I need to display the entire list.</p> <p>I am not very experienced in eeking performance out of .NET controls with a large sample like this, so I don't really know a better way to do it. Is there any way around using the .Add() method, or if not, just e better general solution?</p>
[ { "answer_id": 169611, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 2, "selected": false, "text": "MyListView.AddRange(items)\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053/" ]
169,555
<p>Greetings,</p> <p>I need to include a property in my class which is a collection of System.IO.FileInfo objects. I am not really sure how to do this and how I would add and removed objects from an instance of the the class (I would assume like any other collection). </p> <p>Please let me know if I need to add more information.</p> <p>Thank you</p> <p>Update: Am I approaching this the wrong way? I have read comments that adding to a collection which is a property is bad practice. If this is true what is good practice? I have a bunch of objects I need to store in a collection. The collection will be added to and removed from before a final action will be taken on it. Is this a correct approach or am I missing something?</p>
[ { "answer_id": 169568, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "File FileInfo class Foo {\n public IEnumerable<FileInfo> LotsOfFile {\n get {\n for (int i=0; i < 100; i++) {\n yield return new FileInfo(\"C:\\\\\" + i + \".txt\");\n }\n }\n }\n private List<FileInfo> files = new List<FileInfo>();\n public List<FileInfo> MoreFiles {\n get {\n return files;\n }\n }\n public ReadOnlyCollection<FileInfo> MoreFilesReadOnly {\n get {\n return files.AsReadOnly();\n }\n }\n\n}\n MoreFiles Foo f = new Foo();\nf.MoreFiles.Add(new FileInfo(\"foo.txt\"));\nf.MoreFiles.Add(new FileInfo(\"BAR.txt\"));\nf.MoreFiles.Add(new FileInfo(\"baz.txt\"));\nConsole.WriteLine(f.MoreFiles.Count);\n" }, { "answer_id": 169572, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "Public ReadOnly Property Files As Generic.List(Of IO.File)\n GET\n Return _Files\n END GET\nEND Property\n" }, { "answer_id": 169608, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "using System.Collections.ObjectModel;\n\npublic class Foo\n { private Collection<FileInfo> files = new Collection<FileInfo>();\n public Collection<FileInfo> Files { get { return files;} }\n }\n\n//...\nFoo f = new Foo();\nf.Files.Add(file);\n" }, { "answer_id": 169619, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": 0, "selected": false, "text": "class Example\n{\n public List<FileInfo> FileList { get; set; }\n public Dictionary<string, FileInfo> Files { get; set; }\n\n public Example()\n {\n FileList = new List<FileInfo>();\n Files = new Dictionary<string, FileInfo>();\n }\n\n}\n var obj = new Example();\nobj.FileList.Add(new FileInfo(\"file.txt\")); // List<>\nobj.Files.Add(\"file.txt\", new FileInfo(\"file.txt\")); // Dictionary<>\n// also\nobj.Files[\"file2.txt\"] = new FileInfo(\"file2.txt\"); // Dictionary<>\n\n// fetch \nvar myListedFile = obj.FileList[0]; // List<>\nvar myFile = obj.Files[\"file.txt\"]; // Dictionary<>\n obj.Files = new Dictionary<string, FileInfo>();\n// or\nvar otherFiles = new Dictionary<string, FileInfo>();\notherFiles[\"otherfile.txt\"] = new FileInfo(\"otherfile.txt\");\nobj.Files = otherFiles;\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ]
169,562
<p>Ok, my actual problem was this: I was implementing an <code>IList&lt;T&gt;</code>. When I got to <code>CopyTo(Array array, int index)</code>, this was my solution:</p> <pre><code>void ICollection.CopyTo(Array array, int index) { // Bounds checking, etc here. if (!(array.GetValue(0) is T)) throw new ArgumentException("Cannot cast to this type of Array."); // Handle copying here. } </code></pre> <p>This worked in my original code, and still works. But it has a small flaw, which wasn't exposed till I started building tests for it, specifically this one:</p> <pre><code>public void CopyToObjectArray() { ICollection coll = (ICollection)_list; string[] testArray = new string[6]; coll.CopyTo(testArray, 2); } </code></pre> <p>Now, this test should pass. It throws the <code>ArgumentException</code> about not being able to cast. Why? <code>array[0] == null</code>. The <code>is</code> keyword always returns false when checking a variable that is set to <code>null</code>. Now, this is handy for all sorts of reasons, including avoiding null dereferences, etc. What I finally came up with for my type checking was this:</p> <pre><code>try { T test = (T)array.GetValue(0); } catch (InvalidCastException ex) { throw new ArgumentException("Cannot cast to this type of Array.", ex); } </code></pre> <p>This isn't exactly elegant, but it works... Is there a better way though?</p>
[ { "answer_id": 169579, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 2, "selected": false, "text": "if(!typeof(T).IsAssignableFrom(array.GetElementType()))\n" }, { "answer_id": 169595, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "List<T> try\n{\n Array.Copy(this._items, 0, array, index, this.Count);\n}\ncatch (ArrayTypeMismatchException)\n{\n //throw exception...\n}\n" }, { "answer_id": 169613, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 3, "selected": true, "text": "array is T[] class MyCollection : ICollection<T> {\n void ICollection<T>.CopyTo(T[] array, int index) {\n // Bounds checking, etc here.\n CopyToImpl(array, index);\n }\n void ICollection.CopyTo(Array array, int index) {\n // Bounds checking, etc here.\n if (array is T[]) { // quick, avoids reflection, but only works if array is typed as exactly T[]\n CopyToImpl((T[])localArray, index);\n } else {\n Type elementType = array.GetType().GetElementType();\n if (!elementType.IsAssignableFrom(typeof(T)) && !typeof(T).IsAssignableFrom(elementType)) {\n throw new Exception();\n }\n CopyToImpl((object[])array, index);\n }\n }\n private void CopyToImpl(object[] array, int index) {\n // array will always have a valid type by this point, and the bounds will be checked\n // Handle the copying here\n }\n}\n element.IsAssignableFrom(typeof(T)) typeof(T).IsAssignableFrom(elementType) ICollection S T S[]" }, { "answer_id": 546208, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 0, "selected": false, "text": "object[] obj = new object[] { };\nDateTime start = DateTime.Now;\n\nfor (int x = 0; x < 1000; x++)\n{\n try\n {\n throw new Exception();\n }\n catch (Exception ex) { }\n}\nDateTime end = DateTime.Now;\nConsole.WriteLine(\"Try/Catch: \" + (end - start).TotalSeconds.ToString());\n\nstart = DateTime.Now;\n\nfor (int x = 0; x < 1000; x++)\n{\n bool assignable = typeof(int).IsAssignableFrom(obj.GetType().GetElementType());\n}\nend = DateTime.Now;\nConsole.WriteLine(\"IsAssignableFrom: \" + (end - start).TotalSeconds.ToString());\n Try/Catch: 1.7501001\nIsAssignableFrom: 0\n Try/Catch: 1.8171039\nIsAssignableFrom: 0.0010001\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
169,573
<p>I am searching for an open source Java library to generate thumbnails for a given URL. I need to bundle this capability, rather than call out to external services, such as <a href="http://aws.amazon.com/ast/" rel="nofollow noreferrer">Amazon</a> or <a href="http://www.websnapr.com/" rel="nofollow noreferrer">websnapr</a>.</p> <p><a href="http://www.webrenderer.com/" rel="nofollow noreferrer">http://www.webrenderer.com/</a> was mentioned in this post: <a href="https://stackoverflow.com/questions/119116/server-generated-web-screenshots#119264">Server generated web screenshots</a>, but it is a commercial solution.</p> <p>I'm hoping for a Java based solution, but may need to look into executing an external process such as <a href="http://khtml2png.sourceforge.net/index.php?page=faq" rel="nofollow noreferrer">khtml2png</a>, or integrating something like <a href="http://user.it.uu.se/~jan/html2ps.html" rel="nofollow noreferrer">html2ps</a>.</p> <p>Any suggestions?</p>
[ { "answer_id": 170392, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "import java.awt.Component;\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JLabel;\n\npublic class Capture {\n\n private static final int WIDTH = 128;\n private static final int HEIGHT = 128;\n\n private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,\n BufferedImage.TYPE_INT_RGB);\n\n public void capture(Component component) {\n component.setSize(image.getWidth(), image.getHeight());\n\n Graphics2D g = image.createGraphics();\n try {\n component.paint(g);\n } finally {\n g.dispose();\n }\n }\n\n private BufferedImage getScaledImage(int width, int height) {\n BufferedImage buffer = new BufferedImage(width, height,\n BufferedImage.TYPE_INT_RGB);\n Graphics2D g = buffer.createGraphics();\n try {\n g.drawImage(image, 0, 0, width, height, null);\n } finally {\n g.dispose();\n }\n return buffer;\n }\n\n public void save(File png, int width, int height) throws IOException {\n ImageIO.write(getScaledImage(width, height), \"png\", png);\n }\n\n public static void main(String[] args) throws IOException {\n JLabel label = new JLabel();\n label.setText(\"Hello, World!\");\n label.setOpaque(true);\n\n Capture cap = new Capture();\n cap.capture(label);\n cap.save(new File(\"foo.png\"), 64, 64);\n }\n\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14419/" ]
169,574
<p>Like most *nix people, I tend to play with my tools and get them configured just the way that I like them. This was all well and good until recently. As I do more and more work, I tend to log onto more and more machines, and have more and more stuff that's configured great on my home machine, but not necessarily on my work machine, or my web server, or any of my work servers...</p> <p>How do you keep these config files updated? Do you just manually copy them over? Do you have them stored somewhere public?</p>
[ { "answer_id": 169638, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "sh" }, { "answer_id": 169663, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 2, "selected": false, "text": "svn co http://my.rep/home/public\n" }, { "answer_id": 169686, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 2, "selected": false, "text": "git" }, { "answer_id": 989666, "author": "claytron", "author_id": 34530, "author_profile": "https://Stackoverflow.com/users/34530", "pm_score": 3, "selected": false, "text": "$HOME $ cd\n\n# checkout the files\n$ svn co https://path/to/my/dotfiles/trunk .dotfiles\n\n# remove any files that might be in the way\n$ .dotfiles/create_links.sh unlink\n\n# create the symlinks and other random tasks needed for setup\n$ .dotfiles/create_links.sh\n" }, { "answer_id": 7755329, "author": "andsens", "author_id": 339505, "author_profile": "https://Stackoverflow.com/users/339505", "pm_score": 3, "selected": false, "text": "homesick track homesick symlink" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24817/" ]
169,590
<p>I need to fire an event when the mouse is above a PictureBox with the mouse button already clicked and held down.</p> <p>Problems: </p> <p>The MouseDown and MouseEnter event handlers do not work together very well.</p> <p>For instance once a mouse button is clicked and held down, C# will fire the MouseDown event handler, but when the cursor moves over the PictureBox the MouseEnter event does not fire, until the mouse button is realeased.</p>
[ { "answer_id": 169604, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": false, "text": "System.Windows.Control.MousePosition PictureBox.ClientRectangle Control.MouseButtons if (pictureBox.ClientRectangle.Contains(pictureBox.PointToClient(Control.MousePosition)))\n{\n if ((Control.MouseButtons & MouseButtons.Left) != 0)\n {\n // Left button is down.\n }\n}\n" }, { "answer_id": 169666, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 5, "selected": true, "text": "Application.AddMessageFilter(myFilterClassInstance);\n public class MyFilterClass : IMessageFilter\n{\n public bool PreFilterMessage(ref Message m)\n {\n if (m.Msg == WM_MOUSEMOVE)\n // Check if mouse is over my picture box!\n\n return false;\n }\n}\n" }, { "answer_id": 4305905, "author": "Ian Campbell", "author_id": 524134, "author_profile": "https://Stackoverflow.com/users/524134", "pm_score": 3, "selected": false, "text": "this.myPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.myPictureBox_MouseMove);\n private void myPictureBox_MouseMove(object sender, MouseEventArgs e)\n{ \n if (e.Button == MouseButtons.Left)\n // Do what you want to do\n}\n" }, { "answer_id": 6060735, "author": "Bruno Ratnieks", "author_id": 761309, "author_profile": "https://Stackoverflow.com/users/761309", "pm_score": 0, "selected": false, "text": " private void imgMoveWindow_MouseMove(object sender, MouseEventArgs e)\n {\n if (e.Button == MouseButtons.Left)\n {\n Form1.ActiveForm.Left = Control.MousePosition.X - imgMoveWindow.Left - (imgMoveWindow.Size.Width/2);\n Form1.ActiveForm.Top = Control.MousePosition.Y - imgMoveWindow.Top - (imgMoveWindow.Size.Height/2); \n }\n\n }\n" }, { "answer_id": 65057624, "author": "Jamisco", "author_id": 7082154, "author_profile": "https://Stackoverflow.com/users/7082154", "pm_score": 1, "selected": false, "text": " private void MyButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // code here\n }\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ]
169,596
<p><strong>EDIT:</strong> <em>I'm still waiting for more answers. Thanks!</em></p> <p>In SQL 2000 days, I used to use temp table method where you create a temp table with new identity column and primary key then select where identity column between A and B.</p> <p>When <strong>SQL 2005</strong> came along I found out about <code>Row_Number()</code> and I've been using it ever since...</p> <p>But now, I found a serious performance issue with <code>Row_Number()</code>. It performs very well when you are working with not-so-gigantic result sets and sorting over an identity column. However, <strong>it performs very poorly</strong> when you are working with <strong>large result sets</strong> like over 10,000 records and <strong>sorting it over non-identity column</strong>. <code>Row_Number()</code> performs poorly even if you sort by an identity column if the result set is over 250,000 records. For me, it came to a point where it throws an error, "<strong>command timeout!</strong>"</p> <p><strong>What do you use to do paginate a large result set on SQL 2005?</strong> Is temp table method still better in this case? I'm not sure if this method <a href="https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml" rel="noreferrer">using temp table with SET ROWCOUNT</a> will perform better... But some say there is an issue of giving wrong row number if you have multi-column primary key.</p> <p>In my case, I need to be able to sort the result set by a date type column... for my production web app.</p> <p>Let me know what you use for <strong>high-performing pagination in SQL 2005</strong>. And I'd also like to know a smart way of creating indexes. <strong>I'm suspecting choosing right primary keys and/or indexes (clustered/non-clustered) will play a big role here.</strong></p> <p>Thanks in advance.</p> <p>P.S. <strong>Does anyone know what stackoverflow uses?</strong></p> <p><strong>EDIT:</strong> Mine looks something like...</p> <pre><code>SELECT postID, postTitle, postDate FROM (SELECT postID, postTitle, postDate, ROW_NUMBER() OVER(ORDER BY postDate DESC, postID DESC) as RowNum FROM MyTable ) as DerivedMyTable WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1 </code></pre> <p>postID: Int, Identity (auto-increment), Primary key</p> <p>postDate: DateTime</p> <p><strong>EDIT:</strong> Is everyone using Row_Number()?</p>
[ { "answer_id": 169655, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "SELECT column_list\nFROM\n (SELECT column_list\n ROW_NUMBER() OVER(ORDER BY OrderByColumnName) as RowNum\n FROM MyTable m\n ) as DerivedTableName\nWHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5704/" ]
169,610
<p>I'm writing a function that gets the path environment variable of a system, splits up each path, then concats on some other extra characters onto the end of each path.</p> <p>Everything works fine until I use the <code>strcat()</code> function (see code below).</p> <pre><code>char* prependPath( char* exeName ) { char* path = getenv("PATH"); char* pathDeepCopy = (char *)malloc(strlen(path) + 1); char* token[80]; int j, i=0; // used to iterate through array strcpy(pathDeepCopy, path); //parse and split token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0 //place in array while(token[i]!= NULL) { //ensure a pointer was found i++; token[i] = strtok(NULL, ":"); //continue to tokenize the string } for(j = 0; j &lt;= i-1; j++) { strcat(token[j], "/"); //strcat(token[j], exeName); printf("%s\n", token[j]); //print out all of the tokens } } </code></pre> <p>My shell output is like this (I'm concatenating "/which" onto everything):</p> <pre><code>... /usr/local/applic/Maple/bin/which which/which /usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which which/which Bus error (core dumped) </code></pre> <p>I'm wondering why <code>strcat</code> is displaying a new line and then repeating <code>which/which</code>. I'm also wondering about the <code>Bus error (core dumped)</code> at the end.</p> <p>Has anyone seen this before when using <code>strcat()</code>? And if so, anyone know how to fix it?</p> <p>Thanks</p>
[ { "answer_id": 169615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "strtok" }, { "answer_id": 169629, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "char* prependPath( char* exeName )\n{\n char* path = getenv(\"PATH\");\n char* pathDeepCopy = strdup(path);\n char* token[80];\n int j, i; // used to iterate through array\n\n token[0] = strtok(pathDeepCopy, \":\");\n for(i = 0;(token[i] != NULL) && (i < 80);++i)\n {\n token[i] = strtok(NULL, \":\");\n }\n\n for(j = 0; j <= i; ++j)\n {\n char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1);\n strcpy(tmp,token[j]);\n strcat(tmp,\"/\");\n strcat(tmp,exeName);\n printf(\"%s\\n\",tmp); //print out all of the tokens\n free(tmp);\n }\n free(pathDeepCopy);\n}\n" }, { "answer_id": 169640, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": " //parse and split\n token[0] = strtok(pathDeepCopy, \":\");//get pointer to first token found and store in 0\n //place in array\n while(token[i]!= NULL) { //ensure a pointer was found\n i++;\n token[i] = strtok(NULL, \":\"); //continue to tokenize the string\n }\n\n// use new array for storing the new tokens \n// pardon my C lang skills. IT's been a \"while\" since I wrote device drivers in C.\nconst int I = i;\nconst int MAX_SIZE = MAX_PATH;\nchar ** newTokens = new char [MAX_PATH][I];\nfor (int k = 0; k < i; ++k) {\n sprintf(newTokens[k], \"%s%c\", token[j], '/');\n printf(\"%s\\n\", newtoken[j]); //print out all of the tokens\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,624
<p>I was looking into sorting tables by a column designated given some input, and from what I've found, there is no easy way to do this. The best I've found is a switch statement: </p> <pre><code>SELECT Column1, Column2, Column3, Column4 FROM Table ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1 WHEN @OrderBY = 'Column2' THEN Column2 WHEN @OrderBY = 'Column3' THEN Column3 WHEN @OrderBY = 'Column4' THEN Column4 </code></pre> <p>Is it possible to do this without having a <code>CASE</code> statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy.</p> <p>The only way I've been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain.</p>
[ { "answer_id": 169632, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 1, "selected": false, "text": "Select\n *\nFrom\n myTableFUnction()\nOrder by\n 1, 2, 3, 6 <-- defined by application code in the SQL for the query\n" }, { "answer_id": 169636, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": true, "text": "sp_executesql" }, { "answer_id": 169918, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 1, "selected": false, "text": "DECLARE @column varchar(10)\n\nSET @column = 'D'\n\nSELECT *\nFROM Collection.Account AS A\nORDER BY \n CASE \n WHEN @column = 'A' THEN (RANK() OVER(ORDER BY A.Code ASC))\n WHEN @column = 'D' THEN (RANK() OVER(ORDER BY A.Code DESC))\n END\n" }, { "answer_id": 3116332, "author": "Harun", "author_id": 376013, "author_profile": "https://Stackoverflow.com/users/376013", "pm_score": 1, "selected": false, "text": "SELECT Column1, Column2, Column3 \nFROM SOME_TABLE\nORDER BY 1,2,3\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
169,625
<p>I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.</p>
[ { "answer_id": 169631, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 6, "selected": false, "text": "#fragments ?querystrings localhost" }, { "answer_id": 169634, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "^((http(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.(jpg|png|gif))\n" }, { "answer_id": 169635, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "(?i)\\.(jpg|png|gif)$\n" }, { "answer_id": 1443294, "author": "FDisk", "author_id": 175404, "author_profile": "https://Stackoverflow.com/users/175404", "pm_score": 4, "selected": false, "text": "(http(s?):)|([/|.|\\w|\\s])*\\.(?:jpg|gif|png)\n background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto;\n<div id=\"divbg\" style=\"background-color:#ff0000\"><img id=\"bg\" src=\"../res/img/temp/634043/original/cc3d8715eed0c.jpg\" width=\"100%\" height=\"100%\" /></div>\nbackground-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png);\nbackground: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3 _d8715eed0c.jpg) repeat fixed left top; cursor: auto;\nbackground: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto;\n" }, { "answer_id": 31155189, "author": "shyammakwana.me", "author_id": 2219158, "author_profile": "https://Stackoverflow.com/users/2219158", "pm_score": 0, "selected": false, "text": "^https?://(?:[a-z0-9\\-]+\\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif|png)$\n" }, { "answer_id": 44216396, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 2, "selected": false, "text": "(http(s?):)([/|.|\\w|\\s|-])*\\.(?:jpg|gif|png) https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg\nhttp://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg\nhttps://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg\nhttps://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg\nhttps://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif\nhttp://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif\nhttps://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif\nhttps://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif\nhttps://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png\nhttp://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png\nhttps://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png\nhttps://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png\n" }, { "answer_id": 51493215, "author": "Tushar Walzade", "author_id": 5729813, "author_profile": "https://Stackoverflow.com/users/5729813", "pm_score": 0, "selected": false, "text": "^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$\n https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png\nhttp://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg\nexample.com/de_home_teaser-box_puzzle_in_the_sun.png\nwww.example.com/de_home_teaser-box_puzzle_in_the_sun.png\nhttps://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg\nhttp://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg\nhttps://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg\n https://www.example.com\nhttp://www.example.com\nwww.example.com\nexample.com\nhttp://blog.example.com\nhttp://www.example.com/product\nhttp://www.example.com/products?id=1&page=2\nhttp://www.example.com#up\nhttp://255.255.255.255\n255.255.255.255\nhttp://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2\nhttp://www.siteabcd.com:8008\n" }, { "answer_id": 55179161, "author": "kevthanewversi", "author_id": 3469960, "author_profile": "https://Stackoverflow.com/users/3469960", "pm_score": 0, "selected": false, "text": "import (\n \"encoding/base64\"\n \"fmt\"\n \"image\"\n \"log\"\n \"strings\"\n \"net/http\"\n\n // Package image/jpeg is not used explicitly in the code below,\n // but is imported for its initialization side-effect, which allows\n // image.Decode to understand JPEG formatted images. Uncomment these\n // two lines to also understand GIF and PNG images:\n // _ \"image/gif\"\n // _ \"image/png\"\n _ \"image/jpeg\"\n )\n\nfunc main() {\n resp, err := http.Get(\"http://i.imgur.com/Peq1U1u.jpg\")\n if err != nil {\n log.Fatal(err)\n }\n defer resp.Body.Close()\n data, _, err := image.Decode(resp.Body)\n if err != nil {\n log.Fatal(err)\n }\n reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))\n config, format, err := image.DecodeConfig(reader)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(\"Width:\", config.Width, \"Height:\", config.Height, \"Format:\", format)\n}\n" }, { "answer_id": 69288289, "author": "Quico Llinares Llorens", "author_id": 5393734, "author_profile": "https://Stackoverflow.com/users/5393734", "pm_score": 0, "selected": false, "text": "public class IsImageUriValid\n{\n private readonly string[] _supportedImageFormats =\n {\n \".jpg\",\n \".gif\",\n \".png\"\n };\n\n public bool IsValid(string uri)\n {\n var isUriWellFormed = Uri.IsWellFormedUriString(uri, UriKind.Absolute);\n\n return isUriWellFormed && IsSupportedFormat(uri);\n }\n\n private bool IsSupportedFormat(string uri) => _supportedImageFormats.Any(supportedImageExtension => uri.EndsWith(supportedImageExtension));\n}\n" }, { "answer_id": 69288448, "author": "momoSakhoMano", "author_id": 9537088, "author_profile": "https://Stackoverflow.com/users/9537088", "pm_score": 0, "selected": false, "text": " const url = \"https://www.laoz.com/image.png\";\n const acceptedImage = [\".png\", \".jpg\", \".gif\"];\n const extension = url.substring(url.lastIndexOf(\".\"));\n const isValidImage = acceptedImage.find((m) => m === extension) != null;\n console.log(\"isValidImage\", isValidImage);\n console.log(\"extension\", extension);\n\n" }, { "answer_id": 71661951, "author": "Sasikumar", "author_id": 2845594, "author_profile": "https://Stackoverflow.com/users/2845594", "pm_score": 0, "selected": false, "text": "[^\\\\s]+(.*?)\\\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
169,637
<p>When I retrieve a record using LINQ that has a DateTime field only the ToString() is available. </p> <p>Where are all the other DateTime methods? </p> <p>I have to Convert.ToDateTime the DateTime? that the Field returns?</p> <p>What is the difference between (DateTime) and (DateTime?)</p>
[ { "answer_id": 169644, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 0, "selected": false, "text": "new DateTime()" }, { "answer_id": 169651, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "DateTime? Nullable<DateTime> DateTime DateTime?. Value" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6161/" ]
169,662
<p>Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example:</p> <pre><code>public abstract class A {} public final class B extends A {} public final class C extends A {} public final class D extends A {} </code></pre> <p>Can I somehow enforce that no other subclasses of A can ever be created?</p>
[ { "answer_id": 169671, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "A" }, { "answer_id": 169675, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 2, "selected": false, "text": "enum A {\n\n B,\n C,\n D;\n\n public int someField;\n\n public void someMethod() {\n }\n\n\n}\n" }, { "answer_id": 56738000, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 1, "selected": true, "text": "public abstract class A {\n public abstract <R> R fold(R b, R c, R d);\n}\n public final class B extends A {\n public <R> R fold(R b, R c, R d) {\n return b;\n }\n}\n\npublic final class C extends A {\n public <R> R fold(R b, R c, R d) {\n return c;\n }\n}\n\npublic final class D extends A {\n public <R> R fold(R b, R c, R d) {\n return d;\n }\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434/" ]
169,695
<p>What is the best way to persist/save printer settings in .Net? There used to be a bug in .Net 1.1 in the serialization of the <code>PrinterSetting</code> object and there were some <a href="http://www.codeproject.com/KB/cs/printersettings.aspx" rel="nofollow noreferrer">workarounds</a> but I'm wondering if there isn't a better or easier way of doing this in the more recent versions of the framework.</p> <p>The main use case is to allow a user to define, using the standard printer setting user interfaces, all print details (including printer-specific options) for a given printer and have these saved so they get restored the next time the user prints to that printer.</p>
[ { "answer_id": 170030, "author": "Dmitry Shechtman", "author_id": 3583, "author_profile": "https://Stackoverflow.com/users/3583", "pm_score": 1, "selected": false, "text": "PrinterSettings" }, { "answer_id": 33784768, "author": "Marco Guignard", "author_id": 2087090, "author_profile": "https://Stackoverflow.com/users/2087090", "pm_score": 0, "selected": false, "text": "Me.ReportViewer.PrinterSettings.PrintFileName = \"abc\"\nMy.Settings.PrinterSettings = Me.ReportViewer.PrinterSettings\nMy.Settings.Save()\n If My.Settings.PrinterSettings IsNot Nothing Then Me.ReportViewer.PrinterSettings = My.Settings.PrinterSettings\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3811/" ]
169,713
<p>What made it hard to find? How did you track it down?</p> <p>Not close enough to close but see also<br> <a href="https://stackoverflow.com/questions/175854/what-is-the-funniest-bug-youve-ever-experienced">https://stackoverflow.com/questions/175854/what-is-the-funniest-bug-youve-ever-experienced</a></p>
[ { "answer_id": 169725, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "XMLEncoder XMLEncoder" }, { "answer_id": 171872, "author": "Tal", "author_id": 11287, "author_profile": "https://Stackoverflow.com/users/11287", "pm_score": 2, "selected": false, "text": "n = strlen(p->s) - 1;\nif (p->s[n] == '\\n')\n p->s[n] = '\\0'; \n" }, { "answer_id": 176657, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "if (socket = accept() == 0)\n return false;\n\n//code using the socket()\n socket send() send(socket, \"mystring\", 7);\n stdout printf()" }, { "answer_id": 179825, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 4, "selected": false, "text": "(product-id, quantity, price) \"<\" \"insert into ... values (\" \">\" \");\" \"insert ...; insert ...;\" insert" }, { "answer_id": 235280, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 4, "selected": false, "text": "AddRef() Release() AddRef Release" }, { "answer_id": 823891, "author": "Chris Walton", "author_id": 93236, "author_profile": "https://Stackoverflow.com/users/93236", "pm_score": 2, "selected": false, "text": "enum {\n EDITION_A = 0,\n EDITION_B,\n //EDITION_DEMO,\n EDITION_MAX,\n\n EDITION_DEMO,\n};\n EDITION_DEMO EDITION_MAX EDITION_DEMO EDITION_REAL_MAX" }, { "answer_id": 1040929, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 1, "selected": false, "text": "this" }, { "answer_id": 1041017, "author": "Bastien Léonard", "author_id": 88851, "author_profile": "https://Stackoverflow.com/users/88851", "pm_score": 1, "selected": false, "text": "while True:\n with some_mutex:\n ...\n clock.tick(60)\n clock.tick(60) while True:\n with some_mutex:\n ...\n\n clock.tick(60)\n" }, { "answer_id": 1041442, "author": "user47559", "author_id": 47559, "author_profile": "https://Stackoverflow.com/users/47559", "pm_score": 1, "selected": false, "text": " for (i = 0; i < NUM_ELEMS; i++) {\n array[i] = &head[i*sizeof(foo)];\n }\n" }, { "answer_id": 1150888, "author": "JBrooks", "author_id": 136059, "author_profile": "https://Stackoverflow.com/users/136059", "pm_score": 0, "selected": false, "text": " --get all permissions for the specified user\n select permissionLocationId,\n permissionId,\n siteNodeHierarchyPermissionId,\n contactDescr as contactName,\n l.locationId, description, siteNodeId, roleId\n into #tmpPLoc\n from vw_PermissionLocationUsers vplu\n inner join vw_ContactAllTypes vcat on vplu.contactId = vcat.contactId\n inner join Location l on vplu.locationId = l.locationId\n where isSelected = 1 and\n contactStatusId = 1 and\n vplu.contactId = @contactId\n" }, { "answer_id": 1990981, "author": "Nick Manley", "author_id": 242213, "author_profile": "https://Stackoverflow.com/users/242213", "pm_score": 1, "selected": false, "text": "myString = myString.substr(0,pos);\n myString.substr(0,pos).swap(myString);\n" }, { "answer_id": 1990998, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 0, "selected": false, "text": "private void foo(Bar bar) {\n bar = new Bar();\n bar.setXXX(yyy);\n}\n bar foo" }, { "answer_id": 3035036, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 1, "selected": false, "text": "int value = obj.CalculateSomething();\n int value;\nvalue = obj.CalculateSomething();\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10960/" ]
169,721
<p>I keep hearing that Flex is open source and I figured that a great way to learn about the inner workings would be to look at it. I can easily find the Flex SDK (<a href="http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code" rel="noreferrer">http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code</a>), but I'm wanting to look at the class definitions for the MXML core library (like NumericStepper). Have I misunderstood, or is this kind of thing available somewhere?</p> <p>Note, I'm looking for the source of some core MXML components so I can see how they work internally, not for the compiler's source. Does what I've linked above have what I'm looking for and I just can't find it in the director structure?</p>
[ { "answer_id": 169724, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "http://opensource.adobe.com/wiki/display/flexsdk/Downloads\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9619/" ]
169,731
<p>In Javascript, I have an object:</p> <pre><code>obj = { one: "foo", two: "bar" }; </code></pre> <p>Now, I want do do this</p> <pre><code>var a = 'two'; if(confirm('Do you want One')) { a = 'one'; } alert(obj.a); </code></pre> <p>But of course it doesn't work. What would be the correct way of referencing this object dynamically?</p>
[ { "answer_id": 169737, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "obj[a]\n" }, { "answer_id": 169740, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 5, "selected": true, "text": "obj[a] obj.field obj[\"field\"]" }, { "answer_id": 170528, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "var myGlobal = 'hello';\nvar a = 'myGlobal';\nalert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal);\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
169,759
<p>What's the best .NET communication component or protocol for very low bandwidth and intermittently connected communication (i.e.: &lt; 10 kilobits/sec)?</p>
[ { "answer_id": 169763, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "System.Net.Sockets. Socket TcpClient UdpClient" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25010/" ]
169,784
<p>I am totally new to <code>SQL</code>. I have a simple select query similar to this:</p> <pre><code>SELECT COUNT(col1) FROM table1 </code></pre> <p>There are some 120 records in the table and shown on the <code>GUI</code>. For some reason, this query always returns a number which is less than the actual count.</p> <p>Can somebody please help me?</p>
[ { "answer_id": 169785, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": false, "text": "select count(*) from table1\n count(*) count(isnull(col1,0)) isnull" }, { "answer_id": 169786, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": true, "text": "SELECT COUNT(ISNULL(col1,0)) FROM table1\n" }, { "answer_id": 176035, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 1, "selected": false, "text": "SELECT count(distinct cola) from table1\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25065/" ]
169,799
<p>I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.</p> <p>When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. </p> <p>I've been trying to use <code>JPanels</code> like usercontrols in C#. I created a <code>JPanel</code> form called <code>BlurbEditor</code>. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event. </p> <p>Here is the code that I thought would work:</p> <pre><code>mainPanel.add(new BlurbEditor()); mainPanel.revalidate(); //I've also tried all possible combinations of these too //mainPanel.repaint(); //mainPanel.validate(); </code></pre> <p>This unfortunately is not working. What am I doing wrong?</p>
[ { "answer_id": 169805, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": -1, "selected": false, "text": "mainPanel.invalidate() mainPanel.validate()" }, { "answer_id": 169857, "author": "BFreeman", "author_id": 21811, "author_profile": "https://Stackoverflow.com/users/21811", "pm_score": 5, "selected": true, "text": "mainPanel.setLayout(new java.awt.BorderLayout());\n" }, { "answer_id": 170029, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 0, "selected": false, "text": "// Do long running calculations and other stuff outside the event dispatch thread\nwhile (! finished )\n calculate();\nSwingUtilities.invokeLater(new Runnable(){\n public void run() {\n // update gui here\n }\n}\n" }, { "answer_id": 170134, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 3, "selected": false, "text": "Swing/AWT UI BorderLayout FlowLayout textarea GridBagLayout HTML" }, { "answer_id": 19604428, "author": "Dimitris", "author_id": 872536, "author_profile": "https://Stackoverflow.com/users/872536", "pm_score": 1, "selected": false, "text": "parentPanel.remove(childPanel); \neditParentLayout();\nparentPanel.revalidate();\nparentPanel.repaint();\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21811/" ]
169,815
<p>In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't.</p> <p>I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for.</p> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/questions/166653/perl-common-gotchas">Perl - Common gotchas</a></li> <li><a href="https://stackoverflow.com/questions/66117/aspnet-common-gotchas">.NET - Common gotchas</a></li> </ul>
[ { "answer_id": 169824, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 1, "selected": false, "text": "Long long public void foo(Object obj) {\n if (grass.isGreen()) {\n Long id = grass.getId();\n foo(id);\n }\n}\nprivate void foo(long id) {\n Lawn lawn = bar.getLawn(id);\n if (lawn == null) {\n throw new IllegalStateException(\"grass should be associated with a lawn\");\n } \n}\n" }, { "answer_id": 169853, "author": "David", "author_id": 24731, "author_profile": "https://Stackoverflow.com/users/24731", "pm_score": 5, "selected": false, "text": "== .equals() \"foo\" == \"foo\" new String(\"foo\") != new String(\"foo\")" }, { "answer_id": 170049, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 5, "selected": false, "text": "String.substring char[] offset length XML String Reader substring char[]" }, { "answer_id": 170054, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 1, "selected": false, "text": "JTable" }, { "answer_id": 170127, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 2, "selected": false, "text": "public static void main(String[] args) {\n System.out.println(new Object().hashCode());\n}\n" }, { "answer_id": 170173, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 2, "selected": false, "text": "Long msec = getSleepMsec();\nThread.sleep(msec);\n" }, { "answer_id": 170338, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "List<Integer> list = new java.util.ArrayList<Integer>();\nlist.add(1);\nlist.remove(1); // throws...\n" }, { "answer_id": 171073, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "if (a = b) if (a == true) if (a) if (a = true) true a if (str == \"foo\") == == final String F = \"Foo\";\nString a = F;\nString b = F;\nassert a == b; // Works! They refer to the same object\nString c = \"F\" + F.substring(1); // Still \"Foo\"\nassert c.equals(a); // Works\nassert c == a; // Fails\n if (a == b & c == d) if (r != null & r.isSomething()) a && b a & b" }, { "answer_id": 171108, "author": "MBCook", "author_id": 18189, "author_profile": "https://Stackoverflow.com/users/18189", "pm_score": 5, "selected": false, "text": "int x = 5;\nint y = 5;\nInteger z = new Integer(5);\nInteger t = new Integer(5);\n\nSystem.out.println(5 == x); // Prints true\nSystem.out.println(x == y); // Prints true\nSystem.out.println(x == z); // Prints true (auto-boxing can be so nice)\nSystem.out.println(5 == z); // Prints true\nSystem.out.println(z == t); // Prints SOMETHING\n System.out.println(z.equals(t)); // Prints true\n List<Integer> stuff = new ArrayList<Integer>();\n\nstuff.add(5);\n" }, { "answer_id": 171885, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 3, "selected": false, "text": "1/2 == 0 not 0.5\n" }, { "answer_id": 171893, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 4, "selected": false, "text": "floata == floatb\n Math.abs(floata - floatb) < 0.001\n" }, { "answer_id": 171949, "author": "riadd", "author_id": 23227, "author_profile": "https://Stackoverflow.com/users/23227", "pm_score": 3, "selected": false, "text": "String text = \"foobar\";\ntext.replace(\"foo\", \"super\");\nSystem.out.print(text); // still prints \"foobar\" instead of \"superbar\"\n" }, { "answer_id": 215354, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "double[] aList = new double[400];\n\nList l = Arrays.asList(aList);\n//do intense stuff with l\n Arrays.asList() asList() Arrays.asList(1, 9, 4, 4, 20);\n List double[]" }, { "answer_id": 1400149, "author": "butterchicken", "author_id": 78677, "author_profile": "https://Stackoverflow.com/users/78677", "pm_score": 5, "selected": false, "text": "\"a,b,c,d,,,\".split(\",\").length\n split \",,,a,b,c,d\".split(\",\").length\n \"a,b,c,d,,,\".split(\",\",-1).length\n" }, { "answer_id": 1400192, "author": "mkoryak", "author_id": 26188, "author_profile": "https://Stackoverflow.com/users/26188", "pm_score": 3, "selected": false, "text": " List list = new ArrayList();\n Iterator it = list.iterator();\n while(it.hasNext()){\n //some code that does some stuff\n list.remove(0); //BOOM!\n }\n" }, { "answer_id": 1400240, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "% public static void main(String[] args)\n{\n String a = null;\n int n = \"number\".hashCode();\n\n switch( n % 2 ) {\n case 0:\n a = \"even\";\n break;\n case 1:\n a = \"odd\";\n break;\n }\n\n System.out.println( a );\n}\n n % 2 a null %" }, { "answer_id": 2530345, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 2, "selected": false, "text": "duplicate slice ByteBuffer order ByteBuffer buffer1 = ByteBuffer.allocate(8);\nbuffer1.order(ByteOrder.LITTLE_ENDIAN);\nbuffer1.putInt(2, 1234);\n\nByteBuffer buffer2 = buffer1.duplicate();\nSystem.out.println(buffer2.getInt(2));\n// Output is \"-771489792\", not \"1234\" as expected\n" }, { "answer_id": 4724126, "author": "zawhtut", "author_id": 379779, "author_profile": "https://Stackoverflow.com/users/379779", "pm_score": 1, "selected": false, "text": " System.out.println(Calendar.getInstance(TimeZone.getTimeZone(\"Asia/Hong_Kong\")).getTime());\n System.out.println(Calendar.getInstance(TimeZone.getTimeZone(\"America/Jamaica\")).getTime());\n" }, { "answer_id": 5856052, "author": "Michael Borgwardt", "author_id": 16883, "author_profile": "https://Stackoverflow.com/users/16883", "pm_score": 3, "selected": false, "text": "? List<?> List List<Object> add() List<?> List Object" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205/" ]
169,817
<p>I'm thinking the answer is no, but I'd love it it anybody had any insight into how to crawl a tree structure to any depth in SQL (MySQL), but with a single query</p> <p>More specifically, given a tree structured table (id, data, data, parent_id), and one row in the table, is it possible to get <em>all</em> descendants (child/grandchild/etc), or for that matter all ancestors (parent/grandparent/etc) without knowing how far down or up it will go, using a single query?</p> <p>Or is using some kind of recursion require, where I keep querying deeper until there are no new results?</p> <p>Specifically, I'm using Ruby and Rails, but I'm guessing that's not very relevant.</p>
[ { "answer_id": 169834, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": -1, "selected": false, "text": "getChildren(parent){\n children = query(SELECT * FROM table WHERE parent_id = parent.id)\n return children\n}\n\nprintTree(root){\n print root\n children = getChildren(root)\n for child in children {\n printTree(child)\n }\n}\n" }, { "answer_id": 169876, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 2, "selected": false, "text": "SELECT FROM table WHERE ancestors LIKE \"%6,2,1\"\n" }, { "answer_id": 9568897, "author": "Kray", "author_id": 1250119, "author_profile": "https://Stackoverflow.com/users/1250119", "pm_score": 2, "selected": false, "text": "SELECT FROM table WHERE ancestors LIKE \"1,2,6%\"\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14873/" ]
169,818
<h2>What should happen when I call <code>$user-&gt;get_email_address()</code>?</h2> <h3>Option 1: Pull the email address from the database on demand</h3> <pre><code>public function get_email_address() { if (!$this-&gt;email_address) { $this-&gt;read_from_database('email_address'); } return $this-&gt;email_address; } </code></pre> <h3>Option 2: Pull the email address (and the other User attributes) from the database on object creation</h3> <pre><code>public function __construct(..., $id = 0) { if ($id) { $this-&gt;load_all_data_from_db($id); } } public function get_email_address() { return $this-&gt;email_address; } </code></pre> <p>My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database.</p> <p>Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand.</p> <p>A follow-up question: What do ORM abstraction frameworks like Activerecord do?</p>
[ { "answer_id": 169923, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 4, "selected": true, "text": "public function get_email_address() {\n if (!$this->email_address) {\n $this->load_all_data_from_db($this->id)\n }\n return $this->email_address;\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25068/" ]
169,828
<p>Interested if anyone has used VSTS Database Edition extensively and, if so, which features did you find the most useful over the standard Visual Studio database projects?</p> <p>What are the most compelling features as opposed to alternative schema management options or tools like RedGate's SqlCompare etc?</p> <p><strong>Edit</strong>: Microsoft just released the <b>RTM version of Database Edition (GDR)</b> which adds support for SQL Server 2008 - link is <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en" rel="nofollow noreferrer">here</a>. I've previously blogged (briefly) about it <a href="http://internationalized.spaces.live.com/blog/cns!43F3A7682D1564E4!1177.entry" rel="nofollow noreferrer">here.</a></p> <p>Has anyone had a chance to do any real work with the GDR? It looks like there are some real enhancements including refactoring support. I'd be really interested to hear if people are using it with SQL Server 2008...</p> <p>Download From: [<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en]" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&amp;displaylang=en]</a></p>
[ { "answer_id": 1847699, "author": "Andy", "author_id": 442820, "author_profile": "https://Stackoverflow.com/users/442820", "pm_score": 2, "selected": false, "text": "TaskName=\"DataGeneratorTask\"\nAssemblyName=\"Microsoft.Data.Schema.Tasks, Version=9.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" \n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18471/" ]
169,829
<p>INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values).<br> If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur. </p> <p>So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully. </p> <p>If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change? </p> <p>What is the contract for this event and what side effects would there be in subscribers?</p>
[ { "answer_id": 169849, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "PropertyChanging public T Foo\n { get\n { return m_Foo;\n }\n set\n { if (m_Foo == value) return; //no need for change (or notification)\n OnPropertyChanging(\"Foo\");\n m_Foo = value;\n OnPropertyChanged(\"Foo\");\n }\n }\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15572/" ]
169,833
<p>I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?</p>
[ { "answer_id": 169840, "author": "Giao", "author_id": 14099, "author_profile": "https://Stackoverflow.com/users/14099", "pm_score": -1, "selected": false, "text": "myWindow.document.writeln(documentString)\n" }, { "answer_id": 169843, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 3, "selected": false, "text": " function popUp(){\n\n var newWindow = window.open(\"\",\"Test\",\"width=300,height=300,scrollbars=1,resizable=1\")\n\n //read text from textbox placed in parent window\n var text = document.form.input.value\n\n var html = \"<html><head></head><body>Hello, <b>\"+ text +\"</b>.\"\n html += \"How are you today?</body></html>\"\n\n\n newWindow .document.open()\n newWindow .document.write(html)\n newWindow .document.close()\n\n } \n" }, { "answer_id": 169846, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": true, "text": "window.open() window var myWindow = window.open('...')\nmyWindow.document.getElementById('foo').style.backgroundColor = 'red'\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
169,866
<p>How to export pictures in Microsoft Word to TIFF file using Visual Studio Tools for Office? I can obtain a reference to the pictures as InlineShape object collection, the hard part now is how to save them as TIFF images.</p>
[ { "answer_id": 169893, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 3, "selected": true, "text": " private void SaveToImage(Word.InlineShape picShape, string filePath)\n {\n picShape.Select();\n theApp.Selection.CopyAsPicture();\n IDataObject data = Clipboard.GetDataObject();\n if (data.GetDataPresent(typeof(Bitmap)))\n {\n Bitmap image = (Bitmap)data.GetData(typeof(Bitmap));\n image.Save(filePath);\n }\n }\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
169,877
<p>Being new to test based development, this question has been bugging me. How much is too much? What should be tested, how should it be tested, and why should it be tested? The examples given are in C# with NUnit, but I assume the question itself is language agnostic.</p> <p>Here are two current examples of my own, tests on a generic list object (being tested with strings, the initialisation function adds three items <code>{"Foo", "Bar", "Baz"}</code>):</p> <pre><code>[Test] public void CountChanging() { Assert.That(_list.Count, Is.EqualTo(3)); _list.Add("Qux"); Assert.That(_list.Count, Is.EqualTo(4)); _list[7] = "Quuuux"; Assert.That(_list.Count, Is.EqualTo(8)); _list.Remove("Quuuux"); Assert.That(_list.Count, Is.EqualTo(7)); } [Test] public void ContainsItem() { Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); _list.Add("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(true)); _list.Remove("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); } </code></pre> <p>The code is fairly self-commenting, so I won't go into what's happening, but is this sort of thing taking it too far? <code>Add()</code> and <code>Remove()</code> are tested seperately of course, so what level should I go to with these sorts of tests? Should I even have these sorts of tests?</p>
[ { "answer_id": 169886, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "_list" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
169,889
<p>There's another post on SO relating to .NET -- not us. Pure PHP. Trying to find the best way/process to deploy stable version of our PHP app. I've seen an article on <a href="http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/" rel="nofollow noreferrer">Capistrano</a>, but am curious what else is out there. Aside from the obvious reasons, I'm also looking to add some scripting so that the <a href="https://stackoverflow.com/questions/111436/how-can-i-get-the-svn-revision-number-in-php">SVN rev number gets added in there as well</a>.</p> <p>Much thanks.</p>
[ { "answer_id": 169935, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 3, "selected": true, "text": "svn export scp ssh" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24708/" ]
169,894
<p>The <a href="http://flot.googlecode.com/svn/trunk/API.txt" rel="nofollow noreferrer">Flot API documentation</a> describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines without also removing the x-axis labels. I've tried changing the tickColor, ticks, and tickSize options with no success.</p> <p>I want to create beautiful, Tufte-compatible graphs such as these:</p> <p><a href="http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif" rel="nofollow noreferrer"><a href="http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif" rel="nofollow noreferrer">http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif</a></a> <a href="http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg" rel="nofollow noreferrer"><a href="http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg" rel="nofollow noreferrer">http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg</a></a></p> <p>I find the vertical ticks on my graphs to be chart junk. I am working with a time series that I am displaying as vertical bars so the vertical ticks often cut through the bars in a way that is visually noisy.</p>
[ { "answer_id": 4569708, "author": "Laurimann", "author_id": 328958, "author_profile": "https://Stackoverflow.com/users/328958", "pm_score": 3, "selected": false, "text": "var options = {\n grid: {show: true,\n color: \"rgb(48, 48, 48)\",\n tickColor: \"rgba(255, 255, 255, 0)\",\n backgroundColor: \"rgb(255, 255, 255)\"}\n };\n" }, { "answer_id": 4695438, "author": "Darren", "author_id": 401702, "author_profile": "https://Stackoverflow.com/users/401702", "pm_score": 7, "selected": true, "text": "xaxis: {\n tickLength: 0\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10419/" ]
169,897
<p>I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error. </p> <p>And I found the py2exe said:</p> <blockquote> <p>The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security']</p> </blockquote> <p>So how do I solve this problem?</p> <p>Thanks.</p>
[ { "answer_id": 169913, "author": "teratorn", "author_id": 14739, "author_profile": "https://Stackoverflow.com/users/14739", "pm_score": 5, "selected": true, "text": "python setup.py py2exe -p win32com -i twisted.web.resource\n" }, { "answer_id": 31598939, "author": "K246", "author_id": 3990239, "author_profile": "https://Stackoverflow.com/users/3990239", "pm_score": 0, "selected": false, "text": "setup(console = ['main.py'])\n setup(console = ['main.py'], \n options={\"py2exe\":{\"includes\":[\"email.mime.multipart\",\"email.mime.text\"]}})\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25077/" ]
169,902
<p>Given two image buffers (assume it's an array of ints of size width * height, with each element a color value), how can I map an area defined by a quadrilateral from one image buffer into the other (always square) image buffer? I'm led to understand this is called "projective transformation".</p> <p>I'm also looking for a general (not language- or library-specific) way of doing this, such that it could be reasonably applied in any language without relying on "magic function X that does all the work for me".</p> <p>An example: I've written a short program in Java using the Processing library (processing.org) that captures video from a camera. During an initial "calibrating" step, the captured video is output directly into a window. The user then clicks on four points to define an area of the video that will be transformed, then mapped into the square window during subsequent operation of the program. If the user were to click on the four points defining the corners of a door visible at an angle in the camera's output, then this transformation would cause the subsequent video to map the transformed image of the door to the entire area of the window, albeit somewhat distorted.</p>
[ { "answer_id": 170108, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "t a a t b b b t" }, { "answer_id": 170124, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 3, "selected": false, "text": "AD = sqrt((xA-xD)^2 + (yA-yD)^2)\nCD = sqrt((xC-xD)^2 + (yC-yD)^2)\nAC = sqrt((xA-xC)^2 + (yA-yC)^2)\nBD = sqrt((xB-xD)^2 + (yB-yD)^2)\nBC = sqrt((xB-xC)^2 + (yB-yC)^2)\n thetaD = arccos((AD^2 + CD^2 - AC^2) / (2*AD*CD))\nthetaC = arccos((BC^2 + CD^2 - BD^2) / (2*BC*CD))\n DP = sqrt((xP-xD)^2 + (yP-yD)^2)\n CP = sqrt((xP-xC)^2 + (yP-yC)^2)\n thetaP1 = arccos((DP^2 + CD^2 - CP^2) / (2*DP*CD))\n thetaP2 = arccos((CP^2 + CD^2 - DP^2) / (2*CP*CD))\n thetaQ1 = thetaP1 * 90 / thetaD\n thetaQ2 = thetaP2 * 90 / thetaC\n HQ = m * sin(thetaQ2) / sin(180-thetaQ1-thetaQ2)\n x = HQ * cos(thetaQ1)\ny = HQ * sin(thetaQ1)\n" }, { "answer_id": 2551747, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 3, "selected": false, "text": " [x ]\n[a b c d]*[y ] = [x']\n[e f g h] [x*y] [y']\n [1 ]\n a*x_0 + b*y_0 + c*x_0*y_0 + d = i_0\na*x_1 + b*y_1 + c*x_1*y_1 + d = i_1\na*x_2 + b*y_2 + c*x_2*y_2 + d = i_2\na*x_3 + b*y_3 + c*x_3*y_3 + d = i_3\n\ne*x_0 + f*y_0 + g*x_0*y_0 + h = j_0\ne*x_1 + f*y_1 + g*x_1*y_1 + h = j_1\ne*x_2 + f*y_2 + g*x_2*y_2 + h = j_2\ne*x_3 + f*y_3 + g*x_3*y_3 + h = j_3\n [x_0 y_0 x_0*y_0 1] [a e] [i_0 j_0]\n[x_1 y_1 x_1*y_1 1] * [b f] = [i_1 j_1]\n[x_2 y_2 x_2*y_2 1] [c g] [i_2 j_2]\n[x_3 y_3 x_3*y_3 1] [d h] [i_3 j_3]\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173449/" ]
169,904
<p>I'm using HttpListener to allow a user to set up a proxy on a user-defined port. When I start the HttpListener, I get an exception if the application isn't running under administrator privileges in Vista.</p> <p>From what I've read, <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=93940" rel="noreferrer">this is expected behavior</a> - administrator privileges are required to start listening on a port. But I'm sure there are ways around this, as I run plenty of programs (like Skype) which listen on a port without requiring elevation to administrator.</p> <p>Is there a way to do this with HttpListener? If not, can I make other API calls in .NET code to set up the port?</p>
[ { "answer_id": 195256, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 6, "selected": false, "text": "netsh http show urlacl\n netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\\User listen=yes\n" }, { "answer_id": 6663823, "author": "rob", "author_id": 840650, "author_profile": "https://Stackoverflow.com/users/840650", "pm_score": 3, "selected": false, "text": " [...]\n Reservierte URL : http://+:80/Temporary_Listen_Addresses/\n Benutzer: \\Jeder\n Abhören: Yes\n Delegieren: No\n SDDL: D:(A;;GX;;;WD)\n [...]\n [...]\n HttpListener l = new HttpListener();\n string prefix = \"http://+:80/Temporary_Listen_Addresses/\";\n l.Prefixes.Add(prefix);\n l.Start(); // does not throw any \"Permission Denied/Access Denied/Zugriff verweigert\"\n [...]\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
169,905
<p>I want to write a script which cleans the 'run' dialogue automatically every log off. Where is the history stored?</p>
[ { "answer_id": 169911, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 2, "selected": false, "text": "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
169,907
<p>I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from <a href="http://www.vbforums.com/showthread.php?t=379072" rel="noreferrer">dbb</a> and <a href="http://www.motobit.com/tips/detpg_Base64Encode/" rel="noreferrer">marxidad</a>)?</p>
[ { "answer_id": 169945, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": true, "text": "Function EncodeBase64(text As String) As String\n Dim arrData() As Byte\n arrData = StrConv(text, vbFromUnicode) \n\n Dim objXML As MSXML2.DOMDocument\n Dim objNode As MSXML2.IXMLDOMElement\n\n Set objXML = New MSXML2.DOMDocument \n Set objNode = objXML.createElement(\"b64\")\n\n objNode.dataType = \"bin.base64\"\n objNode.nodeTypedValue = arrData\n EncodeBase64 = Replace(objNode.Text, vbLf, \"\") \n\n Set objNode = Nothing\n Set objXML = Nothing\nEnd Function\n" }, { "answer_id": 170018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "Option Explicit\n\nPrivate Const clOneMask = 16515072 '000000 111111 111111 111111\nPrivate Const clTwoMask = 258048 '111111 000000 111111 111111\nPrivate Const clThreeMask = 4032 '111111 111111 000000 111111\nPrivate Const clFourMask = 63 '111111 111111 111111 000000\n\nPrivate Const clHighMask = 16711680 '11111111 00000000 00000000\nPrivate Const clMidMask = 65280 '00000000 11111111 00000000\nPrivate Const clLowMask = 255 '00000000 00000000 11111111\n\nPrivate Const cl2Exp18 = 262144 '2 to the 18th power\nPrivate Const cl2Exp12 = 4096 '2 to the 12th\nPrivate Const cl2Exp6 = 64 '2 to the 6th\nPrivate Const cl2Exp8 = 256 '2 to the 8th\nPrivate Const cl2Exp16 = 65536 '2 to the 16th\n\nPublic Function Encode64(sString As String) As String\n\n Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte\n Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long\n\n For lTemp = 0 To 63 'Fill the translation table.\n Select Case lTemp\n Case 0 To 25\n bTrans(lTemp) = 65 + lTemp 'A - Z\n Case 26 To 51\n bTrans(lTemp) = 71 + lTemp 'a - z\n Case 52 To 61\n bTrans(lTemp) = lTemp - 4 '1 - 0\n Case 62\n bTrans(lTemp) = 43 'Chr(43) = \"+\"\n Case 63\n bTrans(lTemp) = 47 'Chr(47) = \"/\"\n End Select\n Next lTemp\n\n For lTemp = 0 To 255 'Fill the 2^8 and 2^16 lookup tables.\n lPowers8(lTemp) = lTemp * cl2Exp8\n lPowers16(lTemp) = lTemp * cl2Exp16\n Next lTemp\n\n iPad = Len(sString) Mod 3 'See if the length is divisible by 3\n If iPad Then 'If not, figure out the end pad and resize the input.\n iPad = 3 - iPad\n sString = sString & String(iPad, Chr(0))\n End If\n\n bIn = StrConv(sString, vbFromUnicode) 'Load the input string.\n lLen = ((UBound(bIn) + 1) \\ 3) * 4 'Length of resulting string.\n lTemp = lLen \\ 72 'Added space for vbCrLfs.\n lOutSize = ((lTemp * 2) + lLen) - 1 'Calculate the size of the output buffer.\n ReDim bOut(lOutSize) 'Make the output buffer.\n\n lLen = 0 'Reusing this one, so reset it.\n\n For lChar = LBound(bIn) To UBound(bIn) Step 3\n lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2) 'Combine the 3 bytes\n lTemp = lTrip And clOneMask 'Mask for the first 6 bits\n bOut(lPos) = bTrans(lTemp \\ cl2Exp18) 'Shift it down to the low 6 bits and get the value\n lTemp = lTrip And clTwoMask 'Mask for the second set.\n bOut(lPos + 1) = bTrans(lTemp \\ cl2Exp12) 'Shift it down and translate.\n lTemp = lTrip And clThreeMask 'Mask for the third set.\n bOut(lPos + 2) = bTrans(lTemp \\ cl2Exp6) 'Shift it down and translate.\n bOut(lPos + 3) = bTrans(lTrip And clFourMask) 'Mask for the low set.\n If lLen = 68 Then 'Ready for a newline\n bOut(lPos + 4) = 13 'Chr(13) = vbCr\n bOut(lPos + 5) = 10 'Chr(10) = vbLf\n lLen = 0 'Reset the counter\n lPos = lPos + 6\n Else\n lLen = lLen + 4\n lPos = lPos + 4\n End If\n Next lChar\n\n If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.\n\n If iPad = 1 Then 'Add the padding chars if any.\n bOut(lOutSize) = 61 'Chr(61) = \"=\"\n ElseIf iPad = 2 Then\n bOut(lOutSize) = 61\n bOut(lOutSize - 1) = 61\n End If\n\n Encode64 = StrConv(bOut, vbUnicode) 'Convert back to a string and return it.\n\nEnd Function\n\nPublic Function Decode64(sString As String) As String\n\n Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long\n Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String\n Dim lTemp As Long\n\n sString = Replace(sString, vbCr, vbNullString) 'Get rid of the vbCrLfs. These could be in...\n sString = Replace(sString, vbLf, vbNullString) 'either order.\n\n lTemp = Len(sString) Mod 4 'Test for valid input.\n If lTemp Then\n Call Err.Raise(vbObjectError, \"MyDecode\", \"Input string is not valid Base64.\")\n End If\n\n If InStrRev(sString, \"==\") Then 'InStrRev is faster when you know it's at the end.\n iPad = 2 'Note: These translate to 0, so you can leave them...\n ElseIf InStrRev(sString, \"=\") Then 'in the string and just resize the output.\n iPad = 1\n End If\n\n For lTemp = 0 To 255 'Fill the translation table.\n Select Case lTemp\n Case 65 To 90\n bTrans(lTemp) = lTemp - 65 'A - Z\n Case 97 To 122\n bTrans(lTemp) = lTemp - 71 'a - z\n Case 48 To 57\n bTrans(lTemp) = lTemp + 4 '1 - 0\n Case 43\n bTrans(lTemp) = 62 'Chr(43) = \"+\"\n Case 47\n bTrans(lTemp) = 63 'Chr(47) = \"/\"\n End Select\n Next lTemp\n\n For lTemp = 0 To 63 'Fill the 2^6, 2^12, and 2^18 lookup tables.\n lPowers6(lTemp) = lTemp * cl2Exp6\n lPowers12(lTemp) = lTemp * cl2Exp12\n lPowers18(lTemp) = lTemp * cl2Exp18\n Next lTemp\n\n bIn = StrConv(sString, vbFromUnicode) 'Load the input byte array.\n ReDim bOut((((UBound(bIn) + 1) \\ 4) * 3) - 1) 'Prepare the output buffer.\n\n For lChar = 0 To UBound(bIn) Step 4\n lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _\n lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3)) 'Rebuild the bits.\n lTemp = lQuad And clHighMask 'Mask for the first byte\n bOut(lPos) = lTemp \\ cl2Exp16 'Shift it down\n lTemp = lQuad And clMidMask 'Mask for the second byte\n bOut(lPos + 1) = lTemp \\ cl2Exp8 'Shift it down\n bOut(lPos + 2) = lQuad And clLowMask 'Mask for the third byte\n lPos = lPos + 3\n Next lChar\n\n sOut = StrConv(bOut, vbUnicode) 'Convert back to a string.\n If iPad Then sOut = Left$(sOut, Len(sOut) - iPad) 'Chop off any extra bytes.\n Decode64 = sOut\n\nEnd Function\n" }, { "answer_id": 66055477, "author": "Steven", "author_id": 10231600, "author_profile": "https://Stackoverflow.com/users/10231600", "pm_score": 3, "selected": false, "text": "Function EncodeBase64(text As String) As String\n Dim arrData() As Byte\n arrData = StrConv(text, vbFromUnicode)\n\n Dim objXML As Variant\n Dim objNode As Variant\n\n Set objXML = CreateObject(\"MSXML2.DOMDocument\")\n Set objNode = objXML.createElement(\"b64\")\n\n objNode.dataType = \"bin.base64\"\n objNode.nodeTypedValue = arrData\n EncodeBase64 = Replace(objNode.Text, vbLf, \"\")\n\n Set objNode = Nothing\n Set objXML = Nothing\nEnd Function\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
169,925
<p>I want to convert a string into a double and after doing some math on it, convert it back to a string.</p> <p>How do I do this in Objective-C?</p> <p>Is there a way to round a double to the nearest integer too?</p>
[ { "answer_id": 169932, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 9, "selected": true, "text": "double myDouble = [myString doubleValue];\n int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))\n NSString* myNewString = [NSString stringWithFormat:@\"%d\", myInt];\n" }, { "answer_id": 169948, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 3, "selected": false, "text": " int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))\n" }, { "answer_id": 170725, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 5, "selected": false, "text": "NSNumber stringValue [[NSNumber numberWithInt:myInt] stringValue]\n stringValue NSNumber descriptionWithLocale:nil [NSString stringWithFormat:@\"%d\",myInt] myInt" }, { "answer_id": 170867, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 6, "selected": false, "text": "NSNumberFormatter COMMA PERIOD NSNumberFormatter -[NSFormatter numberFromString:] NSNumber -[NSFormatter getObjectValue:forString:range:error:]" }, { "answer_id": 176275, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 2, "selected": false, "text": "int roundedX = round(x);\n round" }, { "answer_id": 960368, "author": "Sam Soffes", "author_id": 118631, "author_profile": "https://Stackoverflow.com/users/118631", "pm_score": 1, "selected": false, "text": "float myFloat = 5.3;\nNSInteger myInt = (NSInteger)myFloat;\n" }, { "answer_id": 4018839, "author": "miker", "author_id": 486881, "author_profile": "https://Stackoverflow.com/users/486881", "pm_score": 3, "selected": false, "text": "NSString *tempStr = @\"8,765.4\"; \n // localization allows other thousands separators, also.\nNSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];\n[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?\n[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];\n // next line is very important!\n[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial\n\nNSNumber *tempNum = [myNumFormatter numberFromString:tempStr];\nNSLog(@\"string '%@' gives NSNumber '%@' with intValue '%i'\", \n tempStr, tempNum, [tempNum intValue]);\n[myNumFormatter release]; // good citizen\n" }, { "answer_id": 4443177, "author": "zoltan", "author_id": 458074, "author_profile": "https://Stackoverflow.com/users/458074", "pm_score": 1, "selected": false, "text": "NSString *str=@\"5678901234567890\";\n\nlong long verylong;\nNSRange range;\nrange.length = 15;\nrange.location = 0;\n\n[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];\n\nNSLog(@\"long long value %lld\",verylong);\n" }, { "answer_id": 11757431, "author": "Samir Jwarchan", "author_id": 578143, "author_profile": "https://Stackoverflow.com/users/578143", "pm_score": 2, "selected": false, "text": "// Converting String in to Double\n\ndouble doubleValue = [yourString doubleValue];\n\n// Converting Double in to String\nNSString *yourString = [NSString stringWithFormat:@\"%.20f\", doubleValue];\n// .20f takes the value up to 20 position after decimal\n\n// Converting double to int\n\nint intValue = (int) doubleValue;\nor\nint intValue = [yourString intValue];\n" }, { "answer_id": 13703696, "author": "Robert", "author_id": 296446, "author_profile": "https://Stackoverflow.com/users/296446", "pm_score": 2, "selected": false, "text": "int myInt = (int)round( [@\"1.6\" floatValue] );\n\nNSString* myString = [@(myInt) description];\n" }, { "answer_id": 14482966, "author": "dimanitm", "author_id": 1791090, "author_profile": "https://Stackoverflow.com/users/1791090", "pm_score": 1, "selected": false, "text": "#define STRING(value) [@(value) stringValue]\n" }, { "answer_id": 15051828, "author": "Ashish P", "author_id": 2072416, "author_profile": "https://Stackoverflow.com/users/2072416", "pm_score": 1, "selected": false, "text": "double mydouble=[_myTextfield.text doubleValue];\n mydouble=(round(mydouble));\n int myint=(int)(mydouble);\n myLabel.text=[NSString stringWithFormat:@\"%f\",mydouble];\n NSString *mystring=[NSString stringWithFormat:@\"%f\",mydouble];\n myLabel.text=[NSString stringWithFormat:@\"%d\",myint];\n NSString *mystring=[NSString stringWithFormat:@\"%f\",mydouble];\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
169,973
<p>When is it better to use a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1" rel="noreferrer">List</a> vs a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1" rel="noreferrer">LinkedList</a>?</p>
[ { "answer_id": 169983, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": false, "text": "List<T> LinkedList<T> List<T> LinkedList<T> List<T> List<T> Find ToArray LinkedList<T>" }, { "answer_id": 7777687, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 8, "selected": false, "text": "LinkedList<T> IList<T> LinkedList<T> List<T> LinkedList<T> LinkedList<T> List<T> List<T> LinkedList<T>.AddLast(item) List<T>.Add(item) LinkedList<T>.AddFirst(item) List<T>.Insert(0, item) LinkedList<T>.AddBefore(node, item) LinkedList<T>.AddAfter(node, item) List<T>.Insert(index, item) LinkedList<T>.Remove(item) LinkedList<T>.Remove(node) List<T>.Remove(item) List<T>.RemoveAt(index) LinkedList<T>.Count List<T>.Count LinkedList<T>.Contains(item) List<T>.Contains(item) LinkedList<T>.Clear() List<T>.Clear() LinkedList<T> List<T>" }, { "answer_id": 12466884, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 8, "selected": true, "text": "// Temporary class to show the example\nclass Temp\n{\n public decimal A, B, C, D;\n\n public Temp(decimal a, decimal b, decimal c, decimal d)\n {\n A = a; B = b; C = c; D = d;\n }\n}\n LinkedList<Temp> list = new LinkedList<Temp>();\n\n for (var i = 0; i < 12345678; i++)\n {\n var a = new Temp(i, i, i, i);\n list.AddLast(a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n List<Temp> list = new List<Temp>(); // 2.4 seconds\n\n for (var i = 0; i < 12345678; i++)\n {\n var a = new Temp(i, i, i, i);\n list.Add(a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n LinkedList<Temp> list = new LinkedList<Temp>();\n\n for (var i = 0; i < 123456; i++)\n {\n var a = new Temp(i, i, i, i);\n\n list.AddLast(a);\n var curNode = list.First;\n\n for (var k = 0; k < i/2; k++) // In order to insert a node at the middle of the list we need to find it\n curNode = curNode.Next;\n\n list.AddAfter(curNode, a); // Insert it after\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n List<Temp> list = new List<Temp>();\n\n for (var i = 0; i < 123456; i++)\n {\n var a = new Temp(i, i, i, i);\n\n list.Insert(i / 2, a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n list.AddLast(new Temp(1,1,1,1));\n var referenceNode = list.First;\n\n for (var i = 0; i < 123456; i++)\n {\n var a = new Temp(i, i, i, i);\n\n list.AddLast(a);\n list.AddBefore(referenceNode, a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n" }, { "answer_id": 13532728, "author": "Antony Thomas", "author_id": 984378, "author_profile": "https://Stackoverflow.com/users/984378", "pm_score": 0, "selected": false, "text": "LinkedList<> Token Stream List<>" }, { "answer_id": 24543197, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 1, "selected": false, "text": "static void Main()\n{\n LinkedListPerformance.AddFirst_List(); // 12028 ms\n LinkedListPerformance.AddFirst_LinkedList(); // 33 ms\n\n LinkedListPerformance.AddLast_List(); // 33 ms\n LinkedListPerformance.AddLast_LinkedList(); // 32 ms\n\n LinkedListPerformance.Enumerate_List(); // 1.08 ms\n LinkedListPerformance.Enumerate_LinkedList(); // 3.4 ms\n\n //I tried below as fun exercise - not very meaningful, see code\n //sort of equivalent to insertion when having the reference to middle node\n\n LinkedListPerformance.AddMiddle_List(); // 5724 ms\n LinkedListPerformance.AddMiddle_LinkedList1(); // 36 ms\n LinkedListPerformance.AddMiddle_LinkedList2(); // 32 ms\n LinkedListPerformance.AddMiddle_LinkedList3(); // 454 ms\n\n Environment.Exit(-1);\n}\n using System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace stackoverflow\n{\n static class LinkedListPerformance\n {\n class Temp\n {\n public decimal A, B, C, D;\n\n public Temp(decimal a, decimal b, decimal c, decimal d)\n {\n A = a; B = b; C = c; D = d;\n }\n }\n\n\n\n static readonly int start = 0;\n static readonly int end = 123456;\n static readonly IEnumerable<Temp> query = Enumerable.Range(start, end - start).Select(temp);\n\n static Temp temp(int i)\n {\n return new Temp(i, i, i, i);\n }\n\n static void StopAndPrint(this Stopwatch watch)\n {\n watch.Stop();\n Console.WriteLine(watch.Elapsed.TotalMilliseconds);\n }\n\n public static void AddFirst_List()\n {\n var list = new List<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i < end; i++)\n list.Insert(0, temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void AddFirst_LinkedList()\n {\n var list = new LinkedList<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (int i = start; i < end; i++)\n list.AddFirst(temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void AddLast_List()\n {\n var list = new List<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i < end; i++)\n list.Add(temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void AddLast_LinkedList()\n {\n var list = new LinkedList<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (int i = start; i < end; i++)\n list.AddLast(temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void Enumerate_List()\n {\n var list = new List<Temp>(query);\n var watch = Stopwatch.StartNew();\n\n foreach (var item in list)\n {\n\n }\n\n watch.StopAndPrint();\n }\n\n public static void Enumerate_LinkedList()\n {\n var list = new LinkedList<Temp>(query);\n var watch = Stopwatch.StartNew();\n\n foreach (var item in list)\n {\n\n }\n\n watch.StopAndPrint();\n }\n\n //for the fun of it, I tried to time inserting to the middle of \n //linked list - this is by no means a realistic scenario! or may be \n //these make sense if you assume you have the reference to middle node\n\n //insertion to the middle of list\n public static void AddMiddle_List()\n {\n var list = new List<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i < end; i++)\n list.Insert(list.Count / 2, temp(i));\n\n watch.StopAndPrint();\n }\n\n //insertion in linked list in such a fashion that \n //it has the same effect as inserting into the middle of list\n public static void AddMiddle_LinkedList1()\n {\n var list = new LinkedList<Temp>();\n var watch = Stopwatch.StartNew();\n\n LinkedListNode<Temp> evenNode = null, oddNode = null;\n for (int i = start; i < end; i++)\n {\n if (list.Count == 0)\n oddNode = evenNode = list.AddLast(temp(i));\n else\n if (list.Count % 2 == 1)\n oddNode = list.AddBefore(evenNode, temp(i));\n else\n evenNode = list.AddAfter(oddNode, temp(i));\n }\n\n watch.StopAndPrint();\n }\n\n //another hacky way\n public static void AddMiddle_LinkedList2()\n {\n var list = new LinkedList<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (var i = start + 1; i < end; i += 2)\n list.AddLast(temp(i));\n for (int i = end - 2; i >= 0; i -= 2)\n list.AddLast(temp(i));\n\n watch.StopAndPrint();\n }\n\n //OP's original more sensible approach, but I tried to filter out\n //the intermediate iteration cost in finding the middle node.\n public static void AddMiddle_LinkedList3()\n {\n var list = new LinkedList<Temp>();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i < end; i++)\n {\n if (list.Count == 0)\n list.AddLast(temp(i));\n else\n {\n watch.Stop();\n var curNode = list.First;\n for (var j = 0; j < list.Count / 2; j++)\n curNode = curNode.Next;\n watch.Start();\n\n list.AddBefore(curNode, temp(i));\n }\n }\n\n watch.StopAndPrint();\n }\n }\n}\n LinkedList<T> List<T>" }, { "answer_id": 25383813, "author": "Tom", "author_id": 1762932, "author_profile": "https://Stackoverflow.com/users/1762932", "pm_score": 2, "selected": false, "text": "LinkedList<String> strings = readStrings();\nHashSet<String> dic = readDic();\nIterator<String> iterator = strings.iterator();\nwhile (iterator.hasNext()){\n String string = iterator.next();\n if (dic.contains(string))\n iterator.remove();\n}\n" }, { "answer_id": 29263914, "author": "Andrew___Pls_Support_UA", "author_id": 4423545, "author_profile": "https://Stackoverflow.com/users/4423545", "pm_score": 5, "selected": false, "text": "LinkedList<T> IList<T> LinkedList<T> LinkedList<T> List<T> List<T> ArrayList<T>" }, { "answer_id": 47707619, "author": "John Smith", "author_id": 3739391, "author_profile": "https://Stackoverflow.com/users/3739391", "pm_score": 2, "selected": false, "text": "List<> LinkedList<>" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]
170,004
<p>Let's say:</p> <pre><code>&lt;div&gt; pre text &lt;div class="remove-just-this"&gt; &lt;p&gt;child foo&lt;/p&gt; &lt;p&gt;child bar&lt;/p&gt; nested text &lt;/div&gt; post text &lt;/div&gt; </code></pre> <p>to this:</p> <pre><code>&lt;div&gt; pre text &lt;p&gt;child foo&lt;/p&gt; &lt;p&gt;child bar&lt;/p&gt; nested text post text &lt;/div&gt; </code></pre> <p>I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.</p>
[ { "answer_id": 170056, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 8, "selected": true, "text": "var cnt = $(\".remove-just-this\").contents();\n$(\".remove-just-this\").replaceWith(cnt);\n" }, { "answer_id": 170142, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 2, "selected": false, "text": "innerHTML removeChild" }, { "answer_id": 170230, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "while (nodeToBeRemoved.firstChild)\n{\n nodeToBeRemoved.parentNode.insertBefore(nodeToBeRemoved.firstChild,\n nodeToBeRemoved);\n}\n\nnodeToBeRemoved.parentNode.removeChild(nodeToBeRemoved);\n" }, { "answer_id": 176404, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 5, "selected": false, "text": "innerHTML innerHTML appendChild DocumentFragment var fragment = document.createDocumentFragment();\nwhile(element.firstChild) {\n fragment.appendChild(element.firstChild);\n}\nelement.parentNode.replaceChild(fragment, element);\n" }, { "answer_id": 227619, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 2, "selected": false, "text": "var children = $('remove-just-this').getChildren();\nchildren.replaces($('remove-just-this');\n" }, { "answer_id": 7822421, "author": "campino2k", "author_id": 988957, "author_profile": "https://Stackoverflow.com/users/988957", "pm_score": 5, "selected": false, "text": " $('.remove-just-this > *').unwrap()\n" }, { "answer_id": 10297373, "author": "user362834", "author_id": 362834, "author_profile": "https://Stackoverflow.com/users/362834", "pm_score": 0, "selected": false, "text": "def remove_node(doc, element):\n \"\"\" removes a specific node, adding its children in its place\n \"\"\"\n fragment = doc.createDocumentFragment()\n while element.firstChild:\n fragment.appendChild(element.firstChild)\n\n parent = element.parentNode\n parent.insertBefore(fragment, element)\n parent.removeChild(element)\n" }, { "answer_id": 36361203, "author": "yunda", "author_id": 2584128, "author_profile": "https://Stackoverflow.com/users/2584128", "pm_score": 5, "selected": false, "text": "$('.remove-just-this').contents().unwrap();\n" }, { "answer_id": 42298924, "author": "maxime_039", "author_id": 3726887, "author_profile": "https://Stackoverflow.com/users/3726887", "pm_score": 2, "selected": false, "text": "$('#remove-just-this').contents().unwrap();\n var cnt = $(\"#remove-just-this\").contents();\n$(\"#remove-just-this\").replaceWith(cnt);\n var element = document.getElementById('remove-just-this');\nvar fragment = document.createDocumentFragment();\nwhile(element.firstChild) {\n fragment.appendChild(element.firstChild);\n}\nelement.parentNode.replaceChild(fragment, element);\n $.unwrap() $.replaceWith()" }, { "answer_id": 43979228, "author": "LaurensVijnck", "author_id": 3912095, "author_profile": "https://Stackoverflow.com/users/3912095", "pm_score": 0, "selected": false, "text": " $(\".card_row\").each(function(){\n var cnt = $(this).contents();\n $(this).replaceWith(cnt);\n });\n" }, { "answer_id": 45663846, "author": "Gibolt", "author_id": 974045, "author_profile": "https://Stackoverflow.com/users/974045", "pm_score": 4, "selected": false, "text": "const node = document.getElementsByClassName('.remove-just-this')[0];\nnode.replaceWith(...node.childNodes); // or node.children, if you don't want textNodes\n oldNode.replaceWith(newNode) ...array" }, { "answer_id": 55103400, "author": "Johannes Buchholz", "author_id": 8678740, "author_profile": "https://Stackoverflow.com/users/8678740", "pm_score": 3, "selected": false, "text": "const wrapper = document.querySelector('.remove-just-this');\nwrapper.outerHTML = wrapper.innerHTML; <div>\n pre text\n <div class=\"remove-just-this\">\n <p>child foo</p>\n <p>child bar</p>\n nested text\n </div>\n post text\n</div>" }, { "answer_id": 73929483, "author": "Franck", "author_id": 14989739, "author_profile": "https://Stackoverflow.com/users/14989739", "pm_score": 0, "selected": false, "text": "$(\".remove-just-this\").contents().unwrap();\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20838/" ]
170,019
<p>I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved. </p> <p>Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session_start() as well as naming it before hand with session_name(). </p> <p><strong>An added note</strong>. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session_id($id); My intention in using session_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session_id not the session_name. </p> <p>It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session_id and your sessions will function as expected. </p>
[ { "answer_id": 170031, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "mysite.com?PHPSESSID=10alksdjfq9e\n" }, { "answer_id": 170764, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "-b/--cookie\n-c/--cookie-jar\n-j/--junk-session-cookies\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8880/" ]
170,021
<p>We are currently running a SQL Job that archives data daily at every 10PM. However, the end users complains that from 10PM to 12, the page shows a time out error.</p> <p>Here's the pseudocode of the job</p> <pre><code>while @jobArchive = 1 and @countProcecessedItem &lt; @maxItem exec ArchiveItems @countProcecessedItem out if error occured set @jobArchive = 0 delay '00:10' </code></pre> <p>The ArchiveItems stored procedure grabs the top 100 item that was created 30 days ago, process and archive them in another database and delete the item in the original table, including other tables that are related with it. finally sets the @countProcecessedItem with the number of item processed. The ArchiveItems also creates and deletes temporary tables it used to hold some records.</p> <p><strong>Note:</strong> if the information I've provide is incomplete, reply and I'll gladly add more information if possible.</p>
[ { "answer_id": 170031, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "mysite.com?PHPSESSID=10alksdjfq9e\n" }, { "answer_id": 170764, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "-b/--cookie\n-c/--cookie-jar\n-j/--junk-session-cookies\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24755/" ]
170,028
<p>This seems very noisy to me. Five lines of overhead is just too much.</p> <pre><code>m_Lock.EnterReadLock() Try Return m_List.Count Finally m_Lock.ExitReadLock() End Try </code></pre> <p>So how would you simply this?</p>
[ { "answer_id": 170032, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 0, "selected": false, "text": "Using m_Lock.ReadSection\n Return m_List.Count\nEnd Using\n <Extension()> Public Function ReadSection(ByVal lock As ReaderWriterLockSlim) As ReadWrapper\n Return New ReadWrapper(lock)\nEnd Function\n\n\nPublic NotInheritable Class ReadWrapper\n Implements IDisposable\n\n Private m_Lock As ReaderWriterLockSlim\n Public Sub New(ByVal lock As ReaderWriterLockSlim)\n m_Lock = lock\n m_Lock.EnterReadLock()\n End Sub\n Public Sub Dispose() Implements IDisposable.Dispose\n m_Lock.ExitReadLock()\n End Sub\n\nEnd Class\n" }, { "answer_id": 170040, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Threading;\n\nclass Program\n{\n static void Main()\n {\n ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\n\n using (sync.Read())\n {\n // etc \n }\n }\n\n\n}\npublic static class ReaderWriterExt\n{\n sealed class ReadLockToken : IDisposable\n {\n private ReaderWriterLockSlim sync;\n public ReadLockToken(ReaderWriterLockSlim sync)\n {\n this.sync = sync;\n sync.EnterReadLock();\n }\n public void Dispose()\n {\n if (sync != null)\n {\n sync.ExitReadLock();\n sync = null;\n }\n }\n }\n public static IDisposable Read(this ReaderWriterLockSlim obj)\n {\n return new ReadLockToken(obj);\n }\n}\n" }, { "answer_id": 215738, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 0, "selected": false, "text": "// Stores a private List<T>, only accessible through lock tokens\n// returned by Read, Write, and UpgradableRead.\nvar lockedList = new LockedList<T>( );\n using( var r = lockedList.Read( ) ) {\n foreach( T item in r.Reader )\n ...\n}\n using( var w = lockedList.Write( ) ) {\n w.Writer.Add( new T( ) );\n}\n T t = ...;\nusing( var u = lockedList.UpgradableRead( ) ) {\n if( !u.Reader.Contains( t ) )\n using( var w = u.Upgrade( ) )\n w.Writer.Add( t );\n}\n List<T> ReadOnlyCollection<T> Locked<T,T> R W List<T> list;\nusing( var w = lockedList.Write( ) )\n list = w.Writable;\n\n//BAD: \"locked\" object leaked outside of lock scope\nlist.MakeChangesWithoutHoldingLock( );\n Locked sealed class LockedList<T> : Locked<List<T>, ReadOnlyCollection<T>> {\n public LockedList( )\n : base( new List<T>( ), list => list.AsReadOnly( ) )\n { }\n}\n\npublic class Locked<W, R> where W : class where R : class {\n private readonly LockerState state_;\n public Locked( W writer, R reader ) { this.state_ = new LockerState( reader, writer ); }\n public Locked( W writer, Func<W, R> getReader ) : this( writer, getReader( writer ) ) { }\n\n public IReadable Read( ) { return new Readable( this.state_ ); }\n public IWritable Write( ) { return new Writable( this.state_ ); }\n public IUpgradable UpgradableRead( ) { return new Upgradable( this.state_ ); }\n\n\n public interface IReadable : IDisposable { R Reader { get; } }\n public interface IWritable : IDisposable { W Writer { get; } }\n public interface IUpgradable : IReadable { IWritable Upgrade( );}\n\n\n #region Private Implementation Details\n sealed class LockerState {\n public readonly R Reader;\n public readonly W Writer;\n public readonly ReaderWriterLockSlim Sync;\n\n public LockerState( R reader, W writer ) {\n Debug.Assert( reader != null && writer != null );\n this.Reader = reader;\n this.Writer = writer;\n this.Sync = new ReaderWriterLockSlim( );\n }\n }\n\n abstract class Accessor : IDisposable {\n private LockerState state_;\n protected LockerState State { get { return this.state_; } }\n protected Accessor( LockerState state ) {\n Debug.Assert( state != null );\n this.Acquire( state.Sync );\n this.state_ = state;\n }\n\n protected abstract void Acquire( ReaderWriterLockSlim sync );\n protected abstract void Release( ReaderWriterLockSlim sync );\n\n public void Dispose( ) {\n if( this.state_ != null ) {\n var sync = this.state_.Sync;\n this.state_ = null;\n this.Release( sync );\n }\n }\n }\n\n class Readable : Accessor, IReadable {\n public Readable( LockerState state ) : base( state ) { }\n public R Reader { get { return this.State.Reader; } }\n protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterReadLock( ); }\n protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitReadLock( ); }\n }\n\n sealed class Writable : Accessor, IWritable {\n public Writable( LockerState state ) : base( state ) { }\n public W Writer { get { return this.State.Writer; } }\n protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterWriteLock( ); }\n protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitWriteLock( ); }\n }\n\n sealed class Upgradable : Readable, IUpgradable {\n public Upgradable( LockerState state ) : base( state ) { }\n public IWritable Upgrade( ) { return new Writable( this.State ); }\n protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterUpgradeableReadLock( ); }\n protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitUpgradeableReadLock( ); }\n }\n #endregion\n}\n" }, { "answer_id": 317448, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 2, "selected": false, "text": "internal static class ReaderWriteLockExtensions\n{\n private struct Disposable : IDisposable\n {\n private readonly Action m_action;\n private Sentinel m_sentinel;\n\n public Disposable(Action action)\n {\n m_action = action;\n m_sentinel = new Sentinel();\n }\n\n public void Dispose()\n {\n m_action();\n GC.SuppressFinalize(m_sentinel);\n }\n }\n\n private class Sentinel\n {\n ~Sentinel()\n {\n throw new InvalidOperationException(\"Lock not properly disposed.\");\n }\n }\n\n public static IDisposable AcquireReadLock(this ReaderWriterLockSlim lock)\n {\n lock.EnterReadLock();\n return new Disposable(lock.ExitReadLock);\n }\n\n public static IDisposable AcquireUpgradableReadLock(this ReaderWriterLockSlim lock)\n {\n lock.EnterUpgradeableReadLock();\n return new Disposable(lock.ExitUpgradeableReadLock);\n }\n\n public static IDisposable AcquireWriteLock(this ReaderWriterLockSlim lock)\n {\n lock.EnterWriteLock();\n return new Disposable(lock.ExitWriteLock);\n }\n} \n using (m_lock.AcquireReadLock())\n{\n // Do stuff\n}\n" }, { "answer_id": 3406461, "author": "Eric Lathrop", "author_id": 18392, "author_profile": "https://Stackoverflow.com/users/18392", "pm_score": 3, "selected": false, "text": "ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\nusing (sync.Read())\n{\n // Do stuff\n}\n ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\nIDisposable d = sync.Read();\ntry\n{\n // Do stuff\n}\nfinally\n{\n d.Dispose();\n}\n try ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();\ntry\n{\n myLock.EnterReadLock();\n // Do stuff\n}\nfinally\n{\n // Release the lock\n myLock.ExitReadLock();\n}\n /// <summary>\n /// Manager for a lock object that acquires and releases the lock in a manner\n /// that avoids the common problem of deadlock within the using block\n /// initialisation.\n /// </summary>\n /// <remarks>\n /// This manager object is, by design, not itself thread-safe.\n /// </remarks>\n public sealed class ReaderWriterLockMgr : IDisposable\n {\n /// <summary>\n /// Local reference to the lock object managed\n /// </summary>\n private ReaderWriterLockSlim _readerWriterLock = null;\n\n private enum LockTypes { None, Read, Write, Upgradeable }\n /// <summary>\n /// The type of lock acquired by this manager\n /// </summary>\n private LockTypes _enteredLockType = LockTypes.None;\n\n /// <summary>\n /// Manager object construction that does not acquire any lock\n /// </summary>\n /// <param name=\"ReaderWriterLock\">The lock object to manage</param>\n public ReaderWriterLockMgr(ReaderWriterLockSlim ReaderWriterLock)\n {\n if (ReaderWriterLock == null)\n throw new ArgumentNullException(\"ReaderWriterLock\");\n _readerWriterLock = ReaderWriterLock;\n }\n\n /// <summary>\n /// Call EnterReadLock on the managed lock\n /// </summary>\n public void EnterReadLock()\n {\n if (_readerWriterLock == null)\n throw new ObjectDisposedException(GetType().FullName);\n if (_enteredLockType != LockTypes.None)\n throw new InvalidOperationException(\"Create a new ReaderWriterLockMgr for each state you wish to enter\");\n // Allow exceptions by the Enter* call to propogate\n // and prevent updating of _enteredLockType\n _readerWriterLock.EnterReadLock();\n _enteredLockType = LockTypes.Read;\n }\n\n /// <summary>\n /// Call EnterWriteLock on the managed lock\n /// </summary>\n public void EnterWriteLock()\n {\n if (_readerWriterLock == null)\n throw new ObjectDisposedException(GetType().FullName);\n if (_enteredLockType != LockTypes.None)\n throw new InvalidOperationException(\"Create a new ReaderWriterLockMgr for each state you wish to enter\");\n // Allow exceptions by the Enter* call to propogate\n // and prevent updating of _enteredLockType\n _readerWriterLock.EnterWriteLock();\n _enteredLockType = LockTypes.Write;\n }\n\n /// <summary>\n /// Call EnterUpgradeableReadLock on the managed lock\n /// </summary>\n public void EnterUpgradeableReadLock()\n {\n if (_readerWriterLock == null)\n throw new ObjectDisposedException(GetType().FullName);\n if (_enteredLockType != LockTypes.None)\n throw new InvalidOperationException(\"Create a new ReaderWriterLockMgr for each state you wish to enter\");\n // Allow exceptions by the Enter* call to propogate\n // and prevent updating of _enteredLockType\n _readerWriterLock.EnterUpgradeableReadLock();\n _enteredLockType = LockTypes.Upgradeable;\n }\n\n /// <summary>\n /// Exit the lock, allowing re-entry later on whilst this manager is in scope\n /// </summary>\n /// <returns>Whether the lock was previously held</returns>\n public bool ExitLock()\n {\n switch (_enteredLockType)\n {\n case LockTypes.Read:\n _readerWriterLock.ExitReadLock();\n _enteredLockType = LockTypes.None;\n return true;\n case LockTypes.Write:\n _readerWriterLock.ExitWriteLock();\n _enteredLockType = LockTypes.None;\n return true;\n case LockTypes.Upgradeable:\n _readerWriterLock.ExitUpgradeableReadLock();\n _enteredLockType = LockTypes.None;\n return true;\n }\n return false;\n }\n\n /// <summary>\n /// Dispose of the lock manager, releasing any lock held\n /// </summary>\n public void Dispose()\n {\n if (_readerWriterLock != null)\n {\n ExitLock();\n // Tidy up managed resources\n // Release reference to the lock so that it gets garbage collected\n // when there are no more references to it\n _readerWriterLock = null;\n // Call GC.SupressFinalize to take this object off the finalization\n // queue and prevent finalization code for this object from\n // executing a second time.\n GC.SuppressFinalize(this);\n }\n }\n\n protected ~ReaderWriterLockMgr()\n {\n if (_readerWriterLock != null)\n ExitLock();\n // Leave references to managed resources so that the garbage collector can follow them\n }\n }\n ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();\n\nusing (ReaderWriterLockMgr lockMgr = new ReaderWriterLockMgr(myLock))\n{\n lockMgr.EnterReadLock();\n // Do stuff\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]
170,036
<p>Does windows have any decent sampling (eg. non-instrumenting) profilers available? Preferably something akin to Shark on MacOS, although i am willing to accept that i am going to have to pay for such a profiler on windows.</p> <p>I've tried the profiler in VS Team Suite and was not overly impressed, and was wondering if there were any other good ones.</p> <p>[Edit: Erk, i forgot to say this is for C/C++, rather than .NET -- sorry for any confusion]</p>
[ { "answer_id": 171709, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "dbghelp.dll symsrv.dll kernrate.exe dbghelp.dll %SystemRoot%\\system32" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784/" ]
170,051
<p>I'm trying to make things simpler. Here is my code:</p> <pre><code> If Threading.Monitor.TryEnter(syncRoot) Then Try 'do something Finally Threading.Monitor.Exit(syncRoot) End Try Else 'do something else End If </code></pre> <p>This is even worse than the ReaderWriterLock in terms of noise. I can use C# or VB, so answers applying to either will be welcome.</p>
[ { "answer_id": 170055, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "using(var token = GetLock(syncLock, timeout)) {\n if(token != null) { ... }\n}\n" }, { "answer_id": 170094, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 4, "selected": true, "text": "public bool TryEnter(object lockObject, Action work) \n{\n if (Monitor.TryEnter(lockObject)) \n {\n try \n {\n work();\n }\n finally \n {\n Monitor.Exit(lockObject);\n } \n return true;\n }\n\n return false;\n}\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]