qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
231,893
<p>I have seen this syntax in MSDN: <a href="https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="noreferrer"><code>yield break</code></a>, but I don't know what it does. Does anyone know?</p>
[ { "answer_id": 231915, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 5, "selected": false, "text": "public interface INode\n{\n IEnumerable<Node> GetChildren();\n}\n\npublic class NodeWithTenChildren : INode\n{\n private Node[] m_children = new Node[10];\n\n public IEnumerable<Node> GetChildren()\n {\n for( int n = 0; n < 10; ++n )\n {\n yield return m_children[ n ];\n }\n }\n}\n\npublic class NodeWithNoChildren : INode\n{\n public IEnumerable<Node> GetChildren()\n {\n yield break;\n }\n}\n" }, { "answer_id": 231945, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 10, "selected": true, "text": "yield break return for (int i = 0; i < 5; i++)\n{\n yield return i;\n}\n\nConsole.Out.WriteLine(\"You will see me\");\n yield break int i = 0;\nwhile (true)\n{\n if (i < 5)\n {\n yield return i;\n }\n else\n {\n // note that i++ will not be executed after this\n yield break;\n }\n i++;\n}\n\nConsole.Out.WriteLine(\"Won't see me\");\n" }, { "answer_id": 1051152, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "yield IEnumerable<T> yield return IEnumerable<T> yield break yield" }, { "answer_id": 2573970, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "yield break" }, { "answer_id": 8771185, "author": "Eranga Dissanayaka", "author_id": 1622207, "author_profile": "https://Stackoverflow.com/users/1622207", "pm_score": -1, "selected": false, "text": " public IEnumerable<int> SampleNumbers()\n {\n int counter = 0;\n yield return counter;\n\n counter = counter + 2;\n\n yield return counter;\n\n counter = counter + 3;\n\n yield return counter ;\n }\n" }, { "answer_id": 40814062, "author": "Wallace Kelly", "author_id": 167920, "author_profile": "https://Stackoverflow.com/users/167920", "pm_score": 4, "selected": false, "text": "yield break yield break IEnumerable<uint> FindPrimes(uint startAt, uint maxCount)\n{\n for (var i = 0UL; i < maxCount; i++)\n {\n startAt = NextPrime(startAt);\n yield return startAt;\n }\n\n Debug.WriteLine(\"All the primes were found.\");\n}\n maxCount yield break IEnumerable<uint> FindPrimes(uint startAt, uint maxCount, int maxMinutes)\n{\n var sw = System.Diagnostics.Stopwatch.StartNew();\n for (var i = 0UL; i < maxCount; i++)\n {\n startAt = NextPrime(startAt);\n yield return startAt;\n\n if (sw.Elapsed.TotalMinutes > maxMinutes)\n yield break;\n }\n\n Debug.WriteLine(\"All the primes were found.\");\n}\n yield break yield break break yield break Debug.WriteLine(..)" }, { "answer_id": 51502141, "author": "John ClearZ", "author_id": 318041, "author_profile": "https://Stackoverflow.com/users/318041", "pm_score": 4, "selected": false, "text": "// returns 1,2,3,4,5\nIEnumerable<int> CountToFive()\n{\n yield return 1;\n yield return 2;\n yield return 3;\n yield return 4;\n yield return 5;\n yield break;\n yield return 6;\n yield return 7;\n yield return 8;\n yield return 9;\n }\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
231,912
<p>I was about to add an extra signal handler to an app we have here and I noticed that the author had used <code>sigaction()</code> to set up the other signal handlers. I was going to use <code>signal()</code>. To follow convention I should use <code>sigaction()</code> but if I was writing from scratch, which should I choose?</p>
[ { "answer_id": 231933, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "signal(3) This signal() facility is a simplified interface to the more\n general sigaction(2) facility.\n" }, { "answer_id": 232711, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 9, "selected": true, "text": "sigaction() signal() sigaction() sigaction() signal() signal() sigaction() signal() SIG_DFL signal() signal() sigaction() signal() sigaction() sighold() sigignore() sigpause() sigrelse() sigaction() signal() sigaction() signal()    signal() sigaction() signal() abort() raise() kill() pthread_kill() sigqueue() errno volatile sig_atomic_t signal() sigaction() sigaction()" }, { "answer_id": 58815445, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 4, "selected": false, "text": "sigaction() signal() man 2 signal signal() sigaction(2) signal() SIG_DFL SIG_IGN signal() signal() sigaction() sigaction(2) signal() signal sigaction signal() sigaction() sigaction() signal() sigaction() sigaction() sigaction() #include <errno.h> // errno\n#include <signal.h> // sigaction()\n#include <stdio.h> // printf()\n#include <string.h> // strerror()\n\n// Format: const char *, unsigned int, const char *\n#define LOG_LOCATION __FILE__, __LINE__, __func__ \n#define LOG_FORMAT_STR \"file: %s, line: %u, func: %s: \"\n\n/// @brief Callback function to handle termination signals, such as \n/// Ctrl + C\n/// @param[in] signal Signal number of the signal being handled by this \n/// callback function\n/// @return None\nstatic void termination_handler(const int signal)\n{\n switch (signal)\n {\n case SIGINT:\n printf(\"\\nSIGINT (%i) (Ctrl + C) signal caught.\\n\", signal);\n break;\n case SIGTERM:\n printf(\"\\nSIGTERM (%i) (default `kill` or `killall`) signal caught.\\n\", \n signal);\n break;\n case SIGHUP:\n printf(\"\\nSIGHUP (%i) (\\\"hang-up\\\") signal caught.\\n\", signal);\n break;\n default:\n printf(\"\\nUnk signal (%i) caught.\\n\", signal);\n break;\n }\n\n // DO PROGRAM CLEANUP HERE, such as freeing memory, closing files, etc.\n\n \n exit(signal);\n}\n\n/// @brief Set a new signal handler action for a given signal\n/// @details Only update the signals with our custom handler if they are NOT\n/// set to \"signal ignore\" (`SIG_IGN`), which means they are currently\n/// intentionally ignored. GCC recommends this \"because non-job-control\n/// shells often ignore certain signals when starting children, and it is\n/// important for children to respect this.\" See\n/// https://www.gnu.org/software/libc/manual/html_node/Basic-Signal-Handling.html#Basic-Signal-Handling\n/// and\n/// https://www.gnu.org/software/libc/manual/html_node/Sigaction-Function-Example.html.\n/// Note that termination signals can be found here:\n/// https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html#Termination-Signals\n/// @param[in] signal Signal to set to this action\n/// @param[in] action Pointer to sigaction struct, including the callback \n/// function inside it, to attach to this signal\n/// @return None\nstatic inline void set_sigaction(int signal, const struct sigaction *action)\n{\n struct sigaction old_action;\n\n // check current signal handler action to see if it's set to SIGNAL IGNORE\n sigaction(signal, NULL, &old_action);\n if (old_action.sa_handler != SIG_IGN)\n {\n // set new signal handler action to what we want\n int ret_code = sigaction(signal, action, NULL);\n if (ret_code == -1)\n {\n printf(LOG_FORMAT_STR \"sigaction failed when setting signal to \"\n \"%i; errno = %i: %s\\n\", \n LOG_LOCATION, signal, errno, strerror(errno));\n }\n }\n}\n\nint main(int argc, char *argv[])\n{\n //...\n\n // Register callbacks to handle kill signals; prefer the Linux function\n // `sigaction()` over the C function `signal()`: \"It is better to use\n // sigaction if it is available since the results are much more reliable.\"\n // Source:\n // https://www.gnu.org/software/libc/manual/html_node/Basic-Signal-Handling.html#Basic-Signal-Handling\n // and\n // https://stackoverflow.com/questions/231912/what-is-the-difference-between-sigaction-and-signal/232711#232711.\n // See here for official gcc `sigaction()` demo, which this code is modeled\n // after:\n // https://www.gnu.org/software/libc/manual/html_node/Sigaction-Function-Example.html\n\n // Set up the structure to specify the new action, per GCC's demo.\n struct sigaction new_action;\n new_action.sa_handler = termination_handler; // set callback function\n sigemptyset(&new_action.sa_mask);\n new_action.sa_flags = 0;\n\n // SIGINT: ie: Ctrl + C kill signal\n set_sigaction(SIGINT, &new_action);\n // SIGTERM: termination signal--the default generated by `kill` and\n // `killall`\n set_sigaction(SIGTERM, &new_action);\n // SIGHUP: \"hang-up\" signal due to lost connection\n set_sigaction(SIGHUP, &new_action);\n\n //...\n}\n signal() #include <signal.h>\n\nvoid\ntermination_handler (int signum)\n{\n struct temp_file *p;\n\n for (p = temp_file_list; p; p = p->next)\n unlink (p->name);\n}\n\nint\nmain (void)\n{\n …\n if (signal (SIGINT, termination_handler) == SIG_IGN)\n signal (SIGINT, SIG_IGN);\n if (signal (SIGHUP, termination_handler) == SIG_IGN)\n signal (SIGHUP, SIG_IGN);\n if (signal (SIGTERM, termination_handler) == SIG_IGN)\n signal (SIGTERM, SIG_IGN);\n …\n}\n signal() sigaction() sigemptyset() sigfillset()" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20889/" ]
231,917
<p>This originally was a problem I ran into at work, but is now something I'm just trying to solve for my own curiosity.</p> <p>I want to find out if int 'a' contains the int 'b' in the most efficient way possible. I wrote some code, but it seems no matter what I write, parsing it into a string and then using indexOf is twice as fast as doing it mathematically.</p> <p>Memory is not an issue (within reason), just sheer processing speed.</p> <p>This is the code I have written to do it mathematically:</p> <pre><code>private static int[] exponents = {10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; private static boolean findMatch(int a, int b) { if (b &gt; a) return false; if (a == b) return true; int needleLength = getLength(b); int exponent = exponents[needleLength]; int subNum; while (a &gt;= 1) { subNum = a % exponent; if (subNum == b) return true; a /= 10; } return false; } private static int getLength(int b) { int len = 0; while (b &gt;= 1) { len++; b /= 10; } return len; } </code></pre> <p>Here's the string method I'm using, which seems to trump the mathematical method above:</p> <pre><code>private static boolean findStringMatch(int a, int b) { return String.valueOf(a).indexOf(String.valueOf(b)) != -1; } </code></pre> <p>So although this isn't really required for me to complete my work, I was just wondering if anyone could think of any way to further optimize my way of doing it mathematically, or an entirely new approach altogether. Again memory is no problem, I am just shooting for sheer speed.</p> <p>I'm really interested to see or hear anything anyone has to offer on this.</p> <p><strong>EDIT:</strong> When I say contains I mean can be anywhere, so for example, findMatch(1234, 23) == true</p> <p><strong>EDIT:</strong> For everyone saying that this crap is unreadable and unnecessary: you're missing the point. The point was to get to geek out on an interesting problem, not come up with an answer to be used in production code.</p>
[ { "answer_id": 231936, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "// Check if A is inside B lol\nbool Contains (int a, int b)\n{\n return (a <= b);\n}\n" }, { "answer_id": 231950, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 0, "selected": false, "text": "findMatch ContainerBuilder.number(int) ContainerBuilder contains boolean b = number(12345).contains(234);\n" }, { "answer_id": 232031, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 2, "selected": false, "text": "private static boolean findMatch(int a, int b) {\n if (b > a) return false;\n\n if (a == b) return true;\n\n int needleLength = getLength(b);\n\n int exponent = exponents[needleLength];\n int subNum;\n while (a > b) {\n subNum = a % exponent;\n\n if (subNum == b)\n return true;\n\n a /= 10;\n }\n return false;\n}\n" }, { "answer_id": 232382, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 2, "selected": false, "text": "% ~ T\n* ~ 4T\n/ ~ 7T\n private static int getLength(final int b) { \n int len = 0;\n while (b > exponents[len]) {\n len++;\n }\n return len + 1\n}\n private static int getLength(final int b) { \n int len = 0;\n final int maxLen = exponents.length;\n while (len < maxLen && b > exponents[len]) {\n len++;\n }\n return len + 1;\n}\n private static boolean findMatch(int a, final int b) {\n if (b > a) return false;\n if (a == b) return true;\n int needleLength = 0;\n while (b > exponents[len]) {\n needleLength ++;\n }\n needleLength++;\n\n final int exponent = exponents[needleLength];\n int subNum;\n while (a >= 1 && a <= b) {\n subNum = a % exponent;\n if (subNum == b)\n return true;\n a /= 10;\n }\n return false;\n}\n" }, { "answer_id": 232559, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 3, "selected": true, "text": "long mask ( long n ) { \n long m = n % 10;\n long n_d = n;\n long div = 10;\n int shl = 0;\n while ( n_d >= 10 ) { \n n_d /= 10;\n long t = n_d % 10;\n m |= ( t << ( shl += 4 ));\n }\n return m;\n}\n\nboolean findMatch( int a, int b ) { \n if ( b < a ) return false;\n if ( a == b ) return true;\n\n long m_a = mask( a ); // set up mask O(n)\n long m_b = mask( b ); // set up mask O(m)\n\n while ( m_a < m_b ) {\n if (( m_a & m_b ) == m_a ) return true;\n m_a <<= 4; // shift - fast!\n if ( m_a == m_b ) return true;\n } // O(p)\n return false;\n} \n\nvoid testContains( int a, int b ) { \n print( \"findMatch( \" + a + \", \" + b + \" )=\" + findMatch( a, b ));\n}\n\ntestContains( 12, 120 );\ntestContains( 12, 125 );\ntestContains( 123, 551241238 );\ntestContains( 131, 1214124 );\ntestContains( 131, 1314124 );\n indexOf boolean findMatch( int a, int b ) { \n String s_a = \"\" + a;\n String s_b = \"\" + b;\n return s_a.indexOf( s_b ) > -1;\n}\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14007/" ]
231,937
<p>I am trying to show and hide an inline element (eg a span) using jQuery.</p> <p>If I just use toggle(), it works as expected but if I use toggle("slow") to give it an animation, it turns the span into a block element and therefore inserts breaks.</p> <p>Is animation possible with inline elements? I would prefer a smooth sliding if possible, rather than a fade in.</p> <pre><code>&lt;script type="text/javascript"&gt; $(function(){ $('.toggle').click(function() { $('.hide').toggle("slow") }); }); &lt;/script&gt; &lt;p&gt;Hello &lt;span class="hide"&gt;there&lt;/span&gt; jquery&lt;/p&gt; &lt;button class="toggle"&gt;Toggle&lt;/button&gt; </code></pre>
[ { "answer_id": 232005, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "$('.toggle').click(function() {\n $('.hide:visible').animate(\n {opacity : 0},\n function() { $(this).hide(); }\n );\n $('.hide:hidden')\n .show()\n .animate({opacity : 1})\n ;\n});\n" }, { "answer_id": 232037, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "toggle() $('.toggle').click(function() {\n $('.hide').animate({\n 'opacity' : 'toggle',\n });\n});\n var hidepos = $('.hide').offset().left;\nvar slidepos = $('.slide').offset().left;\n\n$('.toggle').click(function() {\n var goto = ($('.slide').offset().left < slidepos) ? slidepos : hidepos;\n\n $('.slide').css({\n 'left' : $('.slide').offset().left,\n 'position' : 'fixed',\n }).animate({\n 'left' : goto,\n }, function() {\n $(this).css('position', 'static');\n });\n\n $('.hide').animate({\n 'opacity' : 'toggle',\n });\n});\n <p>Hello <span class=\"hide\">there</span> <span class=\"slide\">jquery</span></p>\n<button class=\"toggle\">Toggle</button>\n" }, { "answer_id": 1146761, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 0, "selected": false, "text": " $('#pnlPopup #btnUpdateButton').assertOne().animate({ width: \"toggle\" });\n #btnUpdateButton {\n float: left;\n margin-right: 5px;\n}\n" }, { "answer_id": 2476900, "author": "Terion", "author_id": 297319, "author_profile": "https://Stackoverflow.com/users/297319", "pm_score": 3, "selected": false, "text": "#animated-element { display: inline-block!important }\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31012/" ]
231,947
<p>I have a project that is based on the Navigation Based Application template. In the AppDelegate are the methods <code>-applicationDidFinishLoading:</code> and <code>-applicationWillTerminate:</code>. In those methods, I am loading and saving the application data, and storing it in an instance variable (it is actually an object-graph).</p> <p>When the application loads, it loads MainWindow.xib, which has a NavigationConroller, which in turn has a RootViewController. The RootViewController <code>nibName</code> property points to RootView (my actual controller class).</p> <p>In my class, I wish to refer to the object that I created in the <code>-applicationDidFinishLoading:</code> method, so that I can get a reference to it.</p> <p>Can anyone tell me how to do that? I know how to reference between objects that I have created programmatically, but I can't seem to figure out to thread my way back, given that the middle step was done from within the NIB file.</p>
[ { "answer_id": 232016, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": false, "text": "UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];\n//do something with mainWindow\n" }, { "answer_id": 232372, "author": "leonho", "author_id": 30883, "author_profile": "https://Stackoverflow.com/users/30883", "pm_score": 8, "selected": false, "text": "YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];\n//and then access the variable by appDelegate.variable \n" }, { "answer_id": 5132864, "author": "Ken", "author_id": 283311, "author_profile": "https://Stackoverflow.com/users/283311", "pm_score": 4, "selected": false, "text": "UIApplication *myApplication = [UIApplication sharedApplication];\nUIWindow *mainWindow = [myApplication keyWindow];\nUIViewController *rootViewController = [mainWindow rootViewController];\n UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];\n rootViewController" }, { "answer_id": 41299691, "author": "tryKuldeepTanwar", "author_id": 6330448, "author_profile": "https://Stackoverflow.com/users/6330448", "pm_score": 2, "selected": false, "text": "#define appDelegateShared ((AppDelegate *)[UIApplication sharedApplication].delegate)\n UIViewController *rootViewController = appDelegateShared.window.rootViewController;\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/231947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,004
<p>For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is:</p> <pre><code>WebBrowser webControl = new WebBrowser(); webControl.DocumentText = html; HtmlDocument doc = webControl.Document; </code></pre> <p>There are two problems:</p> <ol> <li>Requires the <code>WebBrowser</code> object! </li> <li>This can't be used with multiple threads; I need something that would work on different thread (other than the main thread).</li> </ol> <p>Any ideas?</p>
[ { "answer_id": 232021, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "XmlDocument System.Xml.XmlDocument x = new System.Xml.XmlDocument();\nx.LoadXml(html); // as long as html is well-formed, i.e. XHTML\n WebBrowser XmlDocument" }, { "answer_id": 242704, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 3, "selected": false, "text": "string input = \"<p>crappy html<br <img src=foo></div>\";\nHtmlTidy tidy = new HtmlTidy()\nstring output = tidy.CleanHtml(input, HtmlTidyOptions.ConvertToXhtml);\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(output);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/232004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to restrict access to client groups based on tiers. Continually expanding. I have a fairly good idea how I'm going to do this, but am not sure if I'll be able to integrate it well into the pre-built admin interface. </p> <p>I've done absolutely zero Django development otherwise I'd probably have a better idea on whether this would work or not. I probably won't use Django if the generated admin interface is going to be useless to this project - but like I said, there is a heavy reliance on fine-grained custom permissions.</p> <p>Will Django let me build custom permissions/rules and integrate it seamlessly into the admin CRUD interface?</p> <p>Update One: I want to use the admin app to minimise the repitition of generating CRUD interfaces, so yes I consider it a must have.</p> <p>Update Two:</p> <p>I want to describe the permissions required for this project.</p> <p>A client can belong to one or many 'stores'. Full time employees should only be able to edit clients at their store (even if they belong to another store). However, they should not be able to see/edit clients at another store. Casuals should only be able to view clients based on what store they are rostered too (or if the casual is logged in as the store user - more likely).</p> <p>Management above them need to be able to see all employees for the stores they manage, nothing more.</p> <p>Senior management should be able to edit ALL employees and grant permissions below themselves.</p> <p>After reading the django documentation, it says you can't (autmoatically) set permissions for a sub-set of a group. Only the entire group. Is it easy enough to mock up your own permissions for this purpose?</p>
[ { "answer_id": 232051, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "has_add_permission has_change_permission has_delete_permission queryset admin admin admin admin admin" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/232008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
232,020
<p>I am working on a project that I need to use the Infragistics WebGrid control for some lists of data. I am loading the data on the client-side using JavaScript for display on a Map, and then I need to display that same data within multiple WebGrids. All the data available will be displayed in the WebGrids, but only a subset of the data (only that which is currently within view) will be plotted on the Map at any given time. Since I am loading the data using JavaScript/Ajax, I would like to only load it once, and use the same mechanism to populate the WebGrid control with data too.</p> <p>Does anyone have any tips/pointers on working with the WebGrid completely from within client-side JavaScript/Ajax code?</p>
[ { "answer_id": 444340, "author": "Tj Kellie", "author_id": 54055, "author_profile": "https://Stackoverflow.com/users/54055", "pm_score": 2, "selected": false, "text": "var grid = igtbl_getGridById('dataGridControlID');\n var newRow = grid.Rows.addNew()\n var oCols = newRow.Band.Columns;\nfor(var i=0; i < oCols.length; i++) {\n newRow.getCell[i].setValue(yourValue)\n}\n newRow.getCellFromKey(colKey).setValue(yourValue,fireEvents);\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/232020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
232,030
<p>I want a pure virtual parent class to call a child implementation of a function like so:</p> <pre><code>class parent { public: void Read() { //read stuff } virtual void Process() = 0; parent() { Read(); Process(); } } class child : public parent { public: virtual void Process() { //process stuff } child() : parent() { } } int main() { child c; } </code></pre> <p>This should work, but I get an unlinked error :/ This is using VC++ 2k3</p> <p>Or shouldn't it work, am I wrong?</p>
[ { "answer_id": 232042, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "class parent\n{\n public:\n void Read() { //read stuff }\n virtual void Process() { }\n parent() \n {\n Read();\n Process();\n }\n}\n" }, { "answer_id": 232092, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "class parent\n{\n public:\n void Read() { /*read stuff*/ }\n virtual void Process() = 0;\n parent()\n {\n Read();\n }\n};\n\nclass child: public parent\n{\n public:\n virtual void Process() { /*process stuff*/ }\n child() : parent() { }\n};\n\ntemplate<typename T>\nclass Processor\n{\n public:\n Processor()\n :processorObj() // Pass on any args here\n {\n processorObj.Process();\n }\n private:\n T processorObj;\n\n};\n\n\n\n\nint main()\n{\n Processor<child> c;\n}\n" }, { "answer_id": 232924, "author": "Marcin Gil", "author_id": 5731, "author_profile": "https://Stackoverflow.com/users/5731", "pm_score": 2, "selected": false, "text": "class parent\n{\n public:\n void initialize() {\n read();\n process();\n }\n}\n" }, { "answer_id": 232947, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "class Data {};\nclass IReader { public: virtual Data read() = 0; };\nclass IProcessor { public: virtual void process( Data& d) = 0; };\n\nclass ReadNProcess {\npublic:\n ReadNProcess( IReader& reader, IProcessor processor ){\n processor.process( reader.read() );\n }\n};\n template< typename Reader, typename Writer > // definitely could use concepts here :)\nclass ReadNProcess {\npublic:\n ReadNProcess( Reader& r, Processor& p ) {\n p.process( r.read() );\n }\n};\n" } ]
2008/10/23
[ "https://Stackoverflow.com/questions/232030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23829/" ]
232,052
<p>I have an MSBuild task to build a specific project in a solution file. It looks something like this:</p> <pre><code>&lt;Target Name="Baz"&gt; &lt;MSBuild Projects="Foo.sln" Targets="bar:$(BuildCmd)" /&gt; &lt;/Target&gt; </code></pre> <p>From the command line, I can set my <code>BuildCmd</code> to either <code>Rebuild</code> or <code>Clean</code> and it works as expected:</p> <blockquote> <p>msbuild /target:Baz /property:BuildCmd=Rebuild MyMsbuildFile.xml msbuild /target:Baz /property:BuildCmd=Clean MyMsbuildFile.xml</p> </blockquote> <p>But what word do I use to set <code>BuildCmd</code> to in order to just build? I've tried <code>Build</code> and <code>Compile</code> and just leaving it blank or undefined, but I always get an error.</p> <blockquote> <p>msbuild /target:Baz /property:BuildCmd=Build MyMsbuildFile.xml Foo.sln : error MSB4057: The target "bar:Build" does not exist in the project.</p> <p>msbuild /target:Baz /property:BuildCmd=Compile MyMsbuildFile.xml Foo.sln : error MSB4057: The target "bar:Compile" does not exist in the project.</p> <p>msbuild /target:Baz MyMsbuildFile.xml Foo.sln : error MSB4057: The target "bar:" does not exist in the project.</p> </blockquote>
[ { "answer_id": 233738, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 6, "selected": true, "text": "<PropertyGroup>\n <BuildCmd Condition=\" '$(BuildCmd)' == ''\">Build</BuildCmd>\n</PropertyGroup>\n <Target Name=\"Stackoverflow\">\n <MsBuild Projects=\"Foo.sln\" Targets=\"$(BuildCmd)\" />\n</Target>\n msbuild msbuild.xml /t:Stackoverflow /p:BuildCmd=Clean\n" }, { "answer_id": 235257, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<PropertyGroup>\n <ProjBuildCmd Condition=\"'$(BuildCmd)' != 'Build'\">:$(BuildCmd)</ProjBuildCmd>\n <SolnBuildCmd Condition=\"'$(BuildCmd)' != 'Build'\">$(BuildCmd)</SolnBuildCmd>\n</PropertyGroup>\n $(BuildCmd) $(ProjBuildCmd) $(SolnBuildCmd) <!-- Build the 'bar' project only -->\n<Target Name=\"Baz\">\n <MSBuild Projects=\"Foo.sln\" Targets=\"bar$(ProjBuildCmd)\" />\n</Target>\n\n<!-- Build the whole solution -->\n<Target Name=\"Baz2\">\n <MSBuild Projects=\"Foo.sln\" Targets=\"$(SolnBuildCmd)\" />\n</Target>\n" }, { "answer_id": 11689059, "author": "Matt Slagle", "author_id": 1557745, "author_profile": "https://Stackoverflow.com/users/1557745", "pm_score": 2, "selected": false, "text": " <Target Name=\"Baz\">\n <PropertyGroup>\n <BuildCmd Condition=\"'$(BuildCmd)' != ''\">:$(BuildCmd)</BuildCmd>\n </PropertyGroup>\n <MSBuild Projects=\"Foo.sln\" Targets=\"bar$(BuildCmd)\" />\n </Target>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,053
<p>I'm writing javascript code that is read in as a string and executed via eval() by a firefox extension. Firebug does "see" my script so I am not able to use breakpoints, see objects, etc. </p> <p>I am currently using Firefox's error console which I'm starting to find limiting. What are my other options? Ideally, I would be able to use Firebug or something similar to it. How do people generally debug Greasemonkey scripts?</p> <p>I've tried using Lint and other validators, but my script uses a lot of objects and functions provided by the extension environment, making of a lot of the errors reported irrelevant. Also, the output tends to be too nitpicky (focusing of spacing issues, etc). </p>
[ { "answer_id": 232206, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "eval()" }, { "answer_id": 3483247, "author": "knoopx", "author_id": 62368, "author_profile": "https://Stackoverflow.com/users/62368", "pm_score": 1, "selected": false, "text": "(function(_, $){\n try {\n var GM_log = function(obj) { _.console.log(obj); }\n\n // $(\"#my_div\").reaplaceWith(\"hello world!\");\n // _.someFunctionDefinedInTheWebsite();\n\n } catch(e) {\n GM_log(e);\n }\n})(unsafeWindow, unsafeWindow.jQuery);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
232,075
<p>In C and C++ a variable can be marked as <a href="http://en.wikipedia.org/wiki/Volatile_variable" rel="noreferrer"><strong>volatile</strong></a>, which means the compiler will not optimize it because it may be modified external to the declaring object. Is there an equivalent in Delphi programming? If not a keyword, maybe a work around?</p> <p>My thought was to use <strong>Absolute</strong>, but I wasn't sure, and that may introduce other side effects.</p>
[ { "answer_id": 232675, "author": "Thomas Mueller", "author_id": 21506, "author_profile": "https://Stackoverflow.com/users/21506", "pm_score": 0, "selected": false, "text": "var\n MyVarPtr: ^integer;\nbegin\n New(MyVarPtr);\n MyVarPtr^ := 5;\n...\n" }, { "answer_id": 37145389, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 4, "selected": false, "text": "[volatile] volatile volatile type\n TMyClass = class\n private\n [volatile] FMyVariable: TMyType;\n end;\n [volatile]" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255/" ]
232,078
<p>I have three projects. One is a WCF Services Project, one is a WPF Project, and one is a Microsoft Unit Testing Project. I setup the WCF Services project with a data object that looks like this:</p> <pre><code>[DataContract] public enum Priority { Low, Medium, High } [DataContract] public struct TimeInfo { [DataMember] public Int16 EstimatedHours { get; set; } [DataMember] public Int16 ActualHours { get; set; } [DataMember] public DateTime StartDate { get; set; } [DataMember] public DateTime EndDate { get; set; } [DataMember] public DateTime CompletionDate { get; set; } } [DataContract] public class Task { [DataMember] public string Title { get; set; } [DataMember] public string Description { get; set; } [DataMember] public Priority Priority { get; set; } [DataMember] public TimeInfo TimeInformation { get; set; } [DataMember] public Decimal Cost { get; set; } } </code></pre> <p>My contract looks like this:</p> <pre><code>[ServiceContract] public interface ITaskManagement { [OperationContract] List&lt;Task&gt; GetTasks(); [OperationContract] void CreateTask(Task taskToCreate); [OperationContract] void UpdateTask(Task taskToCreate); [OperationContract] void DeleteTask(Task taskToDelete); } </code></pre> <p>When I try to use the service in either the WPF Application or the Unit Test Project with this code:</p> <pre><code>var client = new TaskManagementClient(); textBox1.Text = client.GetTasks().ToString(); client.Close(); </code></pre> <p>I get the following error: "The underlying connection was closed: The connection was closed unexpectedly."</p> <p>The app.config for the WPF and Unit Test Projects look like this:</p> <pre><code>&lt;system.serviceModel&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="WSHttpBinding_ITaskManagement" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"&gt; &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /&gt; &lt;reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /&gt; &lt;security mode="Message"&gt; &lt;transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /&gt; &lt;message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://localhost:9999/TaskManagement.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITaskManagement" contract="TaskManagement.ITaskManagement" name="WSHttpBinding_ITaskManagement"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; </code></pre> <p>and the web.config of the WCF Service looks like this:</p> <pre><code> &lt;system.serviceModel&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="InternetBasedWcfServices.TaskManagementBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="false" /&gt; &lt;/behavior&gt; &lt;behavior name="InternetBasedWcfServices.ScheduleManagementBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="false" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service behaviorConfiguration="InternetBasedWcfServices.TaskManagementBehavior" name="InternetBasedWcfServices.TaskManagement"&gt; &lt;endpoint address="" binding="wsHttpBinding" contract="InternetBasedWcfServices.ITaskManagement"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;/service&gt; &lt;service behaviorConfiguration="InternetBasedWcfServices.ScheduleManagementBehavior" name="InternetBasedWcfServices.ScheduleManagement"&gt; &lt;endpoint address="" binding="wsHttpBinding" contract="InternetBasedWcfServices.IScheduleManagement"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;/system.serviceModel&gt; </code></pre> <p>This is not the first time this has happened, and I'm guessing it is a configuration issue. But each time I've usually just blown away my service and put it back or created a new service project. Then everything works wonderfully. If anyone has any ideas, that would be awesome. Thx.</p> <p>**</p> <blockquote> <p>Updated: I've added comments for more of my troubleshooting on this problem. When an answer is available, if the answer is unpublished, I'll add it as an official "answer".</p> </blockquote> <p>**</p>
[ { "answer_id": 234584, "author": "Adron", "author_id": 29345, "author_profile": "https://Stackoverflow.com/users/29345", "pm_score": 5, "selected": true, "text": "[DataContract]\npublic enum Priority\n{\n [EnumMember]\n Low,\n [EnumMember]\n Medium,\n [EnumMember]\n High\n}\n" }, { "answer_id": 419609, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 3, "selected": false, "text": "public enum Priority\n{ \n Low, \n Medium, \n High\n}\n" }, { "answer_id": 2593256, "author": "Rohini", "author_id": 311070, "author_profile": "https://Stackoverflow.com/users/311070", "pm_score": 1, "selected": false, "text": "new DateTime(adate.Year, adate.Month, firstday).ToString(\"d\", cultureInfo);\n CultureInfo culture = new CultureInfo(this.aculture.Name); \nConvert.ToString(new DateTime(adate.Year, adate.Month, firstday), culture);\n" }, { "answer_id": 7817781, "author": "squig", "author_id": 32254, "author_profile": "https://Stackoverflow.com/users/32254", "pm_score": 3, "selected": false, "text": "<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n" }, { "answer_id": 9524172, "author": "Stewart Anderson", "author_id": 805922, "author_profile": "https://Stackoverflow.com/users/805922", "pm_score": 0, "selected": false, "text": "<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n" }, { "answer_id": 12473530, "author": "Arun M", "author_id": 63709, "author_profile": "https://Stackoverflow.com/users/63709", "pm_score": 1, "selected": false, "text": "DataContract/DataMember Interface Concrete type" }, { "answer_id": 13936160, "author": "Chuck Herrington", "author_id": 1498832, "author_profile": "https://Stackoverflow.com/users/1498832", "pm_score": 1, "selected": false, "text": "Dim oTable As DataTable = New DataTable 'this wont serialize\nDim oTable As DataTable = New DataTable(\"MyTable\") 'this will serialize\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29345/" ]
232,083
<p>Is there a way to know which file is being selected in windows explorer? I've been looking at the tutorial posted here <a href="https://stackoverflow.com/questions/140312/tutorial-for-windows-shell-extensions">Idiots guide to ...</a> but the actions described are:</p> <p>hover</p> <p>context </p> <p>menu properties </p> <p>drag</p> <p>drag and drop</p> <p>I wonder if is there a method that get invoked when a file is selected. For instance to create a thumbnail view of the file. </p> <p>Thanks.</p>
[ { "answer_id": 234584, "author": "Adron", "author_id": 29345, "author_profile": "https://Stackoverflow.com/users/29345", "pm_score": 5, "selected": true, "text": "[DataContract]\npublic enum Priority\n{\n [EnumMember]\n Low,\n [EnumMember]\n Medium,\n [EnumMember]\n High\n}\n" }, { "answer_id": 419609, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 3, "selected": false, "text": "public enum Priority\n{ \n Low, \n Medium, \n High\n}\n" }, { "answer_id": 2593256, "author": "Rohini", "author_id": 311070, "author_profile": "https://Stackoverflow.com/users/311070", "pm_score": 1, "selected": false, "text": "new DateTime(adate.Year, adate.Month, firstday).ToString(\"d\", cultureInfo);\n CultureInfo culture = new CultureInfo(this.aculture.Name); \nConvert.ToString(new DateTime(adate.Year, adate.Month, firstday), culture);\n" }, { "answer_id": 7817781, "author": "squig", "author_id": 32254, "author_profile": "https://Stackoverflow.com/users/32254", "pm_score": 3, "selected": false, "text": "<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n" }, { "answer_id": 9524172, "author": "Stewart Anderson", "author_id": 805922, "author_profile": "https://Stackoverflow.com/users/805922", "pm_score": 0, "selected": false, "text": "<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n" }, { "answer_id": 12473530, "author": "Arun M", "author_id": 63709, "author_profile": "https://Stackoverflow.com/users/63709", "pm_score": 1, "selected": false, "text": "DataContract/DataMember Interface Concrete type" }, { "answer_id": 13936160, "author": "Chuck Herrington", "author_id": 1498832, "author_profile": "https://Stackoverflow.com/users/1498832", "pm_score": 1, "selected": false, "text": "Dim oTable As DataTable = New DataTable 'this wont serialize\nDim oTable As DataTable = New DataTable(\"MyTable\") 'this will serialize\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
232,140
<p>My <sub>crappy</sub> web host did some upgrades the other day and some settings have gone awry, because looking at our company's wiki (MediaWiki), every quote is being escaped with a backslashes. It's not even just data which is being posted (i.e.: the articles) which are affected, but also the standard MediaWiki text. For example,</p> <blockquote> <p>You\'ve followed a link to a page that doesn\'t exist yet. To create the page, start typing in the box below (see the help page for more info). If you are here by mistake, just click your browser\'s \'\'\'back\'\'\' button.</p> </blockquote> <p>The first thing I did was disable <code>magic_quotes_gpc</code> AND <code>magic_quotes_runtime</code> using a <code>.htaccess</code> file, but this is still occurring. My <code>php_info()</code> reports this:</p> <pre><code>Setting Local Value Master Value magic_quotes_gpc Off On magic_quotes_runtime Off On magic_quotes_sybase Off Off </code></pre> <p>Any ideas?</p>
[ { "answer_id": 232242, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "magic_quotes_gpc() if (ini_get('magic_quotes_gpc') ) {\n foreach($_GET as $key=>$value) {\n $_GET[$key] = stripslashes($value);\n }\n} // etc...\n" }, { "answer_id": 232789, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": true, "text": "php_admin_flag php_admin_value .htaccess php.ini" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
232,141
<p>I’m listening to the Hanselminutes Podcast; "StackOverflow uses ASP.NET MVC - Jeff Atwood and his technical team". During the course of the Podcast they are speaking about SQL server and say something along the lines of 'The days of the Stored Procedure are over'. </p> <p>Now I'm not a DBA but this has taken me a bit by surprise. I always assumed that SPs were the way to go for speed (as they are complied) and security not to mention scalability and maintainability. If this is not the case and SPs are on their last legs, what will replace them or what should we be doing in the future?</p>
[ { "answer_id": 232210, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 1, "selected": false, "text": "select a from b where x = y\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26300/" ]
232,144
<p>I have a volunteers_2009 table that lists all the volunteers and a venues table that lists the venues that a volunteer can be assigned to, they are only assigned to one.</p> <p>What I want to do, is print out the number of volunteers assigned to each venue.</p> <p>I want it to print out like this:</p> <p>Name of Venue: # of volunteers</p> <p>table: volunteers_2009 columns: id, name, <code>venue_id</code></p> <p>table: venues columns: id, venue_name</p> <p>They relate by <code>volunteers_2009.venue_id = venues.id</code></p> <p>This is what I have but it is not working properly.</p> <pre><code>$sql = "SELECT venues.venue_name as 'Venue', COUNT(volunteers_2009.id) as 'Number Of Volunteers' FROM venues ven JOIN volunteers_2009 vol ON (venues.id=volunteers_2009.venue_id) GROUP BY venues.venue_name ORDER BY venues.venue_name ASC"; $result = mysql_query($sql); while(list($name,$vols) = mysql_fetch_array($result)) { print '&lt;p&gt;'.$name.': '.$vols.'&lt;/p&gt;'; } </code></pre>
[ { "answer_id": 232159, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "$sql = \"SELECT ven.venue_name as 'Venue', COUNT(vol.id) as 'Number Of \nVolunteers' FROM venues ven JOIN volunteers_2009 vol ON \n(ven.id=vol.venue_id) GROUP BY ven.venue_name ORDER BY ven.venue_name ASC\";\n" }, { "answer_id": 232174, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 0, "selected": false, "text": "$query = \"SELECT ven.venue_name AS 'Venue', count(*) AS 'Number of venues'\n FROM volunteers_2009 AS vol, venues AS ven WHERE vol.venue_id = ven.id \n GROUP BY ven.venue_name\";\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
232,161
<p>I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As such, the launcher project is set as the "Startup Project" and, as a result, it's the only one I can set break points in and debug due to my limited knowledge of VS2005.</p> <p>Is there a way to set multiple breakpoints across my five c++ projects in my single VS solution and debug them at the same time if the launcher project is the only project executed from VS? </p> <p><strong><em>Note:</em></strong> <em>Manually starting new instances of each project via Visual Studio is not an option since their execution needs to be synchronized by the launcher.exe.</em></p> <p>I apologize if this is convoluted, it's the best I can explain it. Thanks in advance for your help! </p>
[ { "answer_id": 232176, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 4, "selected": true, "text": "while( !IsDebuggerPresent() )\n Sleep( 500 );\n while( !System.Diagnostics.Debugger.IsAttached )\n System.Threading.Thread.Sleep( 500 );\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191808/" ]
232,162
<p>I have a bunch of C files that are generated by a collection of python programs that have a number of shared python modules and I need to account for this in my make system.</p> <p>It is easy enough to enumerate which python program need to be run to generate each C file. What I can't find a good solution for is determining which other python files those programs depend on. I need this so make will know what needs regenerating if one of the shared python files changes.</p> <p>Is there a good system for producing make style dependency rules from a collection of python sources?</p>
[ { "answer_id": 232233, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "import import x, y, z\nfrom x import a, b, c\n PYTHONPATH sites sys.path -v >>> import math\n dlopen(\"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload/math.so\", 2);\nimport math # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload/math.so\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471/" ]
232,168
<p>I'm trying to get a file with ant, using the get property. I'm running apache 2, and I can get the file from the indicated URL using wget and firefox, but ant gives me the following error:</p> <pre><code>[get] Error opening connection java.io.IOException: Server returned HTTP response code: 503 for URL: http://localhost/jars/jai_core.jar </code></pre> <p>This is what I'm doing in my build.xml:</p> <pre><code>&lt;get src="http://localhost/jars/jai_core.jar" dest="${build.dir}/lib/jai_core.jar" usetimestamp="true"/&gt; </code></pre> <p>Any idea what could be going wrong?</p> <p><strong>EDIT:</strong> On to something. When I provide the full host name of my box instead of localhost, it works.</p>
[ { "answer_id": 232220, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": true, "text": "src verbose=\"true\" usetimestamp" }, { "answer_id": 232299, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 0, "selected": false, "text": "ant" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434/" ]
232,171
<p>I have an IQueryable and an object of type T.</p> <p>I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName))</p> <p>so ...</p> <pre><code>public IQueryable&lt;T&gt; DoWork&lt;T&gt;(string fieldName) where T : EntityObject { ... T objectOfTypeT = ...; .... return SomeIQueryable&lt;T&gt;().Where(o =&gt; o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName)); } </code></pre> <p>Fyi, GetProperty isn't a valid function. I need something which performs this function.</p> <p>Am I having a Friday afternoon brain melt or is this a complex thing to do?</p> <hr> <p>objectOfTypeT I can do the following ...</p> <pre><code>var matchToValue = Expression.Lambda(ParameterExpression .Property(ParameterExpression.Constant(item), "CustomerKey")) .Compile().DynamicInvoke(); </code></pre> <p>Which works perfectly,now I just need the second part:</p> <p>return SomeIQueryable().Where(o => <strong>o.GetProperty(fieldName)</strong> == matchValue);</p>
[ { "answer_id": 232304, "author": "JTew", "author_id": 25372, "author_profile": "https://Stackoverflow.com/users/25372", "pm_score": 0, "selected": false, "text": "IQueryable<T>().Where(t => \nMemberExpression.Property(MemberExpression.Constant(t), fieldName) == \nParameterExpression.Property(ParameterExpression.Constant(item), fieldName));\n" }, { "answer_id": 232446, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": " var param = Expression.Parameter(typeof(T), \"o\");\n var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));\n var body = Expression.Equal(\n Expression.PropertyOrField(param, fieldName),\n Expression.PropertyOrField(fixedItem, fieldName));\n var lambda = Expression.Lambda<Func<T,bool>>(body,param);\n return source.Where(lambda);\n objectOfTypeT Expression.Constant" }, { "answer_id": 10017752, "author": "Jeroen van Langen", "author_id": 1112646, "author_profile": "https://Stackoverflow.com/users/1112646", "pm_score": 0, "selected": false, "text": " public class Person\n {\n public string Name { get; set; }\n public int Age { get; set; }\n\n }\n\n public Func<T, TRes> GetPropertyFunc<T, TRes>(string propertyName)\n {\n // get the propertyinfo of that property.\n PropertyInfo propInfo = typeof(T).GetProperty(propertyName);\n\n // reference the propertyinfo to get the value directly.\n return (obj) => { return (TRes)propInfo.GetValue(obj, null); };\n }\n\n public void Run()\n {\n List<Person> personList = new List<Person>();\n\n // fill with some data\n personList.Add(new Person { Name = \"John\", Age = 45 });\n personList.Add(new Person { Name = \"Michael\", Age = 31 });\n personList.Add(new Person { Name = \"Rose\", Age = 63 });\n\n // create a lookup functions (should be executed ones)\n Func<Person, string> GetNameValue = GetPropertyFunc<Person, string>(\"Name\");\n Func<Person, int> GetAgeValue = GetPropertyFunc<Person, int>(\"Age\");\n\n\n // filter the list on name\n IEnumerable<Person> filteredOnName = personList.Where(item => GetNameValue(item) == \"Michael\");\n // filter the list on age > 35\n IEnumerable<Person> filteredOnAge = personList.Where(item => GetAgeValue(item) > 35);\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25372/" ]
232,202
<p>I was planning to implememt owner-drawn of CListCtrl. I thought that drawing an item is after the item is inserted into the control. So my method is declare a class which is derived from CListCtrl and override its DrawItem() method. The problem is DrawItem is never invoked after inserting an item. Is there anything wrong with my method?</p> <p>Thank you!</p>
[ { "answer_id": 232209, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 0, "selected": false, "text": "m_myListbox.ModifyStyle(0, LBS_OWNERDRAWFIXED, 0);\n" }, { "answer_id": 232428, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 0, "selected": false, "text": "int CGraphicDroplist::CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct)\n{\n return 0;\n}\n\nvoid CGraphicDroplist::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)\n{\n RECT r = lpDrawItemStruct->rcItem;\n CDC pDC;\n pDC.Attach(lpDrawItemStruct->hDC);\n\n// Put your code to draw the item here.\n\n pDC.Detach();\n}\n\nvoid CGraphicDroplist::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)\n{\n lpMeasureItemStruct->itemHeight = 100;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26404/" ]
232,212
<p>I would guess most people on this site are familiar with tail, if not - it provides a "follow" mode that as text is appended to the file tail will dump those characters out to the terminal.</p> <p>What I am looking for (and possibly to write myself if necessary) is a version of tail that works on binary files. Basically I have a wireless link that I would like to trickle a file across as it comes down from another network link. Looking over the tail source code it wouldn't be too hard to rewrite, but I would rather not reinvent the wheel! This wouldn't strictly be "tail" as I would like the entire file to be copied, but it would watch as new bytes were added and stream those.</p> <p>Ideas?</p>
[ { "answer_id": 232218, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "tail -f somefile | hexdump -C\n" }, { "answer_id": 232229, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 1, "selected": false, "text": "less somefile shift F" }, { "answer_id": 3857534, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 1, "selected": false, "text": "tail" }, { "answer_id": 6171491, "author": "Bin Tail", "author_id": 775608, "author_profile": "https://Stackoverflow.com/users/775608", "pm_score": 2, "selected": false, "text": "# bintail.py -- reads a binary file, writes initial contents to stdout,\n# and writes new data to stdout as it is appended to the file.\n\nimport time\nimport sys\nimport os\nimport msvcrt\nmsvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\n# Time to sleep between file polling (seconds)\nsleep_int = 1\n\ndef main():\n # File is the first argument given to the script (bintail.py file)\n binfile = sys.argv[1]\n\n # Get the initial size of file\n fsize = os.stat(binfile).st_size\n\n # Read entire binary file\n h_file = open(binfile, 'rb')\n h_bytes = h_file.read(128)\n while h_bytes:\n sys.stdout.write(h_bytes)\n h_bytes = h_file.read(128)\n h_file.close()\n\n\n # Loop forever, checking for new content and writing new content to stdout\n while 1:\n current_fsize = os.stat(binfile).st_size\n if current_fsize > fsize:\n h_file = open(binfile, 'rb')\n h_file.seek(fsize)\n h_bytes = h_file.read(128)\n while h_bytes:\n sys.stdout.write(h_bytes)\n h_bytes = h_file.read(128)\n h_file.close()\n fsize = current_fsize\n time.sleep(sleep_int)\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n main()\n else:\n sys.stdout.write(\"No file specified.\")\n" }, { "answer_id": 45293955, "author": "ruief", "author_id": 2046615, "author_profile": "https://Stackoverflow.com/users/2046615", "pm_score": 3, "selected": false, "text": "tail -c +1 -f somefile" }, { "answer_id": 49389210, "author": "Anonymous", "author_id": 1178823, "author_profile": "https://Stackoverflow.com/users/1178823", "pm_score": 0, "selected": false, "text": "cat ./some_file_or_dev | hexdump -C\n [user@localhost input]$ sudo cat /dev/input/event2 | hexdump -C\n00000000 81 32 b1 5a 00 00 00 00 e2 13 02 00 00 00 00 00 |.2.Z............|\n00000010 04 00 04 00 36 00 00 00 81 32 b1 5a 00 00 00 00 |....6....2.Z....|\n00000020 e2 13 02 00 00 00 00 00 01 00 36 00 01 00 00 00 |..........6.....|\n00000030 81 32 b1 5a 00 00 00 00 e2 13 02 00 00 00 00 00 |.2.Z............|\n00000040 00 00 00 00 00 00 00 00 81 32 b1 5a 00 00 00 00 |.........2.Z....|\n00000050 a3 af 02 00 00 00 00 00 04 00 04 00 36 00 00 00 |............6...|\n00000060 81 32 b1 5a 00 00 00 00 a3 af 02 00 00 00 00 00 |.2.Z............|\n^C\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243/" ]
232,222
<p>Are there any Platform agnostic (not CLI) movements to get LINQ going for C++ in some fashion? </p> <p>I mean a great part of server frameworks around the world run on flavors of UNIX and having access to LINQ for C++ on UNIX would probably make lots of people happy!</p>
[ { "answer_id": 2308031, "author": "Chris", "author_id": 36269, "author_profile": "https://Stackoverflow.com/users/36269", "pm_score": 2, "selected": false, "text": "auto" }, { "answer_id": 9160622, "author": "Paolo Severini", "author_id": 980602, "author_profile": "https://Stackoverflow.com/users/980602", "pm_score": 3, "selected": false, "text": "auto source = IEnumerable<int>::Range(0, 10);\n\nauto it = source->Where([](int val) { return ((val % 2) == 0); })\n ->Select<double>([](int val) -> double { return (val * val); }));\n\nforeach<double>(it, [](double& val){\n printf(\"%.2f\\n\", val);\n});\n" }, { "answer_id": 10931413, "author": "Paul Fultz II", "author_id": 375343, "author_profile": "https://Stackoverflow.com/users/375343", "pm_score": 3, "selected": false, "text": "struct student_t\n{\n std::string last_name;\n std::vector<int> scores;\n};\n\nstd::vector<student_t> students = \n{\n {\"Omelchenko\", {97, 72, 81, 60}},\n {\"O'Donnell\", {75, 84, 91, 39}},\n {\"Mortensen\", {88, 94, 65, 85}},\n {\"Garcia\", {97, 89, 85, 82}},\n {\"Beebe\", {35, 72, 91, 70}} \n};\n\nauto scores = LINQ(from(student, students) \n from(score, student.scores) \n where(score > 90) \n select(std::make_pair(student.last_name, score)));\n\nfor (auto x : scores)\n{\n printf(\"%s score: %i\\n\", x.first.c_str(), x.second);\n}\n Omelchenko score: 97\nO'Donnell score: 91\nMortensen score: 94\nGarcia score: 97\nBeebe score: 91\n" }, { "answer_id": 12745814, "author": "ronag", "author_id": 346804, "author_profile": "https://Stackoverflow.com/users/346804", "pm_score": 2, "selected": false, "text": "std::vector<int> xs;\nauto count = from(xs)\n .select([](int x){return x*x;})\n .where([](int x){return x > 16;})\n .count();\nauto xs2 = from(xs)\n .select([](int x){return x*x;})\n .to<std::vector<int>>();\n std::vector<int> xs;\nauto max = from(xs)\n .select([](int x){return x*x;})\n .where([](int x){return x > 16;})\n .max()\n .value_or(default_max_value);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
232,237
<p>What's the best way to return a random line in a text file using C? It has to use the standard I/O library (<code>&lt;stdio.h&gt;</code>) because it's for Nintendo DS homebrew.</p> <p><strong>Clarifications:</strong></p> <ul> <li>Using a header in the file to store the number of lines won't work for what I want to do.</li> <li>I want it to be as random as possible (the best being if each line has an equal probability of being chosen as every other line.)</li> <li>The file will never change while the program is being run. (It's the DS, so no multi-tasking.)</li> </ul>
[ { "answer_id": 232248, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": true, "text": "count = 0;\nwhile (fgets(line, length, stream) != NULL)\n{\n count++;\n if ((rand() * count) / RAND_MAX == 0)\n strcpy(keptline, line);\n}\n if ((rand() / (float)RAND_MAX) <= (1.0 / count)) \n" }, { "answer_id": 232287, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "main(int argc, char **argv)\n{\n FILE *f;\n int nLines = 0;\n char line[1024];\n int randLine;\n int i;\n\n srand(time(0));\n f = fopen(argv[1], \"r\");\n\n/* 1st pass - count the lines. */\n while(!feof(f))\n {\n fgets(line, 1024, f);\n nLines++;\n }\n\n randLine = rand() % nLines;\n printf(\"Chose %d of %d lines\\n\", randLine, nLines);\n\n/* 2nd pass - find the line we want. */\n fseek(f, 0, SEEK_SET);\n for(i = 0; !feof(f) && i <= randLine; i++)\n fgets(line, 1024, f);\n\n printf(\"%s\", line);\n}\n" }, { "answer_id": 267501, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 0, "selected": false, "text": "if(rand() <= RAND_MAX / count)\n" }, { "answer_id": 2933159, "author": "Daniel Trebbien", "author_id": 196844, "author_profile": "https://Stackoverflow.com/users/196844", "pm_score": 3, "selected": false, "text": "length - 1 while count length - 1 length - 1 rand() * count fgets NULL count = 0;\nwhile (fgets(line, length, stream) != NULL)\n{\n char *p = strchr(line, '\\n');\n if (p != NULL) {\n assert(*p == '\\n');\n *p = '\\0'; // trim the newline\n }\n else { // haven't reached EOL yet. Read & discard the rest of the line.\n#define TRASH_LENGTH 1024\n char trash[TRASH_LENGTH];\n while((p = fgets(trash, TRASH_LENGTH, stream)) != NULL) {\n if ((p = strchr(trash, '\\n')) != NULL) // reached EOL\n break;\n }\n }\n assert(strchr(line, '\\n') == NULL); // `line` does not contain a newline\n count++;\n // ...\n int one_chance_in(size_t n)\n{\n if (rand() % n == 0) // `rand` returns an integer in [0, `RAND_MAX`]\n return 1;\n else\n return 0;\n}\n rand() % n rand() rand() % n == 0 RAND_MAX n RAND_MAX RAND_MAX keptline keptline keptline keptline keptline" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
232,267
<p>I've got a complex dialog, and it is full of whitespace and I can't shrink it. In Designer, it has lots of components that then get dynamically hidden, and a few which are dynamically added. I've added dumping of size policies, size hints, and minimum sizes, but still can't figure out why Qt won't let me drag it smaller.</p> <p>There must be some tools or techniques for troubleshooting this. </p> <p>Please share.</p>
[ { "answer_id": 5357723, "author": "Chris", "author_id": 113450, "author_profile": "https://Stackoverflow.com/users/113450", "pm_score": 0, "selected": false, "text": "\nQHBoxLayout* layout = new QHBoxLayout;\nQPushButton* myBtn = new QPushButton(\"Test\");\n\nlayout->insertStretch(1);\nlayout->addWidget(myBtn, 0);\nlayout->insertStretch(1);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19193/" ]
232,269
<p>Is there a way to mount a Linux directory from a different PC to your local Linux PC? How?</p>
[ { "answer_id": 232286, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "/etc/exports mount -t nfs {remote_pc_address}:/remote/dir /some/local/dir\n man" }, { "answer_id": 232340, "author": "Georg Zimmer", "author_id": 3569719, "author_profile": "https://Stackoverflow.com/users/3569719", "pm_score": 5, "selected": false, "text": "sshfs user@remotesystem:/remote/dir /some/local/dir\n" }, { "answer_id": 44303905, "author": "akshaypmurgod", "author_id": 4092467, "author_profile": "https://Stackoverflow.com/users/4092467", "pm_score": 1, "selected": false, "text": "sudo sshfs -o allow_other root@1.2.3.4:/directory local_directory\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
232,271
<p>I have an undefined number of display context and each will display a texture. When I call glGenTextures I get the same name returned across all display contexts. Will this work? Even though they have the same name will they still store and display different textures? If not what should do to get around this? </p>
[ { "answer_id": 232331, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 2, "selected": false, "text": "wglShareLists share aglCreateContext" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55638/" ]
232,274
<p>When I browse code in Vim, I need to see opening and closing parenthesis/ brackets, and pressing <kbd>%</kbd> seems unproductive.</p> <p>I tried <code>:set showmatch</code>, but it makes the cursor jump back and forth when you type in a bracket. But what to do if I am browsing already written code?</p>
[ { "answer_id": 232278, "author": "jcoby", "author_id": 2884, "author_profile": "https://Stackoverflow.com/users/2884", "pm_score": 5, "selected": false, "text": "set showmatch" }, { "answer_id": 232289, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 7, "selected": true, "text": "DoMatchParen\n .vimrc :DoMatchParen\n" }, { "answer_id": 52735311, "author": "Bruce Zhang", "author_id": 5705731, "author_profile": "https://Stackoverflow.com/users/5705731", "pm_score": 1, "selected": false, "text": "/usr/share/vim/vim80/plugin/matchparen.vim Highlight_Matching_Pair() matchaddpos(...)" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29405/" ]
232,280
<p>Im having a problem with a final part of my assignment. We get in a stream of bits, etc etc, in the stream is an integer with the number of 1's in the text portion. I get that integer and its 24 which is correct, now i loop through the text data i get and i try to count all the 1's in there. But my proc is always returning zero.</p> <p>I was able to make sure it was looping properly and it is.</p> <p>The text = Hello which is 16 1's, here is my proc for looping through that text to count the number of ones in it.</p> <pre><code>sub AX,AX sub SI,SI mov bx,[bp+6] ;get message offset @@mainLoop: mov cx,8 mov dh,80h cmp byte ptr [bx + si],0 je @@endChecker @@innerLoop: test byte ptr [bx + si],dh jz @@zeroFound inc AX @@zeroFound: shr bh,1 loop @@innerLoop @@continue: inc si jmp @@mainLoop </code></pre> <p>the rest of the proc is just push/pops. What im wanting this to actually do is use TEST to compare 100000000 to a byte, if its a 1 inc AX else shift right the mask by 1 and loop a whole byte, than inc to next byte and do again.</p>
[ { "answer_id": 232860, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 1, "selected": false, "text": " mov cx, 8\n mov dh, byte ptr [bx+si] \n@@innerLoop:\n add dh, dh \n adc ax, 0\n loop @@innerLoop \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18431/" ]
232,316
<p>I'm tinkering with Silverlight 2.0.</p> <p>I have some images, which I currently have a static URL for the image source. Is there a way to dynamically load the image from a URL path for the site that is hosting the control?</p> <p>Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?</p>
[ { "answer_id": 232414, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 5, "selected": true, "text": " Uri uri = new Uri(\"http://testsvr.com/hello.jpg\");\n YourImage.Source = new BitmapImage(uri);\n" }, { "answer_id": 735677, "author": "mknopf", "author_id": 87680, "author_profile": "https://Stackoverflow.com/users/87680", "pm_score": 2, "selected": false, "text": "img.Source = new BitmapImage(new Uri(\"/images/my-image.jpg\", UriKind.Relative));" }, { "answer_id": 1129711, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "img.Source = new BitmapImage(new Uri(\"/images/my-image.jpg\", UriKind.Relative)); \n" }, { "answer_id": 2828321, "author": "Dan Wygant", "author_id": 340460, "author_profile": "https://Stackoverflow.com/users/340460", "pm_score": 2, "selected": false, "text": "using System.Windows.Resources; // StreamResourceInfo\nusing System.Windows.Media.Imaging; // BitmapImage\n....\n\nStreamResourceInfo sr = Application.GetResourceStream(new Uri(\"SilverlightApplication1;component/MyImage.png\", UriKind.Relative));\nBitmapImage bmp = new BitmapImage();\nbmp.SetSource(sr.Stream);\n" }, { "answer_id": 3853545, "author": "Malcolm Swaine", "author_id": 431246, "author_profile": "https://Stackoverflow.com/users/431246", "pm_score": 3, "selected": false, "text": "// create a new image\nImage image = new Image();\n\n// better to keep this in a global config singleton\nstring hostName = Application.Current.Host.Source.Host; \nif (Application.Current.Host.Source.Port != 80)\n hostName += \":\" + Application.Current.Host.Source.Port;\n\n// set the image source\nimage.Source = new BitmapImage(new Uri(\"http://\" + hostName + \"/cute_kitten112.jpg\", UriKind.Absolute)); \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24126/" ]
232,318
<p>Java requires that you catch all possible exceptions or declare them as thrown in the method signature. This isn't the case with C# but I still feel that it is a good practice to catch all exceptions. Does anybody know of a tool which can process a C# project and point out places where an exception is thrown but not caught? </p>
[ { "answer_id": 232354, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Application.ThreadException += new ThreadExceptionEventHandler( Application_ThreadException );\n\nprivate static void Application_ThreadException( object sender, ThreadExceptionEventArgs e)\n{ \n dispatchException( e.Exception );\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
232,333
<p>How long should it take to run </p> <pre><code>ALTER DATABASE [MySite] SET READ_COMMITTED_SNAPSHOT ON </code></pre> <p>I just ran it and it's taken 10 minutes.</p> <p>How can I check if it is applied?</p>
[ { "answer_id": 232358, "author": "Rick", "author_id": 14138, "author_profile": "https://Stackoverflow.com/users/14138", "pm_score": 7, "selected": true, "text": "sys.databases is_read_committed_snapshot_on sp_who sp_who2" }, { "answer_id": 1253452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "ALTER DATABASE generic SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE\n" }, { "answer_id": 2058352, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 3, "selected": false, "text": "if(charindex('Microsoft SQL Server 2005',@@version) > 0)\nbegin\n declare @sql varchar(8000)\n select @sql = '\n ALTER DATABASE ' + DB_NAME() + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE ;\n ALTER DATABASE ' + DB_NAME() + ' SET READ_COMMITTED_SNAPSHOT ON;\n ALTER DATABASE ' + DB_NAME() + ' SET MULTI_USER;'\n\n Exec(@sql)\nend\n" }, { "answer_id": 10534269, "author": "eLVik", "author_id": 1317263, "author_profile": "https://Stackoverflow.com/users/1317263", "pm_score": 2, "selected": false, "text": "USE Master\nGO\n\nALTER DATABASE [YourDatabase] SET READ_COMMITTED_SNAPSHOT ON\nGO\n" }, { "answer_id": 13731964, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 5, "selected": false, "text": "SELECT is_read_committed_snapshot_on, snapshot_isolation_state_desc,snapshot_isolation_state FROM sys.databases WHERE name='shipperdb'\n\nALTER DATABASE shipperdb SET allow_snapshot_isolation ON\nALTER DATABASE shipperdb SET SINGLE_USER WITH ROLLBACK IMMEDIATE\nALTER DATABASE shipperdb SET read_committed_snapshot ON\nALTER DATABASE shipperdb SET MULTI_USER\n\nSELECT is_read_committed_snapshot_on, snapshot_isolation_state_desc,snapshot_isolation_state FROM sys.databases WHERE name='shipperdb'\n Isolationlevel.ReadCommitted ReadCommitted Snapshot READ COMMITTED SNAPSHOT SNAPSHOT bool snapshotEnabled = true;\n\nusing (var t = new TransactionScope(TransactionScopeOption.Required,\n new TransactionOptions\n{\n IsolationLevel = IsolationLevel.ReadCommitted\n}))\n{\n using (var shipDB = new ShipperDBDataContext())\n {\n\n }\n}\n using (var tran = new TransactionScope(TransactionScopeOption.Suppress))\n {\n using (var shipDB = new ShipperDBDataContext())\n { \n // initialize cache\n }\n }\n Deadlocked" }, { "answer_id": 45599399, "author": "Jeff Mergler", "author_id": 1129926, "author_profile": "https://Stackoverflow.com/users/1129926", "pm_score": 3, "selected": false, "text": "ALTER DATABASE MyDB SET READ_COMMITTED_SNAPSHOT ON\nGO\n USE master\nGO\n\n/** \n * Cut off live connections\n * This will roll back any open transactions after 30 seconds and\n * restricts access to the DB to logins with sysadmin, dbcreator or\n * db_owner roles\n */\nALTER DATABASE MyDB SET RESTRICTED_USER WITH ROLLBACK AFTER 30 SECONDS\nGO\n\n-- Enable RCSI for MyDB\nALTER DATABASE MyDB SET READ_COMMITTED_SNAPSHOT ON\nGO\n\n-- Allow connections to be established once again\nALTER DATABASE MyDB SET MULTI_USER\nGO\n\n-- Check the status afterwards to make sure it worked\nSELECT is_read_committed_snapshot_on\nFROM sys.databases\nWHERE [name] = 'MyDB '\n" }, { "answer_id": 72993041, "author": "Salim", "author_id": 1306836, "author_profile": "https://Stackoverflow.com/users/1306836", "pm_score": 0, "selected": false, "text": "ALTER DATABASE DBNAME SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
232,344
<p>I have some code which ignores a specific exception. </p> <pre><code>try { foreach (FileInfo fi in di.GetFiles()) { collection.Add(fi.Name); } foreach (DirectoryInfo d in di.GetDirectories()) { populateItems(collection, d); } } catch (UnauthorizedAccessException ex) { //ignore and move onto next directory } </code></pre> <p>of course this results in a compile time warning as ex is unused. Is there some standard accept noop which should be used to remove this warning? </p>
[ { "answer_id": 232350, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": "catch (UnauthorizedAccessException) {}\n" }, { "answer_id": 232363, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 1, "selected": false, "text": "Debug.WriteLine(ex.message)\n" }, { "answer_id": 232367, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "catch (UnauthorizedAccessException) {}\n" }, { "answer_id": 232745, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "foreach (FileInfo fi in di.GetFiles())\n{\n //TODO: what exceptions should be handled here?\n collection.Add(fi.Name);\n}\n\n// populate collection for each directory we have authorized access to\nforeach (DirectoryInfo d in di.GetDirectories())\n{\n try\n {\n populateItems(collection, d);\n }\n catch (UnauthorizedAccessException)\n {\n //ignore and move onto next directory\n }\n}\n" }, { "answer_id": 937550, "author": "Matthew", "author_id": 115204, "author_profile": "https://Stackoverflow.com/users/115204", "pm_score": 1, "selected": false, "text": "try\n{\n // do something\n // ...\n}\ncatch(UnauthorizedAccessException)\n{\n // react to this exception in some way\n // ...\n\n // let _someone_ know the exception happened\n throw;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
232,347
<p>Many programs include an auto-updater, where the program occasionally looks online for updates, and then downloads and applies any updates that are found. Program bugs are fixed, supporting files are modified, and things are (usually) made better.</p> <p>Unfortunately no matter how hard I look, I can't find information on this process anywhere. It seems like the auto-updaters that have been implemented have either been proprietary or not considered important.</p> <p>It seems fairly easy to implement the system that looks for updates on a network and downloads them if they are available. That part of the auto-updater will change significantly from implementation to implementation. The question is what are the different approaches of <strong>applying</strong> patches. Just downloading files and replacing old ones with new ones, running a migration script that was downloaded, monkey patching parts of the system, etc.? Concepts are preferred, but examples in Java, C, Python, Ruby, Lisp, etc. would be appreciated.</p>
[ { "answer_id": 339731, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 3, "selected": false, "text": "Version GetLatestVersion() {\nHttpWebRequestrequest = (HttpWebRequest)WebRequest.Create(new Uri(new Uri(http://example.net), \"version.txt));\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\nif (request.HaveResponse)\n{\n StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.Default);\n return new Version(stream.ReadLine());\n}\nelse\n{\n return null;\n}\n}\n\nVersion latest = GetLatestVersion();\nVersion current = new Version(Application.ProductVersion);\nif (current < latest)\n{\n // you need an update\n}\nelse\n{\n // you are up-to-date\n}\n" }, { "answer_id": 486796, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 2, "selected": false, "text": "svn update" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306/" ]
232,386
<p>I'm trying to make an item on ToolBar (specifically a Label, TextBlock, or a TextBox) That will fill all available horizontal space. I've gotten the ToolBar itself to stretch out by taking it out of its ToolBarTray, but I can't figure out how to make items stretch.</p> <p>I tried setting Width to Percenatage or Star values, but it doesn't accept that. Setting Horizontal(Content)Alignment to Stretch in various places seems to have no effect either.</p>
[ { "answer_id": 299786, "author": "Robert Macnee", "author_id": 19273, "author_profile": "https://Stackoverflow.com/users/19273", "pm_score": 4, "selected": false, "text": "<DockPanel>\n <ToolBar DockPanel.Dock=\"Top\">\n <ToolBar.Resources>\n <Style TargetType=\"{x:Type ToolBarPanel}\">\n <Setter Property=\"Orientation\" Value=\"Vertical\"/>\n </Style>\n </ToolBar.Resources>\n <ComboBox HorizontalAlignment=\"Stretch\" SelectedIndex=\"0\">\n <ComboBoxItem>A B C</ComboBoxItem>\n <ComboBoxItem>1 2 3</ComboBoxItem>\n <ComboBoxItem>Do Re Mi</ComboBoxItem>\n </ComboBox>\n </ToolBar>\n <Border Margin=\"10\" BorderBrush=\"Yellow\" BorderThickness=\"3\"/>\n</DockPanel>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7649/" ]
232,387
<p>Suppose I have a table with a numeric column (lets call it "score").</p> <p>I'd like to generate a table of counts, that shows how many times scores appeared in each range.</p> <p>For example:</p> <pre> score range | number of occurrences ------------------------------------- 0-9 | 11 10-19 | 14 20-29 | 3 ... | ... </pre> <p>In this example there were 11 rows with scores in the range of 0 to 9, 14 rows with scores in the range of 10 to 19, and 3 rows with scores in the range 20-29.</p> <p>Is there an easy way to set this up? What do you recommend?</p>
[ { "answer_id": 232405, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "create table scores (\n user_id int,\n score int\n)\n\nselect t.range as [score range], count(*) as [number of occurences]\nfrom (\n select user_id,\n case when score >= 0 and score < 10 then '0-9'\n case when score >= 10 and score < 20 then '10-19'\n ...\n else '90-99' as range\n from scores) t\ngroup by t.range\n" }, { "answer_id": 232406, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "select cast(score/10 as varchar) + '-' + cast(score/10+9 as varchar), \n count(*)\nfrom scores\ngroup by score/10\n" }, { "answer_id": 232420, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 5, "selected": false, "text": "|| select (score/10)*10 || '-' || (score/10)*10+9 as scorerange, count(*)\nfrom scores\ngroup by score/10\norder by 1\n scorerange | count \n------------+-------\n 0-9 | 11\n 10-19 | 14\n 20-29 | 3\n 30-39 | 2\n" }, { "answer_id": 232433, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": -1, "selected": false, "text": "on insert" }, { "answer_id": 232449, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 2, "selected": false, "text": "declare @RangeWidth int\n\nset @RangeWidth = 10\n\nselect\n Floor(Score/@RangeWidth) as LowerBound,\n Floor(Score/@RangeWidth)+@RangeWidth as UpperBound,\n Count(*)\nFrom\n ScoreTable\ngroup by\n Floor(Score/@RangeWidth)\n" }, { "answer_id": 232463, "author": "Ken Paul", "author_id": 26671, "author_profile": "https://Stackoverflow.com/users/26671", "pm_score": 5, "selected": false, "text": "select t.range as [score range], count(*) as [number of occurences]\nfrom (\n select case \n when score between 0 and 9 then ' 0-9 '\n when score between 10 and 19 then '10-19'\n when score between 20 and 29 then '20-29'\n ...\n else '90-99' end as range\n from scores) t\ngroup by t.range\n" }, { "answer_id": 232598, "author": "Timothy Walters", "author_id": 14454, "author_profile": "https://Stackoverflow.com/users/14454", "pm_score": 4, "selected": false, "text": "SELECT \n [score range] = CAST((Score/10)*10 AS VARCHAR) + ' - ' + CAST((Score/10)*10+9 AS VARCHAR), \n [number of occurrences] = COUNT(*)\nFROM #Scores\nGROUP BY Score/10\nORDER BY Score/10\n" }, { "answer_id": 233223, "author": "Ron Tuffin", "author_id": 939, "author_profile": "https://Stackoverflow.com/users/939", "pm_score": 8, "selected": true, "text": "select t.range as [score range], count(*) as [number of occurences]\nfrom (\n select case \n when score between 0 and 9 then ' 0- 9'\n when score between 10 and 19 then '10-19'\n else '20-99' end as range\n from scores) t\ngroup by t.range\n select t.range as [score range], count(*) as [number of occurrences]\nfrom (\n select user_id,\n case when score >= 0 and score< 10 then '0-9'\n when score >= 10 and score< 20 then '10-19'\n else '20-99' end as range\n from scores) t\ngroup by t.range\n" }, { "answer_id": 236314, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 5, "selected": false, "text": "LowerLimit UpperLimit Range \n0 9 '0-9'\n10 19 '10-19'\n20 29 '20-29'\n30 39 '30-39'\n Select\n Range as [Score Range],\n Count(*) as [Number of Occurences]\nfrom\n Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit\ngroup by Range\n" }, { "answer_id": 15715413, "author": "Danny Hui", "author_id": 2226449, "author_profile": "https://Stackoverflow.com/users/2226449", "pm_score": 1, "selected": false, "text": "select t.blah as [score range], count(*) as [number of occurences]\nfrom (\n select case \n when score between 0 and 9 then ' 0-9 '\n when score between 10 and 19 then '10-19'\n when score between 20 and 29 then '20-29'\n ...\n else '90-99' end as blah\n from scores) t\ngroup by t.blah\n" }, { "answer_id": 24758052, "author": "Kevin Hogg", "author_id": 687441, "author_profile": "https://Stackoverflow.com/users/687441", "pm_score": 1, "selected": false, "text": "Range SELECT t.range AS ScoreRange,\n COUNT(*) AS NumberOfOccurrences\n FROM (SELECT CASE\n WHEN score BETWEEN 0 AND 9 THEN '00-09'\n WHEN score BETWEEN 10 AND 19 THEN '10-19'\n ELSE '20-99'\n END AS Range\n FROM Scores) t\n GROUP BY t.Range\n SELECT t.range AS ScoreRange,\n COUNT(*) AS NumberOfOccurrences\n FROM (SELECT CASE\n WHEN score BETWEEN 0 AND 9 THEN '000-009'\n WHEN score BETWEEN 10 AND 19 THEN '010-019'\n WHEN score BETWEEN 20 AND 99 THEN '020-099'\n ELSE '100-999'\n END AS Range\n FROM Scores) t\n GROUP BY t.Range\n" }, { "answer_id": 27131866, "author": "JoshNaro", "author_id": 7423, "author_profile": "https://Stackoverflow.com/users/7423", "pm_score": 2, "selected": false, "text": "select t.range as [score range], count(*) as [number of occurences]\nfrom (\n select FLOOR(score/10) as range\n from scores) t\ngroup by t.range\n" }, { "answer_id": 33000669, "author": "trevorgrayson", "author_id": 965161, "author_profile": "https://Stackoverflow.com/users/965161", "pm_score": 3, "selected": false, "text": "SELECT CONCAT(range,'-',range+9), COUNT(range)\nFROM (\n SELECT \n score - (score % 10) as range\n FROM scores\n)\n" }, { "answer_id": 33830966, "author": "Stubo", "author_id": 5586547, "author_profile": "https://Stackoverflow.com/users/5586547", "pm_score": 1, "selected": false, "text": "SELECT (str(range) + \"-\" + str(range + 9) ) AS [Score range], COUNT(score) AS [number of occurances]\nFROM (SELECT score, int(score / 10 ) * 10 AS range FROM scoredata ) \nGROUP BY range;\n" }, { "answer_id": 63391773, "author": "user8494871", "author_id": 8494871, "author_profile": "https://Stackoverflow.com/users/8494871", "pm_score": 0, "selected": false, "text": "select t.range as score, count(*) as Count \nfrom (\n select UserId,\n case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then '0-5'\n when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then '5-10'\n when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then '10-15'\n when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then '15-20' \n else ' 20+' end as range\n ,case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then 1\n when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then 2\n when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then 3\n when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then 4 \n else 5 end as pd\n from score table\n ) t\n\ngroup by t.range,pd order by pd\n" }, { "answer_id": 65428925, "author": "April Rose Garcia", "author_id": 12310251, "author_profile": "https://Stackoverflow.com/users/12310251", "pm_score": 0, "selected": false, "text": "SELECT --MIN(score), MAX(score),\n [score range] = CAST(ROUND(score-5,-1)AS VARCHAR) + ' - ' + CAST((ROUND(score-5,-1)+10)AS VARCHAR),\n [number of occurrences] = COUNT(*)\nFROM order\nGROUP BY CAST(ROUND(score-5,-1)AS VARCHAR) + ' - ' + CAST((ROUND(score-5,-1)+10)AS VARCHAR)\nORDER BY MIN(score)\n\n\n" }, { "answer_id": 72761784, "author": "Alex Punnen", "author_id": 429476, "author_profile": "https://Stackoverflow.com/users/429476", "pm_score": 0, "selected": false, "text": "select t.range, count(*) as \"Number of Occurance\", ROUND(AVG(fare_amount),2) as \"Avg\",\n ROUND(MAX(fare_amount),2) as \"Max\" ,ROUND(MIN(fare_amount),2) as \"Min\" \nfrom (\n select \n case \n when trip_distance between 0 and 9 then ' 0-9 '\n when trip_distance between 10 and 19 then '10-19'\n when trip_distance between 20 and 29 then '20-29'\n when trip_distance between 30 and 39 then '30-39'\n else '> 39' \n end as range ,fare_amount \n from nyc_in_parquet.tlc_yellow_trip_2022) t\n where fare_amount > 1 and fare_amount < 401092\ngroup by t.range;\n\n range | Number of Occurance | Avg | Max | Min \n-------+---------------------+--------+-------+------\n 0-9 | 2260865 | 10.28 | 720.0 | 1.11 \n 30-39 | 1107 | 104.28 | 280.0 | 5.0 \n 10-19 | 126136 | 43.8 | 413.5 | 2.0 \n > 39 | 42556 | 39.11 | 668.0 | 1.99 \n 20-29 | 19133 | 58.62 | 250.0 | 2.5 \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31060/" ]
232,395
<p>I have a two-dimensional array (of Strings) which make up my data table (of rows and columns). I want to sort this array by any column. I tried to find an algorithm for doing this in C#, but have not been successful.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 232444, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 6, "selected": true, "text": "// assumes stringdata[row, col] is your 2D string array\nDataTable dt = new DataTable();\n// assumes first row contains column names:\nfor (int col = 0; col < stringdata.GetLength(1); col++)\n{\n dt.Columns.Add(stringdata[0, col]);\n}\n// load data from string array to data table:\nfor (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)\n{\n DataRow row = dt.NewRow();\n for (int col = 0; col < stringdata.GetLength(1); col++)\n {\n row[col] = stringdata[rowindex, col];\n }\n dt.Rows.Add(row);\n}\n// sort by third column:\nDataRow[] sortedrows = dt.Select(\"\", \"3\");\n// sort by column name, descending:\nsortedrows = dt.Select(\"\", \"COLUMN3 DESC\");\n" }, { "answer_id": 232452, "author": "Moishe Lettvin", "author_id": 23786, "author_profile": "https://Stackoverflow.com/users/23786", "pm_score": 0, "selected": false, "text": "string values[rows][columns]\n value[1][3] std::string values_by_column[columns][rows];\n\nfor (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n values_by_column[column][row] = values[row][column]\n\nsort_array(values_by_column[column])\n\nfor (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n values[row][column] = values_by_column[column][row]\n string values_to_sort[rows]\n for (int i = 0; i < rows; i++)\n values_to_sort[i] = values[i][column_to_sort]\n\n sort_array(values_to_sort)\n\n for (int i = 0; i < rows; i++)\n values[i][column_to_sort] = values_to_sort[i]\n" }, { "answer_id": 232464, "author": "David Hall", "author_id": 2660, "author_profile": "https://Stackoverflow.com/users/2660", "pm_score": 1, "selected": false, "text": "string[][] array = new string[3][];\n\narray[0] = new string[3] { \"apple\", \"apple\", \"apple\" };\narray[1] = new string[3] { \"banana\", \"banana\", \"dog\" };\narray[2] = new string[3] { \"cat\", \"hippo\", \"cat\" }; \n\nfor (int i = 0; i < 3; i++)\n{\n Console.WriteLine(String.Format(\"{0} {1} {2}\", array[i][0], array[i][1], array[i][2]));\n}\n\nint j = 2;\n\nArray.Sort(array, delegate(object[] x, object[] y)\n {\n return (x[j] as IComparable).CompareTo(y[ j ]);\n }\n);\n\nfor (int i = 0; i < 3; i++)\n{\n Console.WriteLine(String.Format(\"{0} {1} {2}\", array[i][0], array[i][1], array[i][2]));\n}\n" }, { "answer_id": 232465, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": false, "text": "[,] [][] Comparison<T> List<T[]> static void Main()\n{ // could just as easily be string...\n int[][] data = new int[][] { \n new int[] {1,2,3}, \n new int[] {2,3,4}, \n new int[] {2,4,1} \n }; \n Sort<int>(data, 2); \n} \nprivate static void Sort<T>(T[][] data, int col) \n{ \n Comparer<T> comparer = Comparer<T>.Default;\n Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); \n} \n static T[][] ToJagged<T>(this T[,] array) {\n int height = array.GetLength(0), width = array.GetLength(1);\n T[][] jagged = new T[height][];\n\n for (int i = 0; i < height; i++)\n {\n T[] row = new T[width];\n for (int j = 0; j < width; j++)\n {\n row[j] = array[i, j];\n }\n jagged[i] = row;\n }\n return jagged;\n}\nstatic T[,] ToRectangular<T>(this T[][] array)\n{\n int height = array.Length, width = array[0].Length;\n T[,] rect = new T[height, width];\n for (int i = 0; i < height; i++)\n {\n T[] row = array[i];\n for (int j = 0; j < width; j++)\n {\n rect[i, j] = row[j];\n }\n }\n return rect;\n}\n// fill an existing rectangular array from a jagged array\nstatic void WriteRows<T>(this T[,] array, params T[][] rows)\n{\n for (int i = 0; i < rows.Length; i++)\n {\n T[] row = rows[i];\n for (int j = 0; j < row.Length; j++)\n {\n array[i, j] = row[j];\n }\n }\n}\n" }, { "answer_id": 232530, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "\n public class Pair<T> {\n public int Index;\n public T Value;\n public Pair(int i, T v) {\n Index = i;\n Value = v;\n }\n }\n static IEnumerable<Pair<T>> Iterate<T>(this IEnumerable<T> source) {\n int index = 0;\n foreach ( var cur in source) {\n yield return new Pair<T>(index,cur);\n index++;\n }\n }\n static void Sort2d(string[][] source, IComparer comp, int col) {\n var colValues = source.Iterate()\n .Select(x => new Pair<string>(x.Index,source[x.Index][col])).ToList();\n colValues.Sort((l,r) => comp.Compare(l.Value, r.Value));\n var temp = new string[source[0].Length];\n var rest = colValues.Iterate();\n while ( rest.Any() ) {\n var pair = rest.First();\n var cur = pair.Value;\n var i = pair.Index;\n if (i == cur.Index ) {\n rest = rest.Skip(1);\n continue;\n }\n\n Array.Copy(source[i], temp, temp.Length);\n Array.Copy(source[cur.Index], source[i], temp.Length);\n Array.Copy(temp, source[cur.Index], temp.Length);\n rest = rest.Skip(1);\n rest.Where(x => x.Value.Index == i).First().Value.Index = cur.Index;\n }\n }\n\n public static void Test1() {\n var source = new string[][] \n {\n new string[]{ \"foo\", \"bar\", \"4\" },\n new string[] { \"jack\", \"dog\", \"1\" },\n new string[]{ \"boy\", \"ball\", \"2\" },\n new string[]{ \"yellow\", \"green\", \"3\" }\n };\n Sort2d(source, StringComparer.Ordinal, 2);\n }\n" }, { "answer_id": 3161080, "author": "Jeffrey Roughgarden", "author_id": 381465, "author_profile": "https://Stackoverflow.com/users/381465", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n{\n SqlConnection cnnX = new SqlConnection(\"Data Source=r90jroughgarden\\\\;Initial Catalog=Sandbox;Integrated Security=True\");\n SqlCommand cmdX = new SqlCommand(\"select * from tblToBeSorted\", cnnX);\n cmdX.CommandType = CommandType.Text;\n SqlDataReader rdrX = null;\n if (cnnX.State == ConnectionState.Closed) cnnX.Open();\n\n int[,] aintSortingArray = new int[100, 4]; //i, elementid, planid, timeid\n\n try\n {\n //Load unsorted table data from DB to array\n rdrX = cmdX.ExecuteReader();\n if (!rdrX.HasRows) return;\n\n int i = -1;\n while (rdrX.Read() && i < 100)\n {\n i++;\n aintSortingArray[i, 0] = rdrX.GetInt32(0);\n aintSortingArray[i, 1] = rdrX.GetInt32(1);\n aintSortingArray[i, 2] = rdrX.GetInt32(2);\n aintSortingArray[i, 3] = rdrX.GetInt32(3);\n }\n rdrX.Close();\n\n DataTable dtblX = new DataTable();\n dtblX.Columns.Add(\"ChangeID\");\n dtblX.Columns.Add(\"ElementID\");\n dtblX.Columns.Add(\"PlanID\");\n dtblX.Columns.Add(\"TimeID\");\n for (int j = 0; j < i; j++)\n {\n DataRow drowX = dtblX.NewRow();\n for (int k = 0; k < 4; k++)\n {\n drowX[k] = aintSortingArray[j, k];\n }\n dtblX.Rows.Add(drowX);\n }\n\n DataRow[] adrowX = dtblX.Select(\"\", \"ElementID, PlanID, TimeID\");\n adrowX = dtblX.Select(\"\", \"ElementID desc, PlanID asc, TimeID desc\");\n\n }\n catch (Exception ex)\n {\n string strErrMsg = ex.Message;\n }\n finally\n {\n if (cnnX.State == ConnectionState.Open) cnnX.Close();\n }\n}\n" }, { "answer_id": 6483498, "author": "Gregory Massov", "author_id": 816058, "author_profile": "https://Stackoverflow.com/users/816058", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n int[,] arr = { { 20, 9, 11 }, { 30, 5, 6 } };\n Console.WriteLine(\"before\");\n for (int i = 0; i < arr.GetLength(0); i++)\n {\n for (int j = 0; j < arr.GetLength(1); j++)\n {\n Console.Write(\"{0,3}\", arr[i, j]);\n }\n Console.WriteLine();\n }\n Console.WriteLine(\"After\");\n\n for (int i = 0; i < arr.GetLength(0); i++) // Array Sorting\n {\n for (int j = arr.GetLength(1) - 1; j > 0; j--)\n {\n\n for (int k = 0; k < j; k++)\n {\n if (arr[i, k] > arr[i, k + 1])\n {\n int temp = arr[i, k];\n arr[i, k] = arr[i, k + 1];\n arr[i, k + 1] = temp;\n }\n }\n }\n Console.WriteLine();\n }\n\n for (int i = 0; i < arr.GetLength(0); i++)\n {\n for (int j = 0; j < arr.GetLength(1); j++)\n {\n Console.Write(\"{0,3}\", arr[i, j]);\n }\n Console.WriteLine();\n }\n }\n }\n}\n" }, { "answer_id": 18260685, "author": "Chuck Wilbur", "author_id": 99640, "author_profile": "https://Stackoverflow.com/users/99640", "pm_score": 0, "selected": false, "text": "class Array2DSort : IComparer<int>\n{\n // maintain a reference to the 2-dimensional array being sorted\n string[,] _sortArray;\n int[] _tagArray;\n int _sortIndex;\n\n protected string[,] SortArray { get { return _sortArray; } }\n\n // constructor initializes the sortArray reference\n public Array2DSort(string[,] theArray, int sortIndex)\n {\n _sortArray = theArray;\n _tagArray = new int[_sortArray.GetLength(0)];\n for (int i = 0; i < _sortArray.GetLength(0); ++i) _tagArray[i] = i;\n _sortIndex = sortIndex;\n }\n\n public string[,] ToSortedArray()\n {\n Array.Sort(_tagArray, this);\n string[,] result = new string[\n _sortArray.GetLength(0), _sortArray.GetLength(1)];\n for (int i = 0; i < _sortArray.GetLength(0); i++)\n {\n for (int j = 0; j < _sortArray.GetLength(1); j++)\n {\n result[i, j] = _sortArray[_tagArray[i], j];\n }\n }\n return result;\n }\n\n // x and y are integer row numbers into the sortArray\n public virtual int Compare(int x, int y)\n {\n if (_sortIndex < 0) return 0;\n return CompareStrings(x, y, _sortIndex);\n }\n\n protected int CompareStrings(int x, int y, int col)\n {\n return _sortArray[x, col].CompareTo(_sortArray[y, col]);\n }\n}\n data Array2DSort comparer = new Array2DSort(data, 5);\n string[,] sortedData = comparer.ToSortedArray();\n Compare SortArray CompareStrings SortArray[x, col].CompareTo(SortArray[y, col])" }, { "answer_id": 38155641, "author": "Mamoon Ahmed", "author_id": 5647662, "author_profile": "https://Stackoverflow.com/users/5647662", "pm_score": 0, "selected": false, "text": "{\nm,m,m\na,a,a\nb,b,b\nj,j,j\nk,l,m\n}\n string[] newArr = new string[arr.length]\nfor(int a=0;a<arr.length;a++)\n newArr[a] = arr[a][1] + a;\n\n// create new array that contains index number at the end and also the column values\nArray.Sort(newArr);\nfor(int a=0;a<newArr.length;a++)\n{\n int index = Convert.ToInt32(newArr[a][newArr[a].Length -1]);\n //swap whole row with tow at current index\n if(index != a)\n {\n string[] arr2 = arr[a];\n arr[a] = arr[index];\n arr[index] = arr2;\n }\n}\n" }, { "answer_id": 59003014, "author": "AllenJolley", "author_id": 12418768, "author_profile": "https://Stackoverflow.com/users/12418768", "pm_score": 3, "selected": false, "text": "Array.Sort(array, (a, b) => { return a[0] - b[0]; });\n" }, { "answer_id": 70630809, "author": "Shubham Sharma", "author_id": 4446810, "author_profile": "https://Stackoverflow.com/users/4446810", "pm_score": -1, "selected": false, "text": "var myOrderedRows = myArray.OrderBy(row => row[columnIndex]).ToArray();\n ToArray() Array.Sort(myArray, (p, q) => p[columnIndex].CompareTo(q[columnIndex]));\n" }, { "answer_id": 73190340, "author": "Jan Lacina", "author_id": 14104519, "author_profile": "https://Stackoverflow.com/users/14104519", "pm_score": 0, "selected": false, "text": "for (int i = n-1; i >= 0; i--)\n{\n resultsAsArray = resultsAsArray.OrderBy(x => x[i]).ToArray();\n}\n\n var original = new int[][] { new int[] { -3, 1, 2 }, new int[] { -2, -1, 3 }, new int[] { -3, -1, 4 }, new int[] { -3, -2, 5 } };\n\n*var processed = new int[][] { new int[] { -3, -2, 5 }, new int[] { -3, -1, 4 }, new int[] { -3, 1, 2 }, new int[] { -2, -1, 3 } };\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15052/" ]
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Parent) </code></pre> <p>How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"}) </code></pre> <p>but that causes the admin interface to not list any children.</p>
[ { "answer_id": 232644, "author": "Eric Holscher", "author_id": 4169, "author_profile": "https://Stackoverflow.com/users/4169", "pm_score": 4, "selected": false, "text": "class Parent(models.Model):\n name = models.CharField(max_length=255)\n\nclass Child(models.Model):\n name = models.CharField(max_length=255)\n myparent = models.ForeignKey(Parent)\n parent_object.child_set.all() related_name='children' parent_object.children.all()" }, { "answer_id": 234325, "author": "Jeff Mc", "author_id": 25521, "author_profile": "https://Stackoverflow.com/users/25521", "pm_score": 2, "selected": false, "text": "class Parent(models.Model):\n name = models.CharField(max_length=255)\n favoritechild = models.ForeignKey(\"Child\", blank=True, null=True)\n def save(self, force_insert=False, force_update=False):\n if self.favoritechild is not None and self.favoritechild.myparent.id != self.id:\n raise Exception(\"You must select one of your own children as your favorite\")\n super(Parent, self).save(force_insert, force_update)\n" }, { "answer_id": 252087, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 7, "selected": true, "text": "@classmethod\ndef _product_list(cls):\n \"\"\"\n return a list containing the one product_id contained in the request URL,\n or a query containing all valid product_ids if not id present in URL\n\n used to limit the choice of foreign key object to those related to the current product\n \"\"\"\n id = threadlocals.get_current_product()\n if id is not None:\n return [id]\n else:\n return Product.objects.all().values('pk').query\n product = models.ForeignKey(\n Product,\n limit_choices_to={\n id__in=BaseModel._product_list,\n },\n)\n" }, { "answer_id": 1749330, "author": "Anentropic", "author_id": 202168, "author_profile": "https://Stackoverflow.com/users/202168", "pm_score": 2, "selected": false, "text": "class MyModel(models.Model):\n def _get_self_pk(self):\n return self.pk\n favourite = models.ForeignKey(limit_choices_to={'myparent__pk':_get_self_pk})\n" }, { "answer_id": 4653418, "author": "White Box Dev", "author_id": 105792, "author_profile": "https://Stackoverflow.com/users/105792", "pm_score": 4, "selected": false, "text": "class MyModelAdmin(admin.ModelAdmin):\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"favoritechild\":\n kwargs[\"queryset\"] = Child.objects.filter(myparent=request.object_id)\n return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)\n" }, { "answer_id": 19556353, "author": "s29", "author_id": 489638, "author_profile": "https://Stackoverflow.com/users/489638", "pm_score": 5, "selected": false, "text": "from django import forms\nfrom django.contrib import admin \nfrom models import *\n\nclass SupplierAdminForm(forms.ModelForm):\n class Meta:\n model = Supplier\n fields = \"__all__\" # for Django 1.8+\n\n\n def __init__(self, *args, **kwargs):\n super(SupplierAdminForm, self).__init__(*args, **kwargs)\n if self.instance:\n self.fields['cat'].queryset = Cat.objects.filter(supplier=self.instance)\n\nclass SupplierAdmin(admin.ModelAdmin):\n form = SupplierAdminForm\n" }, { "answer_id": 29455444, "author": "wasabigeek", "author_id": 1839532, "author_profile": "https://Stackoverflow.com/users/1839532", "pm_score": 4, "selected": false, "text": "formfield_for_foreignkey admin.py class ParentAdmin(admin.ModelAdmin):\n def get_form(self, request, obj=None, **kwargs):\n self.instance = obj\n return super(ParentAdmin, self).get_form(request, obj=obj, **kwargs)\n\n def formfield_for_foreignkey(self, db_field, request=None, **kwargs):\n if db_field.name == 'favoritechild' and self.instance: \n kwargs['queryset'] = Child.objects.filter(myparent=self.instance.pk)\n return super(ChildAdmin, self).formfield_for_foreignkey(db_field, request=request, **kwargs)\n" }, { "answer_id": 35395212, "author": "Øyvind Saltvik", "author_id": 5925860, "author_profile": "https://Stackoverflow.com/users/5925860", "pm_score": -1, "selected": false, "text": "from django.contrib import admin\nfrom sopin.menus.models import Restaurant, DishType\n\nclass ObjInline(admin.TabularInline):\n def __init__(self, parent_model, admin_site, obj=None):\n self.obj = obj\n super(ObjInline, self).__init__(parent_model, admin_site)\n\nclass ObjAdmin(admin.ModelAdmin):\n\n def get_inline_instances(self, request, obj=None):\n inline_instances = []\n for inline_class in self.inlines:\n inline = inline_class(self.model, self.admin_site, obj)\n if request:\n if not (inline.has_add_permission(request) or\n inline.has_change_permission(request, obj) or\n inline.has_delete_permission(request, obj)):\n continue\n if not inline.has_add_permission(request):\n inline.max_num = 0\n inline_instances.append(inline)\n\n return inline_instances\n\n\n\nclass DishTypeInline(ObjInline):\n model = DishType\n\n def formfield_for_foreignkey(self, db_field, request=None, **kwargs):\n field = super(DishTypeInline, self).formfield_for_foreignkey(db_field, request, **kwargs)\n if db_field.name == 'dishtype':\n if self.obj is not None:\n field.queryset = field.queryset.filter(restaurant__exact = self.obj) \n else:\n field.queryset = field.queryset.none()\n\n return field\n\nclass RestaurantAdmin(ObjAdmin):\n inlines = [\n DishTypeInline\n ]\n" }, { "answer_id": 64581746, "author": "Dcode22", "author_id": 14100714, "author_profile": "https://Stackoverflow.com/users/14100714", "pm_score": 1, "selected": false, "text": "class AddIncomingPaymentForm(forms.ModelForm):\n class Meta: \n model = IncomingPayment\n fields = ('description', 'amount', 'income_source', 'income_category', 'bank_account')\n def addIncomingPayment(request):\n form = AddIncomingPaymentForm()\n form.fields['bank_account'].queryset = BankAccount.objects.filter(profile=request.user.profile)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25521/" ]
232,445
<p>I'm just starting to learn C++ so excuse me for this simple question. What I'm doing is reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { double *x; x = new double[1]; x[0]=5; x = new double[1]; x[1]=6; cout &lt;&lt; x[0] &lt;&lt; "," &lt;&lt; x[1] &lt;&lt; endl; return 0; } </code></pre> <p>But this obviously just overwrites the value, 5, that I initially set to x[0] and so outputs 0,6. How would I make it so that it would output 5,6?<br /><br />Please realize that for the example I've included I didn't want to clutter it up with the code reading from a file or code to get numbers from a user. In the actual application I won't know how big of an array I need at compile time so please don't tell me to just make an array with two elements and set them equal to 5 and 6 respectively.<br /><br />Thanks for your help.</p>
[ { "answer_id": 232454, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "vector push_back #include <iostream>\n#include <vector>\n\nint\nmain() {\n double value;\n std::vector<double> values;\n\n // Read in values\n while (std::cin >> value) {\n values.push_back(value);\n }\n\n // Print them back out\n for (std::size_t i(0), len(values.size()); i != len; ++i) {\n std::cout << values[i];\n }\n}\n" }, { "answer_id": 232462, "author": "markets", "author_id": 4662, "author_profile": "https://Stackoverflow.com/users/4662", "pm_score": 2, "selected": false, "text": "#include <iostream>\nusing namespace std;\nint main() {\n double *x = new double[2];\n x[0]=5;\n x[1]=6;\n cout << x[0] << \",\" << x[1] << endl;\n return 0;\n}\n" }, { "answer_id": 232468, "author": "Moishe Lettvin", "author_id": 23786, "author_profile": "https://Stackoverflow.com/users/23786", "pm_score": 2, "selected": false, "text": "int *a = malloc(int * ARBITRARY_SIZE);\nint size = 0;\nint allocated = ARBITRARY_SIZE;\n void addElement(int value) {\n ++size;\n\n if (size == allocated) {\n allocated *= 2;\n a = realloc(sizeof(int) * allocated);\n a = new_a;\n }\n\n a[size] = value;\n}\n" }, { "answer_id": 232497, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 2, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\nint main() {\n // Allocate some memory for a double array of size 1 and store\n // an address to the beginning of the memory in mem_address.\n double* mem_address = new double[1];\n\n // Assign 5 to the first element in the array.\n mem_address[0] = 5;\n\n // Save the address of the memory mem_address is currently\n // referencing.\n double* saved_address = mem_address;\n\n // Allocate some memory for a double array of size 2 and store\n // an address to the beginning of the memory in mem_address.\n mem_address = new double[2];\n\n // Copy over the 1 element from the first memory block\n // to the new one.\n mem_address[0] = saved_address[0];\n\n // Done with the old memory, so clean it up.\n delete [] saved_address;\n\n // Assign 6 to the second element in the new array.\n mem_address[1] = 6;\n\n // Print out the 2 elements in the new array.\n cout << mem_address[0] << \"\\n\";\n cout << mem_address[1] << \"\\n\";\n\n // Done with the new array memory now, so clean it up.\n delete [] mem_address;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38/" ]
232,450
<p>I wanted to see if folks were using decimal for financial applications instead of double. I have seen lots of folks using double all over the place with unintended consequences . .</p> <p>Do you see others making this mistake . . .</p>
[ { "answer_id": 232460, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "float double decimal" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
232,472
<p>In C and C++ what do the following declarations do?</p> <pre><code>const int * i; int * const i; const volatile int ip; const int *i; </code></pre> <p>Are any of the above declarations wrong?</p> <p>If not what is the meaning and differences between them?</p> <p>What are the useful uses of above declarations (I mean in which situation we have to use them in C/C++/embedded C)?</p>
[ { "answer_id": 232479, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": false, "text": "const int * i; i i i int * const i; i i i const volatile int ip; ip const ip const_cast volatile ip volatile const volatile const int *i;" }, { "answer_id": 232480, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "const int *i; // pointer to a constant int (the integer value doesn't change)\n\nint *const i; // constant pointer to an int (what i points to doesn't change)\n\nconst volatile int ip; // a constant integer whose value will never be cached by the system\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,475
<p>I need to add unit testing to some old scripts, the scripts are all basically in the following form:</p> <pre><code>#!/usr/bin/perl # Main code foo(); bar(); # subs sub foo { } sub bar { } </code></pre> <p>If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to be able to just test "foo" in isolation.</p> <p>Is there any way to do this without moving foo,bar into a seperate .pm file?</p>
[ { "answer_id": 232552, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": false, "text": "use File::Slurp \"read_file\";\neval \"package Script; sub {\" . read_file(\"script\") . \"}\";\n\nis(Script::foo(), \"foo\");\n" }, { "answer_id": 232723, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 5, "selected": true, "text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nunless (caller) {\n # startup code\n}\n\nsub foo { ... }\n #!/usr/bin/perl\n\npackage Tests::Script; # avoid the Test:: namespace to avoid conflicts\n # with testing modules\nuse strict;\nuse warnings;\n\ndo 'some_script' or die \"Cannot (do 'some_script'): $!\";\n\n# write your tests\n" }, { "answer_id": 232787, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 4, "selected": false, "text": "return 1 unless $0 eq __FILE__;\n __FILE__ $0 require \"some/program\";\n...and test...\n main main() if $0 eq __FILE__;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
232,486
<p>I've used Slime within Emacs as my primary development environment for Common Lisp (or Aquamacs on OS X), but are there other compelling choices out there? I've heard about Lispworks, but is that [or something else] worth looking at? Or does anyone have tips to getting the most out of Emacs (e.g., hooking it up to the hyperspec for easy reference)?</p> <p>Update: Section 7 of Pascal Costanza's <a href="http://p-cos.net/lisp/guide.html" rel="noreferrer">Highly Opinionated Guide to Lisp</a> give one perspective. But to me, <a href="http://common-lisp.net/project/slime/" rel="noreferrer">SLIME</a> really seems to be <a href="http://www.cliki.net/Editing%20Lisp%20Code%20with%20Emacs" rel="noreferrer">where it's at</a>.</p> <p>More resources:</p> <ul> <li><a href="http://common-lisp.net/project/movies/movies/slime.mov" rel="noreferrer">Video of Marco Baringer showing SLIME</a></li> <li><a href="http://homepage.mac.com/svc/LispMovies/index.html" rel="noreferrer">Videos of Sven Van Caekenberghe showing the LispWorks IDE</a></li> <li><a href="http://www.cl-http.org:8002/mov/dsl-in-lisp.mov" rel="noreferrer">Video of Rainer Joswig using the LispWorks IDE to create a DSL</a></li> <li><a href="http://bc.tech.coop/blog/041130.html" rel="noreferrer">Blog post by Bill Clementson discussing IDE choices</a></li> </ul>
[ { "answer_id": 232904, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 3, "selected": false, "text": "~/.emacs.el (require 'info-look)\n\n(info-lookup-add-help\n :mode 'lisp-mode\n :regexp \"[^][()'\\\" \\t\\n]+\"\n :ignore-case t\n :doc-spec '((\"(ansicl)Symbol Index\" nil nil nil)))\n C-h S" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31049/" ]
232,506
<p>What tips and "standards" do you use in your Redmine project management process?</p> <p>Do you have a standard wiki insert template you could share or a standard way to work a project using bugs features tasks and support issues?</p> <p>Do you let issues and updates get emailed into Redmine? Do you use the forums? Do you use SVN repository? Do you use Mylyn in eclipse to work the task lists?</p> <p>I'm trying to drag our dept. into some web based PM instead of emailed Word docs of vague requirements followed by Word docs explaining how to QA and Deploy that all get lost in a pile of competing updates and projects so that by the time I have to fix something, no one can find any documentation on how it works.</p>
[ { "answer_id": 10316605, "author": "Scott Corscadden", "author_id": 297472, "author_profile": "https://Stackoverflow.com/users/297472", "pm_score": 3, "selected": false, "text": "svn switch https//.../branches/1.3-stable . rake migrate svn ci -m \"This fixes #1733 @2.5, holy smoke what a weird foo bug. It is now bacon and unicorns.\"" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5281/" ]
232,507
<p>I'm a rookie designer having a few troubles with this page: <a href="http://www.resolvegroup.co.nz/javasurvey.php" rel="nofollow noreferrer">http://www.resolvegroup.co.nz/javasurvey.php</a></p> <p>There are problems with the javascript operation of the expanded questions. For Internet Explorer (Version 7) the first question when expanded gets partly hidden under question 2. This happens to varying degrees with all questions, at times making the next question completely hidden and other problems.</p> <p>Firefox (Version 3.03) does not have the problem as above, but you cannot get access to the explanations or select next question as in IE7.</p> <p>Does anyone know what's going on with this, and how to fix it?</p>
[ { "answer_id": 232514, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "$(\".score-list\").slideUp(speed);\n$(\".score-list\").removeClass(\"open\");\n$(\"a.open-answer\").removeClass(\"hidden\");\n$(this).parent().children(\".score-list\").slideDown(speed);\n$(this).parent().children(\".score-list\").toggleClass(\"open\");\n$(this).toggleClass(\"hidden\");\n $(\".score-list\") // my own preference is to split the calls onto\n .slideUp(speed) // multiple lines to make it easier to read.\n .removeClass(\"open\")\n;\n$(\"a.open-answer\").removeClass(\"hidden\");\n\nvar $this = $(this); // store the result from a query in an object so you\n // don't have to go through that again.\n$this\n .parent()\n .children(\".score-list\")\n .slideDown(speed);\n .toggleClass(\"open\")\n;\n$this.toggleClass(\"hidden\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,508
<p>I am currently using a dotted border for certain UI stuff such as instructions, notes, error boxes, etc.</p> <p>But recently I changed to a solid border, due to a requirement, but I just find it kind of strange.</p> <p>It seems that by making it solid it puts too much emphasis on page elements which are just informational.</p> <p>What are your views?</p>
[ { "answer_id": 232522, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 0, "selected": false, "text": "<abbr style=\"border-bottom:1px dotted #000;cursor:help;\">\n <span style=\"cursor:help;\" title=\"Cascading Style Sheets\">CSS</span>\n</abbr>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25368/" ]
232,519
<p>What I can think of is pre-populating certain form input elements based on the user's geographical information.</p> <p>What are other ways can you think of to speed up user input on long application forms?</p> <p>Or at least keep them focus on completing the application form?</p>
[ { "answer_id": 249177, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 1, "selected": false, "text": "reset" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25368/" ]
232,524
<p>How does one go about creating a virtual CD driver on Mac OS X programatically? </p> <p>I can't find any relevant Cocoa APIs or any pure C BSD solutions. </p> <p>Any help or information is appreciated.</p>
[ { "answer_id": 66885701, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 0, "selected": false, "text": "/Library/Extensions/DAEMONToolsVirtualSCSIBus.kext/Contents/MacOS/DAEMONToolsVirtualSCSIBus" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,535
<p>What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?</p> <p>Consider the following sample code - inside the <code>Example()</code> method, what's the most concise way to invoke <code>GenericMethod&lt;T&gt;()</code> using the <code>Type</code> stored in the <code>myType</code> variable?</p> <pre><code>public class Sample { public void Example(string typeName) { Type myType = FindType(typeName); // What goes here to call GenericMethod&lt;T&gt;()? GenericMethod&lt;myType&gt;(); // This doesn't work // What changes to call StaticMethod&lt;T&gt;()? Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work } public void GenericMethod&lt;T&gt;() { // ... } public static void StaticMethod&lt;T&gt;() { //... } } </code></pre>
[ { "answer_id": 232621, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 11, "selected": true, "text": "MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));\nMethodInfo generic = method.MakeGenericMethod(myType);\ngeneric.Invoke(this, null);\n null Invoke dynamic" }, { "answer_id": 5134251, "author": "Adrian Gallero", "author_id": 636604, "author_profile": "https://Stackoverflow.com/users/636604", "pm_score": 8, "selected": false, "text": "MethodInfo method = typeof(Sample).GetMethod(\"GenericMethod\");\nMethodInfo generic = method.MakeGenericMethod(myType);\ngeneric.Invoke(this, null);\n GenericMethod GenericMethod Action<> GenMethod = GenericMethod<int>; //change int by any base type \n //accepted by GenericMethod\nMethodInfo method = this.GetType().GetMethod(GenMethod.Method.Name);\nMethodInfo generic = method.MakeGenericMethod(myType);\ngeneric.Invoke(this, null);\n GenericMethod GenericMethod GenericMethod Activator" }, { "answer_id": 6583578, "author": "jbtule", "author_id": 637783, "author_profile": "https://Stackoverflow.com/users/637783", "pm_score": 4, "selected": false, "text": "var name = InvokeMemberName.Create;\nDynamic.InvokeMemberAction(this, name(\"GenericMethod\", new[]{myType}));\n\n\nvar staticContext = InvokeContext.CreateStatic;\nDynamic.InvokeMemberAction(staticContext(typeof(Sample)), name(\"StaticMethod\", new[]{myType}));\n" }, { "answer_id": 22441650, "author": "Mariusz Pawelski", "author_id": 350384, "author_profile": "https://Stackoverflow.com/users/350384", "pm_score": 7, "selected": false, "text": "dynamic Type dynamic class Alpha { }\nclass Beta { }\nclass Service\n{\n public void Process<T>(T item)\n {\n Console.WriteLine(\"item.GetType(): \" + item.GetType()\n + \"\\ttypeof(T): \" + typeof(T));\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var a = new Alpha();\n var b = new Beta();\n\n var service = new Service();\n service.Process(a); // Same as \"service.Process<Alpha>(a)\"\n service.Process(b); // Same as \"service.Process<Beta>(b)\"\n\n var objects = new object[] { a, b };\n foreach (var o in objects)\n {\n service.Process(o); // Same as \"service.Process<object>(o)\"\n }\n foreach (var o in objects)\n {\n dynamic dynObj = o;\n service.Process(dynObj); // Or write \"service.Process((dynamic)o)\"\n }\n }\n}\n item.GetType(): Alpha typeof(T): Alpha\nitem.GetType(): Beta typeof(T): Beta\nitem.GetType(): Alpha typeof(T): System.Object\nitem.GetType(): Beta typeof(T): System.Object\nitem.GetType(): Alpha typeof(T): Alpha\nitem.GetType(): Beta typeof(T): Beta\n Process GetType() typeof dynamic Process dynamic foreach (var o in objects)\n{\n MethodInfo method = typeof(Service).GetMethod(\"Process\");\n MethodInfo generic = method.MakeGenericMethod(o.GetType());\n generic.Invoke(service, new object[] { o });\n}\n dynamic class Program\n{\n static void Main(string[] args)\n {\n object obj = new Alpha();\n\n Helper((dynamic)obj);\n }\n\n public static void Helper<T>(T obj)\n {\n GenericMethod<T>();\n }\n\n public static void GenericMethod<T>()\n {\n Console.WriteLine(\"GenericMethod<\" + typeof(T) + \">\");\n }\n}\n dynamic Type.GetMethod MethodInfo.Invoke interface IItem { }\nclass FooItem : IItem { }\nclass BarItem : IItem { }\nclass Alpha { }\n\nclass Program\n{\n static void Main(string[] args)\n {\n var objects = new object[] { new FooItem(), new BarItem(), new Alpha() };\n for (int i = 0; i < objects.Length; i++)\n {\n ProcessItem((dynamic)objects[i], \"test\" + i, i);\n\n //ProcesItm((dynamic)objects[i], \"test\" + i, i);\n //compiler error: The name 'ProcesItm' does not\n //exist in the current context\n\n //ProcessItem((dynamic)objects[i], \"test\" + i);\n //error: No overload for method 'ProcessItem' takes 2 arguments\n }\n }\n\n static string ProcessItem<T>(T item, string text, int number)\n where T : IItem\n {\n Console.WriteLine(\"Generic ProcessItem<{0}>, text {1}, number:{2}\",\n typeof(T), text, number);\n return \"OK\";\n }\n static void ProcessItem(BarItem item, string text, int number)\n {\n Console.WriteLine(\"ProcessItem with Bar, \" + text + \", \" + number);\n }\n}\n dynamic dynamic ProcessItem BarItem Alpha where T : IItem Alpha dynamic var result = ProcessItem((dynamic)testObjects[i], \"test\" + i, i);\n dynamic string result = ProcessItem((dynamic)testObjects[i], \"test\" + i, i);\n" }, { "answer_id": 27870198, "author": "Grax32", "author_id": 1056639, "author_profile": "https://Stackoverflow.com/users/1056639", "pm_score": 4, "selected": false, "text": "((Action)GenericMethod<object>)\n .Method\n .GetGenericMethodDefinition()\n .MakeGenericMethod(typeof(string))\n .Invoke(this, null);\n GenericMethod<object> Func<string,string,int> Action<bool> MethodInfo method = typeof(Sample).GetMethod(\"GenericMethod\");\n MethodInfo method = ((Action)GenericMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n\nMethodInfo method = ((Action)StaticMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n MethodInfo method = ((Action)(new Sample())\n .GenericMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n\nMethodInfo method = ((Action)Sample.StaticMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n ((Action)GenericMethod<object>) ((Func<string, int>)GenericMethod<object>) MethodInfo method = ((MethodCallExpression)((Expression<Action<Sample>>)(\n (Sample v) => v.GenericMethod<object>()\n )).Body).Method.GetGenericMethodDefinition();\n Expression<Action<Sample>> expr = (Sample v) => v.GenericMethod<object>();\n MethodCallExpression methodCallExpr = (MethodCallExpression)expr.Body;\n MethodInfo methodA = methodCallExpr.Method.GetGenericMethodDefinition();\n MethodInfo generic = method.MakeGenericMethod(myType);\n generic.Invoke(this, null);\n" }, { "answer_id": 33292470, "author": "Thierry", "author_id": 815847, "author_profile": "https://Stackoverflow.com/users/815847", "pm_score": 2, "selected": false, "text": "public class Helpers\n{\n public static U ConvertCsvDataToCollection<U, T>(string csvData)\n where U : ObservableCollection<T>\n {\n //transform code here\n }\n}\n object myCollection = Activator.CreateInstance(collectionType);\nobject myoObject = Activator.CreateInstance(objectType);\n MethodInfo method = typeof(Helpers).\nGetMethod(\"ConvertCsvDataToCollection\");\n MethodInfo generic = method.MakeGenericMethod(\nnew Type[] {\n myCollection.GetType(),\n myObject.GetType()\n});\n generic.Invoke(null, new object[] { csvData });\n object myCollection = null;\n\nMethodInfo method = typeof(Helpers).\nGetMethod(\"ConvertCsvDataToCollection\");\n\nMethodInfo generic = method.MakeGenericMethod(\n myClassInfo.CollectionType,\n myClassInfo.ObjectType\n);\n\nmyCollection = generic.Invoke(null, new object[] { csvData });\n Type" }, { "answer_id": 39113035, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace DictionaryRuntime\n{\n public class DynamicDictionaryFactory\n {\n /// <summary>\n /// Factory to create dynamically a generic Dictionary.\n /// </summary>\n public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)\n {\n //Creating the Dictionary.\n Type typeDict = typeof(Dictionary<,>);\n\n //Creating KeyValue Type for Dictionary.\n Type[] typeArgs = { keyType, valueType };\n\n //Passing the Type and create Dictionary Type.\n Type genericType = typeDict.MakeGenericType(typeArgs);\n\n //Creating Instance for Dictionary<K,T>.\n IDictionary d = Activator.CreateInstance(genericType) as IDictionary;\n\n return d;\n\n }\n }\n}\n DynamicDictionaryFactory CreateDynamicGenericInstance(Type keyType, Type valueType) keyType valueType Dictionary<String, int> using System;\nusing System.Collections.Generic;\n\nnamespace DynamicDictionary\n{\n class Test\n {\n static void Main(string[] args)\n {\n var factory = new DictionaryRuntime.DynamicDictionaryFactory();\n var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));\n\n var typedDict = dict as Dictionary<String, int>;\n\n if (typedDict != null)\n {\n Console.WriteLine(\"Dictionary<String, int>\");\n\n typedDict.Add(\"One\", 1);\n typedDict.Add(\"Two\", 2);\n typedDict.Add(\"Three\", 3);\n\n foreach(var kvp in typedDict)\n {\n Console.WriteLine(\"\\\"\" + kvp.Key + \"\\\": \" + kvp.Value);\n }\n }\n else\n Console.WriteLine(\"null\");\n }\n }\n}\n Dictionary<String, int>\n\"One\": 1\n\"Two\": 2\n\"Three\": 3\n" }, { "answer_id": 60504770, "author": "Matt", "author_id": 1016343, "author_profile": "https://Stackoverflow.com/users/1016343", "pm_score": 0, "selected": false, "text": "public class Bar { }\npublic class Square { }\n Foo<T> Bar Square public class myClass\n{\n public void Foo<T>(T item)\n {\n Console.WriteLine(typeof(T).Name);\n }\n}\n public static class Extension\n{\n public static void InvokeFoo<T>(this T t)\n {\n var fooMethod = typeof(myClass).GetMethod(\"Foo\");\n var tType = typeof(T);\n var fooTMethod = fooMethod.MakeGenericMethod(new[] { tType });\n fooTMethod.Invoke(new myClass(), new object[] { t });\n }\n}\n Foo var objSquare = new Square();\nobjSquare.InvokeFoo();\n\nvar objBar = new Bar();\nobjBar.InvokeFoo();\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30280/" ]
232,545
<p>Say I have a rectangular string array - not a jagged array</p> <pre><code>string[,] strings = new string[8, 3]; </code></pre> <p>What's the best way to extract a one-dimensional array from this (either a single row or a single column)? I can do this with a for loop, of course, but I'm hoping .NET has a more elegant way built in.</p> <p>Bonus points for converting the extracted string array to an object array.</p>
[ { "answer_id": 232553, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "static object[] GetColumn(string[][] source, int col) {\n return source.Iterate().Select(x => source[x.Index][col]).Cast<object>().ToArray();\n}\nstatic object[] GetRow(string[][] source, int row) {\n return source.Skip(row).First().Cast<object>().ToArray();\n}\npublic class Pair<T> {\n public int Index;\n public T Value;\n public Pair(int i, T v) {\n Index = i;\n Value = v;\n }\n}\nstatic IEnumerable<Pair<T>> Iterate<T>(this IEnumerable<T> source) {\n int index = 0;\n foreach (var cur in source) {\n yield return new Pair<T>(index, cur);\n index++;\n }\n}\n" }, { "answer_id": 232562, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "Array.Copy Buffer.BlockCopy rowNum object[] row = Enumerable.Range(0, rowLength)\n .Select(colNum => (object) stringArray[rowNum, colNum])\n .ToArray();\n colNum object[] column = Enumerable.Range(0, columnLength)\n .Select(rowNum => (object) stringArray[rowNum, colNum])\n .ToArray();\n ExtractRow ExtractColumn" }, { "answer_id": 232666, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 2, "selected": false, "text": "string[][] data = new string[3][];\ndata[0] = new string[] { \"0,[0]\", \"0,[1]\", \"0,[2]\" };\ndata[1] = new string[] { \"1,[0]\", \"1,[1]\", \"1,[2]\" ];\ndata[2] = new string[] { \"2,[0]\", \"1,[1]\", \"1,[2]\" };\n string[,] data = new string[3,3];\ndata[0,0] = \"0,0\";\ndata[0,1] = \"0,1\";\ndata[0,2] = \"0,2\";\n...etc\n /// INPUT: rowIndex, OUTPUT: An object[] of data for that row\nint colLength = stringArray.GetLength(1);\nobject[] rowData = new object[colLength];\nfor (int col = 0; col < colLength; col++) {\n rowData[col] = stringArray[rowIndex, col] as object;\n}\nreturn rowData;\n\n/// INPUT: colIndex, OUTPUT: An object[] of data for that column\nint rowLength = stringArray.GetLength(0);\nobject[] colData = new object[rowLength];\nfor (int row = 0; r < rowLength; row++) {\n colData[row] = stringArray[row, colIndex] as object;\n}\nreturn colData;\n" }, { "answer_id": 232889, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " int[][] arDouble = new int[2][];\n arDouble[0] = new int[2];\n arDouble[1] = new int[2];\n arDouble[0][0] = 1;\n arDouble[0][1] = 2;\n arDouble[1][0] = 3;\n arDouble[1][1] = 4;\n\n int[] arSingle = new int[arDouble[0].Length];\n\n Array.Copy(arDouble[0], arSingle, arDouble[0].Length);\n" }, { "answer_id": 233488, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 4, "selected": true, "text": "string[,] rectArray = new string[3,3] { \n {\"a\", \"b\", \"c\"}, \n {\"d\", \"e\", \"f\"}, \n {\"g\", \"h\", \"i\"} };\n\nvar rectResult = rectArray.Cast<object>().ToArray();\n string[][] jaggedArray = { \n new string[] {\"a\", \"b\", \"c\", \"d\"}, \n new string[] {\"e\", \"f\"}, \n new string[] {\"g\", \"h\", \"i\"} };\n\nvar jaggedResult = jaggedArray.SelectMany(s => s).Cast<object>().ToArray();\n" }, { "answer_id": 34525680, "author": "user3521369", "author_id": 3521369, "author_profile": "https://Stackoverflow.com/users/3521369", "pm_score": 0, "selected": false, "text": "public static class ExtensionMethods \n{\n public static string[] get1Dim(this string[,] RectArr, int _1DimIndex , int _2DimIndex )\n {\n string[] temp = new string[RectArr.GetLength(1)];\n\n if (_2DimIndex == -1)\n {\n for (int i = 0; i < RectArr.GetLength(1); i++)\n { temp[i] = RectArr[_1DimIndex, i]; }\n }\n else\n {\n for (int i = 0; i < RectArr.GetLength(0); i++)\n { temp[i] = RectArr[ i , _2DimIndex]; }\n }\n\n return temp;\n }\n}\n // we now have this funtionaliy RectArray[1, * ] \n// -1 means ALL \nstring[] _1stRow = RectArray.get1Dim( 0, -1) ; \nstring[] _2ndRow = RectArray.get1Dim( 1, -1) ; \n\nstring[] _1stCol = RectArray.get1Dim( -1, 0) ; \nstring[] _2ndCol = RectArray.get1Dim( -1, 1) ; \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
232,558
<p>I noticed that the generic <code>IEnumerator&lt;T&gt;</code> inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way?</p> <p>Usually, we use foreach statement to go through a <code>IEnumerator&lt;T&gt;</code> instance. The generated code of foreach actually has try-finally block that invokes Dispose() in finally. </p>
[ { "answer_id": 232561, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": -1, "selected": false, "text": "IEnumerable<T> IEnumerable IEnumerable" }, { "answer_id": 232616, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "foreach Dispose foreach finally IDisposable IEnumerator IDisposable IEnumerator foreach IEnumerator IDisposable IDisposable IEnumerator<T> Dispose Dispose Dispose finally Dispose" }, { "answer_id": 8652737, "author": "JAXN", "author_id": 1118803, "author_profile": "https://Stackoverflow.com/users/1118803", "pm_score": 2, "selected": false, "text": "IEnumerable of T IEnumerator of T IEnumerator of T" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
232,575
<p>How do I check if a column exists in SQL Server 2000?</p>
[ { "answer_id": 232582, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME='tablename' AND COLUMN_NAME='columname' )\n" }, { "answer_id": 232613, "author": "user20358", "author_id": 20358, "author_profile": "https://Stackoverflow.com/users/20358", "pm_score": 3, "selected": false, "text": "SELECT count(*) AS [Column Exists] \nFROM SYSOBJECTS \nINNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID \nWHERE \n SYSOBJECTS.NAME = 'myTable' \n AND SYSCOLUMNS.NAME = 'Myfield'\n" }, { "answer_id": 3613216, "author": "Deepak Yadav", "author_id": 217294, "author_profile": "https://Stackoverflow.com/users/217294", "pm_score": 3, "selected": false, "text": "If col_length('table_name','column_name') is null\n select 0 as Present\nELSE\n select 1 as Present\n" }, { "answer_id": 5833757, "author": "Dan", "author_id": 731299, "author_profile": "https://Stackoverflow.com/users/731299", "pm_score": 2, "selected": false, "text": "if COLUMNPROPERTY(object_id('table_name'), 'column_name', 'ColumnId') is null\n print 'doesn\\'t exist'\nelse\n print 'exists'\n" }, { "answer_id": 7610770, "author": "Douglas Tondo", "author_id": 973130, "author_profile": "https://Stackoverflow.com/users/973130", "pm_score": 0, "selected": false, "text": "SELECT COLUMNS.*\nFROM INFORMATION_SCHEMA.COLUMNS COLUMNS, INFORMATION_SCHEMA.TABLES TABLES\nWHERE COLUMNS.TABLE_NAME=TABLES.TABLE_NAME AND UPPER(COLUMNS.COLUMN_NAME)=UPPER('column_name')\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31071/" ]
232,622
<p><strong>Update:</strong> So, this turns out to have nothing to do with Tortoise SVN. I use Mozy.com for off-site backups and their new version includes these icon overlays. They can be disabled via the config options...or see here <a href="http://forum.pcmech.com/showthread.php?p=1385433" rel="nofollow noreferrer">http://forum.pcmech.com/showthread.php?p=1385433</a>. Thanks @OS for the answer.</p> <p>Been using Tortoise SVN for some time on my Vista box. Within the last few days (and after recently upgrading to 1.5.4) the icon overlays are displaying on all files. </p> <p>My exclude path is:</p> <p>*</p> <p>My include paths are:</p> <p>C:\Users\jw\Documents\Visual Studio 2008\Projects\SVNProjects*</p> <p>C:\Users\jw\Documents\VB Projects\SVNProjects*</p> <p>I haven't touched those settings in months. Any ideas? Help. Thanks.</p>
[ { "answer_id": 232628, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "%USERPROFILE%\\AppData\\Local attrib –h IconCache.db del IconCache.db" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/689/" ]
232,625
<p>How to invoke the default browser with an URL from C#?</p>
[ { "answer_id": 232633, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "System.Diagnostics.Process.Start(\"http://mysite.com\");\n" }, { "answer_id": 232634, "author": "Anindya", "author_id": 4741, "author_profile": "https://Stackoverflow.com/users/4741", "pm_score": 4, "selected": false, "text": "System.Diagnostics.Process.Start(\"http://www.google.com\");\n" }, { "answer_id": 235926, "author": "Lex Li", "author_id": 11182, "author_profile": "https://Stackoverflow.com/users/11182", "pm_score": 2, "selected": false, "text": "\nHelp.ShowHelp(null, \"http://www.google.com\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,651
<p>While running a batch file in Windows XP I have found randomly occurring error message:</p> <blockquote> <p>The system cannot find the batch label specified name_of_label</p> </blockquote> <p>Of course label existed. What causes this error?</p>
[ { "answer_id": 232674, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": true, "text": ".bat .cmd CALL .bat vcvarsall.bat .gitattributes *.bat text eol=crlf\n" }, { "answer_id": 6419068, "author": "Marshal", "author_id": 548098, "author_profile": "https://Stackoverflow.com/users/548098", "pm_score": 6, "selected": false, "text": "CALL CALL" }, { "answer_id": 20558108, "author": "Greg", "author_id": 2081656, "author_profile": "https://Stackoverflow.com/users/2081656", "pm_score": 2, "selected": false, "text": "call:function_A \"..\\..\\folderA\\\"\ncall:function_B \"..\\..\\folderB\\\"\ncall:function_C \"..\\..\\folderC\\\"\ncall:function_D \"..\\..\\folderD\\\"\ngoto:eof\n\n:function_A\nrem do stuff\ngoto:eof\n\n...etc...\n" }, { "answer_id": 60265222, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 2, "selected": false, "text": "@echo off\ncall :func\necho back from second\nexit /b\n:func\nsecond.bat\necho NEVER COME BACK HERE goto :func" }, { "answer_id": 73136207, "author": "Cristian F.", "author_id": 11302775, "author_profile": "https://Stackoverflow.com/users/11302775", "pm_score": 0, "selected": false, "text": "goto : eof\n goto :eof\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31086/" ]
232,662
<p>I have a function which launches a javascript window, like this</p> <pre><code> function genericPop(strLink, strName, iWidth, iHeight) { var parameterList = "location=0,directories=0,status=0,menubar=0,resizable=no, scrollbars=no,toolbar=0,maximize=0,width=" + iWidth + ", height=" + iHeight; var new_window=""; new_window = open(strLink, strName, parameterList); window.self.name = "main"; new_window.moveTo(((screen.availWidth/2)-(iWidth/2)),((screen.availHeight/2)-(iHeight/2))); new_window.focus(); } </code></pre> <p>This function is called about 52 times from different places in my web application.</p> <p>I want to re-factor this code to use a DHTML modal pop-up window. The change should be as unobtrusive as possible.</p> <p>To keep this solution at par with the old solution, I think would also need to do the following</p> <ol> <li>Provide a handle to "Close" the window.</li> <li>Ensure the window cannot be moved, and is positioned at the center of the screen.</li> <li>Blur the background as an option.</li> </ol> <p>I thought <a href="http://particletree.com/features/lightbox-gone-wild/" rel="nofollow noreferrer">this solution</a> is the closest to what I want, but I could not understand how to incorporate it.</p> <p>Edit: A couple of you have given me a good lead. Thank you. But let me re-state my problem here. I am re-factoring existing code. I should avoid any change to the present HTML or CSS. Ideally I would like to achieve this effect by keeping the function signature of the genericPop(...) same as well.</p>
[ { "answer_id": 232684, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 2, "selected": false, "text": "showDialog('title','content (can be html if encoded)','dialog_style/*4 predefined styles to choose from*/');\n" }, { "answer_id": 232727, "author": "derfred", "author_id": 10286, "author_profile": "https://Stackoverflow.com/users/10286", "pm_score": 1, "selected": false, "text": "<a href=\"/messages/new\" class=\"popup_window\">New Message</a>\n $(document).observe(\"dom:loaded\", function() {\n $$(\"a.popup_window\").each(function(element) {\n new Control.Modal(element, { overlayOpacity: 0.75, \n className: 'modal',\n method: 'get',\n position: 'center' });\n });\n});\n Control.Modal.current.close()\n" }, { "answer_id": 233372, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 3, "selected": true, "text": "iframe strLink iframe div function genericPop(strLink, strName, iWidth, iHeight) {\n var dialog = $('#dialog');\n if (dialog.length > 0) {\n dialog.parents('div.ui-dialog').eq(0).remove();\n }\n\n dialog = $(document.createElement('div'))\n .attr('id', 'dialog')\n .css('display', 'none')\n .appendTo('body');\n\n $(document.createElement('iframe'))\n .attr('src', strLink)\n .css('width', '100%')\n .css('height', '100%')\n .appendTo(dialog);\n\n dialog.dialog({ \n draggable: false,\n modal: true, \n width: iWidth,\n height: iHeight,\n title: strName,\n overlay: { \n opacity: 0.5, \n background: \"black\" \n } \n });\n dialog.css('display', 'block');\n}\n\n// example of use\n$(document).ready(function() {\n $('#google').click(function() {\n genericPop('http://www.google.com/', 'Google', 640, 480);\n return false;\n });\n $('#yahoo').click(function() {\n genericPop('http://www.yahoo.com/', 'Yahoo', 640, 480);\n return false;\n });\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11602/" ]
232,677
<p>Could you tell me, please, if it's possible to preview (or at least retroview, for example, in a kind of a log file) SQL commands which SQL Server Management Studio Express is about to execute (or has just executed)?</p> <p>In the past I used Embarcadero DBArtisan which shows SQL queries to be executed before actually running them on the server, so I am eager for this feature in Management Studio.</p> <p>I have found an option "Auto generate change scripts", but it shows only DDL SQL queries (structure change), not data change.</p>
[ { "answer_id": 232700, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 1, "selected": false, "text": "BEGIN TRAN\n\n INSERT INTO Clients \n SELECT 'Bruno', 'Alexandre';\n\nEND\n\nROLLBACK TRAN\n IF @@ERROR > 0 GOTO Error\n\n:Error\nROLLBACK TRANSACTION\n" }, { "answer_id": 241735, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 0, "selected": false, "text": "SET SHOWPLAN_TEXT ON\n SHOWPLAN_TEXT SHOWPLAN_TEXT OFF" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
232,678
<p>I am working on implementing tail for an assignment. I have it working correctly however I seem to be getting an error from free at random times.</p> <p>I can't see, to track it down to a pattern or anything besides it is consistent.</p> <p>For example if I call my program as "tail -24 test.in" I would get the the the incorrect checksum error at the same line on multiple runs. However, with different files and even different numbers of lines to print back I will come back without errors.</p> <p>Any idea on how to track down the issue, I've been trying to debug it for hours to no avail.</p> <p>Here is the offending code:</p> <p>lines is defined as a char** and was malloc as:</p> <pre><code>lines = (char**) malloc(nlines * sizeof(char *)); void insert_line(char *s, int len){ printf("\t\tLine Number: %d Putting a %d line into slot: %d\n",processed,len,slot); if(processed &gt; numlines -1){//clean up free(*(lines+slot)); *(lines + slot) = NULL; } *(lines + slot) = (char *) malloc(len * sizeof(char)); if(*(lines + slot) == NULL) exit(EXIT_FAILURE); strcpy(*(lines+slot),s); slot = ++processed % numlines; } </code></pre>
[ { "answer_id": 232720, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 0, "selected": false, "text": " *(lines + slot) = (char *) malloc(len * sizeof(char));\n if((lines + slot) == NULL) exit(EXIT_FAILURE);\n lines[slot] (lines+slot) lines char" }, { "answer_id": 232731, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "*(lines + slot) = some value\nif((lines + slot) == NULL) then die\nshould be\nif(*(lines + slot) == NULL) then die\n" }, { "answer_id": 233424, "author": "Todd", "author_id": 30841, "author_profile": "https://Stackoverflow.com/users/30841", "pm_score": 1, "selected": false, "text": " *(lines + slot) = (char *) malloc(len * sizeof(char));\n if(*(lines + slot) == NULL) exit(EXIT_FAILURE);\n strcpy(*(lines+slot),s);\n lines[slot] = (char *) malloc((len + 1) * sizeof(char));\n if(lines[slot] == NULL) exit(EXIT_FAILURE);\n if(strlen(s) <= len){\n strcpy(lines[slot],s);\n }\n else{\n /* do something else... */\n }\n free(lines[slot]);\nlines[slot] = NULL;\n free(*(lines+slot));\n*(lines + slot) = NULL;\n static int numlines = 0;\nvoid insert_line(char *s, int len){\n int numlines = 5;\n" }, { "answer_id": 233534, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 4, "selected": true, "text": " *(lines + slot) = (char *) malloc((len + 1) * sizeof(char));\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25012/" ]
232,681
<p>I’ve almost 6 years of experience in application development using .net technologies. Over the years I have improved as a better OO programmer but when I see code written by other guys (especially the likes of Jeffrey Richter, Peter Golde, Ayende Rahien, Jeremy Miller etc), I feel there is a generation gap between mine and their designs. I usually design my classes on the fly with some help from tools like ReSharper for refactoring and code organization. </p> <p>So, my question is “what does it takes to be a better OO programmer”. Is it </p> <p>a) Experience</p> <p>b) Books (reference please)</p> <p>c) Process (tdd or uml) </p> <p>d) patterns</p> <p>e) anything else?</p> <p>And how should one validate that the design is good, easy to understand and maintainable. As there are so many buzzwords in industry like dependency injection, IoC, MVC, MVP, etc where should one concentrate more in design. I feel abstraction is the key. What else?</p>
[ { "answer_id": 232960, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 1, "selected": false, "text": "self/this class/vtable/metatable class" }, { "answer_id": 10637273, "author": "Webist", "author_id": 465096, "author_profile": "https://Stackoverflow.com/users/465096", "pm_score": 0, "selected": false, "text": "interface i { getObject($o); } abstract class Controller { \n function getObject(){} \n function validateObject(){\n\n// o must be a digit\n// o must be between 0 and 120\n// ... etc\n}\n}\n class View extends Controller (InputObject $in, OutputObject $out) {\n\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31081/" ]
232,682
<p>I've already written a generator that does the trick, but I'd like to know the best possible way to implement the off-side rule.</p> <p>Shortly: <a href="http://en.wikipedia.org/wiki/Off-side_rule" rel="noreferrer">Off-side rule</a> means in this context that indentation is getting recognized as a syntactic element.</p> <p>Here is the offside rule in pseudocode for making tokenizers that capture indentation in usable form, I don't want to limit answers by language:</p> <pre><code>token NEWLINE matches r"\n\ *" increase line count pick up and store the indentation level remember to also record the current level of parenthesis procedure layout tokens level = stack of indentation levels push 0 to level last_newline = none per each token if it is NEWLINE put it to last_newline and get next token if last_newline contains something extract new_level and parenthesis_count from last_newline - if newline was inside parentheses, do nothing - if new_level &gt; level.top push new_level to level emit last_newline as INDENT token and clear last_newline - if new_level == level.top emit last_newline and clear last_newline - otherwise while new_level &lt; level.top pop from level if new_level &gt; level.top freak out, indentation is broken. emit last_newline as DEDENT token clear last_newline emit token while level.top != 0 emit token as DEDENT token pop from level comments are ignored before they are getting into the layouter layouter lies between a lexer and a parser </code></pre> <p>This layouter doesn't generate more than one NEWLINE at time, and doesn't generate NEWLINE when there's indentation coming up. Therefore parsing rules remain quite simple. It's pretty good I think but inform if there's better way of accomplishing it.</p> <p>While using this for a while, I've noticed that after DEDENTs it may be nice to emit newline anyway, this way you can separate the expressions with NEWLINE while keeping the INDENT DEDENT as a trailer for expression.</p>
[ { "answer_id": 258167, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 4, "selected": true, "text": "this line introduces an indented block of literal text:\n this line of the block is indented four spaces\n but this line is only indented two spaces\n" }, { "answer_id": 946398, "author": "dkagedal", "author_id": 24458, "author_profile": "https://Stackoverflow.com/users/24458", "pm_score": 2, "selected": false, "text": "line1\n line2\n line3\nline4\n LINE \"line1\" INDENT LINE \"line2\" LINE \"line3\" DEDENT LINE \"line4\" EOF\n match next_token () with\n LINE indentation ->\n if indentation > !current_indentation then\n (\n Stack.push !current_indentation indentation_stack;\n current_indentation := indentation;\n INDENT\n )\n else if indentation < !current_indentation then\n (\n let prev = Stack.pop indentation_stack in\n if indentation > prev then\n (\n current_indentation := indentation;\n BAD_DEDENT\n )\n else\n (\n current_indentation := prev;\n DEDENT\n )\n )\n else (* indentation = !current_indentation *)\n let token = remove_next_token () in\n if next_token () = EOF then\n remove_next_token ()\n else\n token\n | _ ->\n remove_next_token ()\n" }, { "answer_id": 6002740, "author": "balu", "author_id": 490153, "author_profile": "https://Stackoverflow.com/users/490153", "pm_score": 1, "selected": false, "text": "def tokenize(input)\n result, prev_indent, curr_indent, line = [\"\"], 0, 0, \"\"\n line_started = false\n\n input.each_char do |char|\n\n case char\n when ' '\n if line_started\n # Content already started, add it.\n line << char\n else\n # No content yet, just count.\n curr_indent += 1\n end\n when \"\\n\"\n result.last << line + \"\\n\"\n curr_indent, line = 0, \"\"\n line_started = false\n else\n # Check if we are at the first non-space character.\n unless line_started\n # Insert indent and dedent tokens if indentation changed.\n if prev_indent > curr_indent\n # 2 spaces dedentation\n ((prev_indent - curr_indent) / 2).times do\n result << :DEDENT\n end\n result << \"\"\n elsif prev_indent < curr_indent\n result << :INDENT\n result << \"\"\n end\n\n prev_indent = curr_indent\n end\n\n # Mark line as started and add char to line.\n line_started = true; line << char\n end\n\n end\n\n result\nend\n [\"Hello there from level 0\\n\", :INDENT, \"This\\nis level\\ntwo\\n\", :DEDENT, \"This is level0 again\\n\"]" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21711/" ]
232,688
<pre><code>&lt;style type="text/css"&gt; html, body { background: #fff; margin: 0; padding: 0; } #nav { font-family: Verdana, sans-serif; height: 29px; font-size: 12px; padding: 0 0 0 10px; /* this is used for something else */ background-color: #456; } #nav ul, #nav ul li { list-style: none; margin: 0; padding: 9px 0 0 0px; } #nav ul { text-align: center; } #nav ul li { display: inline; } #nav ul li.last { margin-right: 0; } #nav ul li a { color: #FFF; text-decoration: none; padding: 0px 0 0 20px; height: 29px; } #nav ul li a span { padding: 8px 20px 0 0; height: 21px; } #nav ul li a:hover { background: #789; } &lt;/style&gt; &lt;div id="nav"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/1/"&gt;&lt;span&gt;One&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/2/"&gt;&lt;span&gt;Two&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/3/"&gt;&lt;span&gt;Three&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/4/"&gt;&lt;span&gt;Four&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I have a little problem with that, as it doesn't make the "hover background" 100% of the height of the nav bar.</p>
[ { "answer_id": 232699, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 0, "selected": false, "text": "#nav ul li a {\n color: #FFF;\n text-decoration: none;\n padding: 0px 0 0 20px;\n height: 29px;\n line-height: 29px;\n}\n" }, { "answer_id": 232728, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 2, "selected": true, "text": "<style type=\"text/css\">\nhtml, body {\n background: #fff;\n margin: 0;\n padding: 0;\n}\n\n#nav {\n font-family: Verdana, sans-serif;\n height: 29px;\n font-size: 12px;\n padding: 0 0 0 10px; /* this is used for something else */\n background-color: #456;\n}\n\n#nav ul, #nav ul li {\n list-style: none;\n margin: 0;\n padding: 0 0 0 0px;\n}\n\n#nav ul {\n text-align: center;\n position:relative;\n width:300px;\n margin:0 auto 0 auto;\n}\n\n#nav ul li {\n float:left;\n}\n\n#nav ul li.last {\n margin-right: 0;\n}\n\n\n#nav ul li a {\n float:left;\n color: #FFF;\n text-decoration: none;\n padding: 9px 0 0 20px;\n height: 20px;\n\n}\n#nav ul li a span {\n padding: 8px 20px 0 0;\n height: 20px;\n}\n\n#nav ul li a:hover {\n background: #789;\n}\n</style>\n" }, { "answer_id": 244328, "author": "Sal", "author_id": 32144, "author_profile": "https://Stackoverflow.com/users/32144", "pm_score": 0, "selected": false, "text": "<style type=\"text/css\">\nhtml, body {\n background: #fff;\n margin: 0;\n padding: 0;\n}\n\n#nav {\n font-family: Verdana, sans-serif;\n height: 29px;\n font-size: 12px;\n padding: 0 0 0 10px; /* this is used for something else */\n background-color: #456;\n}\n\n#nav ul, #nav ul li {\n list-style: none;\n margin: 0;\n padding: 0px;\n}\n\n#nav ul {\n text-align: center;\n}\n\n#nav ul li {\n display: inline;\n}\n\n#nav ul li.last {\n margin-right: 0;\n}\n\n\n#nav ul li a {\n color: #FFF;\n text-decoration: none;\n padding: 8px 20px 7px 20px;\n line-height:29px;\n}\n\n#nav ul li a:hover {\n background-color: #789;\n}\n</style>\n\n<div id=\"nav\">\n <ul>\n <li><a href=\"/1/\">One</a></li>\n <li><a href=\"/2/\">Two</a></li>\n <li><a href=\"/3/\">Three</a></li>\n <li><a href=\"/4/\">Four</a></li>\n </ul>\n</div>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
232,691
<p>I've allocated an "array" of <code>mystruct</code> of size <code>n</code> like this:</p> <pre><code>if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) { /* handle error */ } </code></pre> <p>Later on, I only have access to <code>p</code>, and no longer have <code>n</code>. Is there a way to determine the length of the array given just the pointer <code>p</code>?</p> <p>I figure it <em>must</em> be possible, since <code>free(p)</code> does just that. I know <code>malloc()</code> keeps track of how much memory it has allocated, and that's why it knows the length; perhaps there is a way to query for this information? Something like...</p> <pre><code>int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct) </code></pre> <p>I know I should just rework the code so that I know <code>n</code>, but I'd rather not if possible. Any ideas?</p>
[ { "answer_id": 232719, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 7, "selected": true, "text": "malloc malloc n n void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1));\n*((unsigned long int*)p) = n;\n n *((unsigned long int*)p) void *arr = p+sizeof(unsigned long int);\n typedef struct { \n unsigned int n;\n void *arr;\n} arrInfo;\n arrInfo typedef void* arrayInfo;\n(arrayInfo)newArrayInfo(unsignd int n, unsigned int itemSize);\n(void)deleteArrayInfo(arrayInfo);\n(unsigned int)arrayLength(arrayInfo);\n(void*)arrayPtr(arrayInfo);\n...\n std::vector" }, { "answer_id": 232729, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "typedef struct MyStructTag\n{ /* etc. */ } MyStruct ;\n\nvoid doSomething(MyStruct * p)\n{\n /* well... extract the memory allocated? */\n size_t i = get_size(p) ;\n initializeMyStructArray(p, i) ;\n}\n\nvoid doSomethingElse()\n{\n MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */\n doSomething(s) ;\n}\n void doSomethingElse()\n{\n MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */\n MyStruct * s2 = s + 5 ; /* s2 points to the 5th item */\n doSomething(s2) ; /* Oops */\n}\n" }, { "answer_id": 232743, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "void *blockOfMem = malloc(sizeof(mystruct)*n + sizeof(int));\n\n((int *)blockofMem)[0] = n;\nmystruct *structs = (mystruct *)(((int *)blockOfMem) + 1);\n int * free" }, { "answer_id": 232882, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 2, "selected": false, "text": "\nint size;\nstruct mystruct *cur;\n\nfor (cur = myarray; cur->name != NULL; cur++)\n ;\n\nsize = cur - myarray;\n" }, { "answer_id": 234492, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "stdlib.h malloc() stdlib.h void* my_malloc(size_t s); /* Calls malloc(s), and if successful stores \n (p,s) in a list of handled blocks */\nvoid my_free(void* p); /* Removes list entry and calls free(p) */\nsize_t my_block_size(void* p); /* Looks up p, and returns the stored size */\n...\n" }, { "answer_id": 3637498, "author": "Wm J", "author_id": 439131, "author_profile": "https://Stackoverflow.com/users/439131", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nfloat a, b, c, d, e, f, g;\n\nfloat myMax(float *apa,int soa){\n int i;\n float max = apa[0];\n for(i=0; i< soa; i++){\n if (apa[i]>max){max=apa[i];}\n printf(\"on i=%d val is %0.2f max is %0.2f, soa=%d\\n\",i,apa[i],max,soa);\n }\n return max;\n}\n\nint main(void)\n{\n a = 2.0;\n b = 1.0;\n c = 4.0;\n d = 3.0;\n e = 7.0;\n f = 9.0;\n g = 5.0;\n float arr[] = {a,b,c,d,e,f,g};\n\n float mmax = myMax((float *)&arr,(int) sizeof(arr)/sizeof(arr[0]));\n printf(\"mmax = %0.2f\\n\",mmax);\n\n return 0;\n}\n" }, { "answer_id": 32662566, "author": "Jonathon Reinhart", "author_id": 119527, "author_profile": "https://Stackoverflow.com/users/119527", "pm_score": 0, "selected": false, "text": "MALLOC_SIZE malloc.h /* The size of a malloc allocation is stored in a size_t word\n MALLOC_HEADER_SIZE bytes prior to the start address of the allocation:\n\n +--------+---------+-------------------+\n | SIZE |(unused) | allocation ... |\n +--------+---------+-------------------+\n ^ BASE ^ ADDR\n ^ ADDR - MALLOC_HEADER_SIZE\n*/\n\n/* The amount of extra space used by the malloc header. */\n#define MALLOC_HEADER_SIZE \\\n (MALLOC_ALIGNMENT < sizeof (size_t) \\\n ? sizeof (size_t) \\\n : MALLOC_ALIGNMENT)\n\n/* Set up the malloc header, and return the user address of a malloc block. */\n#define MALLOC_SETUP(base, size) \\\n (MALLOC_SET_SIZE (base, size), (void *)((char *)base + MALLOC_HEADER_SIZE))\n/* Set the size of a malloc allocation, given the base address. */\n#define MALLOC_SET_SIZE(base, size) (*(size_t *)(base) = (size))\n\n/* Return base-address of a malloc allocation, given the user address. */\n#define MALLOC_BASE(addr) ((void *)((char *)addr - MALLOC_HEADER_SIZE))\n/* Return the size of a malloc allocation, given the user address. */\n#define MALLOC_SIZE(addr) (*(size_t *)MALLOC_BASE(addr))\n" }, { "answer_id": 68453433, "author": "Parampreet Rai", "author_id": 12615039, "author_profile": "https://Stackoverflow.com/users/12615039", "pm_score": 0, "selected": false, "text": "malloc() #include <stdio.h>\n#include <malloc.h>\n\nint size_of_buff(void *buff) {\n return ( *( ( int * ) buff - 2 ) - 17 ); // 32 bit system: ( *( ( int * ) buff - 1 ) - 17 )\n}\n\nvoid main() {\n char *buff = malloc(1024);\n printf(\"Size of Buffer: %d\\n\", size_of_buff(buff));\n}\n Size of Buffer: 1024\n" }, { "answer_id": 73735629, "author": "Aboutaleb Roshan", "author_id": 14512444, "author_profile": "https://Stackoverflow.com/users/14512444", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct _int_array\n{\n int *number;\n int size;\n} int_array;\n\nint int_array_append(int_array *a, int n)\n{\n static char c = 0;\n if(!c)\n {\n a->number = NULL;\n a->size = 0;\n c++;\n }\n\n int *more_numbers = NULL;\n\n a->size++;\n more_numbers = (int *)realloc(a->number, a->size * sizeof(int));\n if(more_numbers != NULL)\n {\n a->number = more_numbers;\n a->number[a->size - 1] = n;\n }\n else\n {\n free(a->number);\n printf(\"Error (re)allocating memory.\\n\");\n return 1;\n }\n\n return 0;\n}\n\nint main()\n{\n int_array a;\n\n int_array_append(&a, 10);\n int_array_append(&a, 20);\n int_array_append(&a, 30);\n int_array_append(&a, 40);\n\n int i;\n for(i = 0; i < a.size; i++)\n printf(\"%d\\n\", a.number[i]);\n\n printf(\"\\nLen: %d\\nSize: %d\\n\", a.size, a.size * sizeof(int));\n\n free(a.number);\n return 0;\n}\n 10\n20\n30\n40\n\nLen: 4\nSize: 16\n" }, { "answer_id": 73735889, "author": "jxh", "author_id": 315052, "author_profile": "https://Stackoverflow.com/users/315052", "pm_score": 0, "selected": false, "text": "int n = 10;\nint (*p)[n] = malloc(n * sizeof(int));\nn = 3;\nprintf(\"%d\\n\", sizeof(*p)/sizeof(**p));\n struct myarray {\n int n;\n struct mystruct a[];\n};\n\nstruct myarray *ma =\n malloc(sizeof(*ma) + n * sizeof(struct mystruct));\nma->n = n;\nstruct mystruct *p = ma->a;\n int get_size (struct mystruct *p) {\n struct myarray *ma;\n char *x = (char *)p;\n ma = (void *)(x - offsetof(struct myarray, a));\n return ma->n;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31092/" ]
232,693
<p>Is it OK (or even recommended/good practice) to <code>#include</code> a <code>.c</code> file in another <code>.c</code> file?</p>
[ { "answer_id": 38953443, "author": "milad", "author_id": 4697004, "author_profile": "https://Stackoverflow.com/users/4697004", "pm_score": -1, "selected": false, "text": "#include <another.c>\n" }, { "answer_id": 39063753, "author": "sumitroy", "author_id": 6458680, "author_profile": "https://Stackoverflow.com/users/6458680", "pm_score": 3, "selected": false, "text": "gcc main.c support.c -o main.out\n ./main.out\n" }, { "answer_id": 63726144, "author": "Kurt E. Clothier", "author_id": 2251630, "author_profile": "https://Stackoverflow.com/users/2251630", "pm_score": 1, "selected": false, "text": "/**\n * @file vendor_wrap.c\n * @brief vendor source code wrapper to prevent warnings\n */\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wnested-externs\"\n#include \"vendor_source_code.c\"\n#pragma GCC diagnostic pop\n gcc main.c vendor_wrap.c -o $(CFLAGS) main.out\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,722
<p>When querying ntp servers with the command <strong>ntpdate</strong>, I can use the <strong>-u</strong> argument to make the source port an unrestricted port (port 1024 and above).</p> <p>With ntpd, which is meant to run in the background, I can't seem to find a way to turn this option on. So the source port is always 123. It's playing around horribly with my firewall configuration.</p> <p>Is there a configuration option in <strong>ntp.conf</strong> to make it use a random source port?</p>
[ { "answer_id": 29970572, "author": "Daniel Alder", "author_id": 1353930, "author_profile": "https://Stackoverflow.com/users/1353930", "pm_score": 1, "selected": false, "text": "ntpdate -q" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15087/" ]
232,732
<p>How do I convert a string to DateTime format? For example, if I had a string like:</p> <p><code>"24/10/2008"</code></p> <p>How do I get that into DateTime format ?</p>
[ { "answer_id": 232739, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "string str = \"24/10/2008\";\nDateTime dt = DateTime.ParseExact(str, \"dd/MM/yyyy\", \n Thread.CurrentThread.CurrentCulture);\n Thread.CurrentThread.CurrentCulture" }, { "answer_id": 232749, "author": "Michal Sznajder", "author_id": 501, "author_profile": "https://Stackoverflow.com/users/501", "pm_score": 0, "selected": false, "text": "DateTime date = System.DateTime.ParseExact(str, \"dd/MM/yyyy\", null);\n DateTime date = System.DateTime.ParseExact(str, \"HH:mm:ss\", null);\n" }, { "answer_id": 232754, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "string str = \"24/10/2008\";\nDateTime dt = Convert.ToDateTime(str);\n" }, { "answer_id": 232845, "author": "mr_georg", "author_id": 26070, "author_profile": "https://Stackoverflow.com/users/26070", "pm_score": 2, "selected": false, "text": "DateTime d = DateTime.Parse(dateString);\n CultureInfo culture = CultureInfo.CreateSpecificCulture(\"en-US\");\nDateTime d = DateTime.Parse(dateString, culture);\n DateTime.TryParse(dateString, out dateTime) dateTime DateTime d = DateTime.ParseExact(dateString, \"dd/MM/yyyy\", null);\n" }, { "answer_id": 232966, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 2, "selected": false, "text": "DateTime.TryParse DateTime.ParseExact" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,736
<p>Has anybody used a good obfuscator for PHP? I've tried some but they don't work for very big projects. They can't handle variables that are included in one file and used in another, for instance.</p> <p>Or do you have any other tricks for stopping the spread of your code?</p>
[ { "answer_id": 232767, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 7, "selected": false, "text": "perl -MO=Deparse some_program\n" }, { "answer_id": 3781356, "author": "John", "author_id": 456505, "author_profile": "https://Stackoverflow.com/users/456505", "pm_score": 5, "selected": false, "text": "<?php\n$infile=$_SERVER['argv'][1];\n$outfile=$_SERVER['argv'][2];\nif (!$infile || !$outfile) {\n die(\"Usage: php {$_SERVER['argv'][0]} <input file> <output file>\\n\");\n}\necho \"Processing $infile to $outfile\\n\";\n$data=\"ob_end_clean();?>\";\n$data.=php_strip_whitespace($infile);\n// compress data\n$data=gzcompress($data,9);\n// encode in base64\n$data=base64_encode($data);\n// generate output text\n$out='<?ob_start();$a=\\''.$data.'\\';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?>';\n// write output text\nfile_put_contents($outfile,$out);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29593/" ]
232,744
<p>Sometimes gdb prints "incomplete type" for some type of variables. What does this mean and how can we see that value?</p>
[ { "answer_id": 240856, "author": "Daniel Cassidy", "author_id": 31662, "author_profile": "https://Stackoverflow.com/users/31662", "pm_score": 6, "selected": true, "text": "struct hatstand;\nstruct hatstand *foo;\n foo hatstand foo lampshade print (struct lampshade *)foo\n print (void *)foo\nprint (int)foo\n" }, { "answer_id": 12884788, "author": "Peter", "author_id": 1128151, "author_profile": "https://Stackoverflow.com/users/1128151", "pm_score": 3, "selected": false, "text": "struct my_string {\n char * _string,\n int _size\n} ;\n my_string * create_string(const char *) {...}\nconst char * get_string(my_string *){...}\n int main(int argc, char *argv[]) {\n my_string *str = create_string(\"Hello World!\") ;\n printf(\"String value: %s\\n\", get_string(str)) ;\n ...\n}\n" }, { "answer_id": 36620946, "author": "isilpekel", "author_id": 1031224, "author_profile": "https://Stackoverflow.com/users/1031224", "pm_score": 0, "selected": false, "text": "set auto-solib-add off\nattach thread_id\nshared any_lib\nshared another_lib\n" }, { "answer_id": 56313562, "author": "I. Yegor", "author_id": 4911986, "author_profile": "https://Stackoverflow.com/users/4911986", "pm_score": 2, "selected": false, "text": "(gdb) info share Qt\nFrom To Syms Read Shared Object Library\n0x00007ffff5336080 0x00007ffff56ba585 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5\n0x00007ffff4ad3510 0x00007ffff4ef0cbe Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5\n0x00007ffff47829c0 0x00007ffff47e1ba1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5\n0x00007ffff40bb5e0 0x00007ffff439dd92 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\n0x00007ffff2e581e0 0x00007ffff2e78e4f Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5\n0x00007ffff28c8a00 0x00007ffff29d9999 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Network.so.5\n0x00007ffff2251750 0x00007ffff2252a46 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5\n0x00007ffff1cc9f80 0x00007ffff1cfc861 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5\n0x00007fffee269c10 0x00007fffee297b57 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5\n0x00007fffed987560 0x00007fffed98b6a8 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5\n0x00007fffe980e130 0x00007fffe9900c0c Yes (*) /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5\n0x00007fffe69ef650 0x00007fffe69ffe0d Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5\n0x00007fffe5c0f890 0x00007fffe5eae1c1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5\n0x00007fffe5522690 0x00007fffe581f636 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5\n0x00007fffe51996b0 0x00007fffe5221363 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5\n(*): Shared library is missing debugging information.\n whatis (gdb) whatis e\ntype = QEvent *\n (gdb) p e->type()\nCouldn't find method QEvent::type\n (gdb) ptype e\ntype = class QEvent {\n <incomplete type>\n} *\n $ dpkg -S /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\nlibqt5core5a:amd64: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\n libqt5core5a libqt5core5a libqt5core5a-dbgsym $ sudo apt install libqt5core5a-dbgsym libqt5widgets5-dbgsym libqt5gui5-dbgsym\n gdb (gdb) info share Qt\nFrom To Syms Read Shared Object Library\n0x00007ffff5336080 0x00007ffff56ba585 Yes /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5\n0x00007ffff4ad3510 0x00007ffff4ef0cbe Yes /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5\n0x00007ffff47829c0 0x00007ffff47e1ba1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5\n0x00007ffff40bb5e0 0x00007ffff439dd92 Yes /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\n0x00007ffff2e571e0 0x00007ffff2e77e4f Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5\n0x00007ffff28c7a00 0x00007ffff29d8999 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Network.so.5\n0x00007ffff2250750 0x00007ffff2251a46 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5\n0x00007ffff1cc8f80 0x00007ffff1cfb861 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5\n0x00007fffee268c10 0x00007fffee296b57 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5\n0x00007fffed985560 0x00007fffed9896a8 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5\n0x00007fffe95fc130 0x00007fffe96eec0c Yes (*) /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5\n0x00007fffe701f650 0x00007fffe702fe0d Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5\n0x00007fffe623c890 0x00007fffe64db1c1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5\n0x00007fffe5b4f690 0x00007fffe5e4c636 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5\n0x00007fffe57c66b0 0x00007fffe584e363 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5\n(*): Shared library is missing debugging information.\n (gdb) p e->type()\n$4 = QEvent::Paint\n(gdb) ptype e\ntype = class QEvent {\n public:\n...\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
232,747
<p>I'm trying to read variables from a batch file for later use in the batch script, which is a Java launcher. I'd ideally like to have the same format for the settings file on all platforms (Unix, Windows), and also be a valid Java Properties file. That is, it should look like this:</p> <pre><code>setting1=Value1 setting2=Value2 ... </code></pre> <p>Is it possible to read such values like you would in a Unix shell script? The could should look something like this:</p> <pre><code>READ settingsfile.xy java -Dsetting1=%setting1% ... </code></pre> <p>I know that this is probably possible with <code>SET setting1=Value1</code>, but I'd really rather have the same file format for the settings on all platforms.</p> <p>To clarify: I need to do this in the command line/batch environment as I also need to set parameters that cannot be altered from within the JVM, like -Xmx or -classpath.</p>
[ { "answer_id": 232813, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 6, "selected": true, "text": "setlocal\nFOR /F \"tokens=*\" %%i in ('type Settings.txt') do SET %%i\njava -Dsetting1=%setting1% ...\nendlocal\n" }, { "answer_id": 235538, "author": "micro", "author_id": 23275, "author_profile": "https://Stackoverflow.com/users/23275", "pm_score": 0, "selected": false, "text": "import java.util.Map;\n\npublic class EnvMap {\n public static void main (String[] args) {\n Map<String, String> env = System.getenv();\n for (String envName : env.keySet()) {\n System.out.format(\"%s=%s%n\", envName, env.get(envName));\n }\n }\n}\n" }, { "answer_id": 6204481, "author": "Jared", "author_id": 745412, "author_profile": "https://Stackoverflow.com/users/745412", "pm_score": 1, "selected": false, "text": ":parsePropertiesFile\n set PROPS_FILE=%1\n shift\n :propLoop\n if \"%1\"==\"\" goto:eof\n FOR /F \"tokens=*\" %%i in ('type %PROPS_FILE% ^| findStr.exe \"%1=\"') do SET %%i\n shift\n GOTO propLoop\ngoto:eof\n call:parsePropertiesFile props.properties setting1 setting2" }, { "answer_id": 70467042, "author": "Eboubaker", "author_id": 10387008, "author_profile": "https://Stackoverflow.com/users/10387008", "pm_score": 0, "selected": false, "text": "# .env SET FOR /F \"eol=# tokens=*\" %%i IN (%~dp0.env) DO SET %%i\n /A /A PORT=1215 # The name of the mariadb service to be installed\nMariaDb_serviceName=Swoole_MariaDB\n# which port the mariadb server will run at\n# notice i added /A flag so that the SET command stores the variable as a number\n/A MariaDb_port=1214\n# password of mariadb root user\nMariaDb_rootPassword=\n# Database to be created after installing mariadb\nMariaDb_createDataBase=data\n# the server service name to be installed\nServer_serviceName=Swoole_Server\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22227/" ]
232,748
<p>User A logs into a ticket management system to edit content on "SomePage.aspx"</p> <p>User B logs in 30 seconds later to edit the same ticket on "SomePage.aspx"</p> <p>What are some of the best known practices(in a 3-tier architecture) for notifying each of the users that someone else is modifying the same content? </p>
[ { "answer_id": 232770, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 1, "selected": false, "text": "SELECT * FROM Tickets WHERE TicketID = 897; \nUPDATE Tickets SET EditingBy = @UserID WHERE TicketID = 897;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4646/" ]
232,775
<p>This is one of those ajax "alternate flow" questions. Normally I expect my ajax request to return a part of the page. But sometimes it may return a full page with html, head and body tag. </p> <p>At the time I return from my ajax-request I can detect if this is a full page, but is it possible to trigger a full page reload (with full event cycle) based on the string content I have ?</p> <p>(And yes, I have tried replacing the body element, but that does not give me the events and does not allow me to change the content in the head block)</p> <p>Any framework reference is ok</p>
[ { "answer_id": 232784, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "location.href = ..." }, { "answer_id": 232809, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "Replace the current document with the one at the given URL:\n\nfunction goMoz() { \n window.location = \"http://www.mozilla.org\";\n} \n\n// in html: <button onclick=\"goMoz();\">Mozilla</button>\n" }, { "answer_id": 232857, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 2, "selected": false, "text": "window.location new Ajax.Request(url, {\n method: 'get',\n // status 200: yadaa\n onSuccess: function(transport) {\n // doSomething\n },\n // status 301: moved permanently\n on301: function(transport){ \n window.location = transport.responseText;\n }\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23691/" ]
232,781
<p>can anybody show me how to build a string using checkbox. what would be the best way to do this.</p> <p>for example i have 4 checkbox's each with its own value (valueA, valueB, valueC, valueD) the thing is i want to display each result in different lines.</p> <p>result if B &amp; C is selected : </p> <p>valueB <br> valueC </p> <p>and how would i display this again if i saved this into a database?</p>
[ { "answer_id": 232801, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "\"if I saved this into a database\" ? \n" }, { "answer_id": 232803, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "StringBuilder builder = new StringBuilder();\nforeach (CheckBox cb in checkboxes)\n{\n if (cb.Checked)\n {\n builder.AppendLine(cb.Text); // Or whatever\n\n // Alternatively:\n // builder.Append(cb.Text);\n // builder.Append(Environment.NewLine); // Or a different line ending\n }\n}\n// Call Trim if you want to remove the trailing newline\nstring result = builder.ToString();\n" }, { "answer_id": 232804, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 2, "selected": false, "text": "For each checkbox in the target list of controls\n append value and a newline character to a temporary string variable\noutput temporary string \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
232,785
<p>What are some uses of <code>#pragma</code> in C, with examples?</p>
[ { "answer_id": 232790, "author": "Schildmeijer", "author_id": 148909, "author_profile": "https://Stackoverflow.com/users/148909", "pm_score": 4, "selected": false, "text": "#pragma once #pragma once #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */" }, { "answer_id": 232793, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 6, "selected": false, "text": "#pragma #pragma pack(1) #dogma" }, { "answer_id": 232796, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 6, "selected": false, "text": "#pragma" }, { "answer_id": 235918, "author": "Justin Love", "author_id": 30203, "author_profile": "https://Stackoverflow.com/users/30203", "pm_score": 3, "selected": false, "text": "#pragma code BANK1\n#pragma data BANK2\n\n#pragma INT3 TimerHandler\n" }, { "answer_id": 235922, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": false, "text": "#if #endif #pragma pack(push, 1)\nstruct PackedStructure\n{\n char a;\n int b;\n short c;\n};\n#pragma pack(pop)\n// sizeof(PackedStructure) == 7\n struct PackedStructure __attribute__((__packed__))\n{\n char a;\n int b;\n short c;\n};\n// sizeof(PackedStructure == 7)\n #define __attribute__(x) #if #endif" }, { "answer_id": 13639835, "author": "sandeep", "author_id": 1865360, "author_profile": "https://Stackoverflow.com/users/1865360", "pm_score": 3, "selected": false, "text": "#pragma #pragma vector=ADC12_VECTOR" }, { "answer_id": 24056459, "author": "suresh pareek", "author_id": 2692601, "author_profile": "https://Stackoverflow.com/users/2692601", "pm_score": 2, "selected": false, "text": "#pragma startup #pragma exit #pragma warn #pragma startup #pragma exit #pragma warn #pragma" }, { "answer_id": 35187479, "author": "Sparkzz", "author_id": 5516474, "author_profile": "https://Stackoverflow.com/users/5516474", "pm_score": 2, "selected": false, "text": "#pragma startup #pragma startup func1\n#pragma exit func2\n func1 main func2 func1 func2 void __attribute__((constructor)) func1();\nvoid __attribute__((destructor)) func2();\n" }, { "answer_id": 36985271, "author": "Basheer AL-MOMANI", "author_id": 4251431, "author_profile": "https://Stackoverflow.com/users/4251431", "pm_score": 3, "selected": false, "text": "#pragma simple OpenMP example #pragma briefly machine-specific operating-system-specific #include <stdio.h>\n#include <omp.h>// compile with: /openmp\n\nint main() {\n #pragma omp parallel num_threads(4)\n {\n int i = omp_get_thread_num();\n printf_s(\"Hello from thread %d\\n\", i);\n }\n}\n Hello from thread 0\nHello from thread 1\nHello from thread 2\nHello from thread 3\n\nNote that the order of output can vary on different machines.\n #pragma many many applications #pragma OpenMP" }, { "answer_id": 42677417, "author": "MD XF", "author_id": 7659995, "author_profile": "https://Stackoverflow.com/users/7659995", "pm_score": 2, "selected": false, "text": "#pragma #pragma #pragma GCC diagnostic ignored \"-Wimplicit-function-declaration\"\n libportable #pragma once libportable" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,846
<p>After installing asp.net (and aspnet_regIIS.exe -i) the site doesn't accept my default.aspx page. When trying to access it I get a 404. When hitting directly to my mvc pages (/search.mvc for example) it works like a charm.</p> <p>We checked the website configuration and noted that there are no .aspx references in the scriptmaps node.</p> <p>What am I missing?</p>
[ { "answer_id": 232868, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "aspnet_regIIS.exe -i" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,848
<p>I'm writing code like this, doing a little quick and dirty timing:</p> <pre><code>var sw = new Stopwatch(); sw.Start(); for (int i = 0; i &lt; 1000; i++) { b = DoStuff(s); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); </code></pre> <p>Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the <strong><code>DoStuff(s)</code></strong> with <strong><code>DoSomethingElse(s)</code></strong>?</p> <p>I know it can be done as a <code>Delegate</code> but I'm wondering about the lambda way.</p>
[ { "answer_id": 232852, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": false, "text": "Stopwatch sw = MyObject.TimedFor(1000, () => DoStuff(s));\n public static Stopwatch TimedFor(this DependencyObject source, Int32 loops, Action action)\n{\nvar sw = new Stopwatch();\nsw.Start();\nfor (int i = 0; i < loops; ++i)\n{\n action.Invoke();\n}\nsw.Stop();\n\nreturn sw;\n}\n public class Timing\n{\n public static Stopwatch TimedFor(Action action, Int32 loops)\n {\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < loops; ++i)\n {\n action.Invoke();\n }\n sw.Stop();\n\n return sw;\n }\n}\n Stopwatch sw = Timing.TimedFor(() => DoStuff(s), 1000);\n" }, { "answer_id": 232870, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 8, "selected": true, "text": "public static class StopwatchExtensions\n{\n public static long Time(this Stopwatch sw, Action action, int iterations)\n {\n sw.Reset();\n sw.Start(); \n for (int i = 0; i < iterations; i++)\n {\n action();\n }\n sw.Stop();\n\n return sw.ElapsedMilliseconds;\n }\n}\n var s = new Stopwatch();\nConsole.WriteLine(s.Time(() => DoStuff(), 1000));\n" }, { "answer_id": 232871, "author": "Morten Christiansen", "author_id": 4055, "author_profile": "https://Stackoverflow.com/users/4055", "pm_score": 2, "selected": false, "text": "public static Stopwatch MeasureTime<T>(int iterations, Action<T> action, T param)\n{\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < iterations; i++)\n {\n action.Invoke(param);\n }\n sw.Stop();\n\n return sw;\n}\n\npublic static Stopwatch MeasureTime<T, K>(int iterations, Action<T, K> action, T param1, K param2)\n{\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < iterations; i++)\n {\n action.Invoke(param1, param2);\n }\n sw.Stop();\n\n return sw;\n}\n" }, { "answer_id": 232879, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 3, "selected": false, "text": "static void Main(string[] args)\n{\n Action action = () =>\n {\n for (int i = 0; i < 10000000; i++)\n Math.Sqrt(i);\n };\n\n for(int i=1; i<=16; i++)\n Console.WriteLine(i + \" thread(s):\\t\" + \n CodeProfiler.ProfileAction(action, 100, i));\n\n Console.Read();\n}\n" }, { "answer_id": 233519, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 2, "selected": false, "text": " public static class Test {\n public static void Invoke() {\n using( SingleTimer.Start )\n Thread.Sleep( 200 );\n Console.WriteLine( SingleTimer.Elapsed );\n\n using( SingleTimer.Start ) {\n Thread.Sleep( 300 );\n }\n Console.WriteLine( SingleTimer.Elapsed );\n }\n}\n\npublic class SingleTimer :IDisposable {\n private Stopwatch stopwatch = new Stopwatch();\n\n public static readonly SingleTimer timer = new SingleTimer();\n public static SingleTimer Start {\n get {\n timer.stopwatch.Reset();\n timer.stopwatch.Start();\n return timer;\n }\n }\n\n public void Stop() {\n stopwatch.Stop();\n }\n public void Dispose() {\n stopwatch.Stop();\n }\n\n public static TimeSpan Elapsed {\n get { return timer.stopwatch.Elapsed; }\n }\n}\n" }, { "answer_id": 741630, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "static class BenchmarkExtension {\n\n public static void Times(this int times, string description, Action action) {\n Stopwatch watch = new Stopwatch();\n watch.Start();\n for (int i = 0; i < times; i++) {\n action();\n }\n watch.Stop();\n Console.WriteLine(\"{0} ... Total time: {1}ms ({2} iterations)\", \n description, \n watch.ElapsedMilliseconds,\n times);\n }\n}\n var randomStrings = Enumerable.Range(0, 10000)\n .Select(_ => Guid.NewGuid().ToString())\n .ToArray();\n\n50.Times(\"Add 10,000 random strings to a Dictionary\", \n () => {\n var dict = new Dictionary<string, object>();\n foreach (var str in randomStrings) {\n dict.Add(str, null);\n }\n });\n\n50.Times(\"Add 10,000 random strings to a SortedList\",\n () => {\n var list = new SortedList<string, object>();\n foreach (var str in randomStrings) {\n list.Add(str, null);\n }\n });\n Add 10,000 random strings to a Dictionary ... Total time: 144ms (50 iterations)\nAdd 10,000 random strings to a SortedList ... Total time: 4088ms (50 iterations)\n" }, { "answer_id": 855624, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 5, "selected": false, "text": "public class DisposableStopwatch: IDisposable {\n private readonly Stopwatch sw;\n private readonly Action<TimeSpan> f;\n\n public DisposableStopwatch(Action<TimeSpan> f) {\n this.f = f;\n sw = Stopwatch.StartNew();\n }\n\n public void Dispose() {\n sw.Stop();\n f(sw.Elapsed);\n }\n}\n using (new DisposableStopwatch(t => Console.WriteLine(\"{0} elapsed\", t))) {\n // do stuff that I want to measure\n}\n" }, { "answer_id": 1820942, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 3, "selected": false, "text": "StopWatch Disposed Stopped public partial class With\n{\n public static long Benchmark(Action action)\n {\n var stopwatch = Stopwatch.StartNew();\n action();\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n}\n public void Execute(Action action)\n{\n var time = With.Benchmark(action);\n log.DebugFormat(“Did action in {0} ms.”, time);\n}\n StopWatch N public partial class With\n{\n public static void Iterations(int n, Action action)\n {\n for(int count = 0; count < n; count++)\n action();\n }\n}\n public void Execute(Action action, int n)\n{\n var time = With.Benchmark(With.Iterations(n, action));\n log.DebugFormat(“Did action {0} times in {1} ms.”, n, time);\n}\n public static class Extensions\n{\n public static long Benchmark(this Action action)\n {\n return With.Benchmark(action);\n }\n\n public static Action Iterations(this Action action, int n)\n {\n return () => With.Iterations(n, action);\n }\n}\n public void Execute(Action action, int n)\n{\n var time = action.Iterations(n).Benchmark()\n log.DebugFormat(“Did action {0} times in {1} ms.”, n, time);\n}\n" }, { "answer_id": 57419714, "author": "Alper Ebicoglu", "author_id": 1767482, "author_profile": "https://Stackoverflow.com/users/1767482", "pm_score": 0, "selected": false, "text": "public static class StopWatchExtensions\n{\n public static async Task<TimeSpan> LogElapsedMillisecondsAsync(\n this Stopwatch stopwatch,\n ILogger logger,\n string actionName,\n Func<Task> action)\n {\n stopwatch.Reset();\n stopwatch.Start();\n\n await action();\n\n stopwatch.Stop();\n\n logger.LogDebug(string.Format(actionName + \" completed in {0}.\", stopwatch.Elapsed.ToString(\"hh\\\\:mm\\\\:ss\")));\n\n return stopwatch.Elapsed;\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
232,861
<p>Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, <code>f</code>, which prints the Fibonacci numbers.</p> <p>Starting point: <strong><s>25</s> 14 characters</strong> in <strong>Haskell</strong>:</p> <p><s> <code>f=0:1:zipWith(+)f(tail f)</code> </s></p> <pre><code>f=0:scanl(+)1f </code></pre>
[ { "answer_id": 232943, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 3, "selected": false, "text": "1[pdd5**v1++2/lxx]dsxx\n" }, { "answer_id": 233161, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "2,~{..p@+.}do\n 2, [0 1] ~ do 0 1 do . 0 1 1 1 p 0 1 1 @ 1 1 0 + 1 1 . do do" }, { "answer_id": 233342, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "function f(n)if n<2 then return n else return f(n-1)+f(n-2)end end function f(n){return n<2?n:f(n-1)+f(n-2)} int f(int n){return n<2?n:f(n-1)+f(n-2);} function f(n)a=1;b=0;for i=1,n do a,b=b,a+b end return b end function f(n){a=1;b=i=0;for(;i++<n;){x=a+b;a=b;b=x}return b} int f(int n){int a=1,b=0,i=0;for(;i++<n;){int x=a+b;a=b;b=x;}return b;} local a,b=1,0 function f(n,a,b)if n<1 then return b else return f(n-1,b,a+b)end end function f(n,a,b){return n<1?b:f(n-1,b,a+b)} int f(int n,int a,int b){return n<1?b:f(n-1,b,a+b);}" }, { "answer_id": 233471, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 3, "selected": false, "text": "def f(a=0,b=1):\n while 1:yield a;a,b=b,a+b\n f=lambda n:n if n<2 else f(n-1)+f(n-2)\n f=lambda n:int(.5+(.5+5**.5/2)**n/5**.5)\n" }, { "answer_id": 233568, "author": "mpeters", "author_id": 12094, "author_profile": "https://Stackoverflow.com/users/12094", "pm_score": 4, "selected": false, "text": "sub f{1,1...{$^a+$^b}}\n" }, { "answer_id": 233889, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 1, "selected": false, "text": "float f(float n) {\n return (pow(1+sqrt(5.0))/2.0),n) - pow(1+sqrt(5.0))/2.0),n)/sqrt(n));\n}\n" }, { "answer_id": 234690, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "f=:3 :'{:}.@(,+/)^:y(0 1x)'\n +/ (,+/) }.@(,+/) }.@(,+/)^:y y }.@(,+/)^:y(0 1x) (0,1) x {:}.@(,+/)^:y(0 1x) f=:3 :'{:}.@(,+/)^:y(0 1x)' f y" }, { "answer_id": 234747, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "F(n){return n<2?n:F(n-1)+F(n-2);}" }, { "answer_id": 249970, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 2, "selected": false, "text": "def f(n)n<2?n:f(n-1)+f(n-2)end\n" }, { "answer_id": 250041, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "fibonacci() def fibonacci(a=0, b=1):\n while True:\n yield b\n a, b = b, a+b\n" }, { "answer_id": 250202, "author": "Paulius", "author_id": 1353085, "author_profile": "https://Stackoverflow.com/users/1353085", "pm_score": 3, "selected": false, "text": ":f\n set i=0\n set r=1\n set n=1\n set f=0\n :l\n if %n% GTR %~1 goto e\n set f=%f% %r%\n set /A s=%i%+%r%\n set i=%r%\n set r=%s%\n set /A n+=1\n goto l\n :e\n set r=%f%\n exit /B 0\n @echo off\ncall :ff 0\ncall :ff 1\ncall :ff 2\ncall :ff 3\ncall :ff 5\ncall :ff 10\ncall :ff 15\ncall :ff 20\nexit /B 0\n\n:ff\n call :f \"%~1\"\n echo %~1: %r%\n exit /B 0\n\n:f\n set i=0\n set r=1\n set n=1\n set f=0\n :l\n if %n% GTR %~1 goto e\n set f=%f% %r%\n set /A s=%i%+%r%\n set i=%r%\n set r=%s%\n set /A n+=1\n goto l\n :e\n set r=%f%\n exit /B 0\n" }, { "answer_id": 270470, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 1, "selected": false, "text": "f:func<int32,int32>:=n->iif(n>1,f(n-1)+f(n-2),n)\n" }, { "answer_id": 332302, "author": "Lex", "author_id": 28994, "author_profile": "https://Stackoverflow.com/users/28994", "pm_score": 1, "selected": false, "text": "def f(n);n<2?1:f(n-1)+f(n-2);end\n0.upto 20 {|n|p f n}\n def f(n);n<2?1:f(n-1)+f(n-2);end\ndef s(n);(0..n).to_a.map {|n| f(n)};end\n def f(n);n<2?1:f(n-1)+f(n-2);end\np (0..$*[0].to_i).to_a.map {|n| f(n)}\n" }, { "answer_id": 396990, "author": "Hynek -Pichi- Vychodil", "author_id": 49197, "author_profile": "https://Stackoverflow.com/users/49197", "pm_score": 3, "selected": false, "text": "dc -e'1df[dsa+plarlbx]dsbx'\n" }, { "answer_id": 411894, "author": "BenAlabaster", "author_id": 40650, "author_profile": "https://Stackoverflow.com/users/40650", "pm_score": 2, "selected": false, "text": "using System;\nstatic void Main()\n{\n var x = Math.Sqrt(5);\n for (int n = 0; n < 10; n++)\n Console.WriteLine((Math.Pow((1 + x) / 2, n) - Math.Pow((1 - x) / 2, n)) / p) ;\n}\n" }, { "answer_id": 412040, "author": "Henk", "author_id": 44427, "author_profile": "https://Stackoverflow.com/users/44427", "pm_score": 3, "selected": false, "text": "(let f((a 0)(b 1))(printf\"~a,\"b)(f b(+ a b)))\n" }, { "answer_id": 412152, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "#define t template <int n> struct \n#define u template <> struct f\nt g { int v[0]; };\nt f { enum { v = f<n-1>::v + f<n-2>::v }; g<v> x;};\nu<1> { enum { v = 1 }; };\nu<0> { enum { v = 0 }; };\nint main() { f<10> x; }\n" }, { "answer_id": 537083, "author": "leen", "author_id": 26462, "author_profile": "https://Stackoverflow.com/users/26462", "pm_score": 3, "selected": false, "text": "(0,1)|>Seq.unfold(fun(a,b)->Some(a,(b,a+b)))\n" }, { "answer_id": 1057022, "author": "Francois G", "author_id": 47978, "author_profile": "https://Stackoverflow.com/users/47978", "pm_score": 2, "selected": false, "text": "let rec f l a b =function 0->a::l|1->b::l|n->f (a::l) b (a+b) (n-1) in f [] 1 1;;\n" }, { "answer_id": 1396539, "author": "Matt Lewis", "author_id": 28987, "author_profile": "https://Stackoverflow.com/users/28987", "pm_score": 0, "selected": false, "text": "object f=1&1 loop do f&=f[$]+f[$-1]until 0\n" }, { "answer_id": 1396574, "author": "Nican", "author_id": 99966, "author_profile": "https://Stackoverflow.com/users/99966", "pm_score": 2, "selected": false, "text": "function f(n)return n<2 and n or f(n-1)+f(n-2)end\n" }, { "answer_id": 1396763, "author": "I. J. Kennedy", "author_id": 8677, "author_profile": "https://Stackoverflow.com/users/8677", "pm_score": 4, "selected": false, "text": "59 31 C0 E3 08 89 C3 40 93 01 D8 E2 FB C3\n" }, { "answer_id": 1396828, "author": "Chris Dodd", "author_id": 29759, "author_profile": "https://Stackoverflow.com/users/29759", "pm_score": 0, "selected": false, "text": "f = 1 fby 1 fby f + prev f;\n" }, { "answer_id": 1548888, "author": "Mark Rushakoff", "author_id": 126042, "author_profile": "https://Stackoverflow.com/users/126042", "pm_score": 2, "selected": false, "text": "9," }, { "answer_id": 2901383, "author": "Eric Mickelsen", "author_id": 214146, "author_profile": "https://Stackoverflow.com/users/214146", "pm_score": 4, "selected": false, "text": "+.>+.[<[>+>+<<-]>.[<+>-]>[<+>-]<]\n" }, { "answer_id": 3029192, "author": "Callum Rogers", "author_id": 139766, "author_profile": "https://Stackoverflow.com/users/139766", "pm_score": 6, "selected": true, "text": "1↓[2?+1]\n 1↓[2?+↓£1]\n RePeNt \"1↓[2?+1]\"\n Command Explanation Stack\n------- ----------- -----\n\n1 Push a 1 onto the stack 1\n↓ Push last stack value 1 1\n[ Start a do-while loop 1 1\n2? Push a two, then pop the 2 and copy the last 2 stack 1 1 1 1\n items onto the stack\n+ Add on the stack 1 1 2\n↓£ Push last stack value then print it 1 1 2\n1 Push a 1 onto the stack 1 1 2 1\n] Pop value (1 in this case), if it is a 0 exit the loop 1 1 2\n otherwise go back to the loop start.\n 1 1\n1 1 2\n1 1 2 3\n1 1 2 3 5\n do { } while(true) N_1↓nI{2?+}\n" }, { "answer_id": 3029228, "author": "JUST MY correct OPINION", "author_id": 282658, "author_profile": "https://Stackoverflow.com/users/282658", "pm_score": 1, "selected": false, "text": " .globl start\n .text\nstart:\n mov $0,(sp)\n mov $27,-(sp)\n jsr pc, lambda\nprint_r1:\n mov $outbyte,r3\ndiv_loop:\n sxt r0\n div $12,r0\n add $60,r1\n movb r1,-(r3)\n mov r0,r1\n tst r1\n jne div_loop\n mov $1,r0\n sys 4; outtext; 37\n mov $1,r0\n sys 1\nlambda:\n mov 2(sp),r1\n cmp $2,r1\n beq gottwo\n bgt gotone\n sxt r0\n div $2,r0\n tst r1\n beq even\nodd:\n mov 2(sp),r1\n dec r1\n sxt r0\n div $2,r0\n mov r0,-(sp)\n jsr pc,lambda\n add $2,sp\n mov r0,r3\n mov r1,r2\n mov r3,r4\n mul r2,r4\n mov r5,r1\n mov r3,r4\n add r2,r4\n mul r2,r4\n add r5,r1\n mul r3,r3\n mov r3,r0\n mul r2,r2\n add r3,r0\n rts pc\neven:\n mov 2(sp),r1\n sxt r0\n div $2,r0\n dec r0\n mov r0,-(sp)\n jsr pc,lambda\n add $2,sp\n mov r0,r3\n mov r1,r2\n mov r2,r4\n mul r2,r4\n mov r5,r1\n mov r2,r4\n add r3,r4\n mul r4,r4\n add r5,r1\n mov r2,r4\n add r3,r4\n mul r2,r4\n mov r5,r0\n mul r2,r3\n add r3,r0\n rts pc\ngotone:\n mov $1,r0\n mov $1,r1\n rts pc\ngottwo:\n mov $1,r0\n mov $2,r1\n rts pc\n\n .data\nouttext:\n .byte 62,63,162,144,40,106,151,142,157,156\n .byte 141,143,143,151,40,156,165,155\n .byte 142,145,162,40,151,163,40\n .byte 60,60,60,60,60\noutbyte:\n .byte 12\n" }, { "answer_id": 3040636, "author": "Tom H", "author_id": 350202, "author_profile": "https://Stackoverflow.com/users/350202", "pm_score": 2, "selected": false, "text": ">+++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]\n >++++++++++++++++++++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]\n" }, { "answer_id": 3146561, "author": "st0le", "author_id": 216517, "author_profile": "https://Stackoverflow.com/users/216517", "pm_score": 0, "selected": false, "text": "void f(int n){for(int a=1,b=1;n-->0;b=a+(a=b)){System.out.print(a+\",\");}}\n def f(n);a,b=1,1;1.upto(n){p a;b=a+(a=b);};end\n def f(n);a=b=1;n.times{p a;b=a+(a=b);};end\n" }, { "answer_id": 4842173, "author": "Eelvex", "author_id": 349708, "author_profile": "https://Stackoverflow.com/users/349708", "pm_score": 1, "selected": false, "text": "(+/@(2&{.),])^:n i.2\n" }, { "answer_id": 4935807, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 2, "selected": false, "text": "=SUM(A1:A2)\n 1 #NUM!" }, { "answer_id": 6639376, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "f(){int cn=2,*n=calloc(9,9);n[1]=1;while(cn<32)printf(\"%d \",n[cn]=n[cn-1]+n[cn++-2]);}" }, { "answer_id": 11119340, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "%1\n%0 %1%2 %1 #\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
232,863
<p>How can I check in C# if button.Click event has any handlers associated? If (button.Click != null) throws compile error.</p>
[ { "answer_id": 232927, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 0, "selected": false, "text": "event System.EventHandler NewEvent;\n EventHandler handler = NewEvent;\n if(handler != null)\n {\n handler(this, e);\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,869
<pre><code>&lt;style type="text/css"&gt; body { font-family:Helvetica, sans-serif; font-size:12px; } p, h1, form, button { border: 0; margin: 0; padding: 0; } .spacer { clear: both; height: 1px; } /* ----------- My Form ----------- */ .myform { margin: 0 auto; width: 400px; padding: 14px; } /* ----------- basic ----------- */ #basic { border: solid 2px #DEDEDE; } #basic h1 { font-size: 14px; font-weight: bold; margin-bottom: 8px; } #basic p { font-size: 11px; color: #666666; margin-bottom: 20px; border-bottom: solid 1px #dedede; padding-bottom: 10px; } #basic label { display: block; font-weight: bold; text-align: right; width: 140px; float: left; } #basic .small{ color:#666666; display:block; font-size:11px; font-weight:normal; text-align:right; width:140px; } #basic input{ float:left; width:200px; margin:2px 0 30px 10px; } #basic button{ clear:both; margin-left:150px; background:#888888; color:#FFFFFF; border:solid 1px #666666; font-size:11px; font-weight:bold; padding:4px 6px; } &lt;/style&gt; &lt;div id="basic" class="myform"&gt; &lt;form id="form1" name="form1" method="post" action=""&gt; &lt;h1&gt;Sign-up form&lt;/h1&gt; &lt;p&gt;This is the basic look of my form without table&lt;/p&gt; &lt;label&gt;Name &lt;span class="small"&gt;Add your name&lt;/span&gt; &lt;/label&gt; &lt;input type="text" name="textfield" id="textfield" /&gt; &lt;label&gt;Email &lt;span class="small"&gt;Add a valid address&lt;/span&gt; &lt;/label&gt; &lt;input type="text" name="textfield" id="textfield" /&gt; &lt;label&gt;Email &lt;span class="small"&gt;Add a valid address&lt;/span&gt; &lt;/label&gt; &lt;!-- Problem ---&gt; &lt;input type="radio" name="something" id="r1" class="radio" value="1" /&gt;&lt;label for="r1"&gt;One&lt;/label&gt; &lt;input type="radio" name="something" id="r2" class="radio" value="2" /&gt;&lt;label for="r2"&gt;Two&lt;/label&gt; &lt;!-- Problem ---&gt; &lt;button type="submit"&gt;Sign-up&lt;/button&gt; &lt;div class="spacer"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>I was given this example form, however I cannot add radio buttons without them being messed up.</p>
[ { "answer_id": 232880, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "name=\"textfield\" name=\"my_radio\"" }, { "answer_id": 232910, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 1, "selected": false, "text": "<label for=\"input\">Label: <input type=\"radio\" id=\"input\" name=\"input\" /></label>\n" }, { "answer_id": 232913, "author": "monkey do", "author_id": 29951, "author_profile": "https://Stackoverflow.com/users/29951", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\nbody{\n font-family:Helvetica, sans-serif; \n font-size:12px;\n}\np, h1, form, button{border:0; margin:0; padding:0;}\n.spacer{clear:both; height:1px;}\n/* ----------- My Form ----------- */\n.myform{\n margin:0 auto;\n width:400px;\n padding:14px;\n}\n /* ----------- basic ----------- */\n #basic{\n border:solid 2px #DEDEDE;\n }\n #basic h1 {\n font-size:14px;\n font-weight:bold;\n margin-bottom:8px;\n }\n #basic p{\n font-size:11px;\n color:#666666;\n margin-bottom:20px;\n border-bottom:solid 1px #dedede;\n padding-bottom:10px;\n }\n #basic label{\n font-weight:bold;\n text-align:right;\n width:140px;\n float:left;\n }\n #basic .small{\n color:#666666;\n display:block;\n font-size:11px;\n font-weight:normal;\n text-align:right;\n width:140px;\n }\n #basic input{\n float:left;\n width:200px;\n margin:2px 0 30px 10px;\n }\n #basic button{ \n clear:both;\n margin-left:150px;\n background:#888888;\n color:#FFFFFF;\n border:solid 1px #666666;\n font-size:11px;\n font-weight:bold;\n padding:4px 6px;\n }\n #basic input.radio{\n width:50px;\n margin:2px 0 30px 10px;\n }\n #basic label.radio {\n width:40px;\n text-align:left;\n }\n</style>\n\n<div id=\"basic\" class=\"myform\">\n <form id=\"form1\" name=\"form1\" method=\"post\" action=\"\">\n <h1>Sign-up form</h1>\n <p>This is the basic look of my form without table</p>\n <label>Name\n <span class=\"small\">Add your name</span>\n </label>\n <input type=\"text\" name=\"textfield\" id=\"textfield\" />\n\n <label>Email\n <span class=\"small\">Add a valid address</span>\n </label>\n <input type=\"text\" name=\"textfield\" id=\"textfield\" />\n\n <label>Email\n <span class=\"small\">Add a valid address</span>\n </label>\n <!-- Problem --->\n <input type=\"radio\" name=\"r1\" id=\"r1\" class=\"radio\" value=\"1\" /><label class=\"radio\" for=\"r1\">One</label>\n <input type=\"radio\" name=\"r2\" id=\"r2\" class=\"radio\" value=\"2\" /><label class=\"radio\" for=\"r2\">Two</label>\n <!-- Problem --->\n <button type=\"submit\">Sign-up</button>\n <div class=\"spacer\"></div>\n\n\n </form>\n</div>\n" }, { "answer_id": 232920, "author": "Wayne Austin", "author_id": 31109, "author_profile": "https://Stackoverflow.com/users/31109", "pm_score": 3, "selected": true, "text": "#basic input.radio\n{\n width:20px;\n\n}\n#basic label.radiolabel\n{\n width:40px;\n text-align:left;\n line-height:24px;\n}\n <!-- Problem ---> \n<input type=\"radio\" name=\"textfield\" id=\"r1\" class=\"radio\" value=\"1\" />\n<label for=\"r1\" class=\"radiolabel\">One</label> \n<input type=\"radio\" name=\"textfield\" id=\"r2\" class=\"radio\" value=\"2\" />\n<label for=\"r2\" class=\"radiolabel\">Two</label> \n<!-- Problem --->\n" }, { "answer_id": 232965, "author": "philistyne", "author_id": 16597, "author_profile": "https://Stackoverflow.com/users/16597", "pm_score": 0, "selected": false, "text": "#basic input.radio { width:20px; }\n #basic input { width:200px;}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
232,881
<p>In VS2005 and up, is it possible to specify which configuration should be selected by default?</p> <p>I have several configurations in my solution but one of them should be used in most cases. Hence I'd like to make sure that devs who pull it out of Source Control use the right configuration(unless of course they specifically choose another one).</p> <p>Ideally, this setting should be in the .sln file since that one is under Source Control.</p>
[ { "answer_id": 31524307, "author": "Ringil", "author_id": 4882032, "author_profile": "https://Stackoverflow.com/users/4882032", "pm_score": 3, "selected": false, "text": "Debug Debug Test Test Debug Debug" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
232,884
<p>Like most developers here and in the entire world, I have been developing software systems using object-oriented programming (OOP) techniques for many years. So when I read that aspect-oriented programming (AOP) addresses many of the problems that traditional OOP doesn't solve completely or directly, I pause and think, is it real?</p> <p>I have read a lot of information trying to learn the keys of this AOP paradigm and I´m in the same place, so, I wanted to better understand its benefits in real world application development.</p> <p>Does somebody have the answer?</p>
[ { "answer_id": 232918, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 9, "selected": true, "text": "void set...(...) {\n :\n :\n Display.update();\n}\n after() : set() {\n Display.update();\n}\n pointcut set() : execution(* set*(*) ) && this(MyGraphicsClass) && within(com.company.*);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30715/" ]
232,895
<p>I came across an interesting article which shows how we can transparently encrypt jdbc connections using java thin client. </p> <p><a href="http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/" rel="nofollow noreferrer">http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/</a></p> <p>However I want to know how this can be achieved for application servers (like oc4j) datasources.</p>
[ { "answer_id": 574473, "author": "Franklin", "author_id": 67517, "author_profile": "https://Stackoverflow.com/users/67517", "pm_score": 1, "selected": false, "text": "// Set the Client encryption level \n\"oracle.net.encryption_client\" = Service.getLevelString(level) \n\n// Set the Client encryption selected list \n\"oracle.net.encryption_types_client\"= \"(RC4_40)\"\n\n// Set the Client integrity level \n\"oracle.net.crypto_checksum_client\"= Service.getLevelString(level) \n\n// Set the client integrity selected list \n\"oracle.net.crypto_checksum_types_client\"=\"( MD5 )\"\n" }, { "answer_id": 33154232, "author": "osama yaccoub", "author_id": 2866298, "author_profile": "https://Stackoverflow.com/users/2866298", "pm_score": 0, "selected": false, "text": "<connection-factory factory-class=\"oracle.jdbc.pool.OracleDataSource\" user=... >\n <connection-properties>\n <property name=\"oracle.net.encryption_client\" value=\"REQUIRED123\"/>\n <property name=\"oracle.net.crypto_checksum_types_client\" value=\"(SHA1123)\"/>\n <property name=\"oracle.net.crypto_checksum_client\" value=\"REQUIRED\"/>\n <property name=\"oracle.net.encryption_types_client\" value=\"(AES256)\"/>\n </connection-properties>\n </connection-factory>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
232,905
<p>I got this logic in a control to create a correct url for an image. My control basically needs to diplay an image, but the src is actually a complex string based on different parameters pointing at an image-server.</p> <p>So we decided to to create a control MyImage derived from asp:Image - it works like a charm. Now i need the same logic but my image now needs to respond to a click. What i mean is - the 'MyImage' is used to display images on the site but in a few rare cases i would like it to be clickable.</p> <p>I think i got three choices.</p> <ol> <li>Change MyImage to derive from asp:ImageButton instead of asp:Image.</li> <li>Copy all the code from MyImage into a new MyClickImage and derive from asp:ImageButton.</li> <li>Wrap logic on MyImage to add a hyperlink, implement IPostbackHandler for that hyperlink and add the logic to handle the event.</li> </ol> <p>Obviously i would very much like to avoid using option 2) since i would have to maintain two almost identically controls. The problem with option 1) <em>as i see it</em> (perhaps i'm wrong?) Is that all the images on the site that are not supposed to be clickable will automaticly become clickable. Option 3) seems overly complicated as i would have to maintain state, events and building the link manually.</p> <p>I'm looking for a quick answer like 'you're stupid, just set property 'x' to false when you don't want it to be clickable' - but if i'm not mistaking it is not that obvious and ofcourse a more elaborate answer would be fine :)</p> <p>EDIT: Added the 3rd option - i forgot to put that there in the first place :)</p>
[ { "answer_id": 574473, "author": "Franklin", "author_id": 67517, "author_profile": "https://Stackoverflow.com/users/67517", "pm_score": 1, "selected": false, "text": "// Set the Client encryption level \n\"oracle.net.encryption_client\" = Service.getLevelString(level) \n\n// Set the Client encryption selected list \n\"oracle.net.encryption_types_client\"= \"(RC4_40)\"\n\n// Set the Client integrity level \n\"oracle.net.crypto_checksum_client\"= Service.getLevelString(level) \n\n// Set the client integrity selected list \n\"oracle.net.crypto_checksum_types_client\"=\"( MD5 )\"\n" }, { "answer_id": 33154232, "author": "osama yaccoub", "author_id": 2866298, "author_profile": "https://Stackoverflow.com/users/2866298", "pm_score": 0, "selected": false, "text": "<connection-factory factory-class=\"oracle.jdbc.pool.OracleDataSource\" user=... >\n <connection-properties>\n <property name=\"oracle.net.encryption_client\" value=\"REQUIRED123\"/>\n <property name=\"oracle.net.crypto_checksum_types_client\" value=\"(SHA1123)\"/>\n <property name=\"oracle.net.crypto_checksum_client\" value=\"REQUIRED\"/>\n <property name=\"oracle.net.encryption_types_client\" value=\"(AES256)\"/>\n </connection-properties>\n </connection-factory>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
232,926
<p>For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't changed much. It works some what ok. But when they include this with a C# app, the C# app gets access violation errors, but with classic C++ application it works fine.</p> <p>Is there a strategy that I should know when I provide dlls ?</p>
[ { "answer_id": 232959, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 5, "selected": true, "text": " struct IExportedMethods {\n virtual long __stdcall AMethod(void)=0;\n };\n // with the win32 macros:\n interface IExportedMethods {\n STDMETHOD_(long,AMethod)(THIS)PURE;\n };\n class CMyObject: public IExportedMethods { ...\n extern \"C\" __declspec(dllexport) IExportedClass* WINAPI CreateMyExportedObject(){\n return new CMyObject; \n }\n interface IExportedMethods {\n STDMETHOD_(void) Release(THIS) PURE; };\n class CMyObject : public IExportedMethods {\n STDMETHODIMP_(void) Release(){\n delete this;\n }\n };\n" }, { "answer_id": 233197, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 2, "selected": false, "text": "\n#pragma pack(push,4)\ntypedef myStruct {\n int a;\n char b;\n float c;\n}myStruct;\n#pragma pack(pop)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1781/" ]
232,933
<p>How do I multiply the values of a multi-dimensional array with weights and sum up the results into a new array in PHP or in general?</p> <p>The boring way looks like this:</p> <pre><code>$weights = array(0.25, 0.4, 0.2, 0.15); $values = array ( array(5,10,15), array(20,25,30), array(35,40,45), array(50,55,60) ); $result = array(); for($i = 0; $i &lt; count($values[0]); ++$i) { $result[$i] = 0; foreach($weights as $index =&gt; $thisWeight) $result[$i] += $thisWeight * $values[$index][$i]; } </code></pre> <p>Is there a more elegant solution?</p>
[ { "answer_id": 232963, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "foreach($values as $index => $ary )\n $result[$index] = array_sum($ary) * $weights[$index];\n" }, { "answer_id": 233018, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<?php\n\n$weights = array(0.2,0.3,0.4,0.5);\n$values = array(array(1,2,0.5), array(1,1,1), array(1,1,1), array(1,1,1));\n$result = array();\n\nfor($i = 0; $i < count($values[0]); ++$i) {\n $result[$i] = 0;\n foreach($weights as $index => $thisWeight) {\n $result[$i] += $thisWeight * $values[$index][$i];\n }\n}\nprint_r($result);\n\n\n$result = call_user_func_array(\"array_map\",array_merge(array(\"weightedSum\"),$values));\n\nfunction weightedSum() {\n global $weights;\n $args = func_get_args();\n return array_sum(array_map(\"weight\",$weights,$args));\n}\n\nfunction weight($w,$a) {\n return $w*$a;\n}\n\nprint_r($result);\n\n?>\n" }, { "answer_id": 233022, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 2, "selected": true, "text": "function weigh(&$vals, $key, $weights) {\n $sum = 0;\n foreach($vals as $v)\n $sum += $v*$weights[$key];\n $vals = $sum;\n}\n\n$result = $values;\narray_walk($result, \"weigh\", $weights);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260/" ]
232,934
<p>I want to subclass the built-in DropDownList in ASP.NET so that I can add functionality to it and use it in my pages. I tried doing this with a UserControl but found that it doesn't expose the internal DropDownList (logically, I guess). I've googled for the answer but can't find anything. </p> <p>I've come as far as writing the actual class, and it's possible to subclass from DropDownList but I'm unable to register the file in my ASP.NET page and use it in the source view. Maybe I'm missing some properties in my class?</p> <p>Any ideas?</p>
[ { "answer_id": 232972, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 5, "selected": true, "text": "namespace My.Namespace.Controls\n{\n[ToolboxData(\"<{0}:MyDropDownList runat=\\\"server\\\"></{0}:MyDropDownList>\")]\npublic class MyDropDownList: DropDownList\n{\n // your custom code goes here\n // e.g.\n protected override void RenderContents(HtmlTextWriter writer)\n {\n //Your own render code\n }\n}\n}\n <add tagPrefix=\"my\" namespace=\"My.Namespace.Controls\" assembly=\"MyLibrary\" />\n <my:MyDropDownList ID=\"myDDl\" runat=\"server\">\n ...\n</my:MyDropDownList>\n" }, { "answer_id": 233440, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": " public static void BindListControl (ListControl ctl, SqlDataReader dr,\n String textColumn, String valueColumn, bool addBlankRow, string blankRowText)\n {\n ctl.Items.Clear();\n ctl.DataSource = dr;\n ctl.DataTextField = textColumn;\n ctl.DataValueField = valueColumn;\n ctl.DataBind();\n\n if (addBlankRow == true) ctl.Items.Insert(0, blankRowText);\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614/" ]
232,935
<p>I want to find an SQL query to find rows where field1 does not contain $x. How can I do this?</p>
[ { "answer_id": 232942, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; NOT IN LIKE 'xxx%' LIKE '%xxx' LIKE '%xxx%'" }, { "answer_id": 232951, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": 10, "selected": true, "text": "-- subquery\nSELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);\n-- predefined list\nSELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);\n -- Finds all rows where a does not contain \"text\"\nSELECT * FROM x WHERE x.a NOT LIKE '%text%';\n -- Finds all rows where a does not start with \"text\"\nSELECT * FROM x WHERE x.a NOT LIKE 'text%';\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
232,938
<p>I have a .rc file which is used to include some text data in my executable, like this:</p> <pre><code>1234 RCDATA myfile.txt </code></pre> <p>This works fine: the content of the 'myfile.txt' is included in my executable. The problem is that no 0-terminator is added to the string, and I cannot add it to the file. Is there any way of adding a 0-terminator from within the .rc file? Something like this:</p> <pre><code>1234 RCDATA { myfile.txt, "\0" } // error RC2104 </code></pre> <p>Note that I already found this solution, but I am looking for something more elegant.</p> <pre><code>1234 RCDATA myfile.txt 1235 RCDATA { "\0" } </code></pre> <p>Thanks alot, eli</p>
[ { "answer_id": 232992, "author": "eugensk", "author_id": 17495, "author_profile": "https://Stackoverflow.com/users/17495", "pm_score": 3, "selected": true, "text": "makeZ myfile.txt myfileZ.txt\n 1234 RCDATA myfileZ.txt\n" }, { "answer_id": 239279, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "0x3333 RCDATA\nBEGIN\n \"Hello world\"\n \"Hello world (zero terminated)\\0\"\n L\"A Unicode version of the above\\0\"\n 0x9999 ;hex number stored as a word\nEND\n\nMyRes RCDATA\nBEGIN\n 1034 ;decimal number stored as a word\nEND\n\nMyRes MyResType\nBEGIN\n 10456L ;decimal number stored as a dword\n 1234L,56666L,99999L ;decimal numbers stored as dwords\nEND\n\n34h 100h\nBEGIN\n 33hL,34hL,35hL,36hL ;hex numbers stored as dwords\n 0x37L,0x38L,0x39L,0x40L ;C-style hex numbers stored as dwords\nEND \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12893/" ]
232,945
<p>I have an XML document which looks like this:</p> <pre><code>&lt;xconnect&gt; &lt;type&gt;OK&lt;/type&gt; &lt;response/&gt; &lt;report&gt; &lt;id&gt;suppressionlist_get&lt;/id&gt; &lt;name&gt;Suppression List Get&lt;/name&gt; &lt;timestamp&gt;24 Oct 08 @ 10:16AM&lt;/timestamp&gt; &lt;records type=\"user\"/&gt; &lt;records type=\"client\"/&gt; &lt;records type=\"group\"&gt; &lt;record&gt; &lt;email&gt;investorrelations@hfh.com&lt;/email&gt; &lt;type&gt;RECIPSELF&lt;/type&gt; &lt;long_type&gt;Recipient self suppressed&lt;/long_type&gt; &lt;created&gt;23 Oct 08 @ 8:53PM&lt;/created&gt; &lt;user&gt;facm&lt;/user&gt; &lt;/record&gt; </code></pre> <p>I have omitted the closing of the document for clarity and to keep this post short.</p> <p>Anyway, I have a GridView and I want to bind this XML to the GridView so I get table, like:</p> <pre><code>email | type | long | created | user ------------------------------------ data data data data data </code></pre> <p>And so forth.</p> <p>I was playing with DataSets and XMLDataDocuments and when stepping through, each attribute seemed to be represented as its own table in a data collection table.</p> <p>Any ideas on how to achieve the above? I thought it was as simple as just adding a GridView, and XML data source with the data file specified.</p> <p>Thanks</p>
[ { "answer_id": 232954, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 0, "selected": false, "text": "DataSet.LoadXml()" }, { "answer_id": 7355097, "author": "jon3laze", "author_id": 399770, "author_profile": "https://Stackoverflow.com/users/399770", "pm_score": 1, "selected": false, "text": "DataSet dataSet = new DataSet();\ndataSet.ReadXML(\"Path to XML\");\nthis.GridView1.DataMember = \"record\";\nthis.GridView1.DataSource = dataSet;\nthis.GridView1.DataBind();\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30004/" ]
232,979
<p>I'm looking to get data such as Size/Capacity, Serial No, Model No, Heads Sectors, Manufacturer and possibly SMART data.</p>
[ { "answer_id": 232995, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 4, "selected": true, "text": "ManagementObject disk = new ManagementObject(\"win32_logicaldisk.deviceid=\\\"c:\\\"\"); \ndisk.Get(); \nConsole.WriteLine(\"Logical Disk Size = \" + disk[\"Size\"] + \" bytes\"); \nConsole.WriteLine(\"Logical Disk FreeSpace = \" + disk[\"FreeSpace\"] + \"bytes\");\n" }, { "answer_id": 232999, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": false, "text": "System.Management.ManagementObjectSearcher ms =\n new System.Management.ManagementObjectSearcher(\"SELECT * FROM Win32_DiskDrive\");\nforeach (ManagementObject mo in ms.Get())\n{\n System.Console.Write(mo[\"Model\");\n}\n" }, { "answer_id": 233025, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 2, "selected": false, "text": "ManagementClass driveClass = new ManagementClass(\"Win32_DiskDrive\");\nManagementObjectCollection drives = driveClass.GetInstances();\nforeach (ManagementObject drive in drives) \n{ \n foreach (PropertyData property in drive.Properties)\n {\n Console.WriteLine(\"Property: {0}, Value: {1}\", property.Name, property.Value); \n }\n Console.WriteLine();\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
232,982
<p>I'm looking to create an Intellij IDEA language support plugin for Erlang.</p> <p>The first and biggest problem I've had is in making the JFlex Erlang syntax definition.</p> <p>Does anyone know where can I get the EBNF or BNF for Erlang?</p>
[ { "answer_id": 240652, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 1, "selected": false, "text": "lib/compiler/src/core_parse.yrl" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17375/" ]
232,986
<p>I am attempting to bind a WPF textbox's Maxlength property to a known constant deep within a class. I am using c#.</p> <p>The class has a structure not too dissimilar to the following:</p> <pre><code>namespace Blah { public partial class One { public partial class Two { public string MyBindingValue { get; set; } public static class MetaData { public static class Sizes { public const int Length1 = 10; public const int Length2 = 20; } } } } } </code></pre> <p>Yes it is deeply nested, but unfortunately in this instance I can't move things round very much without huge rewrites required.</p> <p>I was hoping I'd be able to bind the textbox MaxLength to the Length1 or Length2 values but I can't get it to work.</p> <p>I was expecting the binding to be something like the following:</p> <pre><code>&lt;Textbox Text="{Binding Path=MyBindingValue}" MaxLength="{Binding Path=Blah.One.Two.MetaData.Sizes.Length1}" /&gt; </code></pre> <p>Any help is appreciated.</p> <p>Many thanks</p>
[ { "answer_id": 232996, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "{x:Static local:Sizes.Length1}\n" }, { "answer_id": 233017, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 0, "selected": false, "text": "Type 'One.Two.MetaData.Sizes' not found xmlns:local=\"clr-namespace:Blah\"\n MaxLength=\"{x:Static local:One.Two.MetaData.Sizes.Length1}\"\n" }, { "answer_id": 233061, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 5, "selected": false, "text": "MaxLength=\"{x:Static local:One+Two+MetaData+Sizes.Length1}\"\n" }, { "answer_id": 233355, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 4, "selected": true, "text": "{Binding Path=MetaData+Sizes.Length1}\n namespace Blah\n{\n public static class One\n {\n // This metadata class is moved outside of class 'Two', but in this instance\n // this doesn't matter as it relates to class 'One' more specifically than class 'Two'\n public static class MetaData\n {\n public static class Sizes\n {\n public static int Length1 { get { return 10; } }\n public static int Length2 { get { return 20; } }\n }\n }\n\n public partial class Two\n {\n public string MyBindingValue { get; set; }\n }\n }\n}\n xmlns:local=\"clr-namespace:Blah\"\n MaxLength=\"{x:Static local:MetaData+Sizes.Length1}\"\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31128/" ]
232,997
<p>I have what is essentially a jagged array of name value pairs - i need to generate a set of unique name values from this. the jagged array is approx 86,000 x 11 values. It does not matter to me what way I have to store a name value pair (a single string "name=value" or a specialised class for example KeyValuePair).<br> <strong>Additional Info:</strong> There are 40 distinct names and a larger number of distinct values - probably in the region 10,000 values.</p> <p>I am using C# and .NET 2.0 (and the performance is so poor I am thinking that it may be better to push my entire jagged array into a sql database and do a select distinct from there).</p> <p>Below is the current code Im using:</p> <pre><code>List&lt;List&lt;KeyValuePair&lt;string,string&gt;&gt;&gt; vehicleList = retriever.GetVehicles(); this.statsLabel.Text = "Unique Vehicles: " + vehicleList.Count; Dictionary&lt;KeyValuePair&lt;string, string&gt;, int&gt; uniqueProperties = new Dictionary&lt;KeyValuePair&lt;string, string&gt;, int&gt;(); foreach (List&lt;KeyValuePair&lt;string, string&gt;&gt; vehicle in vehicleList) { foreach (KeyValuePair&lt;string, string&gt; property in vehicle) { if (!uniqueProperties.ContainsKey(property)) { uniqueProperties.Add(property, 0); } } } this.statsLabel.Text += "\rUnique Properties: " + uniqueProperties.Count; </code></pre>
[ { "answer_id": 233005, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 0, "selected": false, "text": "Dictionary<System.Guid, KeyValuePair<string, string>> myDict \n = new Dictionary<Guid, KeyValuePair<string, string>>();\n\n\nforeach of your key values in their current format\n myDict.Add(System.Guid.NewGuid(), new KeyValuePair<string, string>(yourKey, yourvalue))\n" }, { "answer_id": 233024, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 0, "selected": false, "text": "Dictionary<KeyValuePair, bool> mySet;\n\nfor(int i = 0; i < keys.length; ++i)\n{\n KeyValuePair kvp = new KeyValuePair(keys[i], values[i]);\n mySet[kvp] = true;\n}\n" }, { "answer_id": 233110, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 0, "selected": false, "text": "Dictionary KeyedCollection<TKey, TItem> protected TKey GetKeyForItem(TItem item) IList<T> IDictionary<TKey, TValue>" }, { "answer_id": 233139, "author": "Eric Smith", "author_id": 26054, "author_profile": "https://Stackoverflow.com/users/26054", "pm_score": 0, "selected": false, "text": "Dictionary<NameValuePair,int> hs = new Dictionary<NameValuePair,int>();\nforeach (i in jaggedArray)\n{\n foreach (j in i)\n {\n if (!hs.ContainsKey(j))\n {\n hs.Add(j, 0);\n }\n }\n}\nIEnumerable<NameValuePair> unique = hs.Keys;\n var hs = new HashSet<NameValuePair>();\nhs.UnionWith(jaggedArray.SelectMany(item => item));\n" }, { "answer_id": 237037, "author": "Thomas Eyde", "author_id": 3282, "author_profile": "https://Stackoverflow.com/users/3282", "pm_score": 0, "selected": false, "text": " var s = Guid.NewGuid().ToString();\n return s + s + s + s + s + s + s+ s + s + s;\n" }, { "answer_id": 251619, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 5, "selected": true, "text": "Key class StringPairComparer\n : IEqualityComparer<KeyValuePair<string, string>>\n {\n public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)\n {\n return x.Value == y.Value && x.Key == y.Key;\n }\n public int GetHashCode(KeyValuePair<string, string> obj)\n {\n return (obj.Key + obj.Value).GetHashCode();\n }\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/232997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22100/" ]
233,009
<p>Ok: This is some of my table structure that matters here</p> <pre><code>CaseStudyID int Title nvarchar(50) OverrideTitle nvarchar(50) </code></pre> <p>Part of my procedure</p> <pre><code>Declare @Temp table(CaseStudyID int, Title nvarchar(50)) Insert Into @Temp SELECT CaseStudyID,Title FROM CaseStudy WHERE Visible = 1 AND DisplayOnHomePage = 1 ORDER BY Title Update @Temp Set Title = TitleOverride --Here is where im lost if the title occurs more than once --I need to replace it with the override --Schoolboy error or leaking brain I cant get it going Select * From @Temp </code></pre> <p>Can anyone help?</p>
[ { "answer_id": 233039, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "SELECT \n MIN(CaseStudyID) AS CaseStudyID, \n CASE WHEN count(*) = 1 THEN \n MIN(Title) \n ELSE\n MIN(OverrideTitle) \n END AS Title\nFROM CaseStudy\nGROUP BY Title\nORDER BY Title\n" }, { "answer_id": 233080, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "SELECT CaseStudyID, Title \nFROM CaseStudy c1\nWHERE NOT EXISTS (\n SELECT * FROM CaseStudy c2 \n WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title\n)\n\nUNION ALL\n\nSELECT CaseStudyID, OverrideTitle\nFROM CaseStudy c1\nWHERE exists (\n SELECT * FROM CaseStudy c2\n WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title\n)\n\nORDER BY Title\n" }, { "answer_id": 233091, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 2, "selected": true, "text": "select distinct\n cs1.CaseStudyID,\n case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title\nfrom \n CaseStudy cs1\n left join CaseStudy cs2 \n on cs1.title = cs2.title\n and cs1.CaseStudyID > cs2.CaseStudyID\n select distinct\n cs1.CaseStudyID,\n case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title\nfrom \n CaseStudy cs1\n left join CaseStudy cs2 \n on cs1.title = cs2.title\n and cs1.CaseStudyID <> cs2.CaseStudyID\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11394/" ]
233,013
<p>I recently started learning Python and I was rather surprised to find a 1000 deep recursion limit (by default). If you set it high enough, about 30000, it crashes with a segmentation fault just like C. Although, C seems to go quite a lot higher.</p> <p>(The Python folks are quick to point out that you can always convert recursive functions to iterative ones and that they're always faster. That's 100% true. It's not really what my question is about though.)</p> <p>I tried the same experiment in Perl and somewhere around 10 million recursions it consumed all of my 4 gigs of ram and I used ^C to stop trying. Clearly Perl doesn't use the C stack, but it does use a ridiculous amount of memory when it recurses -- not terribly shocking considering how much work it has to do to call functions.</p> <p>I tried in Pike and was completely surprised to get 100,000,000 recursions in about 2 seconds. I have no idea how it did that, but I suspect it flattened the recursion to an iterative process -- it doesn't seem to consume any extra memory while it does it. [Note: Pike does flatten trivial cases, but segfaults on more complicated ones, or so I'm told.]</p> <p>I used these otherwise useless functions:</p> <pre><code>int f(int i, int l) { if(i&lt;l) return f(i+1,l); return i; } sub f { return f($_[0]+1, $_[1]) if $_[0]&lt;$_[1]; return $_[0] }; def f(i,l): if i&lt;l: return f(i+1,l) return i </code></pre> <p>I'm very curious how other languages (e.g., PHP, Ruby, Java, Lua, Ocaml, Haskell) handle recursion and why they handle it that way. Additionally, please note whether it makes a difference if the function is "tail-recursive" (see comment).</p>
[ { "answer_id": 233028, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "Fatal error: Maximum function nesting level of '100' reached, aborting! ini_set('xdebug.max_nesting_level', 100000); [Fri Oct 24 11:39:41 2008] [notice] Parent: child process exited with status 3221225477 -- Restarting." }, { "answer_id": 233190, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "function f(i, l)\n if i < l then\n return f(i+1, l)\n end\n return i\nend\n\nlocal val1 = arg[1] or 1\nlocal val2 = arg[2] or 100000000\nprint(f(val1 + 0, val2 + 0))\n function g(i, l)\n if i >= l then\n return i\n end\n return g(i+1, l)\nend\n" }, { "answer_id": 233359, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 2, "selected": false, "text": "let rec f i l = \n match i with \n | i when i < l -> f (i+1) l\n | _ -> l\n\nf 0 100000000;;\n let rec g i l = if i < l then g (i+1) l else l\n\ng 0 100000000;;\n int f(int i, int l)\n{\n while(true)\n {\n int num = i;\n if(num >= l)\n return l;\n int i = num;\n l = l;\n i = i + 1;\n }\n}\n int g(int i, int l)\n{\n while(i < l)\n {\n l = l;\n i++;\n }\n return l;\n}\n" }, { "answer_id": 234173, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "Perl goto sub f{\n if( $_[0] < $_[1] ){\n\n # return f( $_[0]+1, $_[1] );\n\n @_ = ( $_[0]+1, $_[1] );\n goto &f;\n\n } else {\n return $_[0]\n }\n}\n use Sub::Call::Recur;\nsub f{\n recur( $_[0]+1, $_[1] ) if $_[0] < $_[1];\n return $_[0];\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388466/" ]
233,026
<p>I have a database with a table which is full of conditions and error messages for checking another database.</p> <p>I want to run a loop such that each of these conditions is checked against all the tables in the second database and generae a report which gives the errors.</p> <p>Is this possible in ms access.</p> <p>For example,</p> <p>querycrit table</p> <pre><code>id query error 1 speed&lt;25 and speed&gt;56 speed above limit 2 dist&lt;56 or dist &gt;78 dist within limit </code></pre> <p>I have more than 400 queries like this of different variables.</p> <p>THe table against which I am running the queries is</p> <p>records table</p> <pre><code>id speed dist accce decele aaa bbb ccc 1 33 34 44 33 33 33 33 2 45 44 55 55 55 22 23 </code></pre> <p>regards ttk</p>
[ { "answer_id": 233136, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "Dim rs AS DAO.Recordset\nDim rs2 AS DAO.Recordset\n\nSet rs=CurrentDB.OpenRecordset(\"querycrit\")\n\nstrSQL=\"SELECT * From Records WHERE \"\nDo While Not rs.EOF\n Set rs2=CurrentDB.OpenRecordset(strSQL & rs![Query])\n If Not rs2.EOF Then\n Debug.Print rs![Error]\n Debug.Print rs2.Fields(1)\n End If\n\n rs.MoveNext\nLoop\n" }, { "answer_id": 233244, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "TableID QueryID\n1 4\n2 1\n2 3\n3 1\n" }, { "answer_id": 233470, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": true, "text": "Dim rs As DAO.Recordset\nDim rs2 As ADODB.Recordset\n\nSet rs = CurrentDb.OpenRecordset(\"querycrit\")\nSet rs2 = CreateObject(\"ADODB.Recordset\")\nrs2.ActiveConnection = CurrentProject.Connection\nFor Each tdf In CurrentDb.TableDefs\n'EDIT: TableDefs includes Microsoft System tables and '\n'these should never be tampered with. They all begin with Msys '\n'so we can leave them out of the loop here. '\n If Left(tdf.Name, 4) <> \"msys\" And tdf.Name <> \"querycrit\" Then\n rs.MoveFirst\n strSQL = \"SELECT * From [\" & tdf.Name & \"] WHERE \"\n\n Do While Not rs.EOF\n On Error Resume Next\n Debug.Print tdf.Name\n rs2.Open strSQL & \" \" & rs![query]\n If Err.Number = 0 Then\n On Error GoTo 0\n If Not rs2.EOF Then\n Debug.Print rs![Error]\n Debug.Print rs2.GetString\n End If\n End If\n Err.Clear\n rs2.Close\n rs.MoveNext\n\n Loop\n End If\nNext\nEnd Sub\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31132/" ]
233,072
<p><p>How to include any assembly code lines into my C program ? <p>In turbo c is there a possibility to add an assembly code file (.asm) to a project of few .c files?</p>
[ { "answer_id": 233090, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 3, "selected": true, "text": "void wrapper_function()\n{\n asm\n {\n /* your assembly code */\n }\n}\n" }, { "answer_id": 4147512, "author": "Rishav Ambasta", "author_id": 503584, "author_profile": "https://Stackoverflow.com/users/503584", "pm_score": 0, "selected": false, "text": "void func()\n{\nasm://assembly statements...\nasm://assembly statements...\n...\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
233,074
<p>Please could someone help me with writing a regex expression to replace 0044 token which will be at the start of the string with a 0. Please note that I do not want to replace all 0044 tokens with 0, only those that appear at the start of the string.</p> <p>Thanks a lot</p>
[ { "answer_id": 233076, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "s/^0044/0/;\n ^" }, { "answer_id": 233442, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 0, "selected": false, "text": "Search: \" 0044\"\nReplace \" 0\"\n" }, { "answer_id": 233480, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "^0044 0 044" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
233,088
<p>The fundamental equation of weight loss/gain is:</p> <pre><code>weight_change = convert_to_weight_diff(calories_consumed - calories_burnt); </code></pre> <p>I'm going on a health kick, and like a good nerd I thought I'd start keeping track of these things and write some software to process my data. I'm not attentive and disciplined enough to count calories in food, so I thought I'd work backwards:</p> <ul> <li>I can weigh myself every day</li> <li>I can calculate my BMR and hence how many calories I burn doing nothing all day</li> <li>I can use my heart-rate monitor to figure out how many calories I burn doing exercise</li> </ul> <p>That way I can generate an approximate "calories consumed" graph based on my exercise and weight records, and use that to motivate myself when I'm tempted to have a donut.</p> <p>The thing I'm stuck on is the function:</p> <pre><code>int convert_to_weight_diff(int calorie_diff); </code></pre> <p>Anybody know the pseudo-code for that function? If you've got some details, make sure you specify if we're talking calories, Calories, kilojoules, pounds, kilograms, etc.</p> <p>Thanks! </p>
[ { "answer_id": 9695826, "author": "hetelek", "author_id": 877651, "author_profile": "https://Stackoverflow.com/users/877651", "pm_score": 1, "selected": false, "text": "int convert_to_weight_diff(int calories)\n{\n return 0.000000000000046 * calories;\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
233,113
<p>How do I get the type of a generic typed class within the class?</p> <p>An example:</p> <p>I build a generic typed collection implementing <em>ICollection&lt; T></em>. Within I have methods like </p> <pre><code> public void Add(T item){ ... } public void Add(IEnumerable&lt;T&gt; enumItems){ ... } </code></pre> <p>How can I ask within the method for the given type <em>T</em>?</p> <p>The reason for my question is: If <em>object</em> is used as <em>T</em> the collection uses Add(object item) instead of Add(IEnumerable&lt;object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.</p> <p>So i need something like </p> <pre><code>if (T is object) { // Check for IEnumerable } </code></pre> <p>but of course that cannot work in C#. Suggestions?</p> <p>Thank you very much!</p> <p>Michael</p>
[ { "answer_id": 233120, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 5, "selected": false, "text": "typeof(T) if (typeof(T) == typeof(object) ) {\n // Check for IEnumerable\n}\n" }, { "answer_id": 233146, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "IEnumerable<T> AddRange List<T>.AddRange T IEnumerable<T>" }, { "answer_id": 233155, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": -1, "selected": false, "text": "is T public void MyMethod<T>(T theItem) where T : class\n{\n if (theItem is IEnumerable) { DoStuff(); }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9470/" ]
233,127
<p>We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread.</p> <p>The result is that the caller can use the function naively, and internally it'll make use of multiple cores.</p> <p><em>All good so far..</em></p> <p>The problem we have is dealing with exceptions. We don't want exceptions on the worker threads to crash the application. We want the caller to the function to be able to catch them on the main thread. We must catch exceptions on the worker threads and propagate them across to the main thread to have them continue unwinding from there.</p> <p><strong><em>How can we do this?</em></strong></p> <p>The best I can think of is:</p> <ol> <li>Catch a whole variety of exceptions on our worker threads (std::exception and a few of our own ones).</li> <li>Record the type and message of the exception.</li> <li>Have a corresponding switch statement on the main thread which rethrows exceptions of whatever type was recorded on the worker thread.</li> </ol> <p>This has the obvious disadvantage of only supporting a limited set of exception types, and would need modification whenever new exception types were added.</p>
[ { "answer_id": 233206, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 2, "selected": false, "text": "try\n{\n start thread();\n wait_finish( thread );\n}\ncatch(...)\n{\n // will catch exceptions generated within start and wait, \n // but not from the thread itself\n}\n" }, { "answer_id": 233588, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 6, "selected": false, "text": "catch(...) std::exception_ptr std::current_exception() std::rethrow_exception() std::exception_ptr" }, { "answer_id": 14513824, "author": "Quuxplusone", "author_id": 1424877, "author_profile": "https://Stackoverflow.com/users/1424877", "pm_score": 4, "selected": false, "text": "std::future std::future::get std::future std::async std::future #include <atomic>\n#include <chrono>\n#include <exception>\n#include <future>\n#include <thread>\n#include <vector>\n#include <stdio.h>\n\nbool is_prime(int n)\n{\n if (n == 1010) {\n puts(\"is_prime(1010) throws an exception\");\n throw std::logic_error(\"1010\");\n }\n /* We actually want this loop to run slowly, for demonstration purposes. */\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n for (int i=2; i < n; ++i) { if (n % i == 0) return false; }\n return (n >= 2);\n}\n\nint worker()\n{\n static std::atomic<int> hundreds(0);\n const int start = 100 * hundreds++;\n const int end = start + 100;\n int sum = 0;\n for (int i=start; i < end; ++i) {\n if (is_prime(i)) { printf(\"%d is prime\\n\", i); sum += i; }\n }\n return sum;\n}\n\nint spawn_workers(int N)\n{\n std::vector<std::future<int>> waitables;\n for (int i=0; i < N; ++i) {\n std::future<int> f = std::async(std::launch::async, worker);\n waitables.emplace_back(std::move(f));\n }\n\n int sum = 0;\n for (std::future<int> &f : waitables) {\n sum += f.get(); /* may throw an exception */\n }\n return sum;\n /* But watch out! When f.get() throws an exception, we still need\n * to unwind the stack, which means destructing \"waitables\" and each\n * of its elements. The destructor of each std::future will block\n * as if calling this->wait(). So in fact this may not do what you\n * really want. */\n}\n\nint main()\n{\n try {\n int sum = spawn_workers(100);\n printf(\"sum is %d\\n\", sum);\n } catch (std::exception &e) {\n /* This line will be printed after all the prime-number output. */\n printf(\"Caught %s\\n\", e.what());\n }\n}\n std::thread std::exception_ptr std::exception_ptr int main() {\n std::exception_ptr e;\n std::thread t1([&e](){\n try {\n ::operator new(-1);\n } catch (...) {\n e = std::current_exception();\n }\n });\n t1.join();\n try {\n std::rethrow_exception(e);\n } catch (const std::bad_alloc&) {\n puts(\"Success!\");\n }\n}\n" }, { "answer_id": 32428427, "author": "Gerardo Hernandez", "author_id": 653991, "author_profile": "https://Stackoverflow.com/users/653991", "pm_score": 8, "selected": true, "text": "exception_ptr #include<iostream>\n#include<thread>\n#include<exception>\n#include<stdexcept>\n\nstatic std::exception_ptr teptr = nullptr;\n\nvoid f()\n{\n try\n {\n std::this_thread::sleep_for(std::chrono::seconds(1));\n throw std::runtime_error(\"To be passed between threads\");\n }\n catch(...)\n {\n teptr = std::current_exception();\n }\n}\n\nint main(int argc, char **argv)\n{\n std::thread mythread(f);\n mythread.join();\n\n if (teptr) {\n try{\n std::rethrow_exception(teptr);\n }\n catch(const std::exception &ex)\n {\n std::cerr << \"Thread exited with exception: \" << ex.what() << \"\\n\";\n }\n }\n\n return 0;\n}\n exception_ptr exception_ptr exception_ptr /EHa" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/233127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ]